mirror of
https://github.com/kyverno/kyverno.git
synced 2025-03-29 02:45:06 +00:00
refactor: improve engine logger management (#6280)
* refactor: improve engine logger management Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * logger Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> --------- Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com>
This commit is contained in:
parent
9b434b995b
commit
15cf69f737
30 changed files with 342 additions and 313 deletions
|
@ -217,7 +217,7 @@ func (c *ApplyCommandConfig) applyCommandHelper() (rc *common.ResultCounts, reso
|
|||
return rc, resources, skipInvalidPolicies, pvInfos, err
|
||||
}
|
||||
|
||||
openApiManager, err := openapi.NewManager()
|
||||
openApiManager, err := openapi.NewManager(log.Log)
|
||||
if err != nil {
|
||||
return rc, resources, skipInvalidPolicies, pvInfos, sanitizederror.NewWithError("failed to initialize openAPIController", err)
|
||||
}
|
||||
|
|
|
@ -17,6 +17,7 @@ import (
|
|||
policyutils "github.com/kyverno/kyverno/pkg/utils/policy"
|
||||
"github.com/spf13/cobra"
|
||||
"go.uber.org/multierr"
|
||||
"sigs.k8s.io/controller-runtime/pkg/log"
|
||||
)
|
||||
|
||||
var policyRef string
|
||||
|
@ -41,7 +42,7 @@ kyverno oci push -p policies. -i <imgref>`,
|
|||
return fmt.Errorf("unable to read policy file or directory %s: %w", policyRef, multierr.Combine(errs...))
|
||||
}
|
||||
|
||||
openApiManager, err := openapi.NewManager()
|
||||
openApiManager, err := openapi.NewManager(log.Log)
|
||||
if err != nil {
|
||||
return fmt.Errorf("creating openapi manager: %v", err)
|
||||
}
|
||||
|
|
|
@ -275,7 +275,7 @@ func testCommandExecute(dirPath []string, fileName string, gitBranch string, tes
|
|||
tf.enabled = false
|
||||
}
|
||||
|
||||
openApiManager, err := openapi.NewManager()
|
||||
openApiManager, err := openapi.NewManager(log.Log)
|
||||
if err != nil {
|
||||
return rc, fmt.Errorf("unable to create open api controller, %w", err)
|
||||
}
|
||||
|
|
|
@ -322,7 +322,7 @@ func main() {
|
|||
logger.Error(err, "failed to initialize configuration")
|
||||
os.Exit(1)
|
||||
}
|
||||
openApiManager, err := openapi.NewManager()
|
||||
openApiManager, err := openapi.NewManager(logger.WithName("openapi"))
|
||||
if err != nil {
|
||||
logger.Error(err, "Failed to create openapi manager")
|
||||
os.Exit(1)
|
||||
|
|
|
@ -22,6 +22,6 @@ func logDiscoveryErrors(err error) {
|
|||
func isMetricsServerUnavailable(groupVersion string, err error) bool {
|
||||
// error message is defined at:
|
||||
// https://github.com/kubernetes/apimachinery/blob/2456ebdaba229616fab2161a615148884b46644b/pkg/api/errors/errors.go#L432
|
||||
return strings.HasPrefix(groupVersion, "metrics.k8s.io/") &&
|
||||
return (strings.HasPrefix(groupVersion, "metrics.k8s.io/") || strings.HasPrefix(groupVersion, "custom.metrics.k8s.io/") || strings.HasPrefix(groupVersion, "external.metrics.k8s.io/")) &&
|
||||
strings.Contains(err.Error(), "the server is currently unable to handle the request")
|
||||
}
|
||||
|
|
|
@ -7,9 +7,9 @@ import (
|
|||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
enginecontext "github.com/kyverno/kyverno/pkg/engine/context"
|
||||
"github.com/kyverno/kyverno/pkg/logging"
|
||||
"gotest.tools/assert"
|
||||
|
||||
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
|
||||
|
@ -41,7 +41,7 @@ func Test_serviceGetRequest(t *testing.T) {
|
|||
entry := kyvernov1.ContextEntry{}
|
||||
ctx := enginecontext.NewContext()
|
||||
|
||||
_, err := New(context.TODO(), entry, ctx, nil, logging.GlobalLogger())
|
||||
_, err := New(context.TODO(), entry, ctx, nil, logr.Discard())
|
||||
assert.ErrorContains(t, err, "missing APICall")
|
||||
|
||||
entry.Name = "test"
|
||||
|
@ -51,19 +51,19 @@ func Test_serviceGetRequest(t *testing.T) {
|
|||
},
|
||||
}
|
||||
|
||||
call, err := New(context.TODO(), entry, ctx, nil, logging.GlobalLogger())
|
||||
call, err := New(context.TODO(), entry, ctx, nil, logr.Discard())
|
||||
assert.NilError(t, err)
|
||||
_, err = call.Execute()
|
||||
assert.ErrorContains(t, err, "invalid request type")
|
||||
|
||||
entry.APICall.Service.Method = "GET"
|
||||
call, err = New(context.TODO(), entry, ctx, nil, logging.GlobalLogger())
|
||||
call, err = New(context.TODO(), entry, ctx, nil, logr.Discard())
|
||||
assert.NilError(t, err)
|
||||
_, err = call.Execute()
|
||||
assert.ErrorContains(t, err, "HTTP 404")
|
||||
|
||||
entry.APICall.Service.URL = s.URL + "/resource"
|
||||
call, err = New(context.TODO(), entry, ctx, nil, logging.GlobalLogger())
|
||||
call, err = New(context.TODO(), entry, ctx, nil, logr.Discard())
|
||||
assert.NilError(t, err)
|
||||
|
||||
data, err := call.Execute()
|
||||
|
@ -88,7 +88,7 @@ func Test_servicePostRequest(t *testing.T) {
|
|||
}
|
||||
|
||||
ctx := enginecontext.NewContext()
|
||||
call, err := New(context.TODO(), entry, ctx, nil, logging.GlobalLogger())
|
||||
call, err := New(context.TODO(), entry, ctx, nil, logr.Discard())
|
||||
assert.NilError(t, err)
|
||||
data, err := call.Execute()
|
||||
assert.NilError(t, err)
|
||||
|
@ -136,7 +136,7 @@ func Test_servicePostRequest(t *testing.T) {
|
|||
},
|
||||
}
|
||||
|
||||
call, err = New(context.TODO(), entry, ctx, nil, logging.GlobalLogger())
|
||||
call, err = New(context.TODO(), entry, ctx, nil, logr.Discard())
|
||||
assert.NilError(t, err)
|
||||
data, err = call.Execute()
|
||||
assert.NilError(t, err)
|
||||
|
|
|
@ -4,10 +4,10 @@ import (
|
|||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
v1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/engine/context"
|
||||
"github.com/kyverno/kyverno/pkg/engine/internal"
|
||||
"github.com/kyverno/kyverno/pkg/logging"
|
||||
"github.com/kyverno/kyverno/pkg/utils/api"
|
||||
"github.com/kyverno/kyverno/pkg/utils/image"
|
||||
"gotest.tools/assert"
|
||||
|
@ -258,7 +258,7 @@ func Test_Conditions(t *testing.T) {
|
|||
err := json.Unmarshal([]byte(scanPredicate), &dataMap)
|
||||
assert.NilError(t, err)
|
||||
|
||||
pass, err := internal.EvaluateConditions(conditions, ctx, dataMap, logging.GlobalLogger())
|
||||
pass, err := internal.EvaluateConditions(conditions, ctx, dataMap, logr.Discard())
|
||||
assert.NilError(t, err)
|
||||
assert.Equal(t, pass, true)
|
||||
}
|
||||
|
|
|
@ -4,13 +4,13 @@ import (
|
|||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/autogen"
|
||||
engineapi "github.com/kyverno/kyverno/pkg/engine/api"
|
||||
"github.com/kyverno/kyverno/pkg/engine/internal"
|
||||
"github.com/kyverno/kyverno/pkg/engine/utils"
|
||||
"github.com/kyverno/kyverno/pkg/engine/variables"
|
||||
"github.com/kyverno/kyverno/pkg/logging"
|
||||
)
|
||||
|
||||
// ApplyBackgroundChecks checks for validity of generate and mutateExisting rules on the resource
|
||||
|
@ -20,14 +20,15 @@ import (
|
|||
// 2. returns the list of rules that are applicable on this policy and resource, if 1 succeed
|
||||
func (e *engine) applyBackgroundChecks(
|
||||
ctx context.Context,
|
||||
logger logr.Logger,
|
||||
policyContext engineapi.PolicyContext,
|
||||
) (resp *engineapi.EngineResponse) {
|
||||
policyStartTime := time.Now()
|
||||
return e.filterRules(policyContext, policyStartTime)
|
||||
return e.filterRules(policyContext, logger, time.Now())
|
||||
}
|
||||
|
||||
func (e *engine) filterRules(
|
||||
policyContext engineapi.PolicyContext,
|
||||
logger logr.Logger,
|
||||
startTime time.Time,
|
||||
) *engineapi.EngineResponse {
|
||||
newResource := policyContext.NewResource()
|
||||
|
@ -57,13 +58,14 @@ func (e *engine) filterRules(
|
|||
}
|
||||
|
||||
if e.configuration.ToFilter(kind, namespace, name) {
|
||||
logging.WithName("ApplyBackgroundChecks").Info("resource excluded", "kind", kind, "namespace", namespace, "name", name)
|
||||
logger.Info("resource excluded")
|
||||
return resp
|
||||
}
|
||||
|
||||
applyRules := policy.GetSpec().GetApplyRules()
|
||||
for _, rule := range autogen.ComputeRules(policy) {
|
||||
if ruleResp := e.filterRule(rule, policyContext); ruleResp != nil {
|
||||
logger := internal.LoggerWithRule(logger, rule)
|
||||
if ruleResp := e.filterRule(rule, logger, policyContext); ruleResp != nil {
|
||||
resp.PolicyResponse.Rules = append(resp.PolicyResponse.Rules, *ruleResp)
|
||||
if applyRules == kyvernov1.ApplyOne && ruleResp.Status != engineapi.RuleStatusSkip {
|
||||
break
|
||||
|
@ -76,14 +78,13 @@ func (e *engine) filterRules(
|
|||
|
||||
func (e *engine) filterRule(
|
||||
rule kyvernov1.Rule,
|
||||
logger logr.Logger,
|
||||
policyContext engineapi.PolicyContext,
|
||||
) *engineapi.RuleResponse {
|
||||
if !rule.HasGenerate() && !rule.IsMutateExisting() {
|
||||
return nil
|
||||
}
|
||||
|
||||
logger := logging.WithName("exception")
|
||||
|
||||
kindsInPolicy := append(rule.MatchResources.GetKinds(), rule.ExcludeResources.GetKinds()...)
|
||||
subresourceGVKToAPIResource := GetSubresourceGVKToAPIResourceMap(e.client, kindsInPolicy, policyContext)
|
||||
|
||||
|
@ -100,7 +101,6 @@ func (e *engine) filterRule(
|
|||
|
||||
startTime := time.Now()
|
||||
|
||||
policy := policyContext.Policy()
|
||||
newResource := policyContext.NewResource()
|
||||
oldResource := policyContext.OldResource()
|
||||
admissionInfo := policyContext.AdmissionInfo()
|
||||
|
@ -108,9 +108,6 @@ func (e *engine) filterRule(
|
|||
excludeGroupRole := e.configuration.GetExcludeGroupRole()
|
||||
namespaceLabels := policyContext.NamespaceLabels()
|
||||
|
||||
logger = logging.WithName(string(ruleType)).WithValues("policy", policy.GetName(),
|
||||
"kind", newResource.GetKind(), "namespace", newResource.GetNamespace(), "name", newResource.GetName())
|
||||
|
||||
if err := MatchesResourceDescription(subresourceGVKToAPIResource, newResource, rule, admissionInfo, excludeGroupRole, namespaceLabels, "", policyContext.SubResource()); err != nil {
|
||||
if ruleType == engineapi.Generation {
|
||||
// if the oldResource matched, return "false" to delete GR for it
|
||||
|
|
|
@ -9,6 +9,8 @@ import (
|
|||
"github.com/kyverno/kyverno/pkg/config"
|
||||
engineapi "github.com/kyverno/kyverno/pkg/engine/api"
|
||||
enginecontext "github.com/kyverno/kyverno/pkg/engine/context"
|
||||
"github.com/kyverno/kyverno/pkg/engine/internal"
|
||||
"github.com/kyverno/kyverno/pkg/logging"
|
||||
"github.com/kyverno/kyverno/pkg/registryclient"
|
||||
)
|
||||
|
||||
|
@ -40,28 +42,32 @@ func (e *engine) Validate(
|
|||
ctx context.Context,
|
||||
policyContext engineapi.PolicyContext,
|
||||
) *engineapi.EngineResponse {
|
||||
return e.validate(ctx, policyContext)
|
||||
logger := internal.LoggerWithPolicyContext(logging.WithName("engine.validate"), policyContext)
|
||||
return e.validate(ctx, logger, policyContext)
|
||||
}
|
||||
|
||||
func (e *engine) Mutate(
|
||||
ctx context.Context,
|
||||
policyContext engineapi.PolicyContext,
|
||||
) *engineapi.EngineResponse {
|
||||
return e.mutate(ctx, policyContext)
|
||||
logger := internal.LoggerWithPolicyContext(logging.WithName("engine.mutate"), policyContext)
|
||||
return e.mutate(ctx, logger, policyContext)
|
||||
}
|
||||
|
||||
func (e *engine) VerifyAndPatchImages(
|
||||
ctx context.Context,
|
||||
policyContext engineapi.PolicyContext,
|
||||
) (*engineapi.EngineResponse, *engineapi.ImageVerificationMetadata) {
|
||||
return e.verifyAndPatchImages(ctx, policyContext)
|
||||
logger := internal.LoggerWithPolicyContext(logging.WithName("engine.verify"), policyContext)
|
||||
return e.verifyAndPatchImages(ctx, logger, policyContext)
|
||||
}
|
||||
|
||||
func (e *engine) ApplyBackgroundChecks(
|
||||
ctx context.Context,
|
||||
policyContext engineapi.PolicyContext,
|
||||
) *engineapi.EngineResponse {
|
||||
return e.applyBackgroundChecks(ctx, policyContext)
|
||||
logger := internal.LoggerWithPolicyContext(logging.WithName("engine.background"), policyContext)
|
||||
return e.applyBackgroundChecks(ctx, logger, policyContext)
|
||||
}
|
||||
|
||||
func (e *engine) GenerateResponse(
|
||||
|
@ -69,7 +75,8 @@ func (e *engine) GenerateResponse(
|
|||
policyContext engineapi.PolicyContext,
|
||||
gr kyvernov1beta1.UpdateRequest,
|
||||
) *engineapi.EngineResponse {
|
||||
return e.generateResponse(ctx, policyContext, gr)
|
||||
logger := internal.LoggerWithPolicyContext(logging.WithName("engine.generate"), policyContext)
|
||||
return e.generateResponse(ctx, logger, policyContext, gr)
|
||||
}
|
||||
|
||||
func (e *engine) ContextLoader(
|
||||
|
|
|
@ -7,9 +7,9 @@ import (
|
|||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
engineapi "github.com/kyverno/kyverno/pkg/engine/api"
|
||||
"github.com/kyverno/kyverno/pkg/engine/context"
|
||||
"github.com/kyverno/kyverno/pkg/engine/internal"
|
||||
"github.com/kyverno/kyverno/pkg/engine/mutate"
|
||||
"github.com/kyverno/kyverno/pkg/engine/variables"
|
||||
"github.com/kyverno/kyverno/pkg/logging"
|
||||
"github.com/kyverno/kyverno/pkg/utils/api"
|
||||
"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
|
@ -17,9 +17,16 @@ import (
|
|||
|
||||
// ForceMutate does not check any conditions, it simply mutates the given resource
|
||||
// It is used to validate mutation logic, and for tests.
|
||||
func ForceMutate(ctx context.Interface, policy kyvernov1.PolicyInterface, resource unstructured.Unstructured) (unstructured.Unstructured, error) {
|
||||
logger := logging.WithName("EngineForceMutate").WithValues("policy", policy.GetName(), "kind", resource.GetKind(),
|
||||
"namespace", resource.GetNamespace(), "name", resource.GetName())
|
||||
func ForceMutate(
|
||||
ctx context.Interface,
|
||||
logger logr.Logger,
|
||||
policy kyvernov1.PolicyInterface,
|
||||
resource unstructured.Unstructured,
|
||||
) (unstructured.Unstructured, error) {
|
||||
logger = internal.LoggerWithPolicy(logger, policy)
|
||||
logger = internal.LoggerWithResource(logger, "resource", resource)
|
||||
// logger := logging.WithName("EngineForceMutate").WithValues("policy", policy.GetName(), "kind", resource.GetKind(),
|
||||
// "namespace", resource.GetNamespace(), "name", resource.GetName())
|
||||
|
||||
patchedResource := resource
|
||||
// TODO: if we apply autogen, tests will fail
|
||||
|
@ -29,6 +36,8 @@ func ForceMutate(ctx context.Interface, policy kyvernov1.PolicyInterface, resour
|
|||
continue
|
||||
}
|
||||
|
||||
logger := internal.LoggerWithRule(logger, rule)
|
||||
|
||||
ruleCopy := rule.DeepCopy()
|
||||
removeConditions(ruleCopy)
|
||||
r, err := variables.SubstituteAllForceMutate(logger, ctx, *ruleCopy)
|
||||
|
|
|
@ -4,6 +4,7 @@ import (
|
|||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/engine/context"
|
||||
kubeutils "github.com/kyverno/kyverno/pkg/utils/kube"
|
||||
|
@ -103,7 +104,7 @@ func Test_ForceMutateSubstituteVars(t *testing.T) {
|
|||
err = context.AddResource(ctx, rawResource)
|
||||
assert.NilError(t, err)
|
||||
|
||||
mutatedResource, err := ForceMutate(ctx, &policy, *resourceUnstructured)
|
||||
mutatedResource, err := ForceMutate(ctx, logr.Discard(), &policy, *resourceUnstructured)
|
||||
assert.NilError(t, err)
|
||||
|
||||
assert.DeepEqual(t, expectedResource, mutatedResource.UnstructuredContent())
|
||||
|
@ -208,7 +209,7 @@ func Test_ForceMutateSubstituteVarsWithPatchesJson6902(t *testing.T) {
|
|||
err = context.AddResource(ctx, rawResource)
|
||||
assert.NilError(t, err)
|
||||
|
||||
mutatedResource, err := ForceMutate(ctx, &policy, *resourceUnstructured)
|
||||
mutatedResource, err := ForceMutate(ctx, logr.Discard(), &policy, *resourceUnstructured)
|
||||
assert.NilError(t, err)
|
||||
|
||||
assert.DeepEqual(t, expectedResource.UnstructuredContent(), mutatedResource.UnstructuredContent())
|
||||
|
@ -294,7 +295,7 @@ func Test_ForceMutateSubstituteVarsWithPatchStrategicMerge(t *testing.T) {
|
|||
err = context.AddResource(ctx, rawResource)
|
||||
assert.NilError(t, err)
|
||||
|
||||
mutatedResource, err := ForceMutate(ctx, &policy, *resourceUnstructured)
|
||||
mutatedResource, err := ForceMutate(ctx, logr.Discard(), &policy, *resourceUnstructured)
|
||||
assert.NilError(t, err)
|
||||
|
||||
assert.DeepEqual(t, expectedResource, mutatedResource.UnstructuredContent())
|
||||
|
|
|
@ -4,25 +4,27 @@ import (
|
|||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
"github.com/kyverno/kyverno/pkg/autogen"
|
||||
engineapi "github.com/kyverno/kyverno/pkg/engine/api"
|
||||
"github.com/kyverno/kyverno/pkg/logging"
|
||||
"github.com/kyverno/kyverno/pkg/engine/internal"
|
||||
"k8s.io/client-go/tools/cache"
|
||||
)
|
||||
|
||||
// GenerateResponse checks for validity of generate rule on the resource
|
||||
func (e *engine) generateResponse(
|
||||
ctx context.Context,
|
||||
logger logr.Logger,
|
||||
policyContext engineapi.PolicyContext,
|
||||
gr kyvernov1beta1.UpdateRequest,
|
||||
) (resp *engineapi.EngineResponse) {
|
||||
policyStartTime := time.Now()
|
||||
return e.filterGenerateRules(policyContext, gr.Spec.Policy, policyStartTime)
|
||||
return e.filterGenerateRules(policyContext, logger, gr.Spec.Policy, time.Now())
|
||||
}
|
||||
|
||||
func (e *engine) filterGenerateRules(
|
||||
policyContext engineapi.PolicyContext,
|
||||
logger logr.Logger,
|
||||
policyNameKey string,
|
||||
startTime time.Time,
|
||||
) *engineapi.EngineResponse {
|
||||
|
@ -33,7 +35,7 @@ func (e *engine) filterGenerateRules(
|
|||
apiVersion := newResource.GetAPIVersion()
|
||||
pNamespace, pName, err := cache.SplitMetaNamespaceKey(policyNameKey)
|
||||
if err != nil {
|
||||
logging.Error(err, "failed to spilt name and namespace", policyNameKey)
|
||||
logger.Error(err, "failed to spilt name and namespace", "policy.key", policyNameKey)
|
||||
}
|
||||
resp := &engineapi.EngineResponse{
|
||||
PolicyResponse: engineapi.PolicyResponse{
|
||||
|
@ -55,15 +57,14 @@ func (e *engine) filterGenerateRules(
|
|||
},
|
||||
}
|
||||
if e.configuration.ToFilter(kind, namespace, name) {
|
||||
logging.WithName("Generate").Info("resource excluded", "kind", kind, "namespace", namespace, "name", name)
|
||||
logger.Info("resource excluded")
|
||||
return resp
|
||||
}
|
||||
|
||||
for _, rule := range autogen.ComputeRules(policyContext.Policy()) {
|
||||
if ruleResp := e.filterRule(rule, policyContext); ruleResp != nil {
|
||||
logger := internal.LoggerWithRule(logger, rule)
|
||||
if ruleResp := e.filterRule(rule, logger, policyContext); ruleResp != nil {
|
||||
resp.PolicyResponse.Rules = append(resp.PolicyResponse.Rules, *ruleResp)
|
||||
}
|
||||
}
|
||||
|
||||
return resp
|
||||
}
|
||||
|
|
|
@ -13,7 +13,6 @@ import (
|
|||
enginecontext "github.com/kyverno/kyverno/pkg/engine/context"
|
||||
"github.com/kyverno/kyverno/pkg/engine/internal"
|
||||
"github.com/kyverno/kyverno/pkg/engine/variables"
|
||||
"github.com/kyverno/kyverno/pkg/logging"
|
||||
"github.com/kyverno/kyverno/pkg/tracing"
|
||||
apiutils "github.com/kyverno/kyverno/pkg/utils/api"
|
||||
"github.com/kyverno/kyverno/pkg/utils/wildcard"
|
||||
|
@ -22,15 +21,12 @@ import (
|
|||
|
||||
func (e *engine) verifyAndPatchImages(
|
||||
ctx context.Context,
|
||||
logger logr.Logger,
|
||||
policyContext engineapi.PolicyContext,
|
||||
) (*engineapi.EngineResponse, *engineapi.ImageVerificationMetadata) {
|
||||
resp := &engineapi.EngineResponse{}
|
||||
|
||||
policy := policyContext.Policy()
|
||||
patchedResource := policyContext.NewResource()
|
||||
logger := logging.WithName("EngineVerifyImages").WithValues("policy", policy.GetName(),
|
||||
"kind", patchedResource.GetKind(), "namespace", patchedResource.GetNamespace(), "name", patchedResource.GetName())
|
||||
|
||||
startTime := time.Now()
|
||||
defer func() {
|
||||
internal.BuildResponse(policyContext, resp, startTime)
|
||||
|
@ -58,6 +54,7 @@ func (e *engine) verifyAndPatchImages(
|
|||
return
|
||||
}
|
||||
startTime := time.Now()
|
||||
logger := internal.LoggerWithRule(logger, rules[i])
|
||||
kindsInPolicy := append(rule.MatchResources.GetKinds(), rule.ExcludeResources.GetKinds()...)
|
||||
subresourceGVKToAPIResource := GetSubresourceGVKToAPIResourceMap(e.client, kindsInPolicy, policyContext)
|
||||
|
||||
|
@ -72,7 +69,7 @@ func (e *engine) verifyAndPatchImages(
|
|||
return
|
||||
}
|
||||
|
||||
logger.V(3).Info("processing image verification rule", "ruleSelector", applyRules)
|
||||
logger.V(3).Info("processing image verification rule")
|
||||
|
||||
ruleImages, imageRefs, err := e.extractMatchingImages(policyContext, rule)
|
||||
if err != nil {
|
||||
|
|
|
@ -7,6 +7,7 @@ import (
|
|||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/config"
|
||||
"github.com/kyverno/kyverno/pkg/cosign"
|
||||
|
@ -15,7 +16,6 @@ import (
|
|||
"github.com/kyverno/kyverno/pkg/engine/context/resolvers"
|
||||
"github.com/kyverno/kyverno/pkg/engine/internal"
|
||||
"github.com/kyverno/kyverno/pkg/engine/utils"
|
||||
"github.com/kyverno/kyverno/pkg/logging"
|
||||
"github.com/kyverno/kyverno/pkg/registryclient"
|
||||
kubeutils "github.com/kyverno/kyverno/pkg/utils/kube"
|
||||
"gotest.tools/assert"
|
||||
|
@ -746,18 +746,18 @@ func Test_ChangedAnnotation(t *testing.T) {
|
|||
|
||||
policyContext := buildContext(t, testPolicyGood, testResource, testResource)
|
||||
|
||||
hasChanged := internal.HasImageVerifiedAnnotationChanged(policyContext, logging.GlobalLogger())
|
||||
hasChanged := internal.HasImageVerifiedAnnotationChanged(policyContext, logr.Discard())
|
||||
assert.Equal(t, hasChanged, false)
|
||||
|
||||
policyContext = buildContext(t, testPolicyGood, newResource, testResource)
|
||||
hasChanged = internal.HasImageVerifiedAnnotationChanged(policyContext, logging.GlobalLogger())
|
||||
hasChanged = internal.HasImageVerifiedAnnotationChanged(policyContext, logr.Discard())
|
||||
assert.Equal(t, hasChanged, true)
|
||||
|
||||
annotationOld := fmt.Sprintf("\"annotations\": {\"%s\": \"%s\"}", annotationKey, "false")
|
||||
oldResource := strings.ReplaceAll(testResource, "\"annotations\": {}", annotationOld)
|
||||
|
||||
policyContext = buildContext(t, testPolicyGood, newResource, oldResource)
|
||||
hasChanged = internal.HasImageVerifiedAnnotationChanged(policyContext, logging.GlobalLogger())
|
||||
hasChanged = internal.HasImageVerifiedAnnotationChanged(policyContext, logr.Discard())
|
||||
assert.Equal(t, hasChanged, true)
|
||||
}
|
||||
|
||||
|
@ -778,7 +778,7 @@ func Test_MarkImageVerified(t *testing.T) {
|
|||
assert.Equal(t, len(verifiedImages.Data), 1)
|
||||
assert.Equal(t, verifiedImages.IsVerified(image), true)
|
||||
|
||||
patches, err := verifiedImages.Patches(false, logging.GlobalLogger())
|
||||
patches, err := verifiedImages.Patches(false, logr.Discard())
|
||||
assert.NilError(t, err)
|
||||
assert.Equal(t, len(patches), 2)
|
||||
|
||||
|
@ -789,7 +789,7 @@ func Test_MarkImageVerified(t *testing.T) {
|
|||
json := patchedAnnotations[engineapi.ImageVerifyAnnotationKey]
|
||||
assert.Assert(t, json != "")
|
||||
|
||||
verified, err := isImageVerified(resource, image, logging.GlobalLogger())
|
||||
verified, err := isImageVerified(resource, image, logr.Discard())
|
||||
assert.NilError(t, err)
|
||||
assert.Equal(t, verified, true)
|
||||
}
|
||||
|
|
|
@ -4,19 +4,37 @@ import (
|
|||
"reflect"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
engineapi "github.com/kyverno/kyverno/pkg/engine/api"
|
||||
"github.com/kyverno/kyverno/pkg/logging"
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
)
|
||||
|
||||
func BuildLogger(ctx engineapi.PolicyContext) logr.Logger {
|
||||
logger := logging.WithName("EngineValidate").WithValues("policy", ctx.Policy().GetName())
|
||||
newResource := ctx.NewResource()
|
||||
oldResource := ctx.OldResource()
|
||||
if reflect.DeepEqual(newResource, unstructured.Unstructured{}) {
|
||||
logger = logger.WithValues("kind", oldResource.GetKind(), "namespace", oldResource.GetNamespace(), "name", oldResource.GetName())
|
||||
} else {
|
||||
logger = logger.WithValues("kind", newResource.GetKind(), "namespace", newResource.GetNamespace(), "name", newResource.GetName())
|
||||
}
|
||||
func LoggerWithPolicyContext(logger logr.Logger, policyContext engineapi.PolicyContext) logr.Logger {
|
||||
logger = LoggerWithPolicy(logger, policyContext.Policy())
|
||||
logger = LoggerWithResource(logger, "new", policyContext.NewResource())
|
||||
logger = LoggerWithResource(logger, "old", policyContext.OldResource())
|
||||
return logger
|
||||
}
|
||||
|
||||
func LoggerWithPolicy(logger logr.Logger, policy kyvernov1.PolicyInterface) logr.Logger {
|
||||
return logger.WithValues(
|
||||
"policy.name", policy.GetName(),
|
||||
"policy.namespace", policy.GetNamespace(),
|
||||
"policy.apply", policy.GetSpec().GetApplyRules(),
|
||||
)
|
||||
}
|
||||
|
||||
func LoggerWithResource(logger logr.Logger, prefix string, resource unstructured.Unstructured) logr.Logger {
|
||||
if reflect.DeepEqual(resource, unstructured.Unstructured{}) {
|
||||
return logger
|
||||
}
|
||||
return logger.WithValues(
|
||||
prefix+".kind", resource.GetKind(),
|
||||
prefix+".namespace", resource.GetNamespace(),
|
||||
prefix+".name", resource.GetName(),
|
||||
)
|
||||
}
|
||||
|
||||
func LoggerWithRule(logger logr.Logger, rule kyvernov1.Rule) logr.Logger {
|
||||
return logger.WithValues("rule.name", rule.Name)
|
||||
}
|
||||
|
|
|
@ -4,10 +4,10 @@ import (
|
|||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
types "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
engineapi "github.com/kyverno/kyverno/pkg/engine/api"
|
||||
"github.com/kyverno/kyverno/pkg/engine/context"
|
||||
"github.com/kyverno/kyverno/pkg/logging"
|
||||
kubeutils "github.com/kyverno/kyverno/pkg/utils/kube"
|
||||
"gotest.tools/assert"
|
||||
"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
|
||||
|
@ -47,7 +47,7 @@ const endpointsDocument string = `{
|
|||
}`
|
||||
|
||||
func applyPatches(rule *types.Rule, resource unstructured.Unstructured) (*engineapi.RuleResponse, unstructured.Unstructured) {
|
||||
mutateResp := Mutate(rule, context.NewContext(), resource, logging.GlobalLogger())
|
||||
mutateResp := Mutate(rule, context.NewContext(), resource, logr.Discard())
|
||||
|
||||
if mutateResp.Status != engineapi.RuleStatusPass {
|
||||
return &engineapi.RuleResponse{
|
||||
|
|
|
@ -5,8 +5,8 @@ import (
|
|||
"testing"
|
||||
|
||||
"github.com/ghodss/yaml"
|
||||
"github.com/go-logr/logr"
|
||||
engineapi "github.com/kyverno/kyverno/pkg/engine/api"
|
||||
"github.com/kyverno/kyverno/pkg/logging"
|
||||
assert "github.com/stretchr/testify/assert"
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
)
|
||||
|
@ -50,7 +50,7 @@ func TestTypeConversion(t *testing.T) {
|
|||
jsonPatches, err := yaml.YAMLToJSON(patchesJSON6902)
|
||||
assert.Nil(t, err)
|
||||
// apply patches
|
||||
resp, _ := ProcessPatchJSON6902("type-conversion", jsonPatches, resource, logging.GlobalLogger())
|
||||
resp, _ := ProcessPatchJSON6902("type-conversion", jsonPatches, resource, logr.Discard())
|
||||
if !assert.Equal(t, engineapi.RuleStatusPass, resp.Status) {
|
||||
t.Fatal(resp.Message)
|
||||
}
|
||||
|
|
|
@ -4,14 +4,14 @@ import (
|
|||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/kyverno/kyverno/pkg/logging"
|
||||
"github.com/go-logr/logr"
|
||||
"github.com/mattbaird/jsonpatch"
|
||||
assertnew "github.com/stretchr/testify/assert"
|
||||
"gotest.tools/assert"
|
||||
)
|
||||
|
||||
func Test_GeneratePatches(t *testing.T) {
|
||||
out, err := strategicMergePatch(logging.GlobalLogger(), string(baseBytes), string(overlayBytes))
|
||||
out, err := strategicMergePatch(logr.Discard(), string(baseBytes), string(overlayBytes))
|
||||
assert.NilError(t, err)
|
||||
|
||||
expectedPatches := map[string]bool{
|
||||
|
|
|
@ -4,9 +4,9 @@ import (
|
|||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/autogen"
|
||||
"github.com/kyverno/kyverno/pkg/logging"
|
||||
assertnew "github.com/stretchr/testify/assert"
|
||||
"gotest.tools/assert"
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
|
@ -163,7 +163,7 @@ func TestMergePatch(t *testing.T) {
|
|||
|
||||
for i, test := range testCases {
|
||||
t.Logf("Running test %d...", i+1)
|
||||
out, err := strategicMergePatch(logging.GlobalLogger(), string(test.rawResource), string(test.rawPolicy))
|
||||
out, err := strategicMergePatch(logr.Discard(), string(test.rawResource), string(test.rawPolicy))
|
||||
assert.NilError(t, err)
|
||||
assert.DeepEqual(t, toJSON(t, test.expected), toJSON(t, out))
|
||||
}
|
||||
|
@ -247,7 +247,7 @@ func Test_PolicyDeserilize(t *testing.T) {
|
|||
patchString, err := json.Marshal(overlayPatches)
|
||||
assert.NilError(t, err)
|
||||
|
||||
out, err := strategicMergePatch(logging.GlobalLogger(), string(baseBytes), string(patchString))
|
||||
out, err := strategicMergePatch(logr.Discard(), string(baseBytes), string(patchString))
|
||||
assert.NilError(t, err)
|
||||
|
||||
var ep unstructured.Unstructured
|
||||
|
|
|
@ -4,8 +4,8 @@ import (
|
|||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
"github.com/kyverno/kyverno/pkg/engine/anchor"
|
||||
"github.com/kyverno/kyverno/pkg/logging"
|
||||
"gotest.tools/assert"
|
||||
yaml "sigs.k8s.io/kustomize/kyaml/yaml"
|
||||
)
|
||||
|
@ -962,7 +962,7 @@ func Test_preProcessStrategicMergePatch_multipleAnchors(t *testing.T) {
|
|||
|
||||
for i, test := range testCases {
|
||||
t.Logf("Running test %d...", i)
|
||||
preProcessedPolicy, err := preProcessStrategicMergePatch(logging.GlobalLogger(), string(test.rawPolicy), string(test.rawResource))
|
||||
preProcessedPolicy, err := preProcessStrategicMergePatch(logr.Discard(), string(test.rawPolicy), string(test.rawResource))
|
||||
assert.NilError(t, err)
|
||||
|
||||
output, err := preProcessedPolicy.MarshalJSON()
|
||||
|
@ -1024,7 +1024,7 @@ func Test_CheckConditionAnchor_Matches(t *testing.T) {
|
|||
pattern := yaml.MustParse(string(patternRaw))
|
||||
resource := yaml.MustParse(string(resourceRaw))
|
||||
|
||||
err := checkCondition(logging.GlobalLogger(), pattern, resource)
|
||||
err := checkCondition(logr.Discard(), pattern, resource)
|
||||
assert.Equal(t, err, nil)
|
||||
}
|
||||
|
||||
|
@ -1035,7 +1035,7 @@ func Test_CheckConditionAnchor_DoesNotMatch(t *testing.T) {
|
|||
pattern := yaml.MustParse(string(patternRaw))
|
||||
resource := yaml.MustParse(string(resourceRaw))
|
||||
|
||||
err := checkCondition(logging.GlobalLogger(), pattern, resource)
|
||||
err := checkCondition(logr.Discard(), pattern, resource)
|
||||
assert.Error(t, err, "resource value 'sample' does not match 'value*' at path /key1/")
|
||||
}
|
||||
|
||||
|
@ -1053,7 +1053,7 @@ func Test_ValidateConditions_MapWithOneCondition_Matches(t *testing.T) {
|
|||
pattern := yaml.MustParse(string(patternRaw))
|
||||
resource := yaml.MustParse(string(resourceRaw))
|
||||
|
||||
err := validateConditions(logging.GlobalLogger(), pattern, resource)
|
||||
err := validateConditions(logr.Discard(), pattern, resource)
|
||||
assert.NilError(t, err)
|
||||
}
|
||||
|
||||
|
@ -1071,7 +1071,7 @@ func Test_ValidateConditions_MapWithOneCondition_DoesNotMatch(t *testing.T) {
|
|||
pattern := yaml.MustParse(string(patternRaw))
|
||||
resource := yaml.MustParse(string(resourceRaw))
|
||||
|
||||
err := validateConditions(logging.GlobalLogger(), pattern, resource)
|
||||
err := validateConditions(logr.Discard(), pattern, resource)
|
||||
_, ok := err.(ConditionError)
|
||||
assert.Assert(t, ok)
|
||||
}
|
||||
|
@ -1208,7 +1208,7 @@ func Test_ConditionCheck_SeveralElementsMatchExceptOne(t *testing.T) {
|
|||
pattern := yaml.MustParse(string(patternRaw))
|
||||
containers := yaml.MustParse(string(containersRaw))
|
||||
|
||||
err := preProcessPattern(logging.GlobalLogger(), pattern, containers)
|
||||
err := preProcessPattern(logr.Discard(), pattern, containers)
|
||||
assert.NilError(t, err)
|
||||
|
||||
patternContainers := pattern.Field("containers")
|
||||
|
@ -1261,7 +1261,7 @@ func Test_NonExistingKeyMustFailPreprocessing(t *testing.T) {
|
|||
|
||||
pattern := yaml.MustParse(string(rawPattern))
|
||||
resource := yaml.MustParse(string(rawResource))
|
||||
err := preProcessPattern(logging.GlobalLogger(), pattern, resource)
|
||||
err := preProcessPattern(logr.Discard(), pattern, resource)
|
||||
assert.Error(t, err, "condition failed: could not found \"key1\" key in the resource")
|
||||
}
|
||||
|
||||
|
@ -1272,7 +1272,7 @@ func Test_NestedConditionals(t *testing.T) {
|
|||
|
||||
pattern := yaml.MustParse(rawPattern)
|
||||
resource := yaml.MustParse(rawResource)
|
||||
err := preProcessPattern(logging.GlobalLogger(), pattern, resource)
|
||||
err := preProcessPattern(logr.Discard(), pattern, resource)
|
||||
assert.NilError(t, err)
|
||||
resultPattern, _ := pattern.String()
|
||||
|
||||
|
@ -1312,6 +1312,6 @@ func Test_GlobalCondition_Fail(t *testing.T) {
|
|||
|
||||
pattern := yaml.MustParse(string(rawPattern))
|
||||
resource := yaml.MustParse(string(rawResource))
|
||||
err := preProcessPattern(logging.GlobalLogger(), pattern, resource)
|
||||
err := preProcessPattern(logr.Discard(), pattern, resource)
|
||||
assert.Error(t, err, "global condition failed: could not found \"emptyDir\" key in the resource")
|
||||
}
|
||||
|
|
|
@ -13,7 +13,6 @@ import (
|
|||
engineapi "github.com/kyverno/kyverno/pkg/engine/api"
|
||||
"github.com/kyverno/kyverno/pkg/engine/internal"
|
||||
"github.com/kyverno/kyverno/pkg/engine/mutate"
|
||||
"github.com/kyverno/kyverno/pkg/logging"
|
||||
"github.com/kyverno/kyverno/pkg/tracing"
|
||||
"github.com/kyverno/kyverno/pkg/utils/api"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
@ -24,6 +23,7 @@ import (
|
|||
// Mutate performs mutation. Overlay first and then mutation patches
|
||||
func (e *engine) mutate(
|
||||
ctx context.Context,
|
||||
logger logr.Logger,
|
||||
policyContext engineapi.PolicyContext,
|
||||
) (resp *engineapi.EngineResponse) {
|
||||
startTime := time.Now()
|
||||
|
@ -35,9 +35,6 @@ func (e *engine) mutate(
|
|||
enginectx := policyContext.JSONContext()
|
||||
var skippedRules []string
|
||||
|
||||
logger := logging.WithName("EngineMutate").WithValues("policy", policy.GetName(), "kind", matchedResource.GetKind(),
|
||||
"namespace", matchedResource.GetNamespace(), "name", matchedResource.GetName())
|
||||
|
||||
logger.V(4).Info("start mutate policy processing", "startTime", startTime)
|
||||
|
||||
startMutateResultResponse(resp, policy, matchedResource)
|
||||
|
@ -60,7 +57,7 @@ func (e *engine) mutate(
|
|||
"pkg/engine",
|
||||
fmt.Sprintf("RULE %s", rule.Name),
|
||||
func(ctx context.Context, span trace.Span) {
|
||||
logger := logger.WithValues("rule", rule.Name)
|
||||
logger := internal.LoggerWithRule(logger, rule)
|
||||
var excludeResource []string
|
||||
if len(e.configuration.GetExcludeGroupRole()) > 0 {
|
||||
excludeResource = e.configuration.GetExcludeGroupRole()
|
||||
|
@ -80,7 +77,7 @@ func (e *engine) mutate(
|
|||
return
|
||||
}
|
||||
|
||||
logger.V(3).Info("processing mutate rule", "applyRules", applyRules)
|
||||
logger.V(3).Info("processing mutate rule")
|
||||
resource, err := policyContext.JSONContext().Query("request.object")
|
||||
policyContext.JSONContext().Reset()
|
||||
if err == nil && resource != nil {
|
||||
|
@ -130,12 +127,12 @@ func (e *engine) mutate(
|
|||
if !policyContext.AdmissionOperation() && rule.IsMutateExisting() {
|
||||
policyContext := policyContext.Copy()
|
||||
if err := policyContext.JSONContext().AddTargetResource(patchedResource.unstructured.Object); err != nil {
|
||||
logging.Error(err, "failed to add target resource to the context")
|
||||
logger.Error(err, "failed to add target resource to the context")
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
logger.V(4).Info("apply rule to resource", "rule", rule.Name, "resource namespace", patchedResource.unstructured.GetNamespace(), "resource name", patchedResource.unstructured.GetName())
|
||||
logger.V(4).Info("apply rule to resource", "resource namespace", patchedResource.unstructured.GetNamespace(), "resource name", patchedResource.unstructured.GetName())
|
||||
var mutateResp *mutate.Response
|
||||
if rule.Mutation.ForEachMutation != nil {
|
||||
m := &forEachMutator{
|
||||
|
|
|
@ -5,19 +5,16 @@ import (
|
|||
|
||||
"github.com/go-logr/logr"
|
||||
"github.com/kyverno/kyverno/pkg/engine/operator"
|
||||
"github.com/kyverno/kyverno/pkg/logging"
|
||||
"gotest.tools/assert"
|
||||
)
|
||||
|
||||
var logger = logging.GlobalLogger()
|
||||
|
||||
func TestValidateString_AsteriskTest(t *testing.T) {
|
||||
pattern := "*"
|
||||
value := "anything"
|
||||
empty := ""
|
||||
|
||||
assert.Assert(t, compareString(logger, value, pattern, operator.Equal))
|
||||
assert.Assert(t, compareString(logger, empty, pattern, operator.Equal))
|
||||
assert.Assert(t, compareString(logr.Discard(), value, pattern, operator.Equal))
|
||||
assert.Assert(t, compareString(logr.Discard(), empty, pattern, operator.Equal))
|
||||
}
|
||||
|
||||
func TestValidateString_LeftAsteriskTest(t *testing.T) {
|
||||
|
@ -25,203 +22,203 @@ func TestValidateString_LeftAsteriskTest(t *testing.T) {
|
|||
value := "leftright"
|
||||
right := "right"
|
||||
|
||||
assert.Assert(t, compareString(logger, value, pattern, operator.Equal))
|
||||
assert.Assert(t, compareString(logger, right, pattern, operator.Equal))
|
||||
assert.Assert(t, compareString(logr.Discard(), value, pattern, operator.Equal))
|
||||
assert.Assert(t, compareString(logr.Discard(), right, pattern, operator.Equal))
|
||||
|
||||
value = "leftmiddle"
|
||||
middle := "middle"
|
||||
|
||||
assert.Assert(t, !compareString(logger, value, pattern, operator.Equal))
|
||||
assert.Assert(t, !compareString(logger, middle, pattern, operator.Equal))
|
||||
assert.Assert(t, !compareString(logr.Discard(), value, pattern, operator.Equal))
|
||||
assert.Assert(t, !compareString(logr.Discard(), middle, pattern, operator.Equal))
|
||||
}
|
||||
|
||||
func TestValidateString_MiddleAsteriskTest(t *testing.T) {
|
||||
pattern := "ab*ba"
|
||||
value := "abbeba"
|
||||
assert.Assert(t, compareString(logger, value, pattern, operator.Equal))
|
||||
assert.Assert(t, compareString(logr.Discard(), value, pattern, operator.Equal))
|
||||
|
||||
value = "abbca"
|
||||
assert.Assert(t, !compareString(logger, value, pattern, operator.Equal))
|
||||
assert.Assert(t, !compareString(logr.Discard(), value, pattern, operator.Equal))
|
||||
}
|
||||
|
||||
func TestValidateString_QuestionMark(t *testing.T) {
|
||||
pattern := "ab?ba"
|
||||
value := "abbba"
|
||||
assert.Assert(t, compareString(logger, value, pattern, operator.Equal))
|
||||
assert.Assert(t, compareString(logr.Discard(), value, pattern, operator.Equal))
|
||||
|
||||
value = "abbbba"
|
||||
assert.Assert(t, !compareString(logger, value, pattern, operator.Equal))
|
||||
assert.Assert(t, !compareString(logr.Discard(), value, pattern, operator.Equal))
|
||||
}
|
||||
|
||||
func TestValidateValueWithNilPattern_NullPatternStringValue(t *testing.T) {
|
||||
assert.Assert(t, !validateNilPattern(logger, "value"))
|
||||
assert.Assert(t, !validateNilPattern(logr.Discard(), "value"))
|
||||
}
|
||||
|
||||
func TestValidateValueWithNilPattern_NullPatternDefaultString(t *testing.T) {
|
||||
assert.Assert(t, validateNilPattern(logger, ""))
|
||||
assert.Assert(t, validateNilPattern(logr.Discard(), ""))
|
||||
}
|
||||
|
||||
func TestValidateValueWithNilPattern_NullPatternDefaultFloat(t *testing.T) {
|
||||
assert.Assert(t, validateNilPattern(logger, 0.0))
|
||||
assert.Assert(t, validateNilPattern(logr.Discard(), 0.0))
|
||||
}
|
||||
|
||||
func TestValidateValueWithNilPattern_NullPatternFloat(t *testing.T) {
|
||||
assert.Assert(t, !validateNilPattern(logger, 0.1))
|
||||
assert.Assert(t, !validateNilPattern(logr.Discard(), 0.1))
|
||||
}
|
||||
|
||||
func TestValidateValueWithNilPattern_NullPatternDefaultInt(t *testing.T) {
|
||||
assert.Assert(t, validateNilPattern(logger, 0))
|
||||
assert.Assert(t, validateNilPattern(logr.Discard(), 0))
|
||||
}
|
||||
|
||||
func TestValidateValueWithNilPattern_NullPatternInt(t *testing.T) {
|
||||
assert.Assert(t, !validateNilPattern(logger, 1))
|
||||
assert.Assert(t, !validateNilPattern(logr.Discard(), 1))
|
||||
}
|
||||
|
||||
func TestValidateValueWithNilPattern_NullPatternDefaultBool(t *testing.T) {
|
||||
assert.Assert(t, validateNilPattern(logger, false))
|
||||
assert.Assert(t, validateNilPattern(logr.Discard(), false))
|
||||
}
|
||||
|
||||
func TestValidateValueWithNilPattern_NullPatternTrueBool(t *testing.T) {
|
||||
assert.Assert(t, !validateNilPattern(logger, true))
|
||||
assert.Assert(t, !validateNilPattern(logr.Discard(), true))
|
||||
}
|
||||
|
||||
func TestValidateValueWithFloatPattern_FloatValue(t *testing.T) {
|
||||
assert.Assert(t, validateFloatPattern(logger, 7.9914, 7.9914))
|
||||
assert.Assert(t, validateFloatPattern(logr.Discard(), 7.9914, 7.9914))
|
||||
}
|
||||
|
||||
func TestValidateValueWithFloatPattern_FloatValueNotPass(t *testing.T) {
|
||||
assert.Assert(t, !validateFloatPattern(logger, 7.9914, 7.99141))
|
||||
assert.Assert(t, !validateFloatPattern(logr.Discard(), 7.9914, 7.99141))
|
||||
}
|
||||
|
||||
func TestValidateValueWithFloatPattern_FloatPatternWithoutFractionIntValue(t *testing.T) {
|
||||
assert.Assert(t, validateFloatPattern(logger, 7, 7.000000))
|
||||
assert.Assert(t, validateFloatPattern(logr.Discard(), 7, 7.000000))
|
||||
}
|
||||
|
||||
func TestValidateValueWithFloatPattern_FloatPatternWithoutFraction(t *testing.T) {
|
||||
assert.Assert(t, validateFloatPattern(logger, 7.000000, 7.000000))
|
||||
assert.Assert(t, validateFloatPattern(logr.Discard(), 7.000000, 7.000000))
|
||||
}
|
||||
|
||||
func TestValidateValueWithIntPattern_FloatValueWithoutFraction(t *testing.T) {
|
||||
assert.Assert(t, validateFloatPattern(logger, 7.000000, 7))
|
||||
assert.Assert(t, validateFloatPattern(logr.Discard(), 7.000000, 7))
|
||||
}
|
||||
|
||||
func TestValidateValueWithIntPattern_FloatValueWitFraction(t *testing.T) {
|
||||
assert.Assert(t, !validateFloatPattern(logger, 7.000001, 7))
|
||||
assert.Assert(t, !validateFloatPattern(logr.Discard(), 7.000001, 7))
|
||||
}
|
||||
|
||||
func TestValidateValueWithIntPattern_NotPass(t *testing.T) {
|
||||
assert.Assert(t, !validateFloatPattern(logger, 8, 7))
|
||||
assert.Assert(t, !validateFloatPattern(logr.Discard(), 8, 7))
|
||||
}
|
||||
|
||||
func TestValidateValueWithStringPattern_WithSpace(t *testing.T) {
|
||||
assert.Assert(t, validateStringPattern(logger, 4, ">= 3"))
|
||||
assert.Assert(t, validateStringPattern(logr.Discard(), 4, ">= 3"))
|
||||
}
|
||||
|
||||
func TestValidateValueWithStringPattern_Ranges(t *testing.T) {
|
||||
assert.Assert(t, validateStringPattern(logger, 0, "0-2"))
|
||||
assert.Assert(t, validateStringPattern(logger, 1, "0-2"))
|
||||
assert.Assert(t, validateStringPattern(logger, 2, "0-2"))
|
||||
assert.Assert(t, !validateStringPattern(logger, 3, "0-2"))
|
||||
assert.Assert(t, validateStringPattern(logr.Discard(), 0, "0-2"))
|
||||
assert.Assert(t, validateStringPattern(logr.Discard(), 1, "0-2"))
|
||||
assert.Assert(t, validateStringPattern(logr.Discard(), 2, "0-2"))
|
||||
assert.Assert(t, !validateStringPattern(logr.Discard(), 3, "0-2"))
|
||||
|
||||
assert.Assert(t, validateStringPattern(logger, 0, "10!-20"))
|
||||
assert.Assert(t, !validateStringPattern(logger, 15, "10!-20"))
|
||||
assert.Assert(t, validateStringPattern(logger, 25, "10!-20"))
|
||||
assert.Assert(t, validateStringPattern(logr.Discard(), 0, "10!-20"))
|
||||
assert.Assert(t, !validateStringPattern(logr.Discard(), 15, "10!-20"))
|
||||
assert.Assert(t, validateStringPattern(logr.Discard(), 25, "10!-20"))
|
||||
|
||||
assert.Assert(t, !validateStringPattern(logger, 0, "0.00001-2.00001"))
|
||||
assert.Assert(t, validateStringPattern(logger, 1, "0.00001-2.00001"))
|
||||
assert.Assert(t, validateStringPattern(logger, 2, "0.00001-2.00001"))
|
||||
assert.Assert(t, !validateStringPattern(logger, 2.0001, "0.00001-2.00001"))
|
||||
assert.Assert(t, !validateStringPattern(logr.Discard(), 0, "0.00001-2.00001"))
|
||||
assert.Assert(t, validateStringPattern(logr.Discard(), 1, "0.00001-2.00001"))
|
||||
assert.Assert(t, validateStringPattern(logr.Discard(), 2, "0.00001-2.00001"))
|
||||
assert.Assert(t, !validateStringPattern(logr.Discard(), 2.0001, "0.00001-2.00001"))
|
||||
|
||||
assert.Assert(t, validateStringPattern(logger, 0, "0.00001!-2.00001"))
|
||||
assert.Assert(t, !validateStringPattern(logger, 1, "0.00001!-2.00001"))
|
||||
assert.Assert(t, !validateStringPattern(logger, 2, "0.00001!-2.00001"))
|
||||
assert.Assert(t, validateStringPattern(logger, 2.0001, "0.00001!-2.00001"))
|
||||
assert.Assert(t, validateStringPattern(logr.Discard(), 0, "0.00001!-2.00001"))
|
||||
assert.Assert(t, !validateStringPattern(logr.Discard(), 1, "0.00001!-2.00001"))
|
||||
assert.Assert(t, !validateStringPattern(logr.Discard(), 2, "0.00001!-2.00001"))
|
||||
assert.Assert(t, validateStringPattern(logr.Discard(), 2.0001, "0.00001!-2.00001"))
|
||||
|
||||
assert.Assert(t, validateStringPattern(logger, 2, "2-2"))
|
||||
assert.Assert(t, !validateStringPattern(logger, 2, "2!-2"))
|
||||
assert.Assert(t, validateStringPattern(logr.Discard(), 2, "2-2"))
|
||||
assert.Assert(t, !validateStringPattern(logr.Discard(), 2, "2!-2"))
|
||||
|
||||
assert.Assert(t, validateStringPattern(logger, 2.99999, "2.99998-3"))
|
||||
assert.Assert(t, validateStringPattern(logger, 2.99997, "2.99998!-3"))
|
||||
assert.Assert(t, validateStringPattern(logger, 3.00001, "2.99998!-3"))
|
||||
assert.Assert(t, validateStringPattern(logr.Discard(), 2.99999, "2.99998-3"))
|
||||
assert.Assert(t, validateStringPattern(logr.Discard(), 2.99997, "2.99998!-3"))
|
||||
assert.Assert(t, validateStringPattern(logr.Discard(), 3.00001, "2.99998!-3"))
|
||||
|
||||
assert.Assert(t, validateStringPattern(logger, "256Mi", "128Mi-512Mi"))
|
||||
assert.Assert(t, !validateStringPattern(logger, "1024Mi", "128Mi-512Mi"))
|
||||
assert.Assert(t, !validateStringPattern(logger, "64Mi", "128Mi-512Mi"))
|
||||
assert.Assert(t, validateStringPattern(logr.Discard(), "256Mi", "128Mi-512Mi"))
|
||||
assert.Assert(t, !validateStringPattern(logr.Discard(), "1024Mi", "128Mi-512Mi"))
|
||||
assert.Assert(t, !validateStringPattern(logr.Discard(), "64Mi", "128Mi-512Mi"))
|
||||
|
||||
assert.Assert(t, !validateStringPattern(logger, "256Mi", "128Mi!-512Mi"))
|
||||
assert.Assert(t, validateStringPattern(logger, "1024Mi", "128Mi!-512Mi"))
|
||||
assert.Assert(t, validateStringPattern(logger, "64Mi", "128Mi!-512Mi"))
|
||||
assert.Assert(t, !validateStringPattern(logr.Discard(), "256Mi", "128Mi!-512Mi"))
|
||||
assert.Assert(t, validateStringPattern(logr.Discard(), "1024Mi", "128Mi!-512Mi"))
|
||||
assert.Assert(t, validateStringPattern(logr.Discard(), "64Mi", "128Mi!-512Mi"))
|
||||
|
||||
assert.Assert(t, validateStringPattern(logger, -9, "-10-8"))
|
||||
assert.Assert(t, !validateStringPattern(logger, 9, "-10--8"))
|
||||
assert.Assert(t, validateStringPattern(logr.Discard(), -9, "-10-8"))
|
||||
assert.Assert(t, !validateStringPattern(logr.Discard(), 9, "-10--8"))
|
||||
|
||||
assert.Assert(t, validateStringPattern(logger, 9, "-10!--8"))
|
||||
assert.Assert(t, validateStringPattern(logger, "9Mi", "-10Mi!--8Mi"))
|
||||
assert.Assert(t, validateStringPattern(logr.Discard(), 9, "-10!--8"))
|
||||
assert.Assert(t, validateStringPattern(logr.Discard(), "9Mi", "-10Mi!--8Mi"))
|
||||
|
||||
assert.Assert(t, !validateStringPattern(logger, -9, "-10!--8"))
|
||||
assert.Assert(t, !validateStringPattern(logr.Discard(), -9, "-10!--8"))
|
||||
|
||||
assert.Assert(t, validateStringPattern(logger, "-9Mi", "-10Mi-8Mi"))
|
||||
assert.Assert(t, validateStringPattern(logger, "9Mi", "-10Mi!-8Mi"))
|
||||
assert.Assert(t, validateStringPattern(logr.Discard(), "-9Mi", "-10Mi-8Mi"))
|
||||
assert.Assert(t, validateStringPattern(logr.Discard(), "9Mi", "-10Mi!-8Mi"))
|
||||
|
||||
assert.Assert(t, validateStringPattern(logger, 0, "-10-+8"))
|
||||
assert.Assert(t, validateStringPattern(logger, "7Mi", "-10Mi-+8Mi"))
|
||||
assert.Assert(t, validateStringPattern(logr.Discard(), 0, "-10-+8"))
|
||||
assert.Assert(t, validateStringPattern(logr.Discard(), "7Mi", "-10Mi-+8Mi"))
|
||||
|
||||
assert.Assert(t, validateStringPattern(logger, 10, "-10!-+8"))
|
||||
assert.Assert(t, validateStringPattern(logger, "10Mi", "-10Mi!-+8Mi"))
|
||||
assert.Assert(t, validateStringPattern(logr.Discard(), 10, "-10!-+8"))
|
||||
assert.Assert(t, validateStringPattern(logr.Discard(), "10Mi", "-10Mi!-+8Mi"))
|
||||
|
||||
assert.Assert(t, validateStringPattern(logger, 0, "+0-+1"))
|
||||
assert.Assert(t, validateStringPattern(logger, "10Mi", "+0Mi-+1024Mi"))
|
||||
assert.Assert(t, validateStringPattern(logr.Discard(), 0, "+0-+1"))
|
||||
assert.Assert(t, validateStringPattern(logr.Discard(), "10Mi", "+0Mi-+1024Mi"))
|
||||
|
||||
assert.Assert(t, validateStringPattern(logger, 10, "+0!-+1"))
|
||||
assert.Assert(t, validateStringPattern(logger, "1025Mi", "+0Mi!-+1024Mi"))
|
||||
assert.Assert(t, validateStringPattern(logr.Discard(), 10, "+0!-+1"))
|
||||
assert.Assert(t, validateStringPattern(logr.Discard(), "1025Mi", "+0Mi!-+1024Mi"))
|
||||
|
||||
}
|
||||
|
||||
func TestValidateNumberWithStr_LessFloatAndInt(t *testing.T) {
|
||||
assert.Assert(t, validateString(logger, 7.00001, "7.000001", operator.More))
|
||||
assert.Assert(t, validateString(logger, 7.00001, "7", operator.NotEqual))
|
||||
assert.Assert(t, validateString(logr.Discard(), 7.00001, "7.000001", operator.More))
|
||||
assert.Assert(t, validateString(logr.Discard(), 7.00001, "7", operator.NotEqual))
|
||||
|
||||
assert.Assert(t, validateString(logger, 7.0000, "7", operator.Equal))
|
||||
assert.Assert(t, !validateString(logger, 6.000000001, "6", operator.Less))
|
||||
assert.Assert(t, validateString(logr.Discard(), 7.0000, "7", operator.Equal))
|
||||
assert.Assert(t, !validateString(logr.Discard(), 6.000000001, "6", operator.Less))
|
||||
}
|
||||
|
||||
func TestValidateQuantity_InvalidQuantity(t *testing.T) {
|
||||
assert.Assert(t, !validateString(logger, "1024Gi", "", operator.Equal))
|
||||
assert.Assert(t, !validateString(logger, "gii", "1024Gi", operator.Equal))
|
||||
assert.Assert(t, !validateString(logr.Discard(), "1024Gi", "", operator.Equal))
|
||||
assert.Assert(t, !validateString(logr.Discard(), "gii", "1024Gi", operator.Equal))
|
||||
}
|
||||
|
||||
func TestValidateDuration(t *testing.T) {
|
||||
assert.Assert(t, validateString(logger, "12s", "12s", operator.Equal))
|
||||
assert.Assert(t, validateString(logger, "12s", "15s", operator.NotEqual))
|
||||
assert.Assert(t, validateString(logger, "12s", "15s", operator.Less))
|
||||
assert.Assert(t, validateString(logger, "12s", "15s", operator.LessEqual))
|
||||
assert.Assert(t, validateString(logger, "12s", "12s", operator.LessEqual))
|
||||
assert.Assert(t, !validateString(logger, "15s", "12s", operator.Less))
|
||||
assert.Assert(t, !validateString(logger, "15s", "12s", operator.LessEqual))
|
||||
assert.Assert(t, validateString(logger, "15s", "12s", operator.More))
|
||||
assert.Assert(t, validateString(logger, "15s", "12s", operator.MoreEqual))
|
||||
assert.Assert(t, validateString(logger, "12s", "12s", operator.MoreEqual))
|
||||
assert.Assert(t, !validateString(logger, "12s", "15s", operator.More))
|
||||
assert.Assert(t, !validateString(logger, "12s", "15s", operator.MoreEqual))
|
||||
assert.Assert(t, validateString(logr.Discard(), "12s", "12s", operator.Equal))
|
||||
assert.Assert(t, validateString(logr.Discard(), "12s", "15s", operator.NotEqual))
|
||||
assert.Assert(t, validateString(logr.Discard(), "12s", "15s", operator.Less))
|
||||
assert.Assert(t, validateString(logr.Discard(), "12s", "15s", operator.LessEqual))
|
||||
assert.Assert(t, validateString(logr.Discard(), "12s", "12s", operator.LessEqual))
|
||||
assert.Assert(t, !validateString(logr.Discard(), "15s", "12s", operator.Less))
|
||||
assert.Assert(t, !validateString(logr.Discard(), "15s", "12s", operator.LessEqual))
|
||||
assert.Assert(t, validateString(logr.Discard(), "15s", "12s", operator.More))
|
||||
assert.Assert(t, validateString(logr.Discard(), "15s", "12s", operator.MoreEqual))
|
||||
assert.Assert(t, validateString(logr.Discard(), "12s", "12s", operator.MoreEqual))
|
||||
assert.Assert(t, !validateString(logr.Discard(), "12s", "15s", operator.More))
|
||||
assert.Assert(t, !validateString(logr.Discard(), "12s", "15s", operator.MoreEqual))
|
||||
}
|
||||
|
||||
func TestValidateQuantity_Equal(t *testing.T) {
|
||||
assert.Assert(t, validateString(logger, "1024Gi", "1024Gi", operator.Equal))
|
||||
assert.Assert(t, validateString(logger, "1024Mi", "1Gi", operator.Equal))
|
||||
assert.Assert(t, validateString(logger, "0.2", "200m", operator.Equal))
|
||||
assert.Assert(t, validateString(logger, "500", "500", operator.Equal))
|
||||
assert.Assert(t, !validateString(logger, "2048", "1024", operator.Equal))
|
||||
assert.Assert(t, validateString(logger, 1024, "1024", operator.Equal))
|
||||
assert.Assert(t, validateString(logr.Discard(), "1024Gi", "1024Gi", operator.Equal))
|
||||
assert.Assert(t, validateString(logr.Discard(), "1024Mi", "1Gi", operator.Equal))
|
||||
assert.Assert(t, validateString(logr.Discard(), "0.2", "200m", operator.Equal))
|
||||
assert.Assert(t, validateString(logr.Discard(), "500", "500", operator.Equal))
|
||||
assert.Assert(t, !validateString(logr.Discard(), "2048", "1024", operator.Equal))
|
||||
assert.Assert(t, validateString(logr.Discard(), 1024, "1024", operator.Equal))
|
||||
}
|
||||
|
||||
func TestValidateQuantity_Operation(t *testing.T) {
|
||||
assert.Assert(t, validateString(logger, "1Gi", "1000Mi", operator.More))
|
||||
assert.Assert(t, validateString(logger, "1G", "1Gi", operator.Less))
|
||||
assert.Assert(t, validateString(logger, "500m", "0.5", operator.MoreEqual))
|
||||
assert.Assert(t, validateString(logger, "1", "500m", operator.MoreEqual))
|
||||
assert.Assert(t, validateString(logger, "0.5", ".5", operator.LessEqual))
|
||||
assert.Assert(t, validateString(logger, "0.2", ".5", operator.LessEqual))
|
||||
assert.Assert(t, validateString(logger, "0.2", ".5", operator.NotEqual))
|
||||
assert.Assert(t, validateString(logr.Discard(), "1Gi", "1000Mi", operator.More))
|
||||
assert.Assert(t, validateString(logr.Discard(), "1G", "1Gi", operator.Less))
|
||||
assert.Assert(t, validateString(logr.Discard(), "500m", "0.5", operator.MoreEqual))
|
||||
assert.Assert(t, validateString(logr.Discard(), "1", "500m", operator.MoreEqual))
|
||||
assert.Assert(t, validateString(logr.Discard(), "0.5", ".5", operator.LessEqual))
|
||||
assert.Assert(t, validateString(logr.Discard(), "0.2", ".5", operator.LessEqual))
|
||||
assert.Assert(t, validateString(logr.Discard(), "0.2", ".5", operator.NotEqual))
|
||||
}
|
||||
|
||||
func TestGetOperatorFromStringPattern_OneChar(t *testing.T) {
|
||||
|
@ -233,11 +230,11 @@ func TestGetOperatorFromStringPattern_EmptyString(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestValidateKernelVersion_NotEquals(t *testing.T) {
|
||||
assert.Assert(t, validateStringPattern(logger, "5.16.5-arch1-1", "!5.10.84-1"))
|
||||
assert.Assert(t, !validateStringPattern(logger, "5.10.84-1", "!5.10.84-1"))
|
||||
assert.Assert(t, validateStringPatterns(logger, "5.16.5-arch1-1", "!5.10.84-1 & !5.15.2-1"))
|
||||
assert.Assert(t, !validateStringPatterns(logger, "5.10.84-1", "!5.10.84-1 & !5.15.2-1"))
|
||||
assert.Assert(t, !validateStringPatterns(logger, "5.15.2-1", "!5.10.84-1 & !5.15.2-1"))
|
||||
assert.Assert(t, validateStringPattern(logr.Discard(), "5.16.5-arch1-1", "!5.10.84-1"))
|
||||
assert.Assert(t, !validateStringPattern(logr.Discard(), "5.10.84-1", "!5.10.84-1"))
|
||||
assert.Assert(t, validateStringPatterns(logr.Discard(), "5.16.5-arch1-1", "!5.10.84-1 & !5.15.2-1"))
|
||||
assert.Assert(t, !validateStringPatterns(logr.Discard(), "5.10.84-1", "!5.10.84-1 & !5.15.2-1"))
|
||||
assert.Assert(t, !validateStringPatterns(logr.Discard(), "5.15.2-1", "!5.10.84-1 & !5.15.2-1"))
|
||||
}
|
||||
|
||||
func TestValidate(t *testing.T) {
|
||||
|
|
|
@ -5,10 +5,10 @@ import (
|
|||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
"github.com/kyverno/kyverno/pkg/engine/anchor"
|
||||
engineapi "github.com/kyverno/kyverno/pkg/engine/api"
|
||||
"github.com/kyverno/kyverno/pkg/engine/variables"
|
||||
"github.com/kyverno/kyverno/pkg/logging"
|
||||
"gotest.tools/assert"
|
||||
)
|
||||
|
||||
|
@ -105,7 +105,7 @@ func TestValidateMap(t *testing.T) {
|
|||
assert.Assert(t, json.Unmarshal(rawPattern, &pattern))
|
||||
assert.Assert(t, json.Unmarshal(rawMap, &resource))
|
||||
|
||||
path, err := validateMap(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
path, err := validateMap(logr.Discard(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
assert.Equal(t, path, "")
|
||||
assert.NilError(t, err)
|
||||
}
|
||||
|
@ -201,7 +201,7 @@ func TestValidateMap_AsteriskForInt(t *testing.T) {
|
|||
assert.Assert(t, json.Unmarshal(rawPattern, &pattern))
|
||||
assert.Assert(t, json.Unmarshal(rawMap, &resource))
|
||||
|
||||
path, err := validateMap(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
path, err := validateMap(logr.Discard(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
t.Log(path)
|
||||
assert.NilError(t, err)
|
||||
}
|
||||
|
@ -294,7 +294,7 @@ func TestValidateMap_AsteriskForMap(t *testing.T) {
|
|||
assert.Assert(t, json.Unmarshal(rawPattern, &pattern))
|
||||
assert.Assert(t, json.Unmarshal(rawMap, &resource))
|
||||
|
||||
path, err := validateMap(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
path, err := validateMap(logr.Discard(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
assert.Equal(t, path, "")
|
||||
assert.NilError(t, err)
|
||||
}
|
||||
|
@ -382,7 +382,7 @@ func TestValidateMap_AsteriskForArray(t *testing.T) {
|
|||
assert.Assert(t, json.Unmarshal(rawPattern, &pattern))
|
||||
assert.Assert(t, json.Unmarshal(rawMap, &resource))
|
||||
|
||||
path, err := validateMap(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
path, err := validateMap(logr.Discard(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
assert.Equal(t, path, "")
|
||||
assert.NilError(t, err)
|
||||
}
|
||||
|
@ -473,7 +473,7 @@ func TestValidateMap_AsteriskFieldIsMissing(t *testing.T) {
|
|||
assert.Assert(t, json.Unmarshal(rawPattern, &pattern))
|
||||
assert.Assert(t, json.Unmarshal(rawMap, &resource))
|
||||
|
||||
path, err := validateMap(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
path, err := validateMap(logr.Discard(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
assert.Equal(t, path, "/spec/template/spec/containers/0/")
|
||||
assert.Assert(t, err != nil)
|
||||
}
|
||||
|
@ -565,7 +565,7 @@ func TestValidateMap_livenessProbeIsNull(t *testing.T) {
|
|||
err := json.Unmarshal(rawMap, &resource)
|
||||
assert.NilError(t, err)
|
||||
|
||||
path, err := validateMap(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
path, err := validateMap(logr.Discard(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
assert.Equal(t, path, "")
|
||||
assert.NilError(t, err)
|
||||
}
|
||||
|
@ -655,7 +655,7 @@ func TestValidateMap_livenessProbeIsMissing(t *testing.T) {
|
|||
assert.Assert(t, json.Unmarshal(rawPattern, &pattern))
|
||||
assert.Assert(t, json.Unmarshal(rawMap, &resource))
|
||||
|
||||
path, err := validateMap(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
path, err := validateMap(logr.Discard(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
assert.Equal(t, path, "")
|
||||
assert.NilError(t, err)
|
||||
}
|
||||
|
@ -701,7 +701,7 @@ func TestValidateMapElement_TwoElementsInArrayOnePass(t *testing.T) {
|
|||
assert.Assert(t, json.Unmarshal(rawPattern, &pattern))
|
||||
assert.Assert(t, json.Unmarshal(rawMap, &resource))
|
||||
|
||||
path, err := validateResourceElement(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
path, err := validateResourceElement(logr.Discard(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
assert.Equal(t, path, "")
|
||||
// assert.Equal(t, path, "/1/object/0/key2/")
|
||||
// assert.NilError(t, err)
|
||||
|
@ -736,7 +736,7 @@ func TestValidateMapElement_OneElementInArrayPass(t *testing.T) {
|
|||
assert.Assert(t, json.Unmarshal(rawPattern, &pattern))
|
||||
assert.Assert(t, json.Unmarshal(rawMap, &resource))
|
||||
|
||||
path, err := validateResourceElement(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
path, err := validateResourceElement(logr.Discard(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
assert.Equal(t, path, "")
|
||||
assert.NilError(t, err)
|
||||
}
|
||||
|
@ -790,10 +790,10 @@ func TestValidateMap_CorrectRelativePathInConfig(t *testing.T) {
|
|||
assert.Assert(t, json.Unmarshal(rawPattern, &pattern))
|
||||
assert.Assert(t, json.Unmarshal(rawMap, &resource))
|
||||
|
||||
pattern, err := variables.SubstituteAll(logging.GlobalLogger(), nil, pattern)
|
||||
pattern, err := variables.SubstituteAll(logr.Discard(), nil, pattern)
|
||||
assert.NilError(t, err)
|
||||
|
||||
path, err := validateResourceElement(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
path, err := validateResourceElement(logr.Discard(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
assert.Equal(t, path, "")
|
||||
assert.NilError(t, err)
|
||||
}
|
||||
|
@ -847,7 +847,7 @@ func TestValidateMap_RelativePathDoesNotExists(t *testing.T) {
|
|||
assert.Assert(t, json.Unmarshal(rawPattern, &pattern))
|
||||
assert.Assert(t, json.Unmarshal(rawMap, &resource))
|
||||
|
||||
path, err := validateResourceElement(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
path, err := validateResourceElement(logr.Discard(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
assert.Equal(t, path, "/spec/containers/0/resources/requests/memory/")
|
||||
assert.Assert(t, err != nil)
|
||||
}
|
||||
|
@ -901,7 +901,7 @@ func TestValidateMap_OnlyAnchorsInPath(t *testing.T) {
|
|||
assert.Assert(t, json.Unmarshal(rawPattern, &pattern))
|
||||
assert.Assert(t, json.Unmarshal(rawMap, &resource))
|
||||
|
||||
path, err := validateResourceElement(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
path, err := validateResourceElement(logr.Discard(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
assert.Equal(t, path, "/spec/containers/0/resources/requests/memory/")
|
||||
assert.Assert(t, err != nil)
|
||||
}
|
||||
|
@ -955,7 +955,7 @@ func TestValidateMap_MalformedReferenceOnlyDolarMark(t *testing.T) {
|
|||
assert.Assert(t, json.Unmarshal(rawPattern, &pattern))
|
||||
assert.Assert(t, json.Unmarshal(rawMap, &resource))
|
||||
|
||||
path, err := validateResourceElement(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
path, err := validateResourceElement(logr.Discard(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
assert.Equal(t, path, "/spec/containers/0/resources/requests/memory/")
|
||||
assert.Assert(t, err != nil)
|
||||
}
|
||||
|
@ -1009,10 +1009,10 @@ func TestValidateMap_RelativePathWithParentheses(t *testing.T) {
|
|||
assert.Assert(t, json.Unmarshal(rawPattern, &pattern))
|
||||
assert.Assert(t, json.Unmarshal(rawMap, &resource))
|
||||
|
||||
pattern, err := variables.SubstituteAll(logging.GlobalLogger(), nil, pattern)
|
||||
pattern, err := variables.SubstituteAll(logr.Discard(), nil, pattern)
|
||||
assert.NilError(t, err)
|
||||
|
||||
path, err := validateResourceElement(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
path, err := validateResourceElement(logr.Discard(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
assert.Equal(t, path, "")
|
||||
assert.NilError(t, err)
|
||||
}
|
||||
|
@ -1066,7 +1066,7 @@ func TestValidateMap_MalformedPath(t *testing.T) {
|
|||
assert.Assert(t, json.Unmarshal(rawPattern, &pattern))
|
||||
assert.Assert(t, json.Unmarshal(rawMap, &resource))
|
||||
|
||||
path, err := validateResourceElement(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
path, err := validateResourceElement(logr.Discard(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
assert.Equal(t, path, "/spec/containers/0/resources/requests/memory/")
|
||||
assert.Assert(t, err != nil)
|
||||
}
|
||||
|
@ -1120,10 +1120,10 @@ func TestValidateMap_AbosolutePathExists(t *testing.T) {
|
|||
assert.Assert(t, json.Unmarshal(rawPattern, &pattern))
|
||||
assert.Assert(t, json.Unmarshal(rawMap, &resource))
|
||||
|
||||
pattern, err := variables.SubstituteAll(logging.GlobalLogger(), nil, pattern)
|
||||
pattern, err := variables.SubstituteAll(logr.Discard(), nil, pattern)
|
||||
assert.NilError(t, err)
|
||||
|
||||
path, err := validateResourceElement(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
path, err := validateResourceElement(logr.Discard(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
assert.Equal(t, path, "")
|
||||
assert.Assert(t, err == nil)
|
||||
}
|
||||
|
@ -1155,7 +1155,7 @@ func TestValidateMap_AbsolutePathToMetadata(t *testing.T) {
|
|||
assert.Assert(t, json.Unmarshal(rawPattern, &pattern))
|
||||
assert.Assert(t, json.Unmarshal(rawMap, &resource))
|
||||
|
||||
path, err := validateResourceElement(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
path, err := validateResourceElement(logr.Discard(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
assert.Equal(t, path, "")
|
||||
assert.Assert(t, err == nil)
|
||||
}
|
||||
|
@ -1197,10 +1197,10 @@ func TestValidateMap_AbsolutePathToMetadata_fail(t *testing.T) {
|
|||
assert.Assert(t, json.Unmarshal(rawPattern, &pattern))
|
||||
assert.Assert(t, json.Unmarshal(rawMap, &resource))
|
||||
|
||||
pattern, err := variables.SubstituteAll(logging.GlobalLogger(), nil, pattern)
|
||||
pattern, err := variables.SubstituteAll(logr.Discard(), nil, pattern)
|
||||
assert.NilError(t, err)
|
||||
|
||||
path, err := validateResourceElement(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
path, err := validateResourceElement(logr.Discard(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
assert.Equal(t, path, "/spec/containers/0/image/")
|
||||
assert.Assert(t, err != nil)
|
||||
}
|
||||
|
@ -1254,7 +1254,7 @@ func TestValidateMap_AbosolutePathDoesNotExists(t *testing.T) {
|
|||
assert.Assert(t, json.Unmarshal(rawPattern, &pattern))
|
||||
assert.Assert(t, json.Unmarshal(rawMap, &resource))
|
||||
|
||||
path, err := validateResourceElement(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
path, err := validateResourceElement(logr.Discard(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
assert.Equal(t, path, "/spec/containers/0/resources/requests/memory/")
|
||||
assert.Assert(t, err != nil)
|
||||
}
|
||||
|
@ -1289,7 +1289,7 @@ func TestValidateMapElement_OneElementInArrayNotPass(t *testing.T) {
|
|||
err = json.Unmarshal(rawMap, &resource)
|
||||
assert.NilError(t, err)
|
||||
|
||||
path, err := validateResourceElement(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
path, err := validateResourceElement(logr.Discard(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
assert.Equal(t, path, "/0/object/0/key2/")
|
||||
assert.Assert(t, err != nil)
|
||||
}
|
||||
|
@ -1347,7 +1347,7 @@ func testValidationPattern(t *testing.T, num string, patternBytes []byte, resour
|
|||
err = json.Unmarshal(resourceBytes, &resource)
|
||||
assert.NilError(t, err)
|
||||
|
||||
p, err := validateResourceElement(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
p, err := validateResourceElement(logr.Discard(), resource, pattern, pattern, "/", anchor.NewAnchorMap())
|
||||
assert.Equal(t, p, path, num)
|
||||
if nilErr {
|
||||
assert.NilError(t, err, num)
|
||||
|
@ -1673,7 +1673,7 @@ func testMatchPattern(t *testing.T, testCase struct {
|
|||
err = json.Unmarshal(testCase.resource, &resource)
|
||||
assert.NilError(t, err)
|
||||
|
||||
err = MatchPattern(logging.GlobalLogger(), resource, pattern)
|
||||
err = MatchPattern(logr.Discard(), resource, pattern)
|
||||
|
||||
if testCase.status == engineapi.RuleStatusPass {
|
||||
assert.NilError(t, err, fmt.Sprintf("\nexpected pass - test: %s\npattern: %s\nresource: %s\n", testCase.name, pattern, resource))
|
||||
|
|
|
@ -32,10 +32,10 @@ import (
|
|||
|
||||
func (e *engine) validate(
|
||||
ctx context.Context,
|
||||
logger logr.Logger,
|
||||
policyContext engineapi.PolicyContext,
|
||||
) *engineapi.EngineResponse {
|
||||
startTime := time.Now()
|
||||
logger := internal.BuildLogger(policyContext)
|
||||
logger.V(4).Info("start validate policy processing", "startTime", startTime)
|
||||
policyResponse := e.validateResource(ctx, logger, policyContext)
|
||||
defer logger.V(4).Info("finished policy processing", "processingTime", policyResponse.ProcessingTime.String(), "validationRulesApplied", policyResponse.RulesAppliedCount)
|
||||
|
@ -45,7 +45,7 @@ func (e *engine) validate(
|
|||
|
||||
func (e *engine) validateResource(
|
||||
ctx context.Context,
|
||||
log logr.Logger,
|
||||
logger logr.Logger,
|
||||
enginectx engineapi.PolicyContext,
|
||||
) *engineapi.PolicyResponse {
|
||||
resp := &engineapi.PolicyResponse{}
|
||||
|
@ -71,7 +71,8 @@ func (e *engine) validateResource(
|
|||
|
||||
for i := range rules {
|
||||
rule := &rules[i]
|
||||
log.V(3).Info("processing validation rule", "matchCount", matchCount, "applyRules", applyRules)
|
||||
logger := internal.LoggerWithRule(logger, rules[i])
|
||||
logger.V(3).Info("processing validation rule", "matchCount", matchCount)
|
||||
enginectx.JSONContext().Reset()
|
||||
startTime := time.Now()
|
||||
ruleResp := tracing.ChildSpan1(
|
||||
|
@ -85,33 +86,31 @@ func (e *engine) validateResource(
|
|||
if !hasValidate && !hasValidateImage {
|
||||
return nil
|
||||
}
|
||||
log = log.WithValues("rule", rule.Name)
|
||||
kindsInPolicy := append(rule.MatchResources.GetKinds(), rule.ExcludeResources.GetKinds()...)
|
||||
subresourceGVKToAPIResource := GetSubresourceGVKToAPIResourceMap(e.client, kindsInPolicy, enginectx)
|
||||
|
||||
if !matches(log, rule, enginectx, subresourceGVKToAPIResource, e.configuration) {
|
||||
if !matches(logger, rule, enginectx, subresourceGVKToAPIResource, e.configuration) {
|
||||
return nil
|
||||
}
|
||||
// check if there is a corresponding policy exception
|
||||
ruleResp := hasPolicyExceptions(log, engineapi.Validation, e.exceptionSelector, enginectx, rule, subresourceGVKToAPIResource, e.configuration)
|
||||
ruleResp := hasPolicyExceptions(logger, engineapi.Validation, e.exceptionSelector, enginectx, rule, subresourceGVKToAPIResource, e.configuration)
|
||||
if ruleResp != nil {
|
||||
return ruleResp
|
||||
}
|
||||
log.V(3).Info("processing validation rule", "matchCount", matchCount, "applyRules", applyRules)
|
||||
enginectx.JSONContext().Reset()
|
||||
if hasValidate && !hasYAMLSignatureVerify {
|
||||
return e.processValidationRule(ctx, log, enginectx, rule)
|
||||
return e.processValidationRule(ctx, logger, enginectx, rule)
|
||||
} else if hasValidateImage {
|
||||
return e.processImageValidationRule(ctx, log, enginectx, rule)
|
||||
return e.processImageValidationRule(ctx, logger, enginectx, rule)
|
||||
} else if hasYAMLSignatureVerify {
|
||||
return processYAMLValidationRule(e.client, log, enginectx, rule)
|
||||
return processYAMLValidationRule(e.client, logger, enginectx, rule)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
)
|
||||
if ruleResp != nil {
|
||||
internal.AddRuleResponse(resp, ruleResp, startTime)
|
||||
log.V(4).Info("finished processing rule", "processingTime", ruleResp.ExecutionStats.ProcessingTime.String())
|
||||
logger.V(4).Info("finished processing rule", "processingTime", ruleResp.ExecutionStats.ProcessingTime.String())
|
||||
}
|
||||
if applyRules == kyvernov1.ApplyOne && resp.RulesAppliedCount > 0 {
|
||||
break
|
||||
|
@ -123,11 +122,11 @@ func (e *engine) validateResource(
|
|||
|
||||
func (e *engine) processValidationRule(
|
||||
ctx context.Context,
|
||||
log logr.Logger,
|
||||
logger logr.Logger,
|
||||
policyContext engineapi.PolicyContext,
|
||||
rule *kyvernov1.Rule,
|
||||
) *engineapi.RuleResponse {
|
||||
v := newValidator(log, e.ContextLoader(policyContext.Policy(), *rule), policyContext, rule)
|
||||
v := newValidator(logger, e.ContextLoader(policyContext.Policy(), *rule), policyContext, rule)
|
||||
return v.validate(ctx)
|
||||
}
|
||||
|
||||
|
|
|
@ -4,9 +4,9 @@ import (
|
|||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/engine/context"
|
||||
"github.com/kyverno/kyverno/pkg/logging"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
|
@ -378,7 +378,7 @@ func TestEvaluate(t *testing.T) {
|
|||
|
||||
ctx := context.NewContext()
|
||||
for _, tc := range testCases {
|
||||
if Evaluate(logging.GlobalLogger(), ctx, tc.Condition) != tc.Result {
|
||||
if Evaluate(logr.Discard(), ctx, tc.Condition) != tc.Result {
|
||||
t.Errorf("%v - expected result to be %v", tc.Condition, tc.Result)
|
||||
}
|
||||
}
|
||||
|
@ -419,13 +419,13 @@ func Test_Eval_Equal_Var_Pass(t *testing.T) {
|
|||
err = json.Unmarshal(conditionJSON, &conditionMap)
|
||||
assert.Nil(t, err)
|
||||
|
||||
conditionWithResolvedVars, _ := SubstituteAllInPreconditions(logging.GlobalLogger(), ctx, conditionMap)
|
||||
conditionWithResolvedVars, _ := SubstituteAllInPreconditions(logr.Discard(), ctx, conditionMap)
|
||||
conditionJSON, err = json.Marshal(conditionWithResolvedVars)
|
||||
assert.Nil(t, err)
|
||||
|
||||
err = json.Unmarshal(conditionJSON, &condition)
|
||||
assert.Nil(t, err)
|
||||
assert.True(t, Evaluate(logging.GlobalLogger(), ctx, condition))
|
||||
assert.True(t, Evaluate(logr.Discard(), ctx, condition))
|
||||
}
|
||||
|
||||
func Test_Eval_Equal_Var_Fail(t *testing.T) {
|
||||
|
@ -454,7 +454,7 @@ func Test_Eval_Equal_Var_Fail(t *testing.T) {
|
|||
RawValue: kyverno.ToJSON("temp1"),
|
||||
}
|
||||
|
||||
if Evaluate(logging.GlobalLogger(), ctx, condition) {
|
||||
if Evaluate(logr.Discard(), ctx, condition) {
|
||||
t.Error("expected to fail")
|
||||
}
|
||||
}
|
||||
|
|
|
@ -5,9 +5,9 @@ import (
|
|||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
urkyverno "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
"github.com/kyverno/kyverno/pkg/engine/context"
|
||||
"github.com/kyverno/kyverno/pkg/logging"
|
||||
"gotest.tools/assert"
|
||||
authenticationv1 "k8s.io/api/authentication/v1"
|
||||
)
|
||||
|
@ -85,7 +85,7 @@ func Test_variablesub1(t *testing.T) {
|
|||
t.Error(err)
|
||||
}
|
||||
|
||||
if patternCopy, err = SubstituteAll(logging.GlobalLogger(), ctx, patternCopy); err != nil {
|
||||
if patternCopy, err = SubstituteAll(logr.Discard(), ctx, patternCopy); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
resultRaw, err := json.Marshal(patternCopy)
|
||||
|
@ -175,7 +175,7 @@ func Test_variablesub_multiple(t *testing.T) {
|
|||
t.Error(err)
|
||||
}
|
||||
|
||||
if patternCopy, err = SubstituteAll(logging.GlobalLogger(), ctx, patternCopy); err != nil {
|
||||
if patternCopy, err = SubstituteAll(logr.Discard(), ctx, patternCopy); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
resultRaw, err := json.Marshal(patternCopy)
|
||||
|
@ -263,7 +263,7 @@ func Test_variablesubstitution(t *testing.T) {
|
|||
t.Error(err)
|
||||
}
|
||||
|
||||
if patternCopy, err = SubstituteAll(logging.GlobalLogger(), ctx, patternCopy); err != nil {
|
||||
if patternCopy, err = SubstituteAll(logr.Discard(), ctx, patternCopy); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
resultRaw, err := json.Marshal(patternCopy)
|
||||
|
@ -323,7 +323,7 @@ func Test_variableSubstitutionValue(t *testing.T) {
|
|||
t.Error(err)
|
||||
}
|
||||
|
||||
if patternCopy, err = SubstituteAll(logging.GlobalLogger(), ctx, patternCopy); err != nil {
|
||||
if patternCopy, err = SubstituteAll(logr.Discard(), ctx, patternCopy); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
resultRaw, err := json.Marshal(patternCopy)
|
||||
|
@ -380,7 +380,7 @@ func Test_variableSubstitutionValueOperatorNotEqual(t *testing.T) {
|
|||
t.Error(err)
|
||||
}
|
||||
|
||||
if patternCopy, err = SubstituteAll(logging.GlobalLogger(), ctx, patternCopy); err != nil {
|
||||
if patternCopy, err = SubstituteAll(logr.Discard(), ctx, patternCopy); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
resultRaw, err := json.Marshal(patternCopy)
|
||||
|
@ -438,7 +438,7 @@ func Test_variableSubstitutionValueFail(t *testing.T) {
|
|||
t.Error(err)
|
||||
}
|
||||
|
||||
if patternCopy, err = SubstituteAll(logging.GlobalLogger(), ctx, patternCopy); err == nil {
|
||||
if patternCopy, err = SubstituteAll(logr.Discard(), ctx, patternCopy); err == nil {
|
||||
t.Log("expected to fails")
|
||||
t.Fail()
|
||||
}
|
||||
|
@ -495,7 +495,7 @@ func Test_variableSubstitutionObject(t *testing.T) {
|
|||
t.Error(err)
|
||||
}
|
||||
|
||||
if patternCopy, err = SubstituteAll(logging.GlobalLogger(), ctx, patternCopy); err != nil {
|
||||
if patternCopy, err = SubstituteAll(logr.Discard(), ctx, patternCopy); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
resultRaw, err := json.Marshal(patternCopy)
|
||||
|
@ -559,7 +559,7 @@ func Test_variableSubstitutionObjectOperatorNotEqualFail(t *testing.T) {
|
|||
t.Error(err)
|
||||
}
|
||||
|
||||
patternCopy, err = SubstituteAll(logging.GlobalLogger(), ctx, patternCopy)
|
||||
patternCopy, err = SubstituteAll(logr.Discard(), ctx, patternCopy)
|
||||
assert.NilError(t, err)
|
||||
|
||||
patternMapCopy, ok := patternCopy.(map[string]interface{})
|
||||
|
@ -634,7 +634,7 @@ func Test_variableSubstitutionMultipleObject(t *testing.T) {
|
|||
t.Error(err)
|
||||
}
|
||||
|
||||
if patternCopy, err = SubstituteAll(logging.GlobalLogger(), ctx, patternCopy); err != nil {
|
||||
if patternCopy, err = SubstituteAll(logr.Discard(), ctx, patternCopy); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
resultRaw, err := json.Marshal(patternCopy)
|
||||
|
|
|
@ -7,10 +7,10 @@ import (
|
|||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
v1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/engine/context"
|
||||
ju "github.com/kyverno/kyverno/pkg/engine/jsonutils"
|
||||
"github.com/kyverno/kyverno/pkg/logging"
|
||||
"gotest.tools/assert"
|
||||
)
|
||||
|
||||
|
@ -70,7 +70,7 @@ func Test_subVars_success(t *testing.T) {
|
|||
t.Error(err)
|
||||
}
|
||||
|
||||
if _, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern); err != nil {
|
||||
if _, err := SubstituteAll(logr.Discard(), ctx, pattern); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
@ -131,7 +131,7 @@ func Test_subVars_failed(t *testing.T) {
|
|||
t.Error(err)
|
||||
}
|
||||
|
||||
if _, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern); err == nil {
|
||||
if _, err := SubstituteAll(logr.Discard(), ctx, pattern); err == nil {
|
||||
t.Error("error is expected")
|
||||
}
|
||||
}
|
||||
|
@ -223,7 +223,7 @@ func Test_subVars_with_JMESPath_At(t *testing.T) {
|
|||
err = context.AddResource(ctx, resourceRaw)
|
||||
assert.NilError(t, err)
|
||||
|
||||
output, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern)
|
||||
output, err := SubstituteAll(logr.Discard(), ctx, pattern)
|
||||
assert.NilError(t, err)
|
||||
out, err := json.Marshal(output)
|
||||
assert.NilError(t, err)
|
||||
|
@ -282,7 +282,7 @@ func Test_subVars_withRegexMatch(t *testing.T) {
|
|||
err = context.AddResource(ctx, resourceRaw)
|
||||
assert.NilError(t, err)
|
||||
|
||||
output, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern)
|
||||
output, err := SubstituteAll(logr.Discard(), ctx, pattern)
|
||||
assert.NilError(t, err)
|
||||
out, err := json.Marshal(output)
|
||||
assert.NilError(t, err)
|
||||
|
@ -312,7 +312,7 @@ func Test_subVars_withMerge(t *testing.T) {
|
|||
err = context.AddResource(ctx, resourceRaw)
|
||||
assert.NilError(t, err)
|
||||
|
||||
output, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern)
|
||||
output, err := SubstituteAll(logr.Discard(), ctx, pattern)
|
||||
assert.NilError(t, err)
|
||||
out, err := json.Marshal(output)
|
||||
assert.NilError(t, err)
|
||||
|
@ -355,7 +355,7 @@ func Test_subVars_withRegexReplaceAll(t *testing.T) {
|
|||
err = context.AddResource(ctx, resourceRaw)
|
||||
assert.NilError(t, err)
|
||||
|
||||
output, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern)
|
||||
output, err := SubstituteAll(logr.Discard(), ctx, pattern)
|
||||
assert.NilError(t, err)
|
||||
out, err := json.Marshal(output)
|
||||
assert.NilError(t, err)
|
||||
|
@ -399,7 +399,7 @@ func Test_ReplacingPathWhenDeleting(t *testing.T) {
|
|||
ctx := context.NewContextFromRaw(resourceRaw)
|
||||
assert.NilError(t, err)
|
||||
|
||||
pattern, err = SubstituteAll(logging.GlobalLogger(), ctx, pattern)
|
||||
pattern, err = SubstituteAll(logr.Discard(), ctx, pattern)
|
||||
assert.NilError(t, err)
|
||||
|
||||
assert.Equal(t, fmt.Sprintf("%v", pattern), "bar")
|
||||
|
@ -434,7 +434,7 @@ func Test_ReplacingNestedVariableWhenDeleting(t *testing.T) {
|
|||
ctx := context.NewContextFromRaw(resourceRaw)
|
||||
assert.NilError(t, err)
|
||||
|
||||
pattern, err = SubstituteAll(logging.GlobalLogger(), ctx, pattern)
|
||||
pattern, err = SubstituteAll(logr.Discard(), ctx, pattern)
|
||||
assert.NilError(t, err)
|
||||
|
||||
assert.Equal(t, fmt.Sprintf("%v", pattern), "nested_target")
|
||||
|
@ -464,7 +464,7 @@ func Test_SubstituteSuccess(t *testing.T) {
|
|||
patternRaw := []byte(`"{{request.object.metadata.annotations.test}}"`)
|
||||
assert.Assert(t, json.Unmarshal(patternRaw, &pattern))
|
||||
|
||||
action := substituteVariablesIfAny(logging.GlobalLogger(), ctx, DefaultVariableResolver)
|
||||
action := substituteVariablesIfAny(logr.Discard(), ctx, DefaultVariableResolver)
|
||||
results, err := action(&ju.ActionData{
|
||||
Document: nil,
|
||||
Element: string(patternRaw),
|
||||
|
@ -488,7 +488,7 @@ func Test_SubstituteRecursiveErrors(t *testing.T) {
|
|||
patternRaw := []byte(`"{{request.object.metadata.{{request.object.metadata.annotations.test2}}}}"`)
|
||||
assert.Assert(t, json.Unmarshal(patternRaw, &pattern))
|
||||
|
||||
action := substituteVariablesIfAny(logging.GlobalLogger(), ctx, DefaultVariableResolver)
|
||||
action := substituteVariablesIfAny(logr.Discard(), ctx, DefaultVariableResolver)
|
||||
results, err := action(&ju.ActionData{
|
||||
Document: nil,
|
||||
Element: string(patternRaw),
|
||||
|
@ -502,7 +502,7 @@ func Test_SubstituteRecursiveErrors(t *testing.T) {
|
|||
patternRaw = []byte(`"{{request.object.metadata2.{{request.object.metadata.annotations.test}}}}"`)
|
||||
assert.Assert(t, json.Unmarshal(patternRaw, &pattern))
|
||||
|
||||
action = substituteVariablesIfAny(logging.GlobalLogger(), ctx, DefaultVariableResolver)
|
||||
action = substituteVariablesIfAny(logr.Discard(), ctx, DefaultVariableResolver)
|
||||
results, err = action(&ju.ActionData{
|
||||
Document: nil,
|
||||
Element: string(patternRaw),
|
||||
|
@ -522,7 +522,7 @@ func Test_SubstituteRecursive(t *testing.T) {
|
|||
patternRaw := []byte(`"{{request.object.metadata.{{request.object.metadata.annotations.test}}}}"`)
|
||||
assert.Assert(t, json.Unmarshal(patternRaw, &pattern))
|
||||
|
||||
action := substituteVariablesIfAny(logging.GlobalLogger(), ctx, DefaultVariableResolver)
|
||||
action := substituteVariablesIfAny(logr.Discard(), ctx, DefaultVariableResolver)
|
||||
results, err := action(&ju.ActionData{
|
||||
Document: nil,
|
||||
Element: string(patternRaw),
|
||||
|
@ -558,7 +558,7 @@ func Test_policyContextValidation(t *testing.T) {
|
|||
|
||||
ctx := context.NewMockContext(nil, "request.object")
|
||||
|
||||
_, err = SubstituteAll(logging.GlobalLogger(), ctx, contextMap)
|
||||
_, err = SubstituteAll(logr.Discard(), ctx, contextMap)
|
||||
assert.Assert(t, err != nil, err)
|
||||
}
|
||||
|
||||
|
@ -636,7 +636,7 @@ func Test_variableSubstitution_array(t *testing.T) {
|
|||
ctx := context.NewContextFromRaw(configmapRaw)
|
||||
context.AddResource(ctx, resourceRaw)
|
||||
|
||||
vars, err := SubstituteAllInRule(logging.GlobalLogger(), ctx, rule)
|
||||
vars, err := SubstituteAllInRule(logr.Discard(), ctx, rule)
|
||||
assert.NilError(t, err)
|
||||
|
||||
assert.DeepEqual(t, vars.Validation.Message, "The animal cow is not in the allowed list of animals: snake\nbear\ncat\ndog.")
|
||||
|
@ -682,7 +682,7 @@ func Test_SubstituteNull(t *testing.T) {
|
|||
ctx := context.NewContext()
|
||||
context.AddResource(ctx, variableObject)
|
||||
|
||||
resolved, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern)
|
||||
resolved, err := SubstituteAll(logr.Discard(), ctx, pattern)
|
||||
assert.NilError(t, err)
|
||||
|
||||
content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"]
|
||||
|
@ -711,7 +711,7 @@ func Test_SubstituteNullInString(t *testing.T) {
|
|||
ctx := context.NewContext()
|
||||
context.AddResource(ctx, variableObject)
|
||||
|
||||
resolved, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern)
|
||||
resolved, err := SubstituteAll(logr.Discard(), ctx, pattern)
|
||||
assert.NilError(t, err)
|
||||
|
||||
content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"]
|
||||
|
@ -740,7 +740,7 @@ func Test_SubstituteArray(t *testing.T) {
|
|||
ctx := context.NewContext()
|
||||
context.AddResource(ctx, variableObject)
|
||||
|
||||
resolved, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern)
|
||||
resolved, err := SubstituteAll(logr.Discard(), ctx, pattern)
|
||||
assert.NilError(t, err)
|
||||
|
||||
content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"]
|
||||
|
@ -769,7 +769,7 @@ func Test_SubstituteArrayInString(t *testing.T) {
|
|||
ctx := context.NewContext()
|
||||
context.AddResource(ctx, variableObject)
|
||||
|
||||
resolved, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern)
|
||||
resolved, err := SubstituteAll(logr.Discard(), ctx, pattern)
|
||||
assert.NilError(t, err)
|
||||
|
||||
content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"]
|
||||
|
@ -798,7 +798,7 @@ func Test_SubstituteInt(t *testing.T) {
|
|||
ctx := context.NewContext()
|
||||
context.AddResource(ctx, variableObject)
|
||||
|
||||
resolved, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern)
|
||||
resolved, err := SubstituteAll(logr.Discard(), ctx, pattern)
|
||||
assert.NilError(t, err)
|
||||
|
||||
content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"]
|
||||
|
@ -827,7 +827,7 @@ func Test_SubstituteIntInString(t *testing.T) {
|
|||
ctx := context.NewContext()
|
||||
context.AddResource(ctx, variableObject)
|
||||
|
||||
resolved, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern)
|
||||
resolved, err := SubstituteAll(logr.Discard(), ctx, pattern)
|
||||
assert.NilError(t, err)
|
||||
|
||||
content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"]
|
||||
|
@ -856,7 +856,7 @@ func Test_SubstituteBool(t *testing.T) {
|
|||
ctx := context.NewContext()
|
||||
context.AddResource(ctx, variableObject)
|
||||
|
||||
resolved, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern)
|
||||
resolved, err := SubstituteAll(logr.Discard(), ctx, pattern)
|
||||
assert.NilError(t, err)
|
||||
|
||||
content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"]
|
||||
|
@ -885,7 +885,7 @@ func Test_SubstituteBoolInString(t *testing.T) {
|
|||
ctx := context.NewContext()
|
||||
context.AddResource(ctx, variableObject)
|
||||
|
||||
resolved, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern)
|
||||
resolved, err := SubstituteAll(logr.Discard(), ctx, pattern)
|
||||
assert.NilError(t, err)
|
||||
|
||||
content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"]
|
||||
|
@ -914,7 +914,7 @@ func Test_SubstituteString(t *testing.T) {
|
|||
ctx := context.NewContext()
|
||||
context.AddResource(ctx, variableObject)
|
||||
|
||||
resolved, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern)
|
||||
resolved, err := SubstituteAll(logr.Discard(), ctx, pattern)
|
||||
assert.NilError(t, err)
|
||||
|
||||
content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"]
|
||||
|
@ -943,7 +943,7 @@ func Test_SubstituteStringInString(t *testing.T) {
|
|||
ctx := context.NewContext()
|
||||
context.AddResource(ctx, variableObject)
|
||||
|
||||
resolved, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern)
|
||||
resolved, err := SubstituteAll(logr.Discard(), ctx, pattern)
|
||||
assert.NilError(t, err)
|
||||
|
||||
content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"]
|
||||
|
@ -995,7 +995,7 @@ func Test_ReferenceSubstitution(t *testing.T) {
|
|||
err = context.AddResource(ctx, jsonRaw)
|
||||
assert.NilError(t, err)
|
||||
|
||||
actualDocument, err := SubstituteAll(logging.GlobalLogger(), ctx, document)
|
||||
actualDocument, err := SubstituteAll(logr.Discard(), ctx, document)
|
||||
assert.NilError(t, err)
|
||||
|
||||
assert.DeepEqual(t, expectedDocument, actualDocument)
|
||||
|
@ -1068,7 +1068,7 @@ func TestActualizePattern_GivenRelativePathThatExists(t *testing.T) {
|
|||
|
||||
// pattern, err := actualizePattern(log.Log, pattern, referencePath, absolutePath)
|
||||
|
||||
pattern, err := resolveReference(logging.GlobalLogger(), pattern, referencePath, absolutePath)
|
||||
pattern, err := resolveReference(logr.Discard(), pattern, referencePath, absolutePath)
|
||||
|
||||
assert.NilError(t, err)
|
||||
assert.DeepEqual(t, resolvedReference, pattern)
|
||||
|
@ -1077,7 +1077,7 @@ func TestActualizePattern_GivenRelativePathThatExists(t *testing.T) {
|
|||
func TestFindAndShiftReferences_PositiveCase(t *testing.T) {
|
||||
message := "Message with $(./../../pattern/spec/containers/0/image) reference inside. Or maybe even two $(./../../pattern/spec/containers/0/image), but they are same."
|
||||
expectedMessage := strings.Replace(message, "$(./../../pattern/spec/containers/0/image)", "$(./../../pattern/spec/jobTemplate/spec/containers/0/image)", -1)
|
||||
actualMessage := FindAndShiftReferences(logging.GlobalLogger(), message, "spec/jobTemplate", "pattern")
|
||||
actualMessage := FindAndShiftReferences(logr.Discard(), message, "spec/jobTemplate", "pattern")
|
||||
|
||||
assert.Equal(t, expectedMessage, actualMessage)
|
||||
}
|
||||
|
@ -1085,7 +1085,7 @@ func TestFindAndShiftReferences_PositiveCase(t *testing.T) {
|
|||
func TestFindAndShiftReferences_AnyPatternPositiveCase(t *testing.T) {
|
||||
message := "Message with $(./../../anyPattern/0/spec/containers/0/image)."
|
||||
expectedMessage := strings.Replace(message, "$(./../../anyPattern/0/spec/containers/0/image)", "$(./../../anyPattern/0/spec/jobTemplate/spec/containers/0/image)", -1)
|
||||
actualMessage := FindAndShiftReferences(logging.GlobalLogger(), message, "spec/jobTemplate", "anyPattern")
|
||||
actualMessage := FindAndShiftReferences(logr.Discard(), message, "spec/jobTemplate", "anyPattern")
|
||||
|
||||
assert.Equal(t, expectedMessage, actualMessage)
|
||||
}
|
||||
|
@ -1139,7 +1139,7 @@ func Test_EscpReferenceSubstitution(t *testing.T) {
|
|||
err = context.AddResource(ctx, jsonRaw)
|
||||
assert.NilError(t, err)
|
||||
|
||||
actualDocument, err := SubstituteAll(logging.GlobalLogger(), ctx, document)
|
||||
actualDocument, err := SubstituteAll(logr.Discard(), ctx, document)
|
||||
assert.NilError(t, err)
|
||||
|
||||
assert.DeepEqual(t, expectedDocument, actualDocument)
|
||||
|
@ -1174,7 +1174,7 @@ func Test_ReplacingEscpNestedVariableWhenDeleting(t *testing.T) {
|
|||
ctx := context.NewContextFromRaw(resourceRaw)
|
||||
assert.NilError(t, err)
|
||||
|
||||
pattern, err = SubstituteAll(logging.GlobalLogger(), ctx, pattern)
|
||||
pattern, err = SubstituteAll(logr.Discard(), ctx, pattern)
|
||||
assert.NilError(t, err)
|
||||
|
||||
assert.Equal(t, fmt.Sprintf("%v", pattern), "{{request.object.metadata.annotations.target}}")
|
||||
|
|
|
@ -5,13 +5,13 @@ import (
|
|||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
"github.com/google/gnostic/compiler"
|
||||
openapiv2 "github.com/google/gnostic/openapiv2"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/autogen"
|
||||
openapicontroller "github.com/kyverno/kyverno/pkg/controllers/openapi"
|
||||
"github.com/kyverno/kyverno/pkg/engine"
|
||||
"github.com/kyverno/kyverno/pkg/logging"
|
||||
cmap "github.com/orcaman/concurrent-map/v2"
|
||||
"gopkg.in/yaml.v3"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
|
@ -47,6 +47,8 @@ type manager struct {
|
|||
|
||||
// kindToAPIVersions stores the Kind and all its available apiVersions, {kind: apiVersions}
|
||||
kindToAPIVersions cmap.ConcurrentMap[string, apiVersions]
|
||||
|
||||
logger logr.Logger
|
||||
}
|
||||
|
||||
// apiVersions stores all available gvks for a kind, a gvk is "/" separated string
|
||||
|
@ -56,11 +58,12 @@ type apiVersions struct {
|
|||
}
|
||||
|
||||
// NewManager initializes a new instance of openapi schema manager
|
||||
func NewManager() (*manager, error) {
|
||||
func NewManager(logger logr.Logger) (*manager, error) {
|
||||
mgr := &manager{
|
||||
definitions: cmap.New[*openapiv2.Schema](),
|
||||
gvkToDefinitionName: cmap.New[string](),
|
||||
kindToAPIVersions: cmap.New[apiVersions](),
|
||||
logger: logger,
|
||||
}
|
||||
|
||||
apiResourceLists, preferredAPIResourcesLists, err := getAPIResourceLists()
|
||||
|
@ -144,14 +147,14 @@ func (o *manager) ValidatePolicyMutation(policy kyvernov1.PolicyInterface) error
|
|||
d, _ := o.definitions.Get(k)
|
||||
resource, _ := o.generateEmptyResource(d).(map[string]interface{})
|
||||
if len(resource) == 0 {
|
||||
logging.V(2).Info("unable to validate resource. OpenApi definition not found", "kind", kind)
|
||||
o.logger.V(2).Info("unable to validate resource. OpenApi definition not found", "kind", kind)
|
||||
return nil
|
||||
}
|
||||
|
||||
newResource := unstructured.Unstructured{Object: resource}
|
||||
newResource.SetKind(kind)
|
||||
|
||||
patchedResource, err := engine.ForceMutate(nil, newPolicy, newResource)
|
||||
patchedResource, err := engine.ForceMutate(nil, o.logger, newPolicy, newResource)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
@ -175,7 +178,7 @@ func (o *manager) UseOpenAPIDocument(doc *openapiv2.Document) error {
|
|||
|
||||
gvk, preferredGVK, err := o.getGVKByDefinitionName(definitionName)
|
||||
if err != nil {
|
||||
logging.V(5).Info("unable to cache OpenAPISchema", "definitionName", definitionName, "reason", err.Error())
|
||||
o.logger.V(5).Info("unable to cache OpenAPISchema", "definitionName", definitionName, "reason", err.Error())
|
||||
continue
|
||||
}
|
||||
|
||||
|
@ -289,7 +292,7 @@ func (o *manager) generateEmptyResource(kindSchema *openapiv2.Schema) interface{
|
|||
return getBoolValue(kindSchema)
|
||||
}
|
||||
|
||||
logging.V(2).Info("unknown type", types[0])
|
||||
o.logger.V(2).Info("unknown type", types[0])
|
||||
return nil
|
||||
}
|
||||
|
||||
|
@ -324,19 +327,19 @@ func (o *manager) ParseCRD(crd unstructured.Unstructured) {
|
|||
}
|
||||
|
||||
if openV3schema == nil {
|
||||
logging.V(4).Info("skip adding schema, CRD has no properties", "name", crdName)
|
||||
o.logger.V(4).Info("skip adding schema, CRD has no properties", "name", crdName)
|
||||
return
|
||||
}
|
||||
|
||||
schemaRaw, _ := json.Marshal(openV3schema)
|
||||
if len(schemaRaw) < 1 {
|
||||
logging.V(4).Info("failed to parse crd schema", "name", crdName)
|
||||
o.logger.V(4).Info("failed to parse crd schema", "name", crdName)
|
||||
return
|
||||
}
|
||||
|
||||
schemaRaw, err = addingDefaultFieldsToSchema(crdName, schemaRaw)
|
||||
if err != nil {
|
||||
logging.Error(err, "failed to parse crd schema", "name", crdName)
|
||||
o.logger.Error(err, "failed to parse crd schema", "name", crdName)
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -347,7 +350,7 @@ func (o *manager) ParseCRD(crd unstructured.Unstructured) {
|
|||
if err != nil {
|
||||
v3valueFound := isOpenV3Error(err)
|
||||
if !v3valueFound {
|
||||
logging.Error(err, "failed to parse crd schema", "name", crdName)
|
||||
o.logger.Error(err, "failed to parse crd schema", "name", crdName)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
|
|
@ -4,6 +4,7 @@ import (
|
|||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
v1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"gotest.tools/assert"
|
||||
)
|
||||
|
@ -72,7 +73,7 @@ func Test_ValidateMutationPolicy(t *testing.T) {
|
|||
},
|
||||
}
|
||||
|
||||
o, _ := NewManager()
|
||||
o, _ := NewManager(logr.Discard())
|
||||
|
||||
for i, tc := range tcs {
|
||||
policy := v1.ClusterPolicy{}
|
||||
|
@ -196,7 +197,7 @@ func Test_matchGVK(t *testing.T) {
|
|||
// networking.k8s.io/v1beta1/Ingress
|
||||
// extensions/v1beta1/Ingress
|
||||
func Test_Ingress(t *testing.T) {
|
||||
o, err := NewManager()
|
||||
o, err := NewManager(logr.Discard())
|
||||
assert.NilError(t, err)
|
||||
|
||||
versions, ok := o.kindToAPIVersions.Get("Ingress")
|
||||
|
|
|
@ -6,6 +6,7 @@ import (
|
|||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/openapi"
|
||||
"gotest.tools/assert"
|
||||
|
@ -346,7 +347,7 @@ func Test_Validate_Policy(t *testing.T) {
|
|||
}
|
||||
}`)
|
||||
|
||||
openApiManager, _ := openapi.NewManager()
|
||||
openApiManager, _ := openapi.NewManager(logr.Discard())
|
||||
var policy *kyverno.ClusterPolicy
|
||||
err := json.Unmarshal(rawPolicy, &policy)
|
||||
assert.NilError(t, err)
|
||||
|
@ -497,7 +498,7 @@ func Test_Validate_ErrorFormat(t *testing.T) {
|
|||
err := json.Unmarshal(rawPolicy, &policy)
|
||||
assert.NilError(t, err)
|
||||
|
||||
openApiManager, _ := openapi.NewManager()
|
||||
openApiManager, _ := openapi.NewManager(logr.Discard())
|
||||
_, err = Validate(policy, nil, true, openApiManager)
|
||||
assert.Assert(t, err != nil)
|
||||
}
|
||||
|
@ -899,7 +900,7 @@ func Test_Validate_Kind(t *testing.T) {
|
|||
err := json.Unmarshal(rawPolicy, &policy)
|
||||
assert.NilError(t, err)
|
||||
|
||||
openApiManager, _ := openapi.NewManager()
|
||||
openApiManager, _ := openapi.NewManager(logr.Discard())
|
||||
_, err = Validate(policy, nil, true, openApiManager)
|
||||
assert.Assert(t, err != nil)
|
||||
}
|
||||
|
@ -948,7 +949,7 @@ func Test_Validate_Any_Kind(t *testing.T) {
|
|||
err := json.Unmarshal(rawPolicy, &policy)
|
||||
assert.NilError(t, err)
|
||||
|
||||
openApiManager, _ := openapi.NewManager()
|
||||
openApiManager, _ := openapi.NewManager(logr.Discard())
|
||||
_, err = Validate(policy, nil, true, openApiManager)
|
||||
assert.Assert(t, err != nil)
|
||||
}
|
||||
|
@ -1038,7 +1039,7 @@ func Test_Wildcards_Kind(t *testing.T) {
|
|||
err := json.Unmarshal(rawPolicy, &policy)
|
||||
assert.NilError(t, err)
|
||||
|
||||
openApiManager, _ := openapi.NewManager()
|
||||
openApiManager, _ := openapi.NewManager(logr.Discard())
|
||||
_, err = Validate(policy, nil, true, openApiManager)
|
||||
assert.Assert(t, err != nil)
|
||||
}
|
||||
|
@ -1088,7 +1089,7 @@ func Test_Namespced_Policy(t *testing.T) {
|
|||
err := json.Unmarshal(rawPolicy, &policy)
|
||||
assert.NilError(t, err)
|
||||
|
||||
openApiManager, _ := openapi.NewManager()
|
||||
openApiManager, _ := openapi.NewManager(logr.Discard())
|
||||
_, err = Validate(policy, nil, true, openApiManager)
|
||||
assert.Assert(t, err != nil)
|
||||
}
|
||||
|
@ -1266,7 +1267,7 @@ func Test_patchesJson6902_Policy(t *testing.T) {
|
|||
err := json.Unmarshal(rawPolicy, &policy)
|
||||
assert.NilError(t, err)
|
||||
|
||||
openApiManager, _ := openapi.NewManager()
|
||||
openApiManager, _ := openapi.NewManager(logr.Discard())
|
||||
_, err = Validate(policy, nil, true, openApiManager)
|
||||
assert.NilError(t, err)
|
||||
}
|
||||
|
@ -1314,7 +1315,7 @@ func Test_deny_exec(t *testing.T) {
|
|||
err = json.Unmarshal(rawPolicy, &policy)
|
||||
assert.NilError(t, err)
|
||||
|
||||
openApiManager, _ := openapi.NewManager()
|
||||
openApiManager, _ := openapi.NewManager(logr.Discard())
|
||||
_, err = Validate(policy, nil, true, openApiManager)
|
||||
assert.NilError(t, err)
|
||||
}
|
||||
|
@ -1462,7 +1463,7 @@ func Test_SignatureAlgorithm(t *testing.T) {
|
|||
err := json.Unmarshal(testcase.policy, &policy)
|
||||
assert.NilError(t, err)
|
||||
|
||||
openApiManager, _ := openapi.NewManager()
|
||||
openApiManager, _ := openapi.NewManager(logr.Discard())
|
||||
_, err = Validate(policy, nil, true, openApiManager)
|
||||
if testcase.expectedOutput {
|
||||
assert.NilError(t, err)
|
||||
|
@ -1512,7 +1513,7 @@ func Test_existing_resource_policy(t *testing.T) {
|
|||
err = json.Unmarshal(rawPolicy, &policy)
|
||||
assert.NilError(t, err)
|
||||
|
||||
openApiManager, _ := openapi.NewManager()
|
||||
openApiManager, _ := openapi.NewManager(logr.Discard())
|
||||
_, err = Validate(policy, nil, true, openApiManager)
|
||||
assert.NilError(t, err)
|
||||
}
|
||||
|
@ -1568,7 +1569,7 @@ func Test_PodControllerAutoGenExclusion_All_Controllers_Policy(t *testing.T) {
|
|||
err := json.Unmarshal(rawPolicy, &policy)
|
||||
assert.NilError(t, err)
|
||||
|
||||
openApiManager, _ := openapi.NewManager()
|
||||
openApiManager, _ := openapi.NewManager(logr.Discard())
|
||||
res, err := Validate(policy, nil, true, openApiManager)
|
||||
assert.NilError(t, err)
|
||||
assert.Assert(t, res == nil)
|
||||
|
@ -1625,7 +1626,7 @@ func Test_PodControllerAutoGenExclusion_Not_All_Controllers_Policy(t *testing.T)
|
|||
err := json.Unmarshal(rawPolicy, &policy)
|
||||
assert.NilError(t, err)
|
||||
|
||||
openApiManager, _ := openapi.NewManager()
|
||||
openApiManager, _ := openapi.NewManager(logr.Discard())
|
||||
warnings, err := Validate(policy, nil, true, openApiManager)
|
||||
assert.Assert(t, warnings != nil)
|
||||
assert.NilError(t, err)
|
||||
|
@ -1682,7 +1683,7 @@ func Test_PodControllerAutoGenExclusion_None_Policy(t *testing.T) {
|
|||
err := json.Unmarshal(rawPolicy, &policy)
|
||||
assert.NilError(t, err)
|
||||
|
||||
openApiManager, _ := openapi.NewManager()
|
||||
openApiManager, _ := openapi.NewManager(logr.Discard())
|
||||
warnings, err := Validate(policy, nil, true, openApiManager)
|
||||
assert.Assert(t, warnings == nil)
|
||||
assert.NilError(t, err)
|
||||
|
@ -2236,7 +2237,7 @@ func Test_Any_wildcard_policy(t *testing.T) {
|
|||
err = json.Unmarshal(rawPolicy, &policy)
|
||||
assert.NilError(t, err)
|
||||
|
||||
openApiManager, _ := openapi.NewManager()
|
||||
openApiManager, _ := openapi.NewManager(logr.Discard())
|
||||
_, err = Validate(policy, nil, true, openApiManager)
|
||||
assert.Assert(t, err != nil)
|
||||
}
|
||||
|
@ -2294,7 +2295,7 @@ func Test_Validate_RuleImageExtractorsJMESPath(t *testing.T) {
|
|||
|
||||
expectedErr := fmt.Errorf("path: spec.rules[0]: jmespath may not be used in an image extractor when mutating digests with verify images")
|
||||
|
||||
openApiManager, _ := openapi.NewManager()
|
||||
openApiManager, _ := openapi.NewManager(logr.Discard())
|
||||
_, actualErr := Validate(policy, nil, true, openApiManager)
|
||||
assert.Equal(t, expectedErr.Error(), actualErr.Error())
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue