diff --git a/cmd/cli/kubectl-kyverno/apply/apply_command.go b/cmd/cli/kubectl-kyverno/apply/apply_command.go index 8ebb793b12..c4f7522bfc 100644 --- a/cmd/cli/kubectl-kyverno/apply/apply_command.go +++ b/cmd/cli/kubectl-kyverno/apply/apply_command.go @@ -185,7 +185,7 @@ func (c *ApplyCommandConfig) applyCommandHelper() (rc *common.ResultCounts, reso return rc, resources, skipInvalidPolicies, pvInfos, err } - openApiManager, err := openapi.NewOpenAPIManager() + openApiManager, err := openapi.NewManager() if err != nil { return rc, resources, skipInvalidPolicies, pvInfos, sanitizederror.NewWithError("failed to initialize openAPIController", err) } diff --git a/cmd/cli/kubectl-kyverno/test/test_command.go b/cmd/cli/kubectl-kyverno/test/test_command.go index b4d31dd688..4d87a092e7 100644 --- a/cmd/cli/kubectl-kyverno/test/test_command.go +++ b/cmd/cli/kubectl-kyverno/test/test_command.go @@ -362,7 +362,7 @@ func testCommandExecute(dirPath []string, fileName string, gitBranch string, tes tf.enabled = false } - openAPIController, err := openapi.NewOpenAPIManager() + openApiManager, err := openapi.NewManager() if err != nil { return rc, fmt.Errorf("unable to create open api controller, %w", err) } @@ -439,7 +439,7 @@ func testCommandExecute(dirPath []string, fileName string, gitBranch string, tes errors = append(errors, sanitizederror.NewWithError("failed to convert to JSON", err)) continue } - if err := applyPoliciesFromPath(fs, policyBytes, true, policyresoucePath, rc, openAPIController, tf, failOnly, removeColor); err != nil { + if err := applyPoliciesFromPath(fs, policyBytes, true, policyresoucePath, rc, openApiManager, tf, failOnly, removeColor); err != nil { return rc, sanitizederror.NewWithError("failed to apply test command", err) } } @@ -451,7 +451,7 @@ func testCommandExecute(dirPath []string, fileName string, gitBranch string, tes } else { var testFiles int path := filepath.Clean(dirPath[0]) - errors = getLocalDirTestFiles(fs, path, fileName, rc, &testFiles, openAPIController, tf, failOnly, removeColor) + errors = getLocalDirTestFiles(fs, path, fileName, rc, &testFiles, openApiManager, tf, failOnly, removeColor) if testFiles == 0 { fmt.Printf("\n No test files found. Please provide test YAML files named kyverno-test.yaml \n") @@ -480,7 +480,7 @@ func testCommandExecute(dirPath []string, fileName string, gitBranch string, tes return rc, nil } -func getLocalDirTestFiles(fs billy.Filesystem, path, fileName string, rc *resultCounts, testFiles *int, openApiManager *openapi.Manager, tf *testFilter, failOnly, removeColor bool) []error { +func getLocalDirTestFiles(fs billy.Filesystem, path, fileName string, rc *resultCounts, testFiles *int, openApiManager openapi.Manager, tf *testFilter, failOnly, removeColor bool) []error { var errors []error files, err := os.ReadDir(path) @@ -819,7 +819,7 @@ func getFullPath(paths []string, policyResourcePath string, isGit bool) []string return paths } -func applyPoliciesFromPath(fs billy.Filesystem, policyBytes []byte, isGit bool, policyResourcePath string, rc *resultCounts, openAPIController *openapi.Manager, tf *testFilter, failOnly, removeColor bool) (err error) { +func applyPoliciesFromPath(fs billy.Filesystem, policyBytes []byte, isGit bool, policyResourcePath string, rc *resultCounts, openApiManager openapi.Manager, tf *testFilter, failOnly, removeColor bool) (err error) { engineResponses := make([]*response.EngineResponse, 0) var dClient dclient.Interface values := &Test{} @@ -985,7 +985,7 @@ func applyPoliciesFromPath(fs billy.Filesystem, policyBytes []byte, isGit bool, } for _, policy := range mutatedPolicies { - _, err := policy2.Validate(policy, nil, true, openAPIController) + _, err := policy2.Validate(policy, nil, true, openApiManager) if err != nil { log.Log.Error(err, "skipping invalid policy", "name", policy.GetName()) continue diff --git a/cmd/kyverno/controller.go b/cmd/kyverno/controller.go index 7c3e012853..a3e2632352 100644 --- a/cmd/kyverno/controller.go +++ b/cmd/kyverno/controller.go @@ -22,6 +22,6 @@ func newController(name string, c controllers.Controller, w int) controller { } func (c controller) run(ctx context.Context, logger logr.Logger) { - logger.Info("start controller...", "name", c.name) + logger.Info("start controller...", "name", c.name, "workers", c.workers) c.controller.Run(ctx, c.workers) } diff --git a/cmd/kyverno/main.go b/cmd/kyverno/main.go index 7dcc204316..985ef8a880 100644 --- a/cmd/kyverno/main.go +++ b/cmd/kyverno/main.go @@ -24,6 +24,7 @@ import ( "github.com/kyverno/kyverno/pkg/controllers/certmanager" configcontroller "github.com/kyverno/kyverno/pkg/controllers/config" policymetricscontroller "github.com/kyverno/kyverno/pkg/controllers/metrics/policy" + openapicontroller "github.com/kyverno/kyverno/pkg/controllers/openapi" policycachecontroller "github.com/kyverno/kyverno/pkg/controllers/policycache" admissionreportcontroller "github.com/kyverno/kyverno/pkg/controllers/report/admission" aggregatereportcontroller "github.com/kyverno/kyverno/pkg/controllers/report/aggregate" @@ -303,14 +304,14 @@ func createNonLeaderControllers( configuration config.Configuration, policyCache policycache.Cache, eventGenerator event.Interface, - manager *openapi.Manager, + manager openapi.Manager, ) ([]controller, func() error) { policyCacheController := policycachecontroller.NewController( policyCache, kyvernoInformer.Kyverno().V1().ClusterPolicies(), kyvernoInformer.Kyverno().V1().Policies(), ) - openApiController := openapi.NewCRDSync( + openApiController := openapicontroller.NewController( dynamicClient, manager, ) @@ -558,7 +559,7 @@ func main() { logger.Error(err, "failed to initialize configuration") os.Exit(1) } - openApiManager, err := openapi.NewOpenAPIManager() + openApiManager, err := openapi.NewManager() if err != nil { logger.Error(err, "Failed to create openapi manager") os.Exit(1) diff --git a/pkg/openapi/crdSync.go b/pkg/controllers/openapi/controller.go similarity index 70% rename from pkg/openapi/crdSync.go rename to pkg/controllers/openapi/controller.go index a3734f3608..e8b3db8c16 100644 --- a/pkg/openapi/crdSync.go +++ b/pkg/controllers/openapi/controller.go @@ -7,6 +7,7 @@ import ( "time" "github.com/kyverno/kyverno/pkg/clients/dclient" + "github.com/kyverno/kyverno/pkg/controllers" "github.com/kyverno/kyverno/pkg/logging" "github.com/kyverno/kyverno/pkg/metrics" util "github.com/kyverno/kyverno/pkg/utils" @@ -17,55 +18,33 @@ import ( "k8s.io/client-go/discovery" ) -type crdSync struct { +type Controller interface { + controllers.Controller + CheckSync(context.Context) +} + +type controller struct { client dclient.Interface - manager *Manager + manager Manager } const ( skipErrorMsg = "Got empty response for" ) -// crdDefinitionPrior represents CRDs version prior to 1.16 -var crdDefinitionPrior struct { - Spec struct { - Names struct { - Kind string `json:"kind"` - } `json:"names"` - Validation struct { - OpenAPIV3Schema interface{} `json:"openAPIV3Schema"` - } `json:"validation"` - } `json:"spec"` -} - -// crdDefinitionNew represents CRDs version 1.16+ -var crdDefinitionNew struct { - Spec struct { - Names struct { - Kind string `json:"kind"` - } `json:"names"` - Versions []struct { - Schema struct { - OpenAPIV3Schema interface{} `json:"openAPIV3Schema"` - } `json:"schema"` - Storage bool `json:"storage"` - } `json:"versions"` - } `json:"spec"` -} - -// NewCRDSync ... -func NewCRDSync(client dclient.Interface, mgr *Manager) *crdSync { +// NewController ... +func NewController(client dclient.Interface, mgr Manager) Controller { if mgr == nil { panic(fmt.Errorf("nil manager sent into crd sync")) } - return &crdSync{ + return &controller{ manager: mgr, client: client, } } -func (c *crdSync) Run(ctx context.Context, workers int) { +func (c *controller) Run(ctx context.Context, workers int) { if err := c.updateInClusterKindToAPIVersions(); err != nil { logging.Error(err, "failed to update in-cluster api versions") } @@ -75,7 +54,7 @@ func (c *crdSync) Run(ctx context.Context, workers int) { logging.Error(err, "cannot get OpenAPI schema") } - err = c.manager.useOpenAPIDocument(newDoc) + err = c.manager.UseOpenAPIDocument(newDoc) if err != nil { logging.Error(err, "Could not set custom OpenAPI document") } @@ -86,7 +65,7 @@ func (c *crdSync) Run(ctx context.Context, workers int) { } } -func (c *crdSync) sync() { +func (c *controller) sync() { c.client.Discovery().DiscoveryCache().Invalidate() crds, err := c.client.GetDynamicInterface().Resource(runtimeSchema.GroupVersionResource{ Group: "apiextensions.k8s.io", @@ -100,7 +79,7 @@ func (c *crdSync) sync() { return } - c.manager.deleteCRDFromPreviousSync() + c.manager.DeleteCRDFromPreviousSync() for _, crd := range crds.Items { c.manager.ParseCRD(crd) @@ -115,13 +94,13 @@ func (c *crdSync) sync() { logging.Error(err, "cannot get OpenAPI schema") } - err = c.manager.useOpenAPIDocument(newDoc) + err = c.manager.UseOpenAPIDocument(newDoc) if err != nil { logging.Error(err, "Could not set custom OpenAPI document") } } -func (c *crdSync) updateInClusterKindToAPIVersions() error { +func (c *controller) updateInClusterKindToAPIVersions() error { util.OverrideRuntimeErrorHandler() _, apiResourceLists, err := discovery.ServerGroupsAndResources(c.client.Discovery().DiscoveryInterface()) @@ -133,11 +112,11 @@ func (c *crdSync) updateInClusterKindToAPIVersions() error { return errors.Wrapf(err, "fetching API server preferreds resources") } - c.manager.updateKindToAPIVersions(apiResourceLists, preferredAPIResourcesLists) + c.manager.UpdateKindToAPIVersions(apiResourceLists, preferredAPIResourcesLists) return nil } -func (c *crdSync) CheckSync(ctx context.Context) { +func (c *controller) CheckSync(ctx context.Context) { crds, err := c.client.GetDynamicInterface().Resource(runtimeSchema.GroupVersionResource{ Group: "apiextensions.k8s.io", Version: "v1", @@ -147,7 +126,7 @@ func (c *crdSync) CheckSync(ctx context.Context) { logging.Error(err, "could not fetch crd's from server") return } - if len(c.manager.crdList) != len(crds.Items) { + if len(c.manager.GetCrdList()) != len(crds.Items) { c.sync() } } diff --git a/pkg/controllers/openapi/manager.go b/pkg/controllers/openapi/manager.go new file mode 100644 index 0000000000..4b4c41abda --- /dev/null +++ b/pkg/controllers/openapi/manager.go @@ -0,0 +1,15 @@ +package openapi + +import ( + openapiv2 "github.com/google/gnostic/openapiv2" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" +) + +type Manager interface { + UseOpenAPIDocument(*openapiv2.Document) error + DeleteCRDFromPreviousSync() + ParseCRD(unstructured.Unstructured) + UpdateKindToAPIVersions([]*metav1.APIResourceList, []*metav1.APIResourceList) + GetCrdList() []string +} diff --git a/pkg/openapi/definitions.go b/pkg/openapi/definitions.go new file mode 100644 index 0000000000..7d8838bed5 --- /dev/null +++ b/pkg/openapi/definitions.go @@ -0,0 +1,28 @@ +package openapi + +// crdDefinitionPrior represents CRDs version prior to 1.16 +var crdDefinitionPrior struct { + Spec struct { + Names struct { + Kind string `json:"kind"` + } `json:"names"` + Validation struct { + OpenAPIV3Schema interface{} `json:"openAPIV3Schema"` + } `json:"validation"` + } `json:"spec"` +} + +// crdDefinitionNew represents CRDs version 1.16+ +var crdDefinitionNew struct { + Spec struct { + Names struct { + Kind string `json:"kind"` + } `json:"names"` + Versions []struct { + Schema struct { + OpenAPIV3Schema interface{} `json:"openAPIV3Schema"` + } `json:"schema"` + Storage bool `json:"storage"` + } `json:"versions"` + } `json:"spec"` +} diff --git a/pkg/openapi/fake.go b/pkg/openapi/fake.go index 728978b90e..e6d2fc8bc0 100644 --- a/pkg/openapi/fake.go +++ b/pkg/openapi/fake.go @@ -1,6 +1,9 @@ package openapi -import "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" +import ( + kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" +) func NewFake() ValidateInterface { return &fakeValidation{} @@ -11,3 +14,7 @@ type fakeValidation struct{} func (f *fakeValidation) ValidateResource(resource unstructured.Unstructured, apiVersion, kind string) error { return nil } + +func (f *fakeValidation) ValidatePolicyMutation(kyvernov1.PolicyInterface) error { + return nil +} diff --git a/pkg/openapi/manager.go b/pkg/openapi/manager.go index 108e19137e..ceb7d710e6 100644 --- a/pkg/openapi/manager.go +++ b/pkg/openapi/manager.go @@ -9,6 +9,7 @@ import ( 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" @@ -21,10 +22,16 @@ import ( ) type ValidateInterface interface { - ValidateResource(resource unstructured.Unstructured, apiVersion, kind string) error + ValidateResource(unstructured.Unstructured, string, string) error + ValidatePolicyMutation(kyvernov1.PolicyInterface) error } -type Manager struct { +type Manager interface { + ValidateInterface + openapicontroller.Manager +} + +type manager struct { // definitions holds the map of {definitionName: *openapiv2.Schema} definitions cmap.ConcurrentMap[*openapiv2.Schema] @@ -49,9 +56,9 @@ type apiVersions struct { gvks []string } -// NewOpenAPIManager initializes a new instance of openapi schema manager -func NewOpenAPIManager() (*Manager, error) { - mgr := &Manager{ +// NewManager initializes a new instance of openapi schema manager +func NewManager() (*manager, error) { + mgr := &manager{ definitions: cmap.New[*openapiv2.Schema](), gvkToDefinitionName: cmap.New[string](), kindToAPIVersions: cmap.New[apiVersions](), @@ -62,14 +69,14 @@ func NewOpenAPIManager() (*Manager, error) { return nil, err } - mgr.updateKindToAPIVersions(apiResourceLists, preferredAPIResourcesLists) + mgr.UpdateKindToAPIVersions(apiResourceLists, preferredAPIResourcesLists) defaultDoc, err := getSchemaDocument() if err != nil { return nil, err } - err = mgr.useOpenAPIDocument(defaultDoc) + err = mgr.UseOpenAPIDocument(defaultDoc) if err != nil { return nil, err } @@ -78,7 +85,7 @@ func NewOpenAPIManager() (*Manager, error) { } // ValidateResource ... -func (o *Manager) ValidateResource(patchedResource unstructured.Unstructured, apiVersion, kind string) error { +func (o *manager) ValidateResource(patchedResource unstructured.Unstructured, apiVersion, kind string) error { var err error gvk := kind @@ -110,7 +117,7 @@ func (o *Manager) ValidateResource(patchedResource unstructured.Unstructured, ap } // ValidatePolicyMutation ... -func (o *Manager) ValidatePolicyMutation(policy kyvernov1.PolicyInterface) error { +func (o *manager) ValidatePolicyMutation(policy kyvernov1.PolicyInterface) error { kindToRules := make(map[string][]kyvernov1.Rule) for _, rule := range autogen.ComputeRules(policy) { if rule.HasMutate() { @@ -151,7 +158,7 @@ func (o *Manager) ValidatePolicyMutation(policy kyvernov1.PolicyInterface) error return nil } -func (o *Manager) useOpenAPIDocument(doc *openapiv2.Document) error { +func (o *manager) UseOpenAPIDocument(doc *openapiv2.Document) error { for _, definition := range doc.GetDefinitions().AdditionalProperties { definitionName := definition.GetName() @@ -183,7 +190,7 @@ func (o *Manager) useOpenAPIDocument(doc *openapiv2.Document) error { return nil } -func (o *Manager) getGVKByDefinitionName(definitionName string) (gvk string, preferredGVK bool, err error) { +func (o *manager) getGVKByDefinitionName(definitionName string) (gvk string, preferredGVK bool, err error) { paths := strings.Split(definitionName, ".") kind := paths[len(paths)-1] versions, ok := o.kindToAPIVersions.Get(kind) @@ -206,8 +213,12 @@ func (o *Manager) getGVKByDefinitionName(definitionName string) (gvk string, pre return "", preferredGVK, fmt.Errorf("gvk not found by the given definition name %s, %v", definitionName, versions.gvks) } -// updateKindToAPIVersions sets kindToAPIVersions with static manifests -func (c *Manager) updateKindToAPIVersions(apiResourceLists, preferredAPIResourcesLists []*metav1.APIResourceList) { +func (c *manager) GetCrdList() []string { + return c.crdList +} + +// UpdateKindToAPIVersions sets kindToAPIVersions with static manifests +func (c *manager) UpdateKindToAPIVersions(apiResourceLists, preferredAPIResourcesLists []*metav1.APIResourceList) { tempKindToAPIVersions := getAllAPIVersions(apiResourceLists) tempKindToAPIVersions = setPreferredVersions(tempKindToAPIVersions, preferredAPIResourcesLists) @@ -218,7 +229,7 @@ func (c *Manager) updateKindToAPIVersions(apiResourceLists, preferredAPIResource } // For crd, we do not store definition in document -func (o *Manager) getCRDSchema(kind string) (proto.Schema, error) { +func (o *manager) getCRDSchema(kind string) (proto.Schema, error) { if kind == "" { return nil, errors.New("invalid kind") } @@ -238,7 +249,7 @@ func (o *Manager) getCRDSchema(kind string) (proto.Schema, error) { return (existingDefinitions).ParseSchema(definition, &path) } -func (o *Manager) generateEmptyResource(kindSchema *openapiv2.Schema) interface{} { +func (o *manager) generateEmptyResource(kindSchema *openapiv2.Schema) interface{} { types := kindSchema.GetType().GetValue() if kindSchema.GetXRef() != "" { @@ -273,7 +284,7 @@ func (o *Manager) generateEmptyResource(kindSchema *openapiv2.Schema) interface{ return nil } -func (o *Manager) deleteCRDFromPreviousSync() { +func (o *manager) DeleteCRDFromPreviousSync() { for _, crd := range o.crdList { o.gvkToDefinitionName.Remove(crd) o.definitions.Remove(crd) @@ -283,7 +294,7 @@ func (o *Manager) deleteCRDFromPreviousSync() { } // ParseCRD loads CRD to the cache -func (o *Manager) ParseCRD(crd unstructured.Unstructured) { +func (o *manager) ParseCRD(crd unstructured.Unstructured) { var err error crdRaw, _ := json.Marshal(crd.Object) diff --git a/pkg/openapi/manager_test.go b/pkg/openapi/manager_test.go index 2a98031d15..dae3167320 100644 --- a/pkg/openapi/manager_test.go +++ b/pkg/openapi/manager_test.go @@ -41,7 +41,7 @@ func Test_ValidateMutationPolicy(t *testing.T) { }, } - o, _ := NewOpenAPIManager() + o, _ := NewManager() for i, tc := range tcs { policy := v1.ClusterPolicy{} @@ -165,7 +165,7 @@ func Test_matchGVK(t *testing.T) { // networking.k8s.io/v1beta1/Ingress // extensions/v1beta1/Ingress func Test_Ingress(t *testing.T) { - o, err := NewOpenAPIManager() + o, err := NewManager() assert.NilError(t, err) versions, ok := o.kindToAPIVersions.Get("Ingress") diff --git a/pkg/openapi/utils.go b/pkg/openapi/utils.go index 1b4f43183f..e9f63e100b 100644 --- a/pkg/openapi/utils.go +++ b/pkg/openapi/utils.go @@ -81,7 +81,7 @@ func getSchemaDocument() (*openapiv2.Document, error) { return openapiv2.NewDocument(root, compiler.NewContext("$root", root, nil)) } -func getArrayValue(kindSchema *openapiv2.Schema, o *Manager) interface{} { +func getArrayValue(kindSchema *openapiv2.Schema, o *manager) interface{} { var array []interface{} for _, schema := range kindSchema.GetItems().GetSchema() { array = append(array, o.generateEmptyResource(schema)) @@ -90,7 +90,7 @@ func getArrayValue(kindSchema *openapiv2.Schema, o *Manager) interface{} { return array } -func getObjectValue(kindSchema *openapiv2.Schema, o *Manager) interface{} { +func getObjectValue(kindSchema *openapiv2.Schema, o *manager) interface{} { props := make(map[string]interface{}) properties := kindSchema.GetProperties().GetAdditionalProperties() if len(properties) == 0 { diff --git a/pkg/policy/validate.go b/pkg/policy/validate.go index 4dca0a77a0..631c714d67 100644 --- a/pkg/policy/validate.go +++ b/pkg/policy/validate.go @@ -17,6 +17,7 @@ import ( "github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/utils/common" "github.com/kyverno/kyverno/pkg/autogen" "github.com/kyverno/kyverno/pkg/clients/dclient" + openapicontroller "github.com/kyverno/kyverno/pkg/controllers/openapi" enginecontext "github.com/kyverno/kyverno/pkg/engine/context" "github.com/kyverno/kyverno/pkg/engine/variables" "github.com/kyverno/kyverno/pkg/logging" @@ -79,13 +80,13 @@ func validateJSONPatchPathForForwardSlash(patch string) error { } // Validate checks the policy and rules declarations for required configurations -func Validate(policy kyvernov1.PolicyInterface, client dclient.Interface, mock bool, openApiManager *openapi.Manager) (*admissionv1.AdmissionResponse, error) { +func Validate(policy kyvernov1.PolicyInterface, client dclient.Interface, mock bool, openApiManager openapi.Manager) (*admissionv1.AdmissionResponse, error) { namespaced := policy.IsNamespaced() spec := policy.GetSpec() background := spec.BackgroundProcessingEnabled() onPolicyUpdate := spec.GetMutateExistingOnPolicyUpdate() if !mock { - openapi.NewCRDSync(client, openApiManager).CheckSync(context.TODO()) + openapicontroller.NewController(client, openApiManager).CheckSync(context.TODO()) } var errs field.ErrorList diff --git a/pkg/policy/validate_test.go b/pkg/policy/validate_test.go index 5675f32a0f..efa2a0bbc7 100644 --- a/pkg/policy/validate_test.go +++ b/pkg/policy/validate_test.go @@ -345,12 +345,12 @@ func Test_Validate_Policy(t *testing.T) { } }`) - openAPIController, _ := openapi.NewOpenAPIManager() + openApiManager, _ := openapi.NewManager() var policy *kyverno.ClusterPolicy err := json.Unmarshal(rawPolicy, &policy) assert.NilError(t, err) - _, err = Validate(policy, nil, true, openAPIController) + _, err = Validate(policy, nil, true, openApiManager) assert.NilError(t, err) } @@ -496,8 +496,8 @@ func Test_Validate_ErrorFormat(t *testing.T) { err := json.Unmarshal(rawPolicy, &policy) assert.NilError(t, err) - openAPIController, _ := openapi.NewOpenAPIManager() - _, err = Validate(policy, nil, true, openAPIController) + openApiManager, _ := openapi.NewManager() + _, err = Validate(policy, nil, true, openApiManager) assert.Assert(t, err != nil) } @@ -898,8 +898,8 @@ func Test_Validate_Kind(t *testing.T) { err := json.Unmarshal(rawPolicy, &policy) assert.NilError(t, err) - openAPIController, _ := openapi.NewOpenAPIManager() - _, err = Validate(policy, nil, true, openAPIController) + openApiManager, _ := openapi.NewManager() + _, err = Validate(policy, nil, true, openApiManager) assert.Assert(t, err != nil) } @@ -947,8 +947,8 @@ func Test_Validate_Any_Kind(t *testing.T) { err := json.Unmarshal(rawPolicy, &policy) assert.NilError(t, err) - openAPIController, _ := openapi.NewOpenAPIManager() - _, err = Validate(policy, nil, true, openAPIController) + openApiManager, _ := openapi.NewManager() + _, err = Validate(policy, nil, true, openApiManager) assert.Assert(t, err != nil) } @@ -1075,8 +1075,8 @@ func Test_Wildcards_Kind(t *testing.T) { err := json.Unmarshal(rawPolicy, &policy) assert.NilError(t, err) - openAPIController, _ := openapi.NewOpenAPIManager() - _, err = Validate(policy, nil, true, openAPIController) + openApiManager, _ := openapi.NewManager() + _, err = Validate(policy, nil, true, openApiManager) assert.Assert(t, err != nil) } @@ -1125,8 +1125,8 @@ func Test_Namespced_Policy(t *testing.T) { err := json.Unmarshal(rawPolicy, &policy) assert.NilError(t, err) - openAPIController, _ := openapi.NewOpenAPIManager() - _, err = Validate(policy, nil, true, openAPIController) + openApiManager, _ := openapi.NewManager() + _, err = Validate(policy, nil, true, openApiManager) assert.Assert(t, err != nil) } @@ -1173,8 +1173,8 @@ func Test_patchesJson6902_Policy(t *testing.T) { err := json.Unmarshal(rawPolicy, &policy) assert.NilError(t, err) - openAPIController, _ := openapi.NewOpenAPIManager() - _, err = Validate(policy, nil, true, openAPIController) + openApiManager, _ := openapi.NewManager() + _, err = Validate(policy, nil, true, openApiManager) assert.NilError(t, err) } @@ -1221,8 +1221,8 @@ func Test_deny_exec(t *testing.T) { err = json.Unmarshal(rawPolicy, &policy) assert.NilError(t, err) - openAPIController, _ := openapi.NewOpenAPIManager() - _, err = Validate(policy, nil, true, openAPIController) + openApiManager, _ := openapi.NewManager() + _, err = Validate(policy, nil, true, openApiManager) assert.NilError(t, err) } @@ -1266,8 +1266,8 @@ func Test_existing_resource_policy(t *testing.T) { err = json.Unmarshal(rawPolicy, &policy) assert.NilError(t, err) - openAPIController, _ := openapi.NewOpenAPIManager() - _, err = Validate(policy, nil, true, openAPIController) + openApiManager, _ := openapi.NewManager() + _, err = Validate(policy, nil, true, openApiManager) assert.NilError(t, err) } @@ -1322,8 +1322,8 @@ func Test_PodControllerAutoGenExclusion_All_Controllers_Policy(t *testing.T) { err := json.Unmarshal(rawPolicy, &policy) assert.NilError(t, err) - openAPIController, _ := openapi.NewOpenAPIManager() - res, err := Validate(policy, nil, true, openAPIController) + openApiManager, _ := openapi.NewManager() + res, err := Validate(policy, nil, true, openApiManager) assert.NilError(t, err) assert.Assert(t, res == nil) } @@ -1379,8 +1379,8 @@ func Test_PodControllerAutoGenExclusion_Not_All_Controllers_Policy(t *testing.T) err := json.Unmarshal(rawPolicy, &policy) assert.NilError(t, err) - openAPIController, _ := openapi.NewOpenAPIManager() - res, err := Validate(policy, nil, true, openAPIController) + openApiManager, _ := openapi.NewManager() + res, err := Validate(policy, nil, true, openApiManager) if res != nil { assert.Assert(t, res.Warnings != nil) } @@ -1438,8 +1438,8 @@ func Test_PodControllerAutoGenExclusion_None_Policy(t *testing.T) { err := json.Unmarshal(rawPolicy, &policy) assert.NilError(t, err) - openAPIController, _ := openapi.NewOpenAPIManager() - res, err := Validate(policy, nil, true, openAPIController) + openApiManager, _ := openapi.NewManager() + res, err := Validate(policy, nil, true, openApiManager) if res != nil { assert.Assert(t, res.Warnings != nil) } diff --git a/pkg/webhooks/policy/handlers.go b/pkg/webhooks/policy/handlers.go index c6bdefb607..0a1700f699 100644 --- a/pkg/webhooks/policy/handlers.go +++ b/pkg/webhooks/policy/handlers.go @@ -18,13 +18,13 @@ import ( type handlers struct { client dclient.Interface - openApiManager *openapi.Manager + openApiManager openapi.Manager } -func NewHandlers(client dclient.Interface, openAPIController *openapi.Manager) webhooks.PolicyHandlers { +func NewHandlers(client dclient.Interface, openApiManager openapi.Manager) webhooks.PolicyHandlers { return &handlers{ client: client, - openApiManager: openAPIController, + openApiManager: openApiManager, } } diff --git a/pkg/webhooks/resource/fake.go b/pkg/webhooks/resource/fake.go index 0b13e1231d..d1dc1632ce 100644 --- a/pkg/webhooks/resource/fake.go +++ b/pkg/webhooks/resource/fake.go @@ -36,18 +36,18 @@ func NewFakeHandlers(ctx context.Context, policyCache policycache.Cache) webhook urLister := kyvernoInformers.Kyverno().V1beta1().UpdateRequests().Lister().UpdateRequests(config.KyvernoNamespace()) return &handlers{ - client: dclient, - configuration: configuration, - metricsConfig: metricsConfig, - pCache: policyCache, - nsLister: informers.Core().V1().Namespaces().Lister(), - rbLister: rbLister, - crbLister: crbLister, - urLister: urLister, - urGenerator: updaterequest.NewFake(), - eventGen: event.NewFake(), - openAPIController: openapi.NewFake(), - pcBuilder: webhookutils.NewPolicyContextBuilder(configuration, dclient, rbLister, crbLister), - urUpdater: webhookutils.NewUpdateRequestUpdater(kyvernoclient, urLister), + client: dclient, + configuration: configuration, + metricsConfig: metricsConfig, + pCache: policyCache, + nsLister: informers.Core().V1().Namespaces().Lister(), + rbLister: rbLister, + crbLister: crbLister, + urLister: urLister, + urGenerator: updaterequest.NewFake(), + eventGen: event.NewFake(), + openApiManager: openapi.NewFake(), + pcBuilder: webhookutils.NewPolicyContextBuilder(configuration, dclient, rbLister, crbLister), + urUpdater: webhookutils.NewUpdateRequestUpdater(kyvernoclient, urLister), } } diff --git a/pkg/webhooks/resource/handlers.go b/pkg/webhooks/resource/handlers.go index 1923f4cb30..abf2b51c51 100644 --- a/pkg/webhooks/resource/handlers.go +++ b/pkg/webhooks/resource/handlers.go @@ -49,11 +49,11 @@ type handlers struct { crbLister rbacv1listers.ClusterRoleBindingLister urLister kyvernov1beta1listers.UpdateRequestNamespaceLister - urGenerator webhookgenerate.Generator - eventGen event.Interface - openAPIController openapi.ValidateInterface - pcBuilder webhookutils.PolicyContextBuilder - urUpdater webhookutils.UpdateRequestUpdater + urGenerator webhookgenerate.Generator + eventGen event.Interface + openApiManager openapi.ValidateInterface + pcBuilder webhookutils.PolicyContextBuilder + urUpdater webhookutils.UpdateRequestUpdater admissionReports bool } @@ -70,25 +70,25 @@ func NewHandlers( urLister kyvernov1beta1listers.UpdateRequestNamespaceLister, urGenerator webhookgenerate.Generator, eventGen event.Interface, - openAPIController openapi.ValidateInterface, + openApiManager openapi.ValidateInterface, admissionReports bool, ) webhooks.ResourceHandlers { return &handlers{ - client: client, - kyvernoClient: kyvernoClient, - configuration: configuration, - metricsConfig: metricsConfig, - pCache: pCache, - nsLister: nsLister, - rbLister: rbLister, - crbLister: crbLister, - urLister: urLister, - urGenerator: urGenerator, - eventGen: eventGen, - openAPIController: openAPIController, - pcBuilder: webhookutils.NewPolicyContextBuilder(configuration, client, rbLister, crbLister), - urUpdater: webhookutils.NewUpdateRequestUpdater(kyvernoClient, urLister), - admissionReports: admissionReports, + client: client, + kyvernoClient: kyvernoClient, + configuration: configuration, + metricsConfig: metricsConfig, + pCache: pCache, + nsLister: nsLister, + rbLister: rbLister, + crbLister: crbLister, + urLister: urLister, + urGenerator: urGenerator, + eventGen: eventGen, + openApiManager: openApiManager, + pcBuilder: webhookutils.NewPolicyContextBuilder(configuration, client, rbLister, crbLister), + urUpdater: webhookutils.NewUpdateRequestUpdater(kyvernoClient, urLister), + admissionReports: admissionReports, } } @@ -174,7 +174,7 @@ func (h *handlers) Mutate(logger logr.Logger, request *admissionv1.AdmissionRequ logger.Error(err, "failed to patch images info to resource, policies that mutate images may be impacted") } - mh := mutation.NewMutationHandler(logger, h.eventGen, h.openAPIController, h.nsLister) + mh := mutation.NewMutationHandler(logger, h.eventGen, h.openApiManager, h.nsLister) mutatePatches, mutateWarnings, err := mh.HandleMutation(h.metricsConfig, request, mutatePolicies, policyContext, startTime) if err != nil { logger.Error(err, "mutation failed") diff --git a/pkg/webhooks/resource/mutation/mutation.go b/pkg/webhooks/resource/mutation/mutation.go index fe8e801830..0a079fe141 100644 --- a/pkg/webhooks/resource/mutation/mutation.go +++ b/pkg/webhooks/resource/mutation/mutation.go @@ -41,22 +41,22 @@ type MutationHandler interface { func NewMutationHandler( log logr.Logger, eventGen event.Interface, - openAPIController openapi.ValidateInterface, + openApiManager openapi.ValidateInterface, nsLister corev1listers.NamespaceLister, ) MutationHandler { return &mutationHandler{ - log: log, - eventGen: eventGen, - openAPIController: openAPIController, - nsLister: nsLister, + log: log, + eventGen: eventGen, + openApiManager: openApiManager, + nsLister: nsLister, } } type mutationHandler struct { - log logr.Logger - eventGen event.Interface - openAPIController openapi.ValidateInterface - nsLister corev1listers.NamespaceLister + log logr.Logger + eventGen event.Interface + openApiManager openapi.ValidateInterface + nsLister corev1listers.NamespaceLister } func (h *mutationHandler) HandleMutation( @@ -157,7 +157,7 @@ func (h *mutationHandler) applyMutation(request *admissionv1.AdmissionRequest, p } if engineResponse.PatchedResource.GetKind() != "*" { - err := h.openAPIController.ValidateResource(*engineResponse.PatchedResource.DeepCopy(), engineResponse.PatchedResource.GetAPIVersion(), engineResponse.PatchedResource.GetKind()) + err := h.openApiManager.ValidateResource(*engineResponse.PatchedResource.DeepCopy(), engineResponse.PatchedResource.GetAPIVersion(), engineResponse.PatchedResource.GetKind()) if err != nil { return nil, nil, errors.Wrapf(err, "failed to validate resource mutated by policy %s", policyContext.Policy.GetName()) }