From 40a6a1d7126e10a6f7c9240edc36c77909367155 Mon Sep 17 00:00:00 2001 From: Dean Coakley Date: Thu, 17 Dec 2020 05:26:45 +0000 Subject: [PATCH 1/3] Update policy and accessControl apiVersion to v1 --- .../crds-v1beta1/k8s.nginx.org_policies.yaml | 4 +- .../common/crds/k8s.nginx.org_policies.yaml | 2 +- .../crds/k8s.nginx.org_policies.yaml | 4 +- docs-web/configuration/policy-resource.md | 14 +- .../access-control-policy-allow.yaml | 2 +- .../access-control-policy-deny.yaml | 2 +- .../egress-mtls/egress-mtls.yaml | 2 +- .../ingress-mtls/ingress-mtls.yaml | 2 +- examples-of-custom-resources/jwt/jwt.yaml | 2 +- .../rate-limit/rate-limit.yaml | 2 +- internal/configs/virtualserver.go | 20 +- internal/configs/virtualserver_test.go | 173 +++++++------ internal/k8s/controller.go | 56 ++--- internal/k8s/controller_test.go | 171 +++++++------ internal/k8s/handlers.go | 8 +- internal/k8s/task_queue.go | 4 +- pkg/apis/configuration/v1/register.go | 2 + pkg/apis/configuration/v1/types.go | 80 ++++++ .../configuration/v1/zz_generated.deepcopy.go | 231 ++++++++++++++++++ pkg/apis/configuration/v1alpha1/register.go | 2 - pkg/apis/configuration/v1alpha1/types.go | 80 ------ .../v1alpha1/zz_generated.deepcopy.go | 231 ------------------ pkg/apis/configuration/validation/policy.go | 16 +- .../configuration/validation/policy_test.go | 118 ++++----- .../configuration/v1/configuration_client.go | 5 + .../v1/fake/fake_configuration_client.go | 4 + .../{v1alpha1 => v1}/fake/fake_policy.go | 44 ++-- .../configuration/v1/generated_expansion.go | 2 + .../configuration/{v1alpha1 => v1}/policy.go | 50 ++-- .../v1alpha1/configuration_client.go | 5 - .../fake/fake_configuration_client.go | 4 - .../v1alpha1/generated_expansion.go | 2 - .../configuration/v1/interface.go | 7 + .../configuration/{v1alpha1 => v1}/policy.go | 26 +- .../configuration/v1alpha1/interface.go | 7 - .../informers/externalversions/generic.go | 4 +- .../configuration/v1/expansion_generated.go | 8 + .../configuration/{v1alpha1 => v1}/policy.go | 24 +- .../v1alpha1/expansion_generated.go | 8 - 39 files changed, 716 insertions(+), 712 deletions(-) rename pkg/client/clientset/versioned/typed/configuration/{v1alpha1 => v1}/fake/fake_policy.go (68%) rename pkg/client/clientset/versioned/typed/configuration/{v1alpha1 => v1}/policy.go (66%) rename pkg/client/informers/externalversions/configuration/{v1alpha1 => v1}/policy.go (73%) rename pkg/client/listers/configuration/{v1alpha1 => v1}/policy.go (78%) diff --git a/deployments/common/crds-v1beta1/k8s.nginx.org_policies.yaml b/deployments/common/crds-v1beta1/k8s.nginx.org_policies.yaml index 7ff5910d6a..3aa8b45331 100644 --- a/deployments/common/crds-v1beta1/k8s.nginx.org_policies.yaml +++ b/deployments/common/crds-v1beta1/k8s.nginx.org_policies.yaml @@ -109,9 +109,9 @@ spec: type: integer zoneSize: type: string - version: v1alpha1 + version: v1 versions: - - name: v1alpha1 + - name: v1 served: true storage: true status: diff --git a/deployments/common/crds/k8s.nginx.org_policies.yaml b/deployments/common/crds/k8s.nginx.org_policies.yaml index c2caa8dc09..11e964152e 100644 --- a/deployments/common/crds/k8s.nginx.org_policies.yaml +++ b/deployments/common/crds/k8s.nginx.org_policies.yaml @@ -16,7 +16,7 @@ spec: singular: policy scope: Namespaced versions: - - name: v1alpha1 + - name: v1 schema: openAPIV3Schema: description: Policy defines a Policy for VirtualServer and VirtualServerRoute resources. diff --git a/deployments/helm-chart/crds/k8s.nginx.org_policies.yaml b/deployments/helm-chart/crds/k8s.nginx.org_policies.yaml index 7ff5910d6a..3aa8b45331 100644 --- a/deployments/helm-chart/crds/k8s.nginx.org_policies.yaml +++ b/deployments/helm-chart/crds/k8s.nginx.org_policies.yaml @@ -109,9 +109,9 @@ spec: type: integer zoneSize: type: string - version: v1alpha1 + version: v1 versions: - - name: v1alpha1 + - name: v1 served: true storage: true status: diff --git a/docs-web/configuration/policy-resource.md b/docs-web/configuration/policy-resource.md index e0256b2b90..90896a152a 100644 --- a/docs-web/configuration/policy-resource.md +++ b/docs-web/configuration/policy-resource.md @@ -6,8 +6,6 @@ The resource is implemented as a [Custom Resource](https://kubernetes.io/docs/co This document is the reference documentation for the Policy resource. An example of a Policy for access control is available in our [GitHub repo](https://github.com/nginxinc/kubernetes-ingress/blob/master/examples-of-custom-resources/access-control). -> **Feature Status**: The Policy resource is available as a preview feature: it is suitable for experimenting and testing; however, it must be used with caution in production environments. Additionally, while the feature is in preview, we might introduce some backward-incompatible changes to the resource specification in the next releases. - ## Contents - [Policy Resource](#policy-resource) @@ -39,7 +37,7 @@ Policies work together with [VirtualServer and VirtualServerRoute resources](/ng Below is an example of a policy that allows access for clients from the subnet `10.0.0.0/8` and denies access for any other clients: ```yaml -apiVersion: k8s.nginx.org/v1alpha1 +apiVersion: k8s.nginx.org/v1 kind: Policy metadata: name: allow-localhost @@ -140,6 +138,8 @@ policies: ### RateLimit +> **Feature Status**: Rate-Limiting is available as a preview feature: it is suitable for experimenting and testing; however, it must be used with caution in production environments. Additionally, while the feature is in preview status, we might introduce some backward-incompatible changes to the resource specification in the next releases. + The rate limit policy configures NGINX to limit the processing rate of requests. For example, the following policy will limit all subsequent requests coming from a single IP address once a rate of 10 requests per second is exceeded: @@ -212,6 +212,8 @@ When you reference more than one rate limit policy, the Ingress Controller will ### JWT +> **Feature Status**: JWT is available as a preview feature: it is suitable for experimenting and testing; however, it must be used with caution in production environments. Additionally, while the feature is in preview status, we might introduce some backward-incompatible changes to the resource specification in the next releases. + > Note: This feature is only available in NGINX Plus. The JWT policy configures NGINX Plus to authenticate client requests using JSON Web Tokens. @@ -277,6 +279,8 @@ In this example the Ingress Controller will use the configuration from the first ### IngressMTLS +> **Feature Status**: IngressMTLS is available as a preview feature: it is suitable for experimenting and testing; however, it must be used with caution in production environments. Additionally, while the feature is in preview status, we might introduce some backward-incompatible changes to the resource specification in the next releases. + The IngressMTLS policy configures client certificate verification. For example, the following policy will verify a client certificate using the CA certificate specified in the `ingress-mtls-secret`: @@ -343,6 +347,8 @@ In this example the Ingress Controller will use the configuration from the first ### EgressMTLS +> **Feature Status**: EgressMTLS is available as a preview feature: it is suitable for experimenting and testing; however, it must be used with caution in production environments. Additionally, while the feature is in preview status, we might introduce some backward-incompatible changes to the resource specification in the next releases. + The EgressMTLS policy configures upstreams authentication and certificate verification. For example, the following policy will use `egress-mtls-secret` to authenticate with the upstream application and `egress-trusted-ca-secret` to verify the certificate of the application: @@ -526,7 +532,7 @@ If you try to create (or update) a resource that violates the structural schema * Example of `kubectl` validation: ``` $ kubectl apply -f access-control-policy-allow.yaml - error: error validating "access-control-policy-allow.yaml": error validating data: ValidationError(Policy.spec.accessControl.allow): invalid type for org.nginx.k8s.v1alpha1.Policy.spec.accessControl.allow: got "string", expected "array"; if you choose to ignore these errors, turn validation off with --validate=false + error: error validating "access-control-policy-allow.yaml": error validating data: ValidationError(Policy.spec.accessControl.allow): invalid type for org.nginx.k8s.v1.Policy.spec.accessControl.allow: got "string", expected "array"; if you choose to ignore these errors, turn validation off with --validate=false ``` * Example of Kubernetes API server validation: ``` diff --git a/examples-of-custom-resources/access-control/access-control-policy-allow.yaml b/examples-of-custom-resources/access-control/access-control-policy-allow.yaml index 4b01f6d817..94db9288da 100644 --- a/examples-of-custom-resources/access-control/access-control-policy-allow.yaml +++ b/examples-of-custom-resources/access-control/access-control-policy-allow.yaml @@ -1,4 +1,4 @@ -apiVersion: k8s.nginx.org/v1alpha1 +apiVersion: k8s.nginx.org/v1 kind: Policy metadata: name: webapp-policy diff --git a/examples-of-custom-resources/access-control/access-control-policy-deny.yaml b/examples-of-custom-resources/access-control/access-control-policy-deny.yaml index bf85a2fe75..d34ac99f80 100644 --- a/examples-of-custom-resources/access-control/access-control-policy-deny.yaml +++ b/examples-of-custom-resources/access-control/access-control-policy-deny.yaml @@ -1,4 +1,4 @@ -apiVersion: k8s.nginx.org/v1alpha1 +apiVersion: k8s.nginx.org/v1 kind: Policy metadata: name: webapp-policy diff --git a/examples-of-custom-resources/egress-mtls/egress-mtls.yaml b/examples-of-custom-resources/egress-mtls/egress-mtls.yaml index e16cdf8bb7..304c093770 100644 --- a/examples-of-custom-resources/egress-mtls/egress-mtls.yaml +++ b/examples-of-custom-resources/egress-mtls/egress-mtls.yaml @@ -1,4 +1,4 @@ -apiVersion: k8s.nginx.org/v1alpha1 +apiVersion: k8s.nginx.org/v1 kind: Policy metadata: name: egress-mtls-policy diff --git a/examples-of-custom-resources/ingress-mtls/ingress-mtls.yaml b/examples-of-custom-resources/ingress-mtls/ingress-mtls.yaml index c6caedea89..af796bab1a 100644 --- a/examples-of-custom-resources/ingress-mtls/ingress-mtls.yaml +++ b/examples-of-custom-resources/ingress-mtls/ingress-mtls.yaml @@ -1,4 +1,4 @@ -apiVersion: k8s.nginx.org/v1alpha1 +apiVersion: k8s.nginx.org/v1 kind: Policy metadata: name: ingress-mtls-policy diff --git a/examples-of-custom-resources/jwt/jwt.yaml b/examples-of-custom-resources/jwt/jwt.yaml index 659cb7395a..de15af029d 100644 --- a/examples-of-custom-resources/jwt/jwt.yaml +++ b/examples-of-custom-resources/jwt/jwt.yaml @@ -1,4 +1,4 @@ -apiVersion: k8s.nginx.org/v1alpha1 +apiVersion: k8s.nginx.org/v1 kind: Policy metadata: name: jwt-policy diff --git a/examples-of-custom-resources/rate-limit/rate-limit.yaml b/examples-of-custom-resources/rate-limit/rate-limit.yaml index 90f33a7337..b56b8b141a 100644 --- a/examples-of-custom-resources/rate-limit/rate-limit.yaml +++ b/examples-of-custom-resources/rate-limit/rate-limit.yaml @@ -1,4 +1,4 @@ -apiVersion: k8s.nginx.org/v1alpha1 +apiVersion: k8s.nginx.org/v1 kind: Policy metadata: name: rate-limit-policy diff --git a/internal/configs/virtualserver.go b/internal/configs/virtualserver.go index 89f7e808f1..b03648ae85 100644 --- a/internal/configs/virtualserver.go +++ b/internal/configs/virtualserver.go @@ -57,7 +57,7 @@ type VirtualServerEx struct { Endpoints map[string][]string VirtualServerRoutes []*conf_v1.VirtualServerRoute ExternalNameSvcs map[string]bool - Policies map[string]*conf_v1alpha1.Policy + Policies map[string]*conf_v1.Policy PodsByIP map[string]PodInfo SecretRefs map[string]*secrets.SecretReference } @@ -629,7 +629,7 @@ func (v *validationResults) addWarningf(msgFmt string, args ...interface{}) { v.warnings = append(v.warnings, fmt.Sprintf(msgFmt, args...)) } -func (p *policiesCfg) addAccessControlConfig(accessControl *conf_v1alpha1.AccessControl) *validationResults { +func (p *policiesCfg) addAccessControlConfig(accessControl *conf_v1.AccessControl) *validationResults { res := newValidationResults() p.Allow = append(p.Allow, accessControl.Allow...) p.Deny = append(p.Deny, accessControl.Deny...) @@ -642,7 +642,7 @@ func (p *policiesCfg) addAccessControlConfig(accessControl *conf_v1alpha1.Access } func (p *policiesCfg) addRateLimitConfig( - rateLimit *conf_v1alpha1.RateLimit, + rateLimit *conf_v1.RateLimit, polKey string, polNamespace string, polName string, @@ -671,7 +671,7 @@ func (p *policiesCfg) addRateLimitConfig( } func (p *policiesCfg) addJWTAuthConfig( - jwtAuth *conf_v1alpha1.JWTAuth, + jwtAuth *conf_v1.JWTAuth, polKey string, polNamespace string, secretRefs map[string]*secrets.SecretReference, @@ -703,7 +703,7 @@ func (p *policiesCfg) addJWTAuthConfig( } func (p *policiesCfg) addIngressMTLSConfig( - ingressMTLS *conf_v1alpha1.IngressMTLS, + ingressMTLS *conf_v1.IngressMTLS, polKey string, polNamespace string, context string, @@ -756,7 +756,7 @@ func (p *policiesCfg) addIngressMTLSConfig( } func (p *policiesCfg) addEgressMTLSConfig( - egressMTLS *conf_v1alpha1.EgressMTLS, + egressMTLS *conf_v1.EgressMTLS, polKey string, polNamespace string, secretRefs map[string]*secrets.SecretReference, @@ -826,7 +826,7 @@ func (p *policiesCfg) addEgressMTLSConfig( func (vsc *virtualServerConfigurator) generatePolicies( ownerDetails policyOwnerDetails, policyRefs []conf_v1.PolicyReference, - policies map[string]*conf_v1alpha1.Policy, + policies map[string]*conf_v1.Policy, context string, policyOpts policyOptions, ) policiesCfg { @@ -887,7 +887,7 @@ func (vsc *virtualServerConfigurator) generatePolicies( return *config } -func generateLimitReq(zoneName string, rateLimitPol *conf_v1alpha1.RateLimit) version2.LimitReq { +func generateLimitReq(zoneName string, rateLimitPol *conf_v1.RateLimit) version2.LimitReq { var limitReq version2.LimitReq limitReq.ZoneName = zoneName @@ -907,7 +907,7 @@ func generateLimitReq(zoneName string, rateLimitPol *conf_v1alpha1.RateLimit) ve return limitReq } -func generateLimitReqZone(zoneName string, rateLimitPol *conf_v1alpha1.RateLimit) version2.LimitReqZone { +func generateLimitReqZone(zoneName string, rateLimitPol *conf_v1.RateLimit) version2.LimitReqZone { return version2.LimitReqZone{ ZoneName: zoneName, Key: rateLimitPol.Key, @@ -916,7 +916,7 @@ func generateLimitReqZone(zoneName string, rateLimitPol *conf_v1alpha1.RateLimit } } -func generateLimitReqOptions(rateLimitPol *conf_v1alpha1.RateLimit) version2.LimitReqOptions { +func generateLimitReqOptions(rateLimitPol *conf_v1.RateLimit) version2.LimitReqOptions { return version2.LimitReqOptions{ DryRun: generateBool(rateLimitPol.DryRun, false), LogLevel: generateString(rateLimitPol.LogLevel, "error"), diff --git a/internal/configs/virtualserver_test.go b/internal/configs/virtualserver_test.go index 070340cb5a..85657b32e6 100644 --- a/internal/configs/virtualserver_test.go +++ b/internal/configs/virtualserver_test.go @@ -11,7 +11,6 @@ import ( "github.com/nginxinc/kubernetes-ingress/internal/k8s/secrets" "github.com/nginxinc/kubernetes-ingress/internal/nginx" conf_v1 "github.com/nginxinc/kubernetes-ingress/pkg/apis/configuration/v1" - conf_v1alpha1 "github.com/nginxinc/kubernetes-ingress/pkg/apis/configuration/v1alpha1" api_v1 "k8s.io/api/core/v1" meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -1850,7 +1849,7 @@ func TestGeneratePolicies(t *testing.T) { tests := []struct { policyRefs []conf_v1.PolicyReference - policies map[string]*conf_v1alpha1.Policy + policies map[string]*conf_v1.Policy policyOpts policyOptions context string expected policiesCfg @@ -1863,10 +1862,10 @@ func TestGeneratePolicies(t *testing.T) { Namespace: "default", }, }, - policies: map[string]*conf_v1alpha1.Policy{ + policies: map[string]*conf_v1.Policy{ "default/allow-policy": { - Spec: conf_v1alpha1.PolicySpec{ - AccessControl: &conf_v1alpha1.AccessControl{ + Spec: conf_v1.PolicySpec{ + AccessControl: &conf_v1.AccessControl{ Allow: []string{"127.0.0.1"}, }, }, @@ -1883,10 +1882,10 @@ func TestGeneratePolicies(t *testing.T) { Name: "allow-policy", }, }, - policies: map[string]*conf_v1alpha1.Policy{ + policies: map[string]*conf_v1.Policy{ "default/allow-policy": { - Spec: conf_v1alpha1.PolicySpec{ - AccessControl: &conf_v1alpha1.AccessControl{ + Spec: conf_v1.PolicySpec{ + AccessControl: &conf_v1.AccessControl{ Allow: []string{"127.0.0.1"}, }, }, @@ -1906,17 +1905,17 @@ func TestGeneratePolicies(t *testing.T) { Name: "allow-policy-2", }, }, - policies: map[string]*conf_v1alpha1.Policy{ + policies: map[string]*conf_v1.Policy{ "default/allow-policy-1": { - Spec: conf_v1alpha1.PolicySpec{ - AccessControl: &conf_v1alpha1.AccessControl{ + Spec: conf_v1.PolicySpec{ + AccessControl: &conf_v1.AccessControl{ Allow: []string{"127.0.0.1"}, }, }, }, "default/allow-policy-2": { - Spec: conf_v1alpha1.PolicySpec{ - AccessControl: &conf_v1alpha1.AccessControl{ + Spec: conf_v1.PolicySpec{ + AccessControl: &conf_v1.AccessControl{ Allow: []string{"127.0.0.2"}, }, }, @@ -1934,10 +1933,10 @@ func TestGeneratePolicies(t *testing.T) { Namespace: "default", }, }, - policies: map[string]*conf_v1alpha1.Policy{ + policies: map[string]*conf_v1.Policy{ "default/rateLimit-policy": { - Spec: conf_v1alpha1.PolicySpec{ - RateLimit: &conf_v1alpha1.RateLimit{ + Spec: conf_v1.PolicySpec{ + RateLimit: &conf_v1.RateLimit{ Key: "test", ZoneSize: "10M", Rate: "10r/s", @@ -1978,10 +1977,10 @@ func TestGeneratePolicies(t *testing.T) { Namespace: "default", }, }, - policies: map[string]*conf_v1alpha1.Policy{ + policies: map[string]*conf_v1.Policy{ "default/rateLimit-policy": { - Spec: conf_v1alpha1.PolicySpec{ - RateLimit: &conf_v1alpha1.RateLimit{ + Spec: conf_v1.PolicySpec{ + RateLimit: &conf_v1.RateLimit{ Key: "test", ZoneSize: "10M", Rate: "10r/s", @@ -1989,8 +1988,8 @@ func TestGeneratePolicies(t *testing.T) { }, }, "default/rateLimit-policy2": { - Spec: conf_v1alpha1.PolicySpec{ - RateLimit: &conf_v1alpha1.RateLimit{ + Spec: conf_v1.PolicySpec{ + RateLimit: &conf_v1.RateLimit{ Key: "test2", ZoneSize: "20M", Rate: "20r/s", @@ -2035,14 +2034,14 @@ func TestGeneratePolicies(t *testing.T) { Namespace: "default", }, }, - policies: map[string]*conf_v1alpha1.Policy{ + policies: map[string]*conf_v1.Policy{ "default/jwt-policy": { ObjectMeta: meta_v1.ObjectMeta{ Name: "jwt-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - JWTAuth: &conf_v1alpha1.JWTAuth{ + Spec: conf_v1.PolicySpec{ + JWTAuth: &conf_v1.JWTAuth{ Realm: "My Test API", Secret: "jwt-secret", }, @@ -2064,14 +2063,14 @@ func TestGeneratePolicies(t *testing.T) { Namespace: "default", }, }, - policies: map[string]*conf_v1alpha1.Policy{ + policies: map[string]*conf_v1.Policy{ "default/ingress-mtls-policy": { ObjectMeta: meta_v1.ObjectMeta{ Name: "ingress-mtls-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - IngressMTLS: &conf_v1alpha1.IngressMTLS{ + Spec: conf_v1.PolicySpec{ + IngressMTLS: &conf_v1.IngressMTLS{ ClientCertSecret: "ingress-mtls-secret", VerifyClient: "off", }, @@ -2095,10 +2094,10 @@ func TestGeneratePolicies(t *testing.T) { Namespace: "default", }, }, - policies: map[string]*conf_v1alpha1.Policy{ + policies: map[string]*conf_v1.Policy{ "default/egress-mtls-policy": { - Spec: conf_v1alpha1.PolicySpec{ - EgressMTLS: &conf_v1alpha1.EgressMTLS{ + Spec: conf_v1.PolicySpec{ + EgressMTLS: &conf_v1.EgressMTLS{ TLSSecret: "egress-mtls-secret", ServerName: true, SessionReuse: createPointerFromBool(false), @@ -2152,7 +2151,7 @@ func TestGeneratePoliciesFails(t *testing.T) { tests := []struct { policyRefs []conf_v1.PolicyReference - policies map[string]*conf_v1alpha1.Policy + policies map[string]*conf_v1.Policy policyOpts policyOptions trustedCAFileName string context string @@ -2167,7 +2166,7 @@ func TestGeneratePoliciesFails(t *testing.T) { Namespace: "default", }, }, - policies: map[string]*conf_v1alpha1.Policy{}, + policies: map[string]*conf_v1.Policy{}, policyOpts: policyOptions{}, expected: policiesCfg{ ErrorReturn: &version2.Return{ @@ -2190,17 +2189,17 @@ func TestGeneratePoliciesFails(t *testing.T) { Name: "deny-policy", }, }, - policies: map[string]*conf_v1alpha1.Policy{ + policies: map[string]*conf_v1.Policy{ "default/allow-policy": { - Spec: conf_v1alpha1.PolicySpec{ - AccessControl: &conf_v1alpha1.AccessControl{ + Spec: conf_v1.PolicySpec{ + AccessControl: &conf_v1.AccessControl{ Allow: []string{"127.0.0.1"}, }, }, }, "default/deny-policy": { - Spec: conf_v1alpha1.PolicySpec{ - AccessControl: &conf_v1alpha1.AccessControl{ + Spec: conf_v1.PolicySpec{ + AccessControl: &conf_v1.AccessControl{ Deny: []string{"127.0.0.2"}, }, }, @@ -2229,10 +2228,10 @@ func TestGeneratePoliciesFails(t *testing.T) { Namespace: "default", }, }, - policies: map[string]*conf_v1alpha1.Policy{ + policies: map[string]*conf_v1.Policy{ "default/rateLimit-policy": { - Spec: conf_v1alpha1.PolicySpec{ - RateLimit: &conf_v1alpha1.RateLimit{ + Spec: conf_v1.PolicySpec{ + RateLimit: &conf_v1.RateLimit{ Key: "test", ZoneSize: "10M", Rate: "10r/s", @@ -2240,8 +2239,8 @@ func TestGeneratePoliciesFails(t *testing.T) { }, }, "default/rateLimit-policy2": { - Spec: conf_v1alpha1.PolicySpec{ - RateLimit: &conf_v1alpha1.RateLimit{ + Spec: conf_v1.PolicySpec{ + RateLimit: &conf_v1.RateLimit{ Key: "test2", ZoneSize: "20M", Rate: "20r/s", @@ -2297,14 +2296,14 @@ func TestGeneratePoliciesFails(t *testing.T) { Namespace: "default", }, }, - policies: map[string]*conf_v1alpha1.Policy{ + policies: map[string]*conf_v1.Policy{ "default/jwt-policy": { ObjectMeta: meta_v1.ObjectMeta{ Name: "jwt-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - JWTAuth: &conf_v1alpha1.JWTAuth{ + Spec: conf_v1.PolicySpec{ + JWTAuth: &conf_v1.JWTAuth{ Realm: "test", Secret: "jwt-secret", }, @@ -2338,14 +2337,14 @@ func TestGeneratePoliciesFails(t *testing.T) { Namespace: "default", }, }, - policies: map[string]*conf_v1alpha1.Policy{ + policies: map[string]*conf_v1.Policy{ "default/jwt-policy": { ObjectMeta: meta_v1.ObjectMeta{ Name: "jwt-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - JWTAuth: &conf_v1alpha1.JWTAuth{ + Spec: conf_v1.PolicySpec{ + JWTAuth: &conf_v1.JWTAuth{ Realm: "test", Secret: "jwt-secret", }, @@ -2382,14 +2381,14 @@ func TestGeneratePoliciesFails(t *testing.T) { Namespace: "default", }, }, - policies: map[string]*conf_v1alpha1.Policy{ + policies: map[string]*conf_v1.Policy{ "default/jwt-policy": { ObjectMeta: meta_v1.ObjectMeta{ Name: "jwt-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - JWTAuth: &conf_v1alpha1.JWTAuth{ + Spec: conf_v1.PolicySpec{ + JWTAuth: &conf_v1.JWTAuth{ Realm: "test", Secret: "jwt-secret", }, @@ -2400,8 +2399,8 @@ func TestGeneratePoliciesFails(t *testing.T) { Name: "jwt-policy2", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - JWTAuth: &conf_v1alpha1.JWTAuth{ + Spec: conf_v1.PolicySpec{ + JWTAuth: &conf_v1.JWTAuth{ Realm: "test", Secret: "jwt-secret2", }, @@ -2440,14 +2439,14 @@ func TestGeneratePoliciesFails(t *testing.T) { Namespace: "default", }, }, - policies: map[string]*conf_v1alpha1.Policy{ + policies: map[string]*conf_v1.Policy{ "default/ingress-mtls-policy": { ObjectMeta: meta_v1.ObjectMeta{ Name: "ingress-mtls-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - IngressMTLS: &conf_v1alpha1.IngressMTLS{ + Spec: conf_v1.PolicySpec{ + IngressMTLS: &conf_v1.IngressMTLS{ ClientCertSecret: "ingress-mtls-secret", }, }, @@ -2481,14 +2480,14 @@ func TestGeneratePoliciesFails(t *testing.T) { Namespace: "default", }, }, - policies: map[string]*conf_v1alpha1.Policy{ + policies: map[string]*conf_v1.Policy{ "default/ingress-mtls-policy": { ObjectMeta: meta_v1.ObjectMeta{ Name: "ingress-mtls-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - IngressMTLS: &conf_v1alpha1.IngressMTLS{ + Spec: conf_v1.PolicySpec{ + IngressMTLS: &conf_v1.IngressMTLS{ ClientCertSecret: "ingress-mtls-secret", }, }, @@ -2526,21 +2525,21 @@ func TestGeneratePoliciesFails(t *testing.T) { Namespace: "default", }, }, - policies: map[string]*conf_v1alpha1.Policy{ + policies: map[string]*conf_v1.Policy{ "default/ingress-mtls-policy": { ObjectMeta: meta_v1.ObjectMeta{ Name: "ingress-mtls-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - IngressMTLS: &conf_v1alpha1.IngressMTLS{ + Spec: conf_v1.PolicySpec{ + IngressMTLS: &conf_v1.IngressMTLS{ ClientCertSecret: "ingress-mtls-secret", }, }, }, "default/ingress-mtls-policy2": { - Spec: conf_v1alpha1.PolicySpec{ - IngressMTLS: &conf_v1alpha1.IngressMTLS{ + Spec: conf_v1.PolicySpec{ + IngressMTLS: &conf_v1.IngressMTLS{ ClientCertSecret: "ingress-mtls-secret2", }, }, @@ -2577,14 +2576,14 @@ func TestGeneratePoliciesFails(t *testing.T) { Namespace: "default", }, }, - policies: map[string]*conf_v1alpha1.Policy{ + policies: map[string]*conf_v1.Policy{ "default/ingress-mtls-policy": { ObjectMeta: meta_v1.ObjectMeta{ Name: "ingress-mtls-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - IngressMTLS: &conf_v1alpha1.IngressMTLS{ + Spec: conf_v1.PolicySpec{ + IngressMTLS: &conf_v1.IngressMTLS{ ClientCertSecret: "ingress-mtls-secret", }, }, @@ -2619,14 +2618,14 @@ func TestGeneratePoliciesFails(t *testing.T) { Namespace: "default", }, }, - policies: map[string]*conf_v1alpha1.Policy{ + policies: map[string]*conf_v1.Policy{ "default/ingress-mtls-policy": { ObjectMeta: meta_v1.ObjectMeta{ Name: "ingress-mtls-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - IngressMTLS: &conf_v1alpha1.IngressMTLS{ + Spec: conf_v1.PolicySpec{ + IngressMTLS: &conf_v1.IngressMTLS{ ClientCertSecret: "ingress-mtls-secret", }, }, @@ -2665,14 +2664,14 @@ func TestGeneratePoliciesFails(t *testing.T) { Namespace: "default", }, }, - policies: map[string]*conf_v1alpha1.Policy{ + policies: map[string]*conf_v1.Policy{ "default/egress-mtls-policy": { ObjectMeta: meta_v1.ObjectMeta{ Name: "egress-mtls-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - EgressMTLS: &conf_v1alpha1.EgressMTLS{ + Spec: conf_v1.PolicySpec{ + EgressMTLS: &conf_v1.EgressMTLS{ TLSSecret: "egress-mtls-secret", }, }, @@ -2682,8 +2681,8 @@ func TestGeneratePoliciesFails(t *testing.T) { Name: "egress-mtls-policy2", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - EgressMTLS: &conf_v1alpha1.EgressMTLS{ + Spec: conf_v1.PolicySpec{ + EgressMTLS: &conf_v1.EgressMTLS{ TLSSecret: "egress-mtls-secret2", }, }, @@ -2724,14 +2723,14 @@ func TestGeneratePoliciesFails(t *testing.T) { Namespace: "default", }, }, - policies: map[string]*conf_v1alpha1.Policy{ + policies: map[string]*conf_v1.Policy{ "default/egress-mtls-policy": { ObjectMeta: meta_v1.ObjectMeta{ Name: "egress-mtls-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - EgressMTLS: &conf_v1alpha1.EgressMTLS{ + Spec: conf_v1.PolicySpec{ + EgressMTLS: &conf_v1.EgressMTLS{ TrustedCertSecret: "egress-trusted-secret", SSLName: "foo.com", }, @@ -2766,14 +2765,14 @@ func TestGeneratePoliciesFails(t *testing.T) { Namespace: "default", }, }, - policies: map[string]*conf_v1alpha1.Policy{ + policies: map[string]*conf_v1.Policy{ "default/egress-mtls-policy": { ObjectMeta: meta_v1.ObjectMeta{ Name: "egress-mtls-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - EgressMTLS: &conf_v1alpha1.EgressMTLS{ + Spec: conf_v1.PolicySpec{ + EgressMTLS: &conf_v1.EgressMTLS{ TLSSecret: "egress-mtls-secret", SSLName: "foo.com", }, @@ -2807,14 +2806,14 @@ func TestGeneratePoliciesFails(t *testing.T) { Namespace: "default", }, }, - policies: map[string]*conf_v1alpha1.Policy{ + policies: map[string]*conf_v1.Policy{ "default/egress-mtls-policy": { ObjectMeta: meta_v1.ObjectMeta{ Name: "egress-mtls-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - EgressMTLS: &conf_v1alpha1.EgressMTLS{ + Spec: conf_v1.PolicySpec{ + EgressMTLS: &conf_v1.EgressMTLS{ TrustedCertSecret: "egress-trusted-secret", SSLName: "foo.com", }, @@ -2848,14 +2847,14 @@ func TestGeneratePoliciesFails(t *testing.T) { Namespace: "default", }, }, - policies: map[string]*conf_v1alpha1.Policy{ + policies: map[string]*conf_v1.Policy{ "default/egress-mtls-policy": { ObjectMeta: meta_v1.ObjectMeta{ Name: "egress-mtls-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - EgressMTLS: &conf_v1alpha1.EgressMTLS{ + Spec: conf_v1.PolicySpec{ + EgressMTLS: &conf_v1.EgressMTLS{ TLSSecret: "egress-mtls-secret", SSLName: "foo.com", }, diff --git a/internal/k8s/controller.go b/internal/k8s/controller.go index 550044e13d..a30a7cf418 100644 --- a/internal/k8s/controller.go +++ b/internal/k8s/controller.go @@ -485,6 +485,19 @@ func (lbc *LoadBalancerController) addVirtualServerRouteHandler(handlers cache.R ) } +func (lbc *LoadBalancerController) addPolicyHandler(handlers cache.ResourceEventHandlerFuncs) { + lbc.policyLister, lbc.policyController = cache.NewInformer( + cache.NewListWatchFromClient( + lbc.confClient.K8sV1().RESTClient(), + "policies", + lbc.namespace, + fields.Everything()), + &conf_v1.Policy{}, + lbc.resync, + handlers, + ) +} + func (lbc *LoadBalancerController) addGlobalConfigurationHandler(handlers cache.ResourceEventHandlerFuncs, namespace string, name string) { lbc.globalConfigurationLister, lbc.globalConfigurationController = cache.NewInformer( cache.NewListWatchFromClient( @@ -511,19 +524,6 @@ func (lbc *LoadBalancerController) addTransportServerHandler(handlers cache.Reso ) } -func (lbc *LoadBalancerController) addPolicyHandler(handlers cache.ResourceEventHandlerFuncs) { - lbc.policyLister, lbc.policyController = cache.NewInformer( - cache.NewListWatchFromClient( - lbc.confClient.K8sV1alpha1().RESTClient(), - "policies", - lbc.namespace, - fields.Everything()), - &conf_v1alpha1.Policy{}, - lbc.resync, - handlers, - ) -} - func (lbc *LoadBalancerController) addNginxCisConnectorHandler(handlers cache.ResourceEventHandlerFuncs, name string) { optionsModifier := func(options *meta_v1.ListOptions) { options.FieldSelector = fields.Set{"metadata.name": name}.String() @@ -842,7 +842,7 @@ func (lbc *LoadBalancerController) syncPolicy(task task) { glog.V(2).Infof("Adding, Updating or Deleting Policy: %v\n", key) if polExists { - pol := obj.(*conf_v1alpha1.Policy) + pol := obj.(*conf_v1.Policy) err := validation.ValidatePolicy(pol, lbc.isNginxPlus) if err != nil { lbc.recorder.Eventf(pol, api_v1.EventTypeWarning, "Rejected", "Policy %v is invalid and was rejected: %v", key, err) @@ -2309,8 +2309,8 @@ func (lbc *LoadBalancerController) createVirtualServerEx(virtualServer *conf_v1. return &virtualServerEx } -func createPolicyMap(policies []*conf_v1alpha1.Policy) map[string]*conf_v1alpha1.Policy { - result := make(map[string]*conf_v1alpha1.Policy) +func createPolicyMap(policies []*conf_v1.Policy) map[string]*conf_v1.Policy { + result := make(map[string]*conf_v1.Policy) for _, p := range policies { key := fmt.Sprintf("%s/%s", p.Namespace, p.Name) @@ -2320,11 +2320,11 @@ func createPolicyMap(policies []*conf_v1alpha1.Policy) map[string]*conf_v1alpha1 return result } -func (lbc *LoadBalancerController) getAllPolicies() []*conf_v1alpha1.Policy { - var policies []*conf_v1alpha1.Policy +func (lbc *LoadBalancerController) getAllPolicies() []*conf_v1.Policy { + var policies []*conf_v1.Policy for _, obj := range lbc.policyLister.List() { - pol := obj.(*conf_v1alpha1.Policy) + pol := obj.(*conf_v1.Policy) err := validation.ValidatePolicy(pol, lbc.isNginxPlus) if err != nil { @@ -2338,8 +2338,8 @@ func (lbc *LoadBalancerController) getAllPolicies() []*conf_v1alpha1.Policy { return policies } -func (lbc *LoadBalancerController) getPolicies(policies []conf_v1.PolicyReference, ownerNamespace string) ([]*conf_v1alpha1.Policy, []error) { - var result []*conf_v1alpha1.Policy +func (lbc *LoadBalancerController) getPolicies(policies []conf_v1.PolicyReference, ownerNamespace string) ([]*conf_v1.Policy, []error) { + var result []*conf_v1.Policy var errors []error for _, p := range policies { @@ -2361,7 +2361,7 @@ func (lbc *LoadBalancerController) getPolicies(policies []conf_v1.PolicyReferenc continue } - policy := policyObj.(*conf_v1alpha1.Policy) + policy := policyObj.(*conf_v1.Policy) err = validation.ValidatePolicy(policy, lbc.isNginxPlus) if err != nil { @@ -2375,7 +2375,7 @@ func (lbc *LoadBalancerController) getPolicies(policies []conf_v1.PolicyReferenc return result, errors } -func (lbc *LoadBalancerController) addJWTSecretRefs(secretRefs map[string]*secrets.SecretReference, policies []*conf_v1alpha1.Policy) error { +func (lbc *LoadBalancerController) addJWTSecretRefs(secretRefs map[string]*secrets.SecretReference, policies []*conf_v1.Policy) error { for _, pol := range policies { if pol.Spec.JWTAuth == nil { continue @@ -2394,7 +2394,7 @@ func (lbc *LoadBalancerController) addJWTSecretRefs(secretRefs map[string]*secre return nil } -func (lbc *LoadBalancerController) addIngressMTLSSecretRefs(secretRefs map[string]*secrets.SecretReference, policies []*conf_v1alpha1.Policy) error { +func (lbc *LoadBalancerController) addIngressMTLSSecretRefs(secretRefs map[string]*secrets.SecretReference, policies []*conf_v1.Policy) error { for _, pol := range policies { if pol.Spec.IngressMTLS == nil { continue @@ -2411,7 +2411,7 @@ func (lbc *LoadBalancerController) addIngressMTLSSecretRefs(secretRefs map[strin return nil } -func (lbc *LoadBalancerController) addEgressMTLSSecretRefs(secretRefs map[string]*secrets.SecretReference, policies []*conf_v1alpha1.Policy) error { +func (lbc *LoadBalancerController) addEgressMTLSSecretRefs(secretRefs map[string]*secrets.SecretReference, policies []*conf_v1.Policy) error { for _, pol := range policies { if pol.Spec.EgressMTLS == nil { continue @@ -2441,12 +2441,12 @@ func (lbc *LoadBalancerController) addEgressMTLSSecretRefs(secretRefs map[string return nil } -func (lbc *LoadBalancerController) getPoliciesForSecret(secretNamespace string, secretName string) []*conf_v1alpha1.Policy { +func (lbc *LoadBalancerController) getPoliciesForSecret(secretNamespace string, secretName string) []*conf_v1.Policy { return findPoliciesForSecret(lbc.getAllPolicies(), secretNamespace, secretName) } -func findPoliciesForSecret(policies []*conf_v1alpha1.Policy, secretNamespace string, secretName string) []*conf_v1alpha1.Policy { - var res []*conf_v1alpha1.Policy +func findPoliciesForSecret(policies []*conf_v1.Policy, secretNamespace string, secretName string) []*conf_v1.Policy { + var res []*conf_v1.Policy for _, pol := range policies { if pol.Spec.IngressMTLS != nil && pol.Spec.IngressMTLS.ClientCertSecret == secretName && pol.Namespace == secretNamespace { diff --git a/internal/k8s/controller_test.go b/internal/k8s/controller_test.go index 46941be1df..e22f1f0f58 100644 --- a/internal/k8s/controller_test.go +++ b/internal/k8s/controller_test.go @@ -16,7 +16,6 @@ import ( "github.com/nginxinc/kubernetes-ingress/internal/metrics/collectors" "github.com/nginxinc/kubernetes-ingress/internal/nginx" conf_v1 "github.com/nginxinc/kubernetes-ingress/pkg/apis/configuration/v1" - "github.com/nginxinc/kubernetes-ingress/pkg/apis/configuration/v1alpha1" conf_v1alpha1 "github.com/nginxinc/kubernetes-ingress/pkg/apis/configuration/v1alpha1" api_v1 "k8s.io/api/core/v1" v1 "k8s.io/api/core/v1" @@ -770,24 +769,24 @@ func TestGetStatusFromEventTitle(t *testing.T) { } func TestGetPolicies(t *testing.T) { - validPolicy := &conf_v1alpha1.Policy{ + validPolicy := &conf_v1.Policy{ ObjectMeta: meta_v1.ObjectMeta{ Name: "valid-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - AccessControl: &conf_v1alpha1.AccessControl{ + Spec: conf_v1.PolicySpec{ + AccessControl: &conf_v1.AccessControl{ Allow: []string{"127.0.0.1"}, }, }, } - invalidPolicy := &conf_v1alpha1.Policy{ + invalidPolicy := &conf_v1.Policy{ ObjectMeta: meta_v1.ObjectMeta{ Name: "invalid-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{}, + Spec: conf_v1.PolicySpec{}, } lbc := LoadBalancerController{ @@ -827,7 +826,7 @@ func TestGetPolicies(t *testing.T) { }, } - expectedPolicies := []*conf_v1alpha1.Policy{validPolicy} + expectedPolicies := []*conf_v1.Policy{validPolicy} expectedErrors := []error{ errors.New("Policy default/invalid-policy is invalid: spec: Invalid value: \"\": must specify exactly one of: `accessControl`, `rateLimit`, `ingressMTLS`, `egressMTLS`, `jwt`"), errors.New("Policy nginx-ingress/valid-policy doesn't exist"), @@ -844,7 +843,7 @@ func TestGetPolicies(t *testing.T) { } func TestCreatePolicyMap(t *testing.T) { - policies := []*conf_v1alpha1.Policy{ + policies := []*conf_v1.Policy{ { ObjectMeta: meta_v1.ObjectMeta{ Name: "policy-1", @@ -871,7 +870,7 @@ func TestCreatePolicyMap(t *testing.T) { }, } - expected := map[string]*conf_v1alpha1.Policy{ + expected := map[string]*conf_v1.Policy{ "default/policy-1": { ObjectMeta: meta_v1.ObjectMeta{ Name: "policy-1", @@ -986,7 +985,7 @@ func createTestObjMeta(kind, name string, podHashLabel bool) meta_v1.ObjectMeta return meta } -func policyMapToString(policies map[string]*conf_v1alpha1.Policy) string { +func policyMapToString(policies map[string]*conf_v1.Policy) string { var keys []string for k := range policies { keys = append(keys, k) @@ -1080,132 +1079,132 @@ func TestRemoveDuplicateResources(t *testing.T) { } func TestFindPoliciesForSecret(t *testing.T) { - jwtPol1 := &conf_v1alpha1.Policy{ + jwtPol1 := &conf_v1.Policy{ ObjectMeta: meta_v1.ObjectMeta{ Name: "jwt-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - JWTAuth: &conf_v1alpha1.JWTAuth{ + Spec: conf_v1.PolicySpec{ + JWTAuth: &conf_v1.JWTAuth{ Secret: "jwk-secret", }, }, } - jwtPol2 := &conf_v1alpha1.Policy{ + jwtPol2 := &conf_v1.Policy{ ObjectMeta: meta_v1.ObjectMeta{ Name: "jwt-policy", Namespace: "ns-1", }, - Spec: conf_v1alpha1.PolicySpec{ - JWTAuth: &conf_v1alpha1.JWTAuth{ + Spec: conf_v1.PolicySpec{ + JWTAuth: &conf_v1.JWTAuth{ Secret: "jwk-secret", }, }, } - ingTLSPol := &conf_v1alpha1.Policy{ + ingTLSPol := &conf_v1.Policy{ ObjectMeta: meta_v1.ObjectMeta{ Name: "ingress-mtls-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - IngressMTLS: &conf_v1alpha1.IngressMTLS{ + Spec: conf_v1.PolicySpec{ + IngressMTLS: &conf_v1.IngressMTLS{ ClientCertSecret: "ingress-mtls-secret", }, }, } - egTLSPol := &conf_v1alpha1.Policy{ + egTLSPol := &conf_v1.Policy{ ObjectMeta: meta_v1.ObjectMeta{ Name: "egress-mtls-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - EgressMTLS: &conf_v1alpha1.EgressMTLS{ + Spec: conf_v1.PolicySpec{ + EgressMTLS: &conf_v1.EgressMTLS{ TLSSecret: "egress-mtls-secret", }, }, } - egTLSPol2 := &conf_v1alpha1.Policy{ + egTLSPol2 := &conf_v1.Policy{ ObjectMeta: meta_v1.ObjectMeta{ Name: "egress-trusted-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - EgressMTLS: &conf_v1alpha1.EgressMTLS{ + Spec: conf_v1.PolicySpec{ + EgressMTLS: &conf_v1.EgressMTLS{ TrustedCertSecret: "egress-trusted-secret", }, }, } tests := []struct { - policies []*conf_v1alpha1.Policy + policies []*conf_v1.Policy secretNamespace string secretName string - expected []*conf_v1alpha1.Policy + expected []*conf_v1.Policy msg string }{ { - policies: []*conf_v1alpha1.Policy{jwtPol1}, + policies: []*conf_v1.Policy{jwtPol1}, secretNamespace: "default", secretName: "jwk-secret", - expected: []*v1alpha1.Policy{jwtPol1}, + expected: []*conf_v1.Policy{jwtPol1}, msg: "Find policy in default ns", }, { - policies: []*conf_v1alpha1.Policy{jwtPol2}, + policies: []*conf_v1.Policy{jwtPol2}, secretNamespace: "default", secretName: "jwk-secret", expected: nil, msg: "Ignore policies in other namespaces", }, { - policies: []*conf_v1alpha1.Policy{jwtPol1, jwtPol2}, + policies: []*conf_v1.Policy{jwtPol1, jwtPol2}, secretNamespace: "default", secretName: "jwk-secret", - expected: []*v1alpha1.Policy{jwtPol1}, + expected: []*conf_v1.Policy{jwtPol1}, msg: "Find policy in default ns, ignore other", }, { - policies: []*conf_v1alpha1.Policy{ingTLSPol}, + policies: []*conf_v1.Policy{ingTLSPol}, secretNamespace: "default", secretName: "ingress-mtls-secret", - expected: []*v1alpha1.Policy{ingTLSPol}, + expected: []*conf_v1.Policy{ingTLSPol}, msg: "Find policy in default ns", }, { - policies: []*conf_v1alpha1.Policy{jwtPol1, ingTLSPol}, + policies: []*conf_v1.Policy{jwtPol1, ingTLSPol}, secretNamespace: "default", secretName: "ingress-mtls-secret", - expected: []*v1alpha1.Policy{ingTLSPol}, + expected: []*conf_v1.Policy{ingTLSPol}, msg: "Find policy in default ns, ignore other types", }, { - policies: []*conf_v1alpha1.Policy{egTLSPol}, + policies: []*conf_v1.Policy{egTLSPol}, secretNamespace: "default", secretName: "egress-mtls-secret", - expected: []*v1alpha1.Policy{egTLSPol}, + expected: []*conf_v1.Policy{egTLSPol}, msg: "Find policy in default ns", }, { - policies: []*conf_v1alpha1.Policy{jwtPol1, egTLSPol}, + policies: []*conf_v1.Policy{jwtPol1, egTLSPol}, secretNamespace: "default", secretName: "egress-mtls-secret", - expected: []*v1alpha1.Policy{egTLSPol}, + expected: []*conf_v1.Policy{egTLSPol}, msg: "Find policy in default ns, ignore other types", }, { - policies: []*conf_v1alpha1.Policy{egTLSPol2}, + policies: []*conf_v1.Policy{egTLSPol2}, secretNamespace: "default", secretName: "egress-trusted-secret", - expected: []*v1alpha1.Policy{egTLSPol2}, + expected: []*conf_v1.Policy{egTLSPol2}, msg: "Find policy in default ns", }, { - policies: []*conf_v1alpha1.Policy{egTLSPol, egTLSPol2}, + policies: []*conf_v1.Policy{egTLSPol, egTLSPol2}, secretNamespace: "default", secretName: "egress-trusted-secret", - expected: []*v1alpha1.Policy{egTLSPol2}, + expected: []*conf_v1.Policy{egTLSPol2}, msg: "Find policy in default ns, ignore other types", }, } @@ -1229,20 +1228,20 @@ func TestAddJWTSecrets(t *testing.T) { invalidErr := errors.New("invalid") tests := []struct { - policies []*conf_v1alpha1.Policy + policies []*conf_v1.Policy expectedSecretRefs map[string]*secrets.SecretReference wantErr bool msg string }{ { - policies: []*conf_v1alpha1.Policy{ + policies: []*conf_v1.Policy{ { ObjectMeta: meta_v1.ObjectMeta{ Name: "jwt-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - JWTAuth: &conf_v1alpha1.JWTAuth{ + Spec: conf_v1.PolicySpec{ + JWTAuth: &conf_v1.JWTAuth{ Secret: "valid-jwk-secret", Realm: "My API", }, @@ -1259,20 +1258,20 @@ func TestAddJWTSecrets(t *testing.T) { msg: "test getting valid secret", }, { - policies: []*conf_v1alpha1.Policy{}, + policies: []*conf_v1.Policy{}, expectedSecretRefs: map[string]*secrets.SecretReference{}, wantErr: false, msg: "test getting valid secret with no policy", }, { - policies: []*conf_v1alpha1.Policy{ + policies: []*conf_v1.Policy{ { ObjectMeta: meta_v1.ObjectMeta{ Name: "jwt-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - AccessControl: &conf_v1alpha1.AccessControl{ + Spec: conf_v1.PolicySpec{ + AccessControl: &conf_v1.AccessControl{ Allow: []string{"127.0.0.1"}, }, }, @@ -1283,14 +1282,14 @@ func TestAddJWTSecrets(t *testing.T) { msg: "test getting invalid secret with wrong policy", }, { - policies: []*conf_v1alpha1.Policy{ + policies: []*conf_v1.Policy{ { ObjectMeta: meta_v1.ObjectMeta{ Name: "jwt-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - JWTAuth: &conf_v1alpha1.JWTAuth{ + Spec: conf_v1.PolicySpec{ + JWTAuth: &conf_v1.JWTAuth{ Secret: "invalid-jwk-secret", Realm: "My API", }, @@ -1351,20 +1350,20 @@ func TestAddIngressMTLSSecret(t *testing.T) { invalidErr := errors.New("invalid") tests := []struct { - policies []*conf_v1alpha1.Policy + policies []*conf_v1.Policy expectedSecretRefs map[string]*secrets.SecretReference wantErr bool msg string }{ { - policies: []*conf_v1alpha1.Policy{ + policies: []*conf_v1.Policy{ { ObjectMeta: meta_v1.ObjectMeta{ Name: "ingress-mtls-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - IngressMTLS: &conf_v1alpha1.IngressMTLS{ + Spec: conf_v1.PolicySpec{ + IngressMTLS: &conf_v1.IngressMTLS{ ClientCertSecret: "valid-ingress-mtls-secret", }, }, @@ -1380,20 +1379,20 @@ func TestAddIngressMTLSSecret(t *testing.T) { msg: "test getting valid secret", }, { - policies: []*conf_v1alpha1.Policy{}, + policies: []*conf_v1.Policy{}, expectedSecretRefs: map[string]*secrets.SecretReference{}, wantErr: false, msg: "test getting valid secret with no policy", }, { - policies: []*conf_v1alpha1.Policy{ + policies: []*conf_v1.Policy{ { ObjectMeta: meta_v1.ObjectMeta{ Name: "ingress-mtls-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - AccessControl: &conf_v1alpha1.AccessControl{ + Spec: conf_v1.PolicySpec{ + AccessControl: &conf_v1.AccessControl{ Allow: []string{"127.0.0.1"}, }, }, @@ -1404,14 +1403,14 @@ func TestAddIngressMTLSSecret(t *testing.T) { msg: "test getting valid secret with wrong policy", }, { - policies: []*conf_v1alpha1.Policy{ + policies: []*conf_v1.Policy{ { ObjectMeta: meta_v1.ObjectMeta{ Name: "ingress-mtls-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - IngressMTLS: &conf_v1alpha1.IngressMTLS{ + Spec: conf_v1.PolicySpec{ + IngressMTLS: &conf_v1.IngressMTLS{ ClientCertSecret: "invalid-ingress-mtls-secret", }, }, @@ -1471,20 +1470,20 @@ func TestAddEgressMTLSSecrets(t *testing.T) { invalidErr := errors.New("invalid") tests := []struct { - policies []*conf_v1alpha1.Policy + policies []*conf_v1.Policy expectedSecretRefs map[string]*secrets.SecretReference wantErr bool msg string }{ { - policies: []*conf_v1alpha1.Policy{ + policies: []*conf_v1.Policy{ { ObjectMeta: meta_v1.ObjectMeta{ Name: "egress-mtls-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - EgressMTLS: &conf_v1alpha1.EgressMTLS{ + Spec: conf_v1.PolicySpec{ + EgressMTLS: &conf_v1.EgressMTLS{ TLSSecret: "valid-egress-mtls-secret", }, }, @@ -1500,14 +1499,14 @@ func TestAddEgressMTLSSecrets(t *testing.T) { msg: "test getting valid TLS secret", }, { - policies: []*conf_v1alpha1.Policy{ + policies: []*conf_v1.Policy{ { ObjectMeta: meta_v1.ObjectMeta{ Name: "egress-egress-trusted-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - EgressMTLS: &conf_v1alpha1.EgressMTLS{ + Spec: conf_v1.PolicySpec{ + EgressMTLS: &conf_v1.EgressMTLS{ TrustedCertSecret: "valid-egress-trusted-secret", }, }, @@ -1523,14 +1522,14 @@ func TestAddEgressMTLSSecrets(t *testing.T) { msg: "test getting valid TrustedCA secret", }, { - policies: []*conf_v1alpha1.Policy{ + policies: []*conf_v1.Policy{ { ObjectMeta: meta_v1.ObjectMeta{ Name: "egress-mtls-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - EgressMTLS: &conf_v1alpha1.EgressMTLS{ + Spec: conf_v1.PolicySpec{ + EgressMTLS: &conf_v1.EgressMTLS{ TLSSecret: "valid-egress-mtls-secret", TrustedCertSecret: "valid-egress-trusted-secret", }, @@ -1551,20 +1550,20 @@ func TestAddEgressMTLSSecrets(t *testing.T) { msg: "test getting valid secrets", }, { - policies: []*conf_v1alpha1.Policy{}, + policies: []*conf_v1.Policy{}, expectedSecretRefs: map[string]*secrets.SecretReference{}, wantErr: false, msg: "test getting valid secret with no policy", }, { - policies: []*conf_v1alpha1.Policy{ + policies: []*conf_v1.Policy{ { ObjectMeta: meta_v1.ObjectMeta{ Name: "ingress-mtls-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - AccessControl: &conf_v1alpha1.AccessControl{ + Spec: conf_v1.PolicySpec{ + AccessControl: &conf_v1.AccessControl{ Allow: []string{"127.0.0.1"}, }, }, @@ -1575,14 +1574,14 @@ func TestAddEgressMTLSSecrets(t *testing.T) { msg: "test getting valid secret with wrong policy", }, { - policies: []*conf_v1alpha1.Policy{ + policies: []*conf_v1.Policy{ { ObjectMeta: meta_v1.ObjectMeta{ Name: "egress-mtls-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - EgressMTLS: &conf_v1alpha1.EgressMTLS{ + Spec: conf_v1.PolicySpec{ + EgressMTLS: &conf_v1.EgressMTLS{ TLSSecret: "invalid-egress-mtls-secret", }, }, @@ -1598,14 +1597,14 @@ func TestAddEgressMTLSSecrets(t *testing.T) { msg: "test getting invalid TLS secret", }, { - policies: []*conf_v1alpha1.Policy{ + policies: []*conf_v1.Policy{ { ObjectMeta: meta_v1.ObjectMeta{ Name: "egress-mtls-policy", Namespace: "default", }, - Spec: conf_v1alpha1.PolicySpec{ - EgressMTLS: &conf_v1alpha1.EgressMTLS{ + Spec: conf_v1.PolicySpec{ + EgressMTLS: &conf_v1.EgressMTLS{ TrustedCertSecret: "invalid-egress-trusted-secret", }, }, diff --git a/internal/k8s/handlers.go b/internal/k8s/handlers.go index ded49825fa..cdf9cfefa3 100644 --- a/internal/k8s/handlers.go +++ b/internal/k8s/handlers.go @@ -437,19 +437,19 @@ func createTransportServerHandlers(lbc *LoadBalancerController) cache.ResourceEv func createPolicyHandlers(lbc *LoadBalancerController) cache.ResourceEventHandlerFuncs { return cache.ResourceEventHandlerFuncs{ AddFunc: func(obj interface{}) { - pol := obj.(*conf_v1alpha1.Policy) + pol := obj.(*conf_v1.Policy) glog.V(3).Infof("Adding Policy: %v", pol.Name) lbc.AddSyncQueue(pol) }, DeleteFunc: func(obj interface{}) { - pol, isPol := obj.(*conf_v1alpha1.Policy) + pol, isPol := obj.(*conf_v1.Policy) if !isPol { deletedState, ok := obj.(cache.DeletedFinalStateUnknown) if !ok { glog.V(3).Infof("Error received unexpected object: %v", obj) return } - pol, ok = deletedState.Obj.(*conf_v1alpha1.Policy) + pol, ok = deletedState.Obj.(*conf_v1.Policy) if !ok { glog.V(3).Infof("Error DeletedFinalStateUnknown contained non-Policy object: %v", deletedState.Obj) return @@ -459,7 +459,7 @@ func createPolicyHandlers(lbc *LoadBalancerController) cache.ResourceEventHandle lbc.AddSyncQueue(pol) }, UpdateFunc: func(old, cur interface{}) { - curPol := cur.(*conf_v1alpha1.Policy) + curPol := cur.(*conf_v1.Policy) if !reflect.DeepEqual(old, cur) { glog.V(3).Infof("Policy %v changed, syncing", curPol.Name) lbc.AddSyncQueue(curPol) diff --git a/internal/k8s/task_queue.go b/internal/k8s/task_queue.go index b724ce011e..22b05b6b9e 100644 --- a/internal/k8s/task_queue.go +++ b/internal/k8s/task_queue.go @@ -144,12 +144,12 @@ func newTask(key string, obj interface{}) (task, error) { k = virtualserver case *conf_v1.VirtualServerRoute: k = virtualServerRoute + case *conf_v1.Policy: + k = policy case *conf_v1alpha1.GlobalConfiguration: k = globalConfiguration case *conf_v1alpha1.TransportServer: k = transportserver - case *conf_v1alpha1.Policy: - k = policy case *unstructured.Unstructured: if objectKind := obj.(*unstructured.Unstructured).GetKind(); objectKind == appProtectPolicyGVK.Kind { k = appProtectPolicy diff --git a/pkg/apis/configuration/v1/register.go b/pkg/apis/configuration/v1/register.go index 03c2aa38e4..5adaf25a27 100644 --- a/pkg/apis/configuration/v1/register.go +++ b/pkg/apis/configuration/v1/register.go @@ -32,6 +32,8 @@ func addKnownTypes(scheme *runtime.Scheme) error { &VirtualServerList{}, &VirtualServerRoute{}, &VirtualServerRouteList{}, + &Policy{}, + &PolicyList{}, ) metav1.AddToGroupVersion(scheme, SchemeGroupVersion) return nil diff --git a/pkg/apis/configuration/v1/types.go b/pkg/apis/configuration/v1/types.go index 6fa1fd49be..1dd96e1f0f 100644 --- a/pkg/apis/configuration/v1/types.go +++ b/pkg/apis/configuration/v1/types.go @@ -313,3 +313,83 @@ type VirtualServerRouteStatus struct { ReferencedBy string `json:"referencedBy"` ExternalEndpoints []ExternalEndpoint `json:"externalEndpoints,omitempty"` } + +// +genclient +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +// +kubebuilder:validation:Optional +// +kubebuilder:resource:shortName=pol + +// Policy defines a Policy for VirtualServer and VirtualServerRoute resources. +type Policy struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec PolicySpec `json:"spec"` +} + +// PolicySpec is the spec of the Policy resource. +// The spec includes multiple fields, where each field represents a different policy. +// Only one policy (field) is allowed. +type PolicySpec struct { + AccessControl *AccessControl `json:"accessControl"` + RateLimit *RateLimit `json:"rateLimit"` + JWTAuth *JWTAuth `json:"jwt"` + IngressMTLS *IngressMTLS `json:"ingressMTLS"` + EgressMTLS *EgressMTLS `json:"egressMTLS"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// PolicyList is a list of the Policy resources. +type PolicyList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata"` + + Items []Policy `json:"items"` +} + +// AccessControl defines an access policy based on the source IP of a request. +type AccessControl struct { + Allow []string `json:"allow"` + Deny []string `json:"deny"` +} + +// RateLimit defines a rate limit policy. +type RateLimit struct { + Rate string `json:"rate"` + Key string `json:"key"` + Delay *int `json:"delay"` + NoDelay *bool `json:"noDelay"` + Burst *int `json:"burst"` + ZoneSize string `json:"zoneSize"` + DryRun *bool `json:"dryRun"` + LogLevel string `json:"logLevel"` + RejectCode *int `json:"rejectCode"` +} + +// JWTAuth holds JWT authentication configuration. +type JWTAuth struct { + Realm string `json:"realm"` + Secret string `json:"secret"` + Token string `json:"token"` +} + +// IngressMTLS defines an Ingress MTLS policy. +type IngressMTLS struct { + ClientCertSecret string `json:"clientCertSecret"` + VerifyClient string `json:"verifyClient"` + VerifyDepth *int `json:"verifyDepth"` +} + +// EgressMTLS defines an Egress MTLS policy. +type EgressMTLS struct { + TLSSecret string `json:"tlsSecret"` + VerifyServer bool `json:"verifyServer"` + VerifyDepth *int `json:"verifyDepth"` + Protocols string `json:"protocols"` + SessionReuse *bool `json:"sessionReuse"` + Ciphers string `json:"ciphers"` + TrustedCertSecret string `json:"trustedCertSecret"` + ServerName bool `json:"serverName"` + SSLName string `json:"sslName"` +} diff --git a/pkg/apis/configuration/v1/zz_generated.deepcopy.go b/pkg/apis/configuration/v1/zz_generated.deepcopy.go index 43f4a94ae8..cad8de5695 100644 --- a/pkg/apis/configuration/v1/zz_generated.deepcopy.go +++ b/pkg/apis/configuration/v1/zz_generated.deepcopy.go @@ -8,6 +8,32 @@ import ( runtime "k8s.io/apimachinery/pkg/runtime" ) +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *AccessControl) DeepCopyInto(out *AccessControl) { + *out = *in + if in.Allow != nil { + in, out := &in.Allow, &out.Allow + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.Deny != nil { + in, out := &in.Deny, &out.Deny + *out = make([]string, len(*in)) + copy(*out, *in) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AccessControl. +func (in *AccessControl) DeepCopy() *AccessControl { + if in == nil { + return nil + } + out := new(AccessControl) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Action) DeepCopyInto(out *Action) { *out = *in @@ -130,6 +156,32 @@ func (in *Condition) DeepCopy() *Condition { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *EgressMTLS) DeepCopyInto(out *EgressMTLS) { + *out = *in + if in.VerifyDepth != nil { + in, out := &in.VerifyDepth, &out.VerifyDepth + *out = new(int) + **out = **in + } + if in.SessionReuse != nil { + in, out := &in.SessionReuse, &out.SessionReuse + *out = new(bool) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EgressMTLS. +func (in *EgressMTLS) DeepCopy() *EgressMTLS { + if in == nil { + return nil + } + out := new(EgressMTLS) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ErrorPage) DeepCopyInto(out *ErrorPage) { *out = *in @@ -258,6 +310,43 @@ func (in *HealthCheck) DeepCopy() *HealthCheck { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *IngressMTLS) DeepCopyInto(out *IngressMTLS) { + *out = *in + if in.VerifyDepth != nil { + in, out := &in.VerifyDepth, &out.VerifyDepth + *out = new(int) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IngressMTLS. +func (in *IngressMTLS) DeepCopy() *IngressMTLS { + if in == nil { + return nil + } + out := new(IngressMTLS) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *JWTAuth) DeepCopyInto(out *JWTAuth) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new JWTAuth. +func (in *JWTAuth) DeepCopy() *JWTAuth { + if in == nil { + return nil + } + out := new(JWTAuth) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Match) DeepCopyInto(out *Match) { *out = *in @@ -291,6 +380,66 @@ func (in *Match) DeepCopy() *Match { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Policy) DeepCopyInto(out *Policy) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Policy. +func (in *Policy) DeepCopy() *Policy { + if in == nil { + return nil + } + out := new(Policy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Policy) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PolicyList) DeepCopyInto(out *PolicyList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Policy, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PolicyList. +func (in *PolicyList) DeepCopy() *PolicyList { + if in == nil { + return nil + } + out := new(PolicyList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *PolicyList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PolicyReference) DeepCopyInto(out *PolicyReference) { *out = *in @@ -307,6 +456,47 @@ func (in *PolicyReference) DeepCopy() *PolicyReference { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PolicySpec) DeepCopyInto(out *PolicySpec) { + *out = *in + if in.AccessControl != nil { + in, out := &in.AccessControl, &out.AccessControl + *out = new(AccessControl) + (*in).DeepCopyInto(*out) + } + if in.RateLimit != nil { + in, out := &in.RateLimit, &out.RateLimit + *out = new(RateLimit) + (*in).DeepCopyInto(*out) + } + if in.JWTAuth != nil { + in, out := &in.JWTAuth, &out.JWTAuth + *out = new(JWTAuth) + **out = **in + } + if in.IngressMTLS != nil { + in, out := &in.IngressMTLS, &out.IngressMTLS + *out = new(IngressMTLS) + (*in).DeepCopyInto(*out) + } + if in.EgressMTLS != nil { + in, out := &in.EgressMTLS, &out.EgressMTLS + *out = new(EgressMTLS) + (*in).DeepCopyInto(*out) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PolicySpec. +func (in *PolicySpec) DeepCopy() *PolicySpec { + if in == nil { + return nil + } + out := new(PolicySpec) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ProxyRequestHeaders) DeepCopyInto(out *ProxyRequestHeaders) { *out = *in @@ -369,6 +559,47 @@ func (in *ProxyResponseHeaders) DeepCopy() *ProxyResponseHeaders { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *RateLimit) DeepCopyInto(out *RateLimit) { + *out = *in + if in.Delay != nil { + in, out := &in.Delay, &out.Delay + *out = new(int) + **out = **in + } + if in.NoDelay != nil { + in, out := &in.NoDelay, &out.NoDelay + *out = new(bool) + **out = **in + } + if in.Burst != nil { + in, out := &in.Burst, &out.Burst + *out = new(int) + **out = **in + } + if in.DryRun != nil { + in, out := &in.DryRun, &out.DryRun + *out = new(bool) + **out = **in + } + if in.RejectCode != nil { + in, out := &in.RejectCode, &out.RejectCode + *out = new(int) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RateLimit. +func (in *RateLimit) DeepCopy() *RateLimit { + if in == nil { + return nil + } + out := new(RateLimit) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Route) DeepCopyInto(out *Route) { *out = *in diff --git a/pkg/apis/configuration/v1alpha1/register.go b/pkg/apis/configuration/v1alpha1/register.go index 563f068297..a6e7301c05 100644 --- a/pkg/apis/configuration/v1alpha1/register.go +++ b/pkg/apis/configuration/v1alpha1/register.go @@ -32,8 +32,6 @@ func addKnownTypes(scheme *runtime.Scheme) error { &GlobalConfigurationList{}, &TransportServer{}, &TransportServerList{}, - &Policy{}, - &PolicyList{}, ) metav1.AddToGroupVersion(scheme, SchemeGroupVersion) return nil diff --git a/pkg/apis/configuration/v1alpha1/types.go b/pkg/apis/configuration/v1alpha1/types.go index 7d43318427..795cbd02b0 100644 --- a/pkg/apis/configuration/v1alpha1/types.go +++ b/pkg/apis/configuration/v1alpha1/types.go @@ -101,83 +101,3 @@ type TransportServerList struct { Items []TransportServer `json:"items"` } - -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +kubebuilder:validation:Optional -// +kubebuilder:resource:shortName=pol - -// Policy defines a Policy for VirtualServer and VirtualServerRoute resources. -type Policy struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - Spec PolicySpec `json:"spec"` -} - -// PolicySpec is the spec of the Policy resource. -// The spec includes multiple fields, where each field represents a different policy. -// Only one policy (field) is allowed. -type PolicySpec struct { - AccessControl *AccessControl `json:"accessControl"` - RateLimit *RateLimit `json:"rateLimit"` - JWTAuth *JWTAuth `json:"jwt"` - IngressMTLS *IngressMTLS `json:"ingressMTLS"` - EgressMTLS *EgressMTLS `json:"egressMTLS"` -} - -// AccessControl defines an access policy based on the source IP of a request. -type AccessControl struct { - Allow []string `json:"allow"` - Deny []string `json:"deny"` -} - -// RateLimit defines a rate limit policy. -type RateLimit struct { - Rate string `json:"rate"` - Key string `json:"key"` - Delay *int `json:"delay"` - NoDelay *bool `json:"noDelay"` - Burst *int `json:"burst"` - ZoneSize string `json:"zoneSize"` - DryRun *bool `json:"dryRun"` - LogLevel string `json:"logLevel"` - RejectCode *int `json:"rejectCode"` -} - -// JWTAuth holds JWT authentication configuration. -type JWTAuth struct { - Realm string `json:"realm"` - Secret string `json:"secret"` - Token string `json:"token"` -} - -// IngressMTLS defines an Ingress MTLS policy. -type IngressMTLS struct { - ClientCertSecret string `json:"clientCertSecret"` - VerifyClient string `json:"verifyClient"` - VerifyDepth *int `json:"verifyDepth"` -} - -// EgressMTLS defines an Egress MTLS policy. -type EgressMTLS struct { - TLSSecret string `json:"tlsSecret"` - VerifyServer bool `json:"verifyServer"` - VerifyDepth *int `json:"verifyDepth"` - Protocols string `json:"protocols"` - SessionReuse *bool `json:"sessionReuse"` - Ciphers string `json:"ciphers"` - TrustedCertSecret string `json:"trustedCertSecret"` - ServerName bool `json:"serverName"` - SSLName string `json:"sslName"` -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// PolicyList is a list of the Policy resources. -type PolicyList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []Policy `json:"items"` -} diff --git a/pkg/apis/configuration/v1alpha1/zz_generated.deepcopy.go b/pkg/apis/configuration/v1alpha1/zz_generated.deepcopy.go index 0ad913889c..dd27745962 100644 --- a/pkg/apis/configuration/v1alpha1/zz_generated.deepcopy.go +++ b/pkg/apis/configuration/v1alpha1/zz_generated.deepcopy.go @@ -8,32 +8,6 @@ import ( runtime "k8s.io/apimachinery/pkg/runtime" ) -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *AccessControl) DeepCopyInto(out *AccessControl) { - *out = *in - if in.Allow != nil { - in, out := &in.Allow, &out.Allow - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.Deny != nil { - in, out := &in.Deny, &out.Deny - *out = make([]string, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AccessControl. -func (in *AccessControl) DeepCopy() *AccessControl { - if in == nil { - return nil - } - out := new(AccessControl) - in.DeepCopyInto(out) - return out -} - // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Action) DeepCopyInto(out *Action) { *out = *in @@ -50,32 +24,6 @@ func (in *Action) DeepCopy() *Action { return out } -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *EgressMTLS) DeepCopyInto(out *EgressMTLS) { - *out = *in - if in.VerifyDepth != nil { - in, out := &in.VerifyDepth, &out.VerifyDepth - *out = new(int) - **out = **in - } - if in.SessionReuse != nil { - in, out := &in.SessionReuse, &out.SessionReuse - *out = new(bool) - **out = **in - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EgressMTLS. -func (in *EgressMTLS) DeepCopy() *EgressMTLS { - if in == nil { - return nil - } - out := new(EgressMTLS) - in.DeepCopyInto(out) - return out -} - // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *GlobalConfiguration) DeepCopyInto(out *GlobalConfiguration) { *out = *in @@ -157,43 +105,6 @@ func (in *GlobalConfigurationSpec) DeepCopy() *GlobalConfigurationSpec { return out } -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *IngressMTLS) DeepCopyInto(out *IngressMTLS) { - *out = *in - if in.VerifyDepth != nil { - in, out := &in.VerifyDepth, &out.VerifyDepth - *out = new(int) - **out = **in - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IngressMTLS. -func (in *IngressMTLS) DeepCopy() *IngressMTLS { - if in == nil { - return nil - } - out := new(IngressMTLS) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *JWTAuth) DeepCopyInto(out *JWTAuth) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new JWTAuth. -func (in *JWTAuth) DeepCopy() *JWTAuth { - if in == nil { - return nil - } - out := new(JWTAuth) - in.DeepCopyInto(out) - return out -} - // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Listener) DeepCopyInto(out *Listener) { *out = *in @@ -210,148 +121,6 @@ func (in *Listener) DeepCopy() *Listener { return out } -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Policy) DeepCopyInto(out *Policy) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Policy. -func (in *Policy) DeepCopy() *Policy { - if in == nil { - return nil - } - out := new(Policy) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *Policy) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PolicyList) DeepCopyInto(out *PolicyList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]Policy, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PolicyList. -func (in *PolicyList) DeepCopy() *PolicyList { - if in == nil { - return nil - } - out := new(PolicyList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *PolicyList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PolicySpec) DeepCopyInto(out *PolicySpec) { - *out = *in - if in.AccessControl != nil { - in, out := &in.AccessControl, &out.AccessControl - *out = new(AccessControl) - (*in).DeepCopyInto(*out) - } - if in.RateLimit != nil { - in, out := &in.RateLimit, &out.RateLimit - *out = new(RateLimit) - (*in).DeepCopyInto(*out) - } - if in.JWTAuth != nil { - in, out := &in.JWTAuth, &out.JWTAuth - *out = new(JWTAuth) - **out = **in - } - if in.IngressMTLS != nil { - in, out := &in.IngressMTLS, &out.IngressMTLS - *out = new(IngressMTLS) - (*in).DeepCopyInto(*out) - } - if in.EgressMTLS != nil { - in, out := &in.EgressMTLS, &out.EgressMTLS - *out = new(EgressMTLS) - (*in).DeepCopyInto(*out) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PolicySpec. -func (in *PolicySpec) DeepCopy() *PolicySpec { - if in == nil { - return nil - } - out := new(PolicySpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *RateLimit) DeepCopyInto(out *RateLimit) { - *out = *in - if in.Delay != nil { - in, out := &in.Delay, &out.Delay - *out = new(int) - **out = **in - } - if in.NoDelay != nil { - in, out := &in.NoDelay, &out.NoDelay - *out = new(bool) - **out = **in - } - if in.Burst != nil { - in, out := &in.Burst, &out.Burst - *out = new(int) - **out = **in - } - if in.DryRun != nil { - in, out := &in.DryRun, &out.DryRun - *out = new(bool) - **out = **in - } - if in.RejectCode != nil { - in, out := &in.RejectCode, &out.RejectCode - *out = new(int) - **out = **in - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RateLimit. -func (in *RateLimit) DeepCopy() *RateLimit { - if in == nil { - return nil - } - out := new(RateLimit) - in.DeepCopyInto(out) - return out -} - // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *TransportServer) DeepCopyInto(out *TransportServer) { *out = *in diff --git a/pkg/apis/configuration/validation/policy.go b/pkg/apis/configuration/validation/policy.go index 92f79d1eed..75d1d6efef 100644 --- a/pkg/apis/configuration/validation/policy.go +++ b/pkg/apis/configuration/validation/policy.go @@ -7,18 +7,18 @@ import ( "strconv" "strings" - "github.com/nginxinc/kubernetes-ingress/pkg/apis/configuration/v1alpha1" + v1 "github.com/nginxinc/kubernetes-ingress/pkg/apis/configuration/v1" "k8s.io/apimachinery/pkg/util/validation" "k8s.io/apimachinery/pkg/util/validation/field" ) // ValidatePolicy validates a Policy. -func ValidatePolicy(policy *v1alpha1.Policy, isPlus bool) error { +func ValidatePolicy(policy *v1.Policy, isPlus bool) error { allErrs := validatePolicySpec(&policy.Spec, field.NewPath("spec"), isPlus) return allErrs.ToAggregate() } -func validatePolicySpec(spec *v1alpha1.PolicySpec, fieldPath *field.Path, isPlus bool) field.ErrorList { +func validatePolicySpec(spec *v1.PolicySpec, fieldPath *field.Path, isPlus bool) field.ErrorList { allErrs := field.ErrorList{} fieldCount := 0 @@ -64,7 +64,7 @@ func validatePolicySpec(spec *v1alpha1.PolicySpec, fieldPath *field.Path, isPlus return allErrs } -func validateAccessControl(accessControl *v1alpha1.AccessControl, fieldPath *field.Path) field.ErrorList { +func validateAccessControl(accessControl *v1.AccessControl, fieldPath *field.Path) field.ErrorList { allErrs := field.ErrorList{} fieldCount := 0 @@ -90,7 +90,7 @@ func validateAccessControl(accessControl *v1alpha1.AccessControl, fieldPath *fie return allErrs } -func validateRateLimit(rateLimit *v1alpha1.RateLimit, fieldPath *field.Path, isPlus bool) field.ErrorList { +func validateRateLimit(rateLimit *v1.RateLimit, fieldPath *field.Path, isPlus bool) field.ErrorList { allErrs := field.ErrorList{} allErrs = append(allErrs, validateRateLimitZoneSize(rateLimit.ZoneSize, fieldPath.Child("zoneSize"))...) @@ -119,7 +119,7 @@ func validateRateLimit(rateLimit *v1alpha1.RateLimit, fieldPath *field.Path, isP return allErrs } -func validateJWT(jwt *v1alpha1.JWTAuth, fieldPath *field.Path) field.ErrorList { +func validateJWT(jwt *v1.JWTAuth, fieldPath *field.Path) field.ErrorList { allErrs := field.ErrorList{} allErrs = append(allErrs, validateJWTRealm(jwt.Realm, fieldPath.Child("realm"))...) @@ -134,7 +134,7 @@ func validateJWT(jwt *v1alpha1.JWTAuth, fieldPath *field.Path) field.ErrorList { return allErrs } -func validateIngressMTLS(ingressMTLS *v1alpha1.IngressMTLS, fieldPath *field.Path) field.ErrorList { +func validateIngressMTLS(ingressMTLS *v1.IngressMTLS, fieldPath *field.Path) field.ErrorList { allErrs := field.ErrorList{} if ingressMTLS.ClientCertSecret == "" { @@ -150,7 +150,7 @@ func validateIngressMTLS(ingressMTLS *v1alpha1.IngressMTLS, fieldPath *field.Pat return allErrs } -func validateEgressMTLS(egressMTLS *v1alpha1.EgressMTLS, fieldPath *field.Path) field.ErrorList { +func validateEgressMTLS(egressMTLS *v1.EgressMTLS, fieldPath *field.Path) field.ErrorList { allErrs := field.ErrorList{} allErrs = append(allErrs, validateSecretName(egressMTLS.TLSSecret, fieldPath.Child("tlsSecret"))...) diff --git a/pkg/apis/configuration/validation/policy_test.go b/pkg/apis/configuration/validation/policy_test.go index acfda3489e..a739157748 100644 --- a/pkg/apis/configuration/validation/policy_test.go +++ b/pkg/apis/configuration/validation/policy_test.go @@ -3,14 +3,14 @@ package validation import ( "testing" - "github.com/nginxinc/kubernetes-ingress/pkg/apis/configuration/v1alpha1" + v1 "github.com/nginxinc/kubernetes-ingress/pkg/apis/configuration/v1" "k8s.io/apimachinery/pkg/util/validation/field" ) func TestValidatePolicy(t *testing.T) { - policy := &v1alpha1.Policy{ - Spec: v1alpha1.PolicySpec{ - AccessControl: &v1alpha1.AccessControl{ + policy := &v1.Policy{ + Spec: v1.PolicySpec{ + AccessControl: &v1.AccessControl{ Allow: []string{"127.0.0.1"}, }, }, @@ -24,8 +24,8 @@ func TestValidatePolicy(t *testing.T) { } func TestValidatePolicyFails(t *testing.T) { - policy := &v1alpha1.Policy{ - Spec: v1alpha1.PolicySpec{}, + policy := &v1.Policy{ + Spec: v1.PolicySpec{}, } isPlus := false @@ -34,12 +34,12 @@ func TestValidatePolicyFails(t *testing.T) { t.Errorf("ValidatePolicy() returned no error for invalid input") } - multiPolicy := &v1alpha1.Policy{ - Spec: v1alpha1.PolicySpec{ - AccessControl: &v1alpha1.AccessControl{ + multiPolicy := &v1.Policy{ + Spec: v1.PolicySpec{ + AccessControl: &v1.AccessControl{ Allow: []string{"127.0.0.1"}, }, - RateLimit: &v1alpha1.RateLimit{ + RateLimit: &v1.RateLimit{ Key: "${uri}", ZoneSize: "10M", Rate: "10r/s", @@ -54,7 +54,7 @@ func TestValidatePolicyFails(t *testing.T) { } func TestValidateAccessControl(t *testing.T) { - validInput := []*v1alpha1.AccessControl{ + validInput := []*v1.AccessControl{ { Allow: []string{}, }, @@ -79,31 +79,31 @@ func TestValidateAccessControl(t *testing.T) { func TestValidateAccessControlFails(t *testing.T) { tests := []struct { - accessControl *v1alpha1.AccessControl + accessControl *v1.AccessControl msg string }{ { - accessControl: &v1alpha1.AccessControl{ + accessControl: &v1.AccessControl{ Allow: nil, Deny: nil, }, msg: "neither allow nor deny is defined", }, { - accessControl: &v1alpha1.AccessControl{ + accessControl: &v1.AccessControl{ Allow: []string{}, Deny: []string{}, }, msg: "both allow and deny are defined", }, { - accessControl: &v1alpha1.AccessControl{ + accessControl: &v1.AccessControl{ Allow: []string{"invalid"}, }, msg: "invalid allow", }, { - accessControl: &v1alpha1.AccessControl{ + accessControl: &v1.AccessControl{ Deny: []string{"invalid"}, }, msg: "invalid deny", @@ -123,11 +123,11 @@ func TestValidateRateLimit(t *testing.T) { noDelay := false tests := []struct { - rateLimit *v1alpha1.RateLimit + rateLimit *v1.RateLimit msg string }{ { - rateLimit: &v1alpha1.RateLimit{ + rateLimit: &v1.RateLimit{ Rate: "10r/s", ZoneSize: "10M", Key: "${request_uri}", @@ -135,7 +135,7 @@ func TestValidateRateLimit(t *testing.T) { msg: "only required fields are set", }, { - rateLimit: &v1alpha1.RateLimit{ + rateLimit: &v1.RateLimit{ Rate: "30r/m", Key: "${request_uri}", Delay: createPointerFromInt(5), @@ -160,8 +160,8 @@ func TestValidateRateLimit(t *testing.T) { } } -func createInvalidRateLimit(f func(r *v1alpha1.RateLimit)) *v1alpha1.RateLimit { - validRateLimit := &v1alpha1.RateLimit{ +func createInvalidRateLimit(f func(r *v1.RateLimit)) *v1.RateLimit { + validRateLimit := &v1.RateLimit{ Rate: "10r/s", ZoneSize: "10M", Key: "${request_uri}", @@ -172,47 +172,47 @@ func createInvalidRateLimit(f func(r *v1alpha1.RateLimit)) *v1alpha1.RateLimit { func TestValidateRateLimitFails(t *testing.T) { tests := []struct { - rateLimit *v1alpha1.RateLimit + rateLimit *v1.RateLimit msg string }{ { - rateLimit: createInvalidRateLimit(func(r *v1alpha1.RateLimit) { + rateLimit: createInvalidRateLimit(func(r *v1.RateLimit) { r.Rate = "0r/s" }), msg: "invalid rateLimit rate", }, { - rateLimit: createInvalidRateLimit(func(r *v1alpha1.RateLimit) { + rateLimit: createInvalidRateLimit(func(r *v1.RateLimit) { r.Key = "${fail}" }), msg: "invalid rateLimit key variable use", }, { - rateLimit: createInvalidRateLimit(func(r *v1alpha1.RateLimit) { + rateLimit: createInvalidRateLimit(func(r *v1.RateLimit) { r.Delay = createPointerFromInt(0) }), msg: "invalid rateLimit delay", }, { - rateLimit: createInvalidRateLimit(func(r *v1alpha1.RateLimit) { + rateLimit: createInvalidRateLimit(func(r *v1.RateLimit) { r.Burst = createPointerFromInt(0) }), msg: "invalid rateLimit burst", }, { - rateLimit: createInvalidRateLimit(func(r *v1alpha1.RateLimit) { + rateLimit: createInvalidRateLimit(func(r *v1.RateLimit) { r.ZoneSize = "31k" }), msg: "invalid rateLimit zoneSize", }, { - rateLimit: createInvalidRateLimit(func(r *v1alpha1.RateLimit) { + rateLimit: createInvalidRateLimit(func(r *v1.RateLimit) { r.RejectCode = createPointerFromInt(600) }), msg: "invalid rateLimit rejectCode", }, { - rateLimit: createInvalidRateLimit(func(r *v1alpha1.RateLimit) { + rateLimit: createInvalidRateLimit(func(r *v1.RateLimit) { r.LogLevel = "invalid" }), msg: "invalid rateLimit logLevel", @@ -231,18 +231,18 @@ func TestValidateRateLimitFails(t *testing.T) { func TestValidateJWT(t *testing.T) { tests := []struct { - jwt *v1alpha1.JWTAuth + jwt *v1.JWTAuth msg string }{ { - jwt: &v1alpha1.JWTAuth{ + jwt: &v1.JWTAuth{ Realm: "My Product API", Secret: "my-jwk", }, msg: "basic", }, { - jwt: &v1alpha1.JWTAuth{ + jwt: &v1.JWTAuth{ Realm: "My Product API", Secret: "my-jwk", Token: "$cookie_auth_token", @@ -261,22 +261,22 @@ func TestValidateJWT(t *testing.T) { func TestValidateJWTFails(t *testing.T) { tests := []struct { msg string - jwt *v1alpha1.JWTAuth + jwt *v1.JWTAuth }{ { - jwt: &v1alpha1.JWTAuth{ + jwt: &v1.JWTAuth{ Realm: "My Product API", }, msg: "missing secret", }, { - jwt: &v1alpha1.JWTAuth{ + jwt: &v1.JWTAuth{ Secret: "my-jwk", }, msg: "missing realm", }, { - jwt: &v1alpha1.JWTAuth{ + jwt: &v1.JWTAuth{ Realm: "My Product API", Secret: "my-jwk", Token: "$uri", @@ -284,28 +284,28 @@ func TestValidateJWTFails(t *testing.T) { msg: "invalid variable use in token", }, { - jwt: &v1alpha1.JWTAuth{ + jwt: &v1.JWTAuth{ Realm: "My Product API", Secret: "my-\"jwk", }, msg: "invalid secret name", }, { - jwt: &v1alpha1.JWTAuth{ + jwt: &v1.JWTAuth{ Realm: "My \"Product API", Secret: "my-jwk", }, msg: "invalid realm due to escaped string", }, { - jwt: &v1alpha1.JWTAuth{ + jwt: &v1.JWTAuth{ Realm: "My Product ${api}", Secret: "my-jwk", }, msg: "invalid variable use in realm with curly braces", }, { - jwt: &v1alpha1.JWTAuth{ + jwt: &v1.JWTAuth{ Realm: "My Product $api", Secret: "my-jwk", }, @@ -503,17 +503,17 @@ func TestValidateJWTToken(t *testing.T) { func TestValidateIngressMTLS(t *testing.T) { tests := []struct { - ing *v1alpha1.IngressMTLS + ing *v1.IngressMTLS msg string }{ { - ing: &v1alpha1.IngressMTLS{ + ing: &v1.IngressMTLS{ ClientCertSecret: "mtls-secret", }, msg: "default", }, { - ing: &v1alpha1.IngressMTLS{ + ing: &v1.IngressMTLS{ ClientCertSecret: "mtls-secret", VerifyClient: "on", VerifyDepth: createPointerFromInt(1), @@ -521,7 +521,7 @@ func TestValidateIngressMTLS(t *testing.T) { msg: "all parameters with default value", }, { - ing: &v1alpha1.IngressMTLS{ + ing: &v1.IngressMTLS{ ClientCertSecret: "ingress-mtls-secret", VerifyClient: "optional", VerifyDepth: createPointerFromInt(2), @@ -539,30 +539,30 @@ func TestValidateIngressMTLS(t *testing.T) { func TestValidateIngressMTLSInvalid(t *testing.T) { tests := []struct { - ing *v1alpha1.IngressMTLS + ing *v1.IngressMTLS msg string }{ { - ing: &v1alpha1.IngressMTLS{ + ing: &v1.IngressMTLS{ VerifyClient: "on", }, msg: "no secret", }, { - ing: &v1alpha1.IngressMTLS{ + ing: &v1.IngressMTLS{ ClientCertSecret: "-foo-", }, msg: "invalid secret name", }, { - ing: &v1alpha1.IngressMTLS{ + ing: &v1.IngressMTLS{ ClientCertSecret: "mtls-secret", VerifyClient: "foo", }, msg: "invalid verify client", }, { - ing: &v1alpha1.IngressMTLS{ + ing: &v1.IngressMTLS{ ClientCertSecret: "ingress-mtls-secret", VerifyClient: "on", VerifyDepth: createPointerFromInt(-1), @@ -600,17 +600,17 @@ func TestValidateIngressMTLSVerifyClient(t *testing.T) { func TestValidateEgressMTLS(t *testing.T) { tests := []struct { - eg *v1alpha1.EgressMTLS + eg *v1.EgressMTLS msg string }{ { - eg: &v1alpha1.EgressMTLS{ + eg: &v1.EgressMTLS{ TLSSecret: "mtls-secret", }, msg: "tls secret", }, { - eg: &v1alpha1.EgressMTLS{ + eg: &v1.EgressMTLS{ TrustedCertSecret: "tls-secret", VerifyServer: true, VerifyDepth: createPointerFromInt(2), @@ -619,13 +619,13 @@ func TestValidateEgressMTLS(t *testing.T) { msg: "verify server set to true", }, { - eg: &v1alpha1.EgressMTLS{ + eg: &v1.EgressMTLS{ VerifyServer: false, }, msg: "verify server set to false", }, { - eg: &v1alpha1.EgressMTLS{ + eg: &v1.EgressMTLS{ SSLName: "foo.com", }, msg: "ssl name", @@ -641,23 +641,23 @@ func TestValidateEgressMTLS(t *testing.T) { func TestValidateEgressMTLSInvalid(t *testing.T) { tests := []struct { - eg *v1alpha1.EgressMTLS + eg *v1.EgressMTLS msg string }{ { - eg: &v1alpha1.EgressMTLS{ + eg: &v1.EgressMTLS{ VerifyServer: true, }, msg: "verify server set to true", }, { - eg: &v1alpha1.EgressMTLS{ + eg: &v1.EgressMTLS{ TrustedCertSecret: "-foo-", }, msg: "invalid secret name", }, { - eg: &v1alpha1.EgressMTLS{ + eg: &v1.EgressMTLS{ TrustedCertSecret: "ingress-mtls-secret", VerifyServer: true, VerifyDepth: createPointerFromInt(-1), @@ -665,7 +665,7 @@ func TestValidateEgressMTLSInvalid(t *testing.T) { msg: "invalid depth", }, { - eg: &v1alpha1.EgressMTLS{ + eg: &v1.EgressMTLS{ SSLName: "foo.com;", }, msg: "invalid name", diff --git a/pkg/client/clientset/versioned/typed/configuration/v1/configuration_client.go b/pkg/client/clientset/versioned/typed/configuration/v1/configuration_client.go index 64744ee65f..efcefdcca4 100644 --- a/pkg/client/clientset/versioned/typed/configuration/v1/configuration_client.go +++ b/pkg/client/clientset/versioned/typed/configuration/v1/configuration_client.go @@ -10,6 +10,7 @@ import ( type K8sV1Interface interface { RESTClient() rest.Interface + PoliciesGetter VirtualServersGetter VirtualServerRoutesGetter } @@ -19,6 +20,10 @@ type K8sV1Client struct { restClient rest.Interface } +func (c *K8sV1Client) Policies(namespace string) PolicyInterface { + return newPolicies(c, namespace) +} + func (c *K8sV1Client) VirtualServers(namespace string) VirtualServerInterface { return newVirtualServers(c, namespace) } diff --git a/pkg/client/clientset/versioned/typed/configuration/v1/fake/fake_configuration_client.go b/pkg/client/clientset/versioned/typed/configuration/v1/fake/fake_configuration_client.go index 8323f45eaf..3281d34a8a 100644 --- a/pkg/client/clientset/versioned/typed/configuration/v1/fake/fake_configuration_client.go +++ b/pkg/client/clientset/versioned/typed/configuration/v1/fake/fake_configuration_client.go @@ -12,6 +12,10 @@ type FakeK8sV1 struct { *testing.Fake } +func (c *FakeK8sV1) Policies(namespace string) v1.PolicyInterface { + return &FakePolicies{c, namespace} +} + func (c *FakeK8sV1) VirtualServers(namespace string) v1.VirtualServerInterface { return &FakeVirtualServers{c, namespace} } diff --git a/pkg/client/clientset/versioned/typed/configuration/v1alpha1/fake/fake_policy.go b/pkg/client/clientset/versioned/typed/configuration/v1/fake/fake_policy.go similarity index 68% rename from pkg/client/clientset/versioned/typed/configuration/v1alpha1/fake/fake_policy.go rename to pkg/client/clientset/versioned/typed/configuration/v1/fake/fake_policy.go index 38595726c6..1eab606fe4 100644 --- a/pkg/client/clientset/versioned/typed/configuration/v1alpha1/fake/fake_policy.go +++ b/pkg/client/clientset/versioned/typed/configuration/v1/fake/fake_policy.go @@ -5,7 +5,7 @@ package fake import ( "context" - v1alpha1 "github.com/nginxinc/kubernetes-ingress/pkg/apis/configuration/v1alpha1" + configurationv1 "github.com/nginxinc/kubernetes-ingress/pkg/apis/configuration/v1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" labels "k8s.io/apimachinery/pkg/labels" schema "k8s.io/apimachinery/pkg/runtime/schema" @@ -16,29 +16,29 @@ import ( // FakePolicies implements PolicyInterface type FakePolicies struct { - Fake *FakeK8sV1alpha1 + Fake *FakeK8sV1 ns string } -var policiesResource = schema.GroupVersionResource{Group: "k8s.nginx.org", Version: "v1alpha1", Resource: "policies"} +var policiesResource = schema.GroupVersionResource{Group: "k8s.nginx.org", Version: "v1", Resource: "policies"} -var policiesKind = schema.GroupVersionKind{Group: "k8s.nginx.org", Version: "v1alpha1", Kind: "Policy"} +var policiesKind = schema.GroupVersionKind{Group: "k8s.nginx.org", Version: "v1", Kind: "Policy"} // Get takes name of the policy, and returns the corresponding policy object, and an error if there is any. -func (c *FakePolicies) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.Policy, err error) { +func (c *FakePolicies) Get(ctx context.Context, name string, options v1.GetOptions) (result *configurationv1.Policy, err error) { obj, err := c.Fake. - Invokes(testing.NewGetAction(policiesResource, c.ns, name), &v1alpha1.Policy{}) + Invokes(testing.NewGetAction(policiesResource, c.ns, name), &configurationv1.Policy{}) if obj == nil { return nil, err } - return obj.(*v1alpha1.Policy), err + return obj.(*configurationv1.Policy), err } // List takes label and field selectors, and returns the list of Policies that match those selectors. -func (c *FakePolicies) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.PolicyList, err error) { +func (c *FakePolicies) List(ctx context.Context, opts v1.ListOptions) (result *configurationv1.PolicyList, err error) { obj, err := c.Fake. - Invokes(testing.NewListAction(policiesResource, policiesKind, c.ns, opts), &v1alpha1.PolicyList{}) + Invokes(testing.NewListAction(policiesResource, policiesKind, c.ns, opts), &configurationv1.PolicyList{}) if obj == nil { return nil, err @@ -48,8 +48,8 @@ func (c *FakePolicies) List(ctx context.Context, opts v1.ListOptions) (result *v if label == nil { label = labels.Everything() } - list := &v1alpha1.PolicyList{ListMeta: obj.(*v1alpha1.PolicyList).ListMeta} - for _, item := range obj.(*v1alpha1.PolicyList).Items { + list := &configurationv1.PolicyList{ListMeta: obj.(*configurationv1.PolicyList).ListMeta} + for _, item := range obj.(*configurationv1.PolicyList).Items { if label.Matches(labels.Set(item.Labels)) { list.Items = append(list.Items, item) } @@ -65,31 +65,31 @@ func (c *FakePolicies) Watch(ctx context.Context, opts v1.ListOptions) (watch.In } // Create takes the representation of a policy and creates it. Returns the server's representation of the policy, and an error, if there is any. -func (c *FakePolicies) Create(ctx context.Context, policy *v1alpha1.Policy, opts v1.CreateOptions) (result *v1alpha1.Policy, err error) { +func (c *FakePolicies) Create(ctx context.Context, policy *configurationv1.Policy, opts v1.CreateOptions) (result *configurationv1.Policy, err error) { obj, err := c.Fake. - Invokes(testing.NewCreateAction(policiesResource, c.ns, policy), &v1alpha1.Policy{}) + Invokes(testing.NewCreateAction(policiesResource, c.ns, policy), &configurationv1.Policy{}) if obj == nil { return nil, err } - return obj.(*v1alpha1.Policy), err + return obj.(*configurationv1.Policy), err } // Update takes the representation of a policy and updates it. Returns the server's representation of the policy, and an error, if there is any. -func (c *FakePolicies) Update(ctx context.Context, policy *v1alpha1.Policy, opts v1.UpdateOptions) (result *v1alpha1.Policy, err error) { +func (c *FakePolicies) Update(ctx context.Context, policy *configurationv1.Policy, opts v1.UpdateOptions) (result *configurationv1.Policy, err error) { obj, err := c.Fake. - Invokes(testing.NewUpdateAction(policiesResource, c.ns, policy), &v1alpha1.Policy{}) + Invokes(testing.NewUpdateAction(policiesResource, c.ns, policy), &configurationv1.Policy{}) if obj == nil { return nil, err } - return obj.(*v1alpha1.Policy), err + return obj.(*configurationv1.Policy), err } // Delete takes name of the policy and deletes it. Returns an error if one occurs. func (c *FakePolicies) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { _, err := c.Fake. - Invokes(testing.NewDeleteAction(policiesResource, c.ns, name), &v1alpha1.Policy{}) + Invokes(testing.NewDeleteAction(policiesResource, c.ns, name), &configurationv1.Policy{}) return err } @@ -98,17 +98,17 @@ func (c *FakePolicies) Delete(ctx context.Context, name string, opts v1.DeleteOp func (c *FakePolicies) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { action := testing.NewDeleteCollectionAction(policiesResource, c.ns, listOpts) - _, err := c.Fake.Invokes(action, &v1alpha1.PolicyList{}) + _, err := c.Fake.Invokes(action, &configurationv1.PolicyList{}) return err } // Patch applies the patch and returns the patched policy. -func (c *FakePolicies) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.Policy, err error) { +func (c *FakePolicies) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *configurationv1.Policy, err error) { obj, err := c.Fake. - Invokes(testing.NewPatchSubresourceAction(policiesResource, c.ns, name, pt, data, subresources...), &v1alpha1.Policy{}) + Invokes(testing.NewPatchSubresourceAction(policiesResource, c.ns, name, pt, data, subresources...), &configurationv1.Policy{}) if obj == nil { return nil, err } - return obj.(*v1alpha1.Policy), err + return obj.(*configurationv1.Policy), err } diff --git a/pkg/client/clientset/versioned/typed/configuration/v1/generated_expansion.go b/pkg/client/clientset/versioned/typed/configuration/v1/generated_expansion.go index d30bed91b1..1edd5af74e 100644 --- a/pkg/client/clientset/versioned/typed/configuration/v1/generated_expansion.go +++ b/pkg/client/clientset/versioned/typed/configuration/v1/generated_expansion.go @@ -2,6 +2,8 @@ package v1 +type PolicyExpansion interface{} + type VirtualServerExpansion interface{} type VirtualServerRouteExpansion interface{} diff --git a/pkg/client/clientset/versioned/typed/configuration/v1alpha1/policy.go b/pkg/client/clientset/versioned/typed/configuration/v1/policy.go similarity index 66% rename from pkg/client/clientset/versioned/typed/configuration/v1alpha1/policy.go rename to pkg/client/clientset/versioned/typed/configuration/v1/policy.go index f90324d076..9a7632a8fa 100644 --- a/pkg/client/clientset/versioned/typed/configuration/v1alpha1/policy.go +++ b/pkg/client/clientset/versioned/typed/configuration/v1/policy.go @@ -1,14 +1,14 @@ // Code generated by client-gen. DO NOT EDIT. -package v1alpha1 +package v1 import ( "context" "time" - v1alpha1 "github.com/nginxinc/kubernetes-ingress/pkg/apis/configuration/v1alpha1" + v1 "github.com/nginxinc/kubernetes-ingress/pkg/apis/configuration/v1" scheme "github.com/nginxinc/kubernetes-ingress/pkg/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" rest "k8s.io/client-go/rest" @@ -22,14 +22,14 @@ type PoliciesGetter interface { // PolicyInterface has methods to work with Policy resources. type PolicyInterface interface { - Create(ctx context.Context, policy *v1alpha1.Policy, opts v1.CreateOptions) (*v1alpha1.Policy, error) - Update(ctx context.Context, policy *v1alpha1.Policy, opts v1.UpdateOptions) (*v1alpha1.Policy, error) - Delete(ctx context.Context, name string, opts v1.DeleteOptions) error - DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.Policy, error) - List(ctx context.Context, opts v1.ListOptions) (*v1alpha1.PolicyList, error) - Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.Policy, err error) + Create(ctx context.Context, policy *v1.Policy, opts metav1.CreateOptions) (*v1.Policy, error) + Update(ctx context.Context, policy *v1.Policy, opts metav1.UpdateOptions) (*v1.Policy, error) + Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error + Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.Policy, error) + List(ctx context.Context, opts metav1.ListOptions) (*v1.PolicyList, error) + Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Policy, err error) PolicyExpansion } @@ -40,7 +40,7 @@ type policies struct { } // newPolicies returns a Policies -func newPolicies(c *K8sV1alpha1Client, namespace string) *policies { +func newPolicies(c *K8sV1Client, namespace string) *policies { return &policies{ client: c.RESTClient(), ns: namespace, @@ -48,8 +48,8 @@ func newPolicies(c *K8sV1alpha1Client, namespace string) *policies { } // Get takes name of the policy, and returns the corresponding policy object, and an error if there is any. -func (c *policies) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.Policy, err error) { - result = &v1alpha1.Policy{} +func (c *policies) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Policy, err error) { + result = &v1.Policy{} err = c.client.Get(). Namespace(c.ns). Resource("policies"). @@ -61,12 +61,12 @@ func (c *policies) Get(ctx context.Context, name string, options v1.GetOptions) } // List takes label and field selectors, and returns the list of Policies that match those selectors. -func (c *policies) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.PolicyList, err error) { +func (c *policies) List(ctx context.Context, opts metav1.ListOptions) (result *v1.PolicyList, err error) { var timeout time.Duration if opts.TimeoutSeconds != nil { timeout = time.Duration(*opts.TimeoutSeconds) * time.Second } - result = &v1alpha1.PolicyList{} + result = &v1.PolicyList{} err = c.client.Get(). Namespace(c.ns). Resource("policies"). @@ -78,7 +78,7 @@ func (c *policies) List(ctx context.Context, opts v1.ListOptions) (result *v1alp } // Watch returns a watch.Interface that watches the requested policies. -func (c *policies) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { +func (c *policies) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { var timeout time.Duration if opts.TimeoutSeconds != nil { timeout = time.Duration(*opts.TimeoutSeconds) * time.Second @@ -93,8 +93,8 @@ func (c *policies) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interf } // Create takes the representation of a policy and creates it. Returns the server's representation of the policy, and an error, if there is any. -func (c *policies) Create(ctx context.Context, policy *v1alpha1.Policy, opts v1.CreateOptions) (result *v1alpha1.Policy, err error) { - result = &v1alpha1.Policy{} +func (c *policies) Create(ctx context.Context, policy *v1.Policy, opts metav1.CreateOptions) (result *v1.Policy, err error) { + result = &v1.Policy{} err = c.client.Post(). Namespace(c.ns). Resource("policies"). @@ -106,8 +106,8 @@ func (c *policies) Create(ctx context.Context, policy *v1alpha1.Policy, opts v1. } // Update takes the representation of a policy and updates it. Returns the server's representation of the policy, and an error, if there is any. -func (c *policies) Update(ctx context.Context, policy *v1alpha1.Policy, opts v1.UpdateOptions) (result *v1alpha1.Policy, err error) { - result = &v1alpha1.Policy{} +func (c *policies) Update(ctx context.Context, policy *v1.Policy, opts metav1.UpdateOptions) (result *v1.Policy, err error) { + result = &v1.Policy{} err = c.client.Put(). Namespace(c.ns). Resource("policies"). @@ -120,7 +120,7 @@ func (c *policies) Update(ctx context.Context, policy *v1alpha1.Policy, opts v1. } // Delete takes name of the policy and deletes it. Returns an error if one occurs. -func (c *policies) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { +func (c *policies) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error { return c.client.Delete(). Namespace(c.ns). Resource("policies"). @@ -131,7 +131,7 @@ func (c *policies) Delete(ctx context.Context, name string, opts v1.DeleteOption } // DeleteCollection deletes a collection of objects. -func (c *policies) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { +func (c *policies) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error { var timeout time.Duration if listOpts.TimeoutSeconds != nil { timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second @@ -147,8 +147,8 @@ func (c *policies) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, } // Patch applies the patch and returns the patched policy. -func (c *policies) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.Policy, err error) { - result = &v1alpha1.Policy{} +func (c *policies) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Policy, err error) { + result = &v1.Policy{} err = c.client.Patch(pt). Namespace(c.ns). Resource("policies"). diff --git a/pkg/client/clientset/versioned/typed/configuration/v1alpha1/configuration_client.go b/pkg/client/clientset/versioned/typed/configuration/v1alpha1/configuration_client.go index 28b5a9809a..fafd2ede6e 100644 --- a/pkg/client/clientset/versioned/typed/configuration/v1alpha1/configuration_client.go +++ b/pkg/client/clientset/versioned/typed/configuration/v1alpha1/configuration_client.go @@ -11,7 +11,6 @@ import ( type K8sV1alpha1Interface interface { RESTClient() rest.Interface GlobalConfigurationsGetter - PoliciesGetter TransportServersGetter } @@ -24,10 +23,6 @@ func (c *K8sV1alpha1Client) GlobalConfigurations(namespace string) GlobalConfigu return newGlobalConfigurations(c, namespace) } -func (c *K8sV1alpha1Client) Policies(namespace string) PolicyInterface { - return newPolicies(c, namespace) -} - func (c *K8sV1alpha1Client) TransportServers(namespace string) TransportServerInterface { return newTransportServers(c, namespace) } diff --git a/pkg/client/clientset/versioned/typed/configuration/v1alpha1/fake/fake_configuration_client.go b/pkg/client/clientset/versioned/typed/configuration/v1alpha1/fake/fake_configuration_client.go index 9ad22127bd..3a9d183f70 100644 --- a/pkg/client/clientset/versioned/typed/configuration/v1alpha1/fake/fake_configuration_client.go +++ b/pkg/client/clientset/versioned/typed/configuration/v1alpha1/fake/fake_configuration_client.go @@ -16,10 +16,6 @@ func (c *FakeK8sV1alpha1) GlobalConfigurations(namespace string) v1alpha1.Global return &FakeGlobalConfigurations{c, namespace} } -func (c *FakeK8sV1alpha1) Policies(namespace string) v1alpha1.PolicyInterface { - return &FakePolicies{c, namespace} -} - func (c *FakeK8sV1alpha1) TransportServers(namespace string) v1alpha1.TransportServerInterface { return &FakeTransportServers{c, namespace} } diff --git a/pkg/client/clientset/versioned/typed/configuration/v1alpha1/generated_expansion.go b/pkg/client/clientset/versioned/typed/configuration/v1alpha1/generated_expansion.go index 80fc437593..5281dc8543 100644 --- a/pkg/client/clientset/versioned/typed/configuration/v1alpha1/generated_expansion.go +++ b/pkg/client/clientset/versioned/typed/configuration/v1alpha1/generated_expansion.go @@ -4,6 +4,4 @@ package v1alpha1 type GlobalConfigurationExpansion interface{} -type PolicyExpansion interface{} - type TransportServerExpansion interface{} diff --git a/pkg/client/informers/externalversions/configuration/v1/interface.go b/pkg/client/informers/externalversions/configuration/v1/interface.go index 2bf37e4715..85ebcfab80 100644 --- a/pkg/client/informers/externalversions/configuration/v1/interface.go +++ b/pkg/client/informers/externalversions/configuration/v1/interface.go @@ -8,6 +8,8 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { + // Policies returns a PolicyInformer. + Policies() PolicyInformer // VirtualServers returns a VirtualServerInformer. VirtualServers() VirtualServerInformer // VirtualServerRoutes returns a VirtualServerRouteInformer. @@ -25,6 +27,11 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } +// Policies returns a PolicyInformer. +func (v *version) Policies() PolicyInformer { + return &policyInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} + // VirtualServers returns a VirtualServerInformer. func (v *version) VirtualServers() VirtualServerInformer { return &virtualServerInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} diff --git a/pkg/client/informers/externalversions/configuration/v1alpha1/policy.go b/pkg/client/informers/externalversions/configuration/v1/policy.go similarity index 73% rename from pkg/client/informers/externalversions/configuration/v1alpha1/policy.go rename to pkg/client/informers/externalversions/configuration/v1/policy.go index 8cb91c2189..4f9a412588 100644 --- a/pkg/client/informers/externalversions/configuration/v1alpha1/policy.go +++ b/pkg/client/informers/externalversions/configuration/v1/policy.go @@ -1,16 +1,16 @@ // Code generated by informer-gen. DO NOT EDIT. -package v1alpha1 +package v1 import ( "context" time "time" - configurationv1alpha1 "github.com/nginxinc/kubernetes-ingress/pkg/apis/configuration/v1alpha1" + configurationv1 "github.com/nginxinc/kubernetes-ingress/pkg/apis/configuration/v1" versioned "github.com/nginxinc/kubernetes-ingress/pkg/client/clientset/versioned" internalinterfaces "github.com/nginxinc/kubernetes-ingress/pkg/client/informers/externalversions/internalinterfaces" - v1alpha1 "github.com/nginxinc/kubernetes-ingress/pkg/client/listers/configuration/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + v1 "github.com/nginxinc/kubernetes-ingress/pkg/client/listers/configuration/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" watch "k8s.io/apimachinery/pkg/watch" cache "k8s.io/client-go/tools/cache" @@ -20,7 +20,7 @@ import ( // Policies. type PolicyInformer interface { Informer() cache.SharedIndexInformer - Lister() v1alpha1.PolicyLister + Lister() v1.PolicyLister } type policyInformer struct { @@ -42,20 +42,20 @@ func NewPolicyInformer(client versioned.Interface, namespace string, resyncPerio func NewFilteredPolicyInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { return cache.NewSharedIndexInformer( &cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.K8sV1alpha1().Policies(namespace).List(context.TODO(), options) + return client.K8sV1().Policies(namespace).List(context.TODO(), options) }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.K8sV1alpha1().Policies(namespace).Watch(context.TODO(), options) + return client.K8sV1().Policies(namespace).Watch(context.TODO(), options) }, }, - &configurationv1alpha1.Policy{}, + &configurationv1.Policy{}, resyncPeriod, indexers, ) @@ -66,9 +66,9 @@ func (f *policyInformer) defaultInformer(client versioned.Interface, resyncPerio } func (f *policyInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&configurationv1alpha1.Policy{}, f.defaultInformer) + return f.factory.InformerFor(&configurationv1.Policy{}, f.defaultInformer) } -func (f *policyInformer) Lister() v1alpha1.PolicyLister { - return v1alpha1.NewPolicyLister(f.Informer().GetIndexer()) +func (f *policyInformer) Lister() v1.PolicyLister { + return v1.NewPolicyLister(f.Informer().GetIndexer()) } diff --git a/pkg/client/informers/externalversions/configuration/v1alpha1/interface.go b/pkg/client/informers/externalversions/configuration/v1alpha1/interface.go index b65ce74c68..1907744bb1 100644 --- a/pkg/client/informers/externalversions/configuration/v1alpha1/interface.go +++ b/pkg/client/informers/externalversions/configuration/v1alpha1/interface.go @@ -10,8 +10,6 @@ import ( type Interface interface { // GlobalConfigurations returns a GlobalConfigurationInformer. GlobalConfigurations() GlobalConfigurationInformer - // Policies returns a PolicyInformer. - Policies() PolicyInformer // TransportServers returns a TransportServerInformer. TransportServers() TransportServerInformer } @@ -32,11 +30,6 @@ func (v *version) GlobalConfigurations() GlobalConfigurationInformer { return &globalConfigurationInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// Policies returns a PolicyInformer. -func (v *version) Policies() PolicyInformer { - return &policyInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} - // TransportServers returns a TransportServerInformer. func (v *version) TransportServers() TransportServerInformer { return &transportServerInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} diff --git a/pkg/client/informers/externalversions/generic.go b/pkg/client/informers/externalversions/generic.go index a4ced52569..382de82263 100644 --- a/pkg/client/informers/externalversions/generic.go +++ b/pkg/client/informers/externalversions/generic.go @@ -38,6 +38,8 @@ func (f *genericInformer) Lister() cache.GenericLister { func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) { switch resource { // Group=k8s.nginx.org, Version=v1 + case v1.SchemeGroupVersion.WithResource("policies"): + return &genericInformer{resource: resource.GroupResource(), informer: f.K8s().V1().Policies().Informer()}, nil case v1.SchemeGroupVersion.WithResource("virtualservers"): return &genericInformer{resource: resource.GroupResource(), informer: f.K8s().V1().VirtualServers().Informer()}, nil case v1.SchemeGroupVersion.WithResource("virtualserverroutes"): @@ -46,8 +48,6 @@ func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource // Group=k8s.nginx.org, Version=v1alpha1 case v1alpha1.SchemeGroupVersion.WithResource("globalconfigurations"): return &genericInformer{resource: resource.GroupResource(), informer: f.K8s().V1alpha1().GlobalConfigurations().Informer()}, nil - case v1alpha1.SchemeGroupVersion.WithResource("policies"): - return &genericInformer{resource: resource.GroupResource(), informer: f.K8s().V1alpha1().Policies().Informer()}, nil case v1alpha1.SchemeGroupVersion.WithResource("transportservers"): return &genericInformer{resource: resource.GroupResource(), informer: f.K8s().V1alpha1().TransportServers().Informer()}, nil diff --git a/pkg/client/listers/configuration/v1/expansion_generated.go b/pkg/client/listers/configuration/v1/expansion_generated.go index 68f1e4ec79..bbbd79253c 100644 --- a/pkg/client/listers/configuration/v1/expansion_generated.go +++ b/pkg/client/listers/configuration/v1/expansion_generated.go @@ -2,6 +2,14 @@ package v1 +// PolicyListerExpansion allows custom methods to be added to +// PolicyLister. +type PolicyListerExpansion interface{} + +// PolicyNamespaceListerExpansion allows custom methods to be added to +// PolicyNamespaceLister. +type PolicyNamespaceListerExpansion interface{} + // VirtualServerListerExpansion allows custom methods to be added to // VirtualServerLister. type VirtualServerListerExpansion interface{} diff --git a/pkg/client/listers/configuration/v1alpha1/policy.go b/pkg/client/listers/configuration/v1/policy.go similarity index 78% rename from pkg/client/listers/configuration/v1alpha1/policy.go rename to pkg/client/listers/configuration/v1/policy.go index 8034a5d068..9d58b364e4 100644 --- a/pkg/client/listers/configuration/v1alpha1/policy.go +++ b/pkg/client/listers/configuration/v1/policy.go @@ -1,9 +1,9 @@ // Code generated by lister-gen. DO NOT EDIT. -package v1alpha1 +package v1 import ( - v1alpha1 "github.com/nginxinc/kubernetes-ingress/pkg/apis/configuration/v1alpha1" + v1 "github.com/nginxinc/kubernetes-ingress/pkg/apis/configuration/v1" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/labels" "k8s.io/client-go/tools/cache" @@ -14,7 +14,7 @@ import ( type PolicyLister interface { // List lists all Policies in the indexer. // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1alpha1.Policy, err error) + List(selector labels.Selector) (ret []*v1.Policy, err error) // Policies returns an object that can list and get Policies. Policies(namespace string) PolicyNamespaceLister PolicyListerExpansion @@ -31,9 +31,9 @@ func NewPolicyLister(indexer cache.Indexer) PolicyLister { } // List lists all Policies in the indexer. -func (s *policyLister) List(selector labels.Selector) (ret []*v1alpha1.Policy, err error) { +func (s *policyLister) List(selector labels.Selector) (ret []*v1.Policy, err error) { err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.Policy)) + ret = append(ret, m.(*v1.Policy)) }) return ret, err } @@ -48,10 +48,10 @@ func (s *policyLister) Policies(namespace string) PolicyNamespaceLister { type PolicyNamespaceLister interface { // List lists all Policies in the indexer for a given namespace. // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1alpha1.Policy, err error) + List(selector labels.Selector) (ret []*v1.Policy, err error) // Get retrieves the Policy from the indexer for a given namespace and name. // Objects returned here must be treated as read-only. - Get(name string) (*v1alpha1.Policy, error) + Get(name string) (*v1.Policy, error) PolicyNamespaceListerExpansion } @@ -63,21 +63,21 @@ type policyNamespaceLister struct { } // List lists all Policies in the indexer for a given namespace. -func (s policyNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Policy, err error) { +func (s policyNamespaceLister) List(selector labels.Selector) (ret []*v1.Policy, err error) { err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.Policy)) + ret = append(ret, m.(*v1.Policy)) }) return ret, err } // Get retrieves the Policy from the indexer for a given namespace and name. -func (s policyNamespaceLister) Get(name string) (*v1alpha1.Policy, error) { +func (s policyNamespaceLister) Get(name string) (*v1.Policy, error) { obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) if err != nil { return nil, err } if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("policy"), name) + return nil, errors.NewNotFound(v1.Resource("policy"), name) } - return obj.(*v1alpha1.Policy), nil + return obj.(*v1.Policy), nil } diff --git a/pkg/client/listers/configuration/v1alpha1/expansion_generated.go b/pkg/client/listers/configuration/v1alpha1/expansion_generated.go index e92ce0c811..82d94dca55 100644 --- a/pkg/client/listers/configuration/v1alpha1/expansion_generated.go +++ b/pkg/client/listers/configuration/v1alpha1/expansion_generated.go @@ -10,14 +10,6 @@ type GlobalConfigurationListerExpansion interface{} // GlobalConfigurationNamespaceLister. type GlobalConfigurationNamespaceListerExpansion interface{} -// PolicyListerExpansion allows custom methods to be added to -// PolicyLister. -type PolicyListerExpansion interface{} - -// PolicyNamespaceListerExpansion allows custom methods to be added to -// PolicyNamespaceLister. -type PolicyNamespaceListerExpansion interface{} - // TransportServerListerExpansion allows custom methods to be added to // TransportServerLister. type TransportServerListerExpansion interface{} From 76470e2c9a4f0d8e74f5996e2c78c1853a8a54a5 Mon Sep 17 00:00:00 2001 From: Dean Coakley Date: Thu, 17 Dec 2020 06:48:54 +0000 Subject: [PATCH 2/3] Update tests to use policy apiVersion v1 --- .../policies/access-control-policy-allow.yaml | 2 +- .../policies/access-control-policy-deny.yaml | 2 +- .../access-control-policy-invalid.yaml | 2 +- .../policies/jwt-policy-invalid-secret.yaml | 2 +- .../policies/jwt-policy-invalid.yaml | 2 +- .../policies/jwt-policy-valid-multi.yaml | 2 +- .../jwt-policy/policies/jwt-policy-valid.yaml | 2 +- .../policies/rate-limit-invalid.yaml | 2 +- .../policies/rate-limit-primary.yaml | 2 +- .../policies/rate-limit-secondary.yaml | 2 +- tests/suite/custom_resources_utils.py | 18 +++++++++--------- tests/suite/test_jwt_policies.py | 2 +- tests/suite/test_jwt_policies_vsr.py | 2 +- tests/suite/test_rl_policies.py | 4 ++-- tests/suite/test_rl_policies_vsr.py | 4 ++-- 15 files changed, 25 insertions(+), 25 deletions(-) diff --git a/tests/data/access-control/policies/access-control-policy-allow.yaml b/tests/data/access-control/policies/access-control-policy-allow.yaml index 1c03925b77..def8538f6d 100644 --- a/tests/data/access-control/policies/access-control-policy-allow.yaml +++ b/tests/data/access-control/policies/access-control-policy-allow.yaml @@ -1,4 +1,4 @@ -apiVersion: k8s.nginx.org/v1alpha1 +apiVersion: k8s.nginx.org/v1 kind: Policy metadata: name: allow-policy diff --git a/tests/data/access-control/policies/access-control-policy-deny.yaml b/tests/data/access-control/policies/access-control-policy-deny.yaml index 2c87aa3a03..227e0640e2 100644 --- a/tests/data/access-control/policies/access-control-policy-deny.yaml +++ b/tests/data/access-control/policies/access-control-policy-deny.yaml @@ -1,4 +1,4 @@ -apiVersion: k8s.nginx.org/v1alpha1 +apiVersion: k8s.nginx.org/v1 kind: Policy metadata: name: deny-policy diff --git a/tests/data/access-control/policies/access-control-policy-invalid.yaml b/tests/data/access-control/policies/access-control-policy-invalid.yaml index a34a70de06..714985b477 100644 --- a/tests/data/access-control/policies/access-control-policy-invalid.yaml +++ b/tests/data/access-control/policies/access-control-policy-invalid.yaml @@ -1,4 +1,4 @@ -apiVersion: k8s.nginx.org/v1alpha1 +apiVersion: k8s.nginx.org/v1 kind: Policy metadata: name: invalid-policy diff --git a/tests/data/jwt-policy/policies/jwt-policy-invalid-secret.yaml b/tests/data/jwt-policy/policies/jwt-policy-invalid-secret.yaml index 1060abf2a3..669bacded9 100644 --- a/tests/data/jwt-policy/policies/jwt-policy-invalid-secret.yaml +++ b/tests/data/jwt-policy/policies/jwt-policy-invalid-secret.yaml @@ -1,4 +1,4 @@ -apiVersion: k8s.nginx.org/v1alpha1 +apiVersion: k8s.nginx.org/v1 kind: Policy metadata: name: jwt-policy-invalid-secret diff --git a/tests/data/jwt-policy/policies/jwt-policy-invalid.yaml b/tests/data/jwt-policy/policies/jwt-policy-invalid.yaml index 9a5cfb3b6b..4c907e4e8a 100644 --- a/tests/data/jwt-policy/policies/jwt-policy-invalid.yaml +++ b/tests/data/jwt-policy/policies/jwt-policy-invalid.yaml @@ -1,4 +1,4 @@ -apiVersion: k8s.nginx.org/v1alpha1 +apiVersion: k8s.nginx.org/v1 kind: Policy metadata: name: jwt-policy-invalid diff --git a/tests/data/jwt-policy/policies/jwt-policy-valid-multi.yaml b/tests/data/jwt-policy/policies/jwt-policy-valid-multi.yaml index db82c1222a..9650c99627 100644 --- a/tests/data/jwt-policy/policies/jwt-policy-valid-multi.yaml +++ b/tests/data/jwt-policy/policies/jwt-policy-valid-multi.yaml @@ -1,4 +1,4 @@ -apiVersion: k8s.nginx.org/v1alpha1 +apiVersion: k8s.nginx.org/v1 kind: Policy metadata: name: jwt-policy-valid-multi diff --git a/tests/data/jwt-policy/policies/jwt-policy-valid.yaml b/tests/data/jwt-policy/policies/jwt-policy-valid.yaml index fdb258ec42..a7fc26afeb 100644 --- a/tests/data/jwt-policy/policies/jwt-policy-valid.yaml +++ b/tests/data/jwt-policy/policies/jwt-policy-valid.yaml @@ -1,4 +1,4 @@ -apiVersion: k8s.nginx.org/v1alpha1 +apiVersion: k8s.nginx.org/v1 kind: Policy metadata: name: jwt-policy-valid diff --git a/tests/data/rate-limit/policies/rate-limit-invalid.yaml b/tests/data/rate-limit/policies/rate-limit-invalid.yaml index 9a1b771eff..abe45414cb 100644 --- a/tests/data/rate-limit/policies/rate-limit-invalid.yaml +++ b/tests/data/rate-limit/policies/rate-limit-invalid.yaml @@ -1,4 +1,4 @@ -apiVersion: k8s.nginx.org/v1alpha1 +apiVersion: k8s.nginx.org/v1 kind: Policy metadata: name: rate-limit-invalid diff --git a/tests/data/rate-limit/policies/rate-limit-primary.yaml b/tests/data/rate-limit/policies/rate-limit-primary.yaml index 2cc3092107..8818efe614 100644 --- a/tests/data/rate-limit/policies/rate-limit-primary.yaml +++ b/tests/data/rate-limit/policies/rate-limit-primary.yaml @@ -1,4 +1,4 @@ -apiVersion: k8s.nginx.org/v1alpha1 +apiVersion: k8s.nginx.org/v1 kind: Policy metadata: name: rate-limit-primary diff --git a/tests/data/rate-limit/policies/rate-limit-secondary.yaml b/tests/data/rate-limit/policies/rate-limit-secondary.yaml index 5bc89f80ff..1956c51575 100644 --- a/tests/data/rate-limit/policies/rate-limit-secondary.yaml +++ b/tests/data/rate-limit/policies/rate-limit-secondary.yaml @@ -1,4 +1,4 @@ -apiVersion: k8s.nginx.org/v1alpha1 +apiVersion: k8s.nginx.org/v1 kind: Policy metadata: name: rate-limit-secondary diff --git a/tests/suite/custom_resources_utils.py b/tests/suite/custom_resources_utils.py index f30bf167ca..9b11f31933 100644 --- a/tests/suite/custom_resources_utils.py +++ b/tests/suite/custom_resources_utils.py @@ -83,7 +83,7 @@ def read_crd(custom_objects: CustomObjectsApi, namespace, plural, name) -> objec return response except ApiException: - logging.exception(f"Exception occured while getting reading CRD") + logging.exception(f"Exception occurred while reading CRD") raise @@ -104,7 +104,7 @@ def read_ap_crd(custom_objects: CustomObjectsApi, namespace, plural, name) -> ob return response except ApiException: - logging.exception(f"Exception occured while getting reading CRD") + logging.exception(f"Exception occurred while reading CRD") raise @@ -122,12 +122,12 @@ def create_policy_from_yaml(custom_objects: CustomObjectsApi, yaml_manifest, nam dep = yaml.safe_load(f) try: custom_objects.create_namespaced_custom_object( - "k8s.nginx.org", "v1alpha1", namespace, "policies", dep + "k8s.nginx.org", "v1", namespace, "policies", dep ) print(f"Policy created with name '{dep['metadata']['name']}'") return dep["metadata"]["name"] except ApiException: - logging.exception(f"Exception occured while creating Policy: {dep['metadata']['name']}") + logging.exception(f"Exception occurred while creating Policy: {dep['metadata']['name']}") raise @@ -144,12 +144,12 @@ def delete_policy(custom_objects: CustomObjectsApi, name, namespace) -> None: delete_options = client.V1DeleteOptions() custom_objects.delete_namespaced_custom_object( - "k8s.nginx.org", "v1alpha1", namespace, "policies", name, delete_options + "k8s.nginx.org", "v1", namespace, "policies", name, delete_options ) ensure_item_removal( custom_objects.get_namespaced_custom_object, "k8s.nginx.org", - "v1alpha1", + "v1", namespace, "policies", name, @@ -169,13 +169,13 @@ def read_policy(custom_objects: CustomObjectsApi, namespace, name) -> object: print(f"Getting info for policy {name} in namespace {namespace}") try: response = custom_objects.get_namespaced_custom_object( - "k8s.nginx.org", "v1alpha1", namespace, "policies", name + "k8s.nginx.org", "v1", namespace, "policies", name ) pprint(response) return response except ApiException: - logging.exception(f"Exception occured while getting reading Policy") + logging.exception(f"Exception occurred while reading Policy") raise @@ -201,7 +201,7 @@ def create_virtual_server_from_yaml( return dep["metadata"]["name"] except ApiException as ex: logging.exception( - f"Exception: {ex} occured while creating VirtualServer: {dep['metadata']['name']}" + f"Exception: {ex} occurred while creating VirtualServer: {dep['metadata']['name']}" ) raise diff --git a/tests/suite/test_jwt_policies.py b/tests/suite/test_jwt_policies.py index 8dd1eb36f1..44332ebded 100644 --- a/tests/suite/test_jwt_policies.py +++ b/tests/suite/test_jwt_policies.py @@ -52,7 +52,7 @@ ( { "type": "complete", - "extra_args": [f"-enable-custom-resources", f"-enable-leader-election=false"], + "extra_args": [f"-enable-custom-resources", f"-enable-preview-policies", f"-enable-leader-election=false"], }, {"example": "virtual-server", "app_type": "simple",}, ) diff --git a/tests/suite/test_jwt_policies_vsr.py b/tests/suite/test_jwt_policies_vsr.py index 2ef80da062..2691fd9319 100644 --- a/tests/suite/test_jwt_policies_vsr.py +++ b/tests/suite/test_jwt_policies_vsr.py @@ -59,7 +59,7 @@ ( { "type": "complete", - "extra_args": [f"-enable-custom-resources", f"-enable-leader-election=false"], + "extra_args": [f"-enable-custom-resources", f"-enable-preview-policies", f"-enable-leader-election=false"], }, {"example": "virtual-server-route"}, ) diff --git a/tests/suite/test_rl_policies.py b/tests/suite/test_rl_policies.py index 7a04aff6cc..94626174d0 100644 --- a/tests/suite/test_rl_policies.py +++ b/tests/suite/test_rl_policies.py @@ -33,14 +33,14 @@ ( { "type": "complete", - "extra_args": [f"-enable-custom-resources", f"-enable-leader-election=false"], + "extra_args": [f"-enable-custom-resources", f"-enable-preview-policies", f"-enable-leader-election=false"], }, {"example": "rate-limit", "app_type": "simple",}, ) ], indirect=True, ) -class TestRateLimitingPolcies: +class TestRateLimitingPolicies: def restore_default_vs(self, kube_apis, virtual_server_setup) -> None: """ Restore VirtualServer without policy spec diff --git a/tests/suite/test_rl_policies_vsr.py b/tests/suite/test_rl_policies_vsr.py index c220abb17e..c1c96b86f8 100644 --- a/tests/suite/test_rl_policies_vsr.py +++ b/tests/suite/test_rl_policies_vsr.py @@ -40,14 +40,14 @@ ( { "type": "complete", - "extra_args": [f"-enable-custom-resources", f"-enable-leader-election=false"], + "extra_args": [f"-enable-custom-resources", f"-enable-preview-policies", f"-enable-leader-election=false"], }, {"example": "virtual-server-route"}, ) ], indirect=True, ) -class TestRateLimitingPolciesVsr: +class TestRateLimitingPoliciesVsr: def restore_default_vsr(self, kube_apis, v_s_route_setup) -> None: """ Function to revert vsr deployments to valid state From 7243581c7277dbf14059d57a2d63fab7d1369813 Mon Sep 17 00:00:00 2001 From: Dean Coakley Date: Mon, 4 Jan 2021 16:48:53 +0000 Subject: [PATCH 3/3] Add preview policies feature flag --- cmd/nginx-ingress/main.go | 6 +- .../crds-v1beta1/k8s.nginx.org_policies.yaml | 10 +- .../common/crds/k8s.nginx.org_policies.yaml | 10 +- deployments/helm-chart/README.md | 1 + .../crds/k8s.nginx.org_policies.yaml | 10 +- .../templates/controller-deployment.yaml | 1 + deployments/helm-chart/values.yaml | 3 + .../command-line-arguments.md | 4 + docs-web/configuration/policy-resource.md | 8 +- .../installation/installation-with-helm.md | 3 + internal/k8s/controller.go | 9 +- pkg/apis/configuration/v1/types.go | 5 + pkg/apis/configuration/validation/policy.go | 22 ++- .../configuration/validation/policy_test.go | 162 ++++++++++++++---- 14 files changed, 196 insertions(+), 58 deletions(-) diff --git a/cmd/nginx-ingress/main.go b/cmd/nginx-ingress/main.go index d7342c4a28..ff524fe519 100644 --- a/cmd/nginx-ingress/main.go +++ b/cmd/nginx-ingress/main.go @@ -157,6 +157,9 @@ var ( enableCustomResources = flag.Bool("enable-custom-resources", true, "Enable custom resources") + enablePreviewPolicies = flag.Bool("enable-preview-policies", false, + "Enable preview policies") + enableSnippets = flag.Bool("enable-snippets", false, "Enable custom NGINX configuration snippets in VirtualServer and VirtualServerRoute resources.") @@ -227,7 +230,7 @@ func main() { } if *enableTLSPassthrough && !*enableCustomResources { - glog.Fatalf("enable-tls-passthrough flag requires -enable-custom-resources") + glog.Fatal("enable-tls-passthrough flag requires -enable-custom-resources") } if *appProtect && !*nginxPlus { @@ -624,6 +627,7 @@ func main() { ConfigMaps: *nginxConfigMaps, GlobalConfiguration: *globalConfiguration, AreCustomResourcesEnabled: *enableCustomResources, + EnablePreviewPolicies: *enablePreviewPolicies, MetricsCollector: controllerCollector, GlobalConfigurationValidator: globalConfigurationValidator, TransportServerValidator: transportServerValidator, diff --git a/deployments/common/crds-v1beta1/k8s.nginx.org_policies.yaml b/deployments/common/crds-v1beta1/k8s.nginx.org_policies.yaml index 3aa8b45331..5032e2b7c1 100644 --- a/deployments/common/crds-v1beta1/k8s.nginx.org_policies.yaml +++ b/deployments/common/crds-v1beta1/k8s.nginx.org_policies.yaml @@ -34,7 +34,7 @@ spec: type: object properties: accessControl: - description: AccessControl defines an access policy based on the source IP of a request. + description: 'AccessControl defines an access policy based on the source IP of a request. policy status: production-ready' type: object properties: allow: @@ -46,7 +46,7 @@ spec: items: type: string egressMTLS: - description: EgressMTLS defines an Egress MTLS policy. + description: 'EgressMTLS defines an Egress MTLS policy. policy status: preview' type: object properties: ciphers: @@ -68,7 +68,7 @@ spec: verifyServer: type: boolean ingressMTLS: - description: IngressMTLS defines an Ingress MTLS policy. + description: 'IngressMTLS defines an Ingress MTLS policy. policy status: preview' type: object properties: clientCertSecret: @@ -78,7 +78,7 @@ spec: verifyDepth: type: integer jwt: - description: JWTAuth holds JWT authentication configuration. + description: 'JWTAuth holds JWT authentication configuration. policy status: preview' type: object properties: realm: @@ -88,7 +88,7 @@ spec: token: type: string rateLimit: - description: RateLimit defines a rate limit policy. + description: 'RateLimit defines a rate limit policy. policy status: preview' type: object properties: burst: diff --git a/deployments/common/crds/k8s.nginx.org_policies.yaml b/deployments/common/crds/k8s.nginx.org_policies.yaml index 11e964152e..abb501cd93 100644 --- a/deployments/common/crds/k8s.nginx.org_policies.yaml +++ b/deployments/common/crds/k8s.nginx.org_policies.yaml @@ -35,7 +35,7 @@ spec: type: object properties: accessControl: - description: AccessControl defines an access policy based on the source IP of a request. + description: 'AccessControl defines an access policy based on the source IP of a request. policy status: production-ready' type: object properties: allow: @@ -47,7 +47,7 @@ spec: items: type: string egressMTLS: - description: EgressMTLS defines an Egress MTLS policy. + description: 'EgressMTLS defines an Egress MTLS policy. policy status: preview' type: object properties: ciphers: @@ -69,7 +69,7 @@ spec: verifyServer: type: boolean ingressMTLS: - description: IngressMTLS defines an Ingress MTLS policy. + description: 'IngressMTLS defines an Ingress MTLS policy. policy status: preview' type: object properties: clientCertSecret: @@ -79,7 +79,7 @@ spec: verifyDepth: type: integer jwt: - description: JWTAuth holds JWT authentication configuration. + description: 'JWTAuth holds JWT authentication configuration. policy status: preview' type: object properties: realm: @@ -89,7 +89,7 @@ spec: token: type: string rateLimit: - description: RateLimit defines a rate limit policy. + description: 'RateLimit defines a rate limit policy. policy status: preview' type: object properties: burst: diff --git a/deployments/helm-chart/README.md b/deployments/helm-chart/README.md index dab9b78f8b..299523ff05 100644 --- a/deployments/helm-chart/README.md +++ b/deployments/helm-chart/README.md @@ -170,6 +170,7 @@ Parameter | Description | Default `controller.setAsDefaultIngress` | New Ingresses without an `"ingressClassName"` field specified will be assigned the class specified in `controller.ingressClass`. Only for kubernetes versions >= 1.18. | false `controller.watchNamespace` | Namespace to watch for Ingress resources. By default the Ingress controller watches all namespaces. | "" `controller.enableCustomResources` | Enable the custom resources. | true +`controller.enablePreviewPolicies` | Enable preview policies. | false `controller.enableTLSPassthrough` | Enable TLS Passthrough on port 443. Requires `controller.enableCustomResources`. | false `controller.globalConfiguration.create` | Creates the GlobalConfiguration custom resource. Requires `controller.enableCustomResources`. | false `controller.globalConfiguration.spec` | The spec of the GlobalConfiguration for defining the global configuration parameters of the Ingress Controller. | {} diff --git a/deployments/helm-chart/crds/k8s.nginx.org_policies.yaml b/deployments/helm-chart/crds/k8s.nginx.org_policies.yaml index 3aa8b45331..5032e2b7c1 100644 --- a/deployments/helm-chart/crds/k8s.nginx.org_policies.yaml +++ b/deployments/helm-chart/crds/k8s.nginx.org_policies.yaml @@ -34,7 +34,7 @@ spec: type: object properties: accessControl: - description: AccessControl defines an access policy based on the source IP of a request. + description: 'AccessControl defines an access policy based on the source IP of a request. policy status: production-ready' type: object properties: allow: @@ -46,7 +46,7 @@ spec: items: type: string egressMTLS: - description: EgressMTLS defines an Egress MTLS policy. + description: 'EgressMTLS defines an Egress MTLS policy. policy status: preview' type: object properties: ciphers: @@ -68,7 +68,7 @@ spec: verifyServer: type: boolean ingressMTLS: - description: IngressMTLS defines an Ingress MTLS policy. + description: 'IngressMTLS defines an Ingress MTLS policy. policy status: preview' type: object properties: clientCertSecret: @@ -78,7 +78,7 @@ spec: verifyDepth: type: integer jwt: - description: JWTAuth holds JWT authentication configuration. + description: 'JWTAuth holds JWT authentication configuration. policy status: preview' type: object properties: realm: @@ -88,7 +88,7 @@ spec: token: type: string rateLimit: - description: RateLimit defines a rate limit policy. + description: 'RateLimit defines a rate limit policy. policy status: preview' type: object properties: burst: diff --git a/deployments/helm-chart/templates/controller-deployment.yaml b/deployments/helm-chart/templates/controller-deployment.yaml index 9673cb7f62..046835c1a8 100644 --- a/deployments/helm-chart/templates/controller-deployment.yaml +++ b/deployments/helm-chart/templates/controller-deployment.yaml @@ -144,6 +144,7 @@ spec: {{- if .Values.controller.enableCustomResources }} - -enable-tls-passthrough={{ .Values.controller.enableTLSPassthrough }} - -enable-snippets={{ .Values.controller.enableSnippets }} + - -enable-preview-policies={{ .Values.controller.enablePreviewPolicies }} {{- if .Values.controller.globalConfiguration.create }} - -global-configuration=$(POD_NAMESPACE)/{{ include "nginx-ingress.name" . }} {{- end }} diff --git a/deployments/helm-chart/values.yaml b/deployments/helm-chart/values.yaml index ba6bc07a7e..e8adeb702b 100644 --- a/deployments/helm-chart/values.yaml +++ b/deployments/helm-chart/values.yaml @@ -146,6 +146,9 @@ controller: ## Enable the custom resources. enableCustomResources: true + ## Enable preview policies. + enablePreviewPolicies: false + ## Enable TLS Passthrough on port 443. Requires controller.enableCustomResources. enableTLSPassthrough: false diff --git a/docs-web/configuration/global-configuration/command-line-arguments.md b/docs-web/configuration/global-configuration/command-line-arguments.md index d24d9563b0..faa4628610 100644 --- a/docs-web/configuration/global-configuration/command-line-arguments.md +++ b/docs-web/configuration/global-configuration/command-line-arguments.md @@ -33,6 +33,10 @@ Below we describe the available command-line arguments: Enables custom resources. (default true) +.. option:: -enable-preview-policies + + Enables preview policies. (default false) + .. option:: -enable-leader-election Enables Leader election to avoid multiple replicas of the controller reporting the status of Ingress, VirtualServer and VirtualServerRoute resources -- only one replica will report status. (default true) diff --git a/docs-web/configuration/policy-resource.md b/docs-web/configuration/policy-resource.md index 90896a152a..8760d6ee86 100644 --- a/docs-web/configuration/policy-resource.md +++ b/docs-web/configuration/policy-resource.md @@ -138,7 +138,7 @@ policies: ### RateLimit -> **Feature Status**: Rate-Limiting is available as a preview feature: it is suitable for experimenting and testing; however, it must be used with caution in production environments. Additionally, while the feature is in preview status, we might introduce some backward-incompatible changes to the resource specification in the next releases. +> **Feature Status**: Rate-Limiting is available as a preview feature: it is suitable for experimenting and testing; however, it must be used with caution in production environments. Additionally, while the feature is in preview status, we might introduce some backward-incompatible changes to the resource specification in the next releases. The feature is disabled by default. To enable it, set the [enable-preview-policies](/nginx-ingress-controller/configuration/global-configuration/command-line-arguments/#cmdoption-enable-preview-policies) command-line argument of the Ingress Controller. The rate limit policy configures NGINX to limit the processing rate of requests. @@ -212,7 +212,7 @@ When you reference more than one rate limit policy, the Ingress Controller will ### JWT -> **Feature Status**: JWT is available as a preview feature: it is suitable for experimenting and testing; however, it must be used with caution in production environments. Additionally, while the feature is in preview status, we might introduce some backward-incompatible changes to the resource specification in the next releases. +> **Feature Status**: JWT is available as a preview feature: it is suitable for experimenting and testing; however, it must be used with caution in production environments. Additionally, while the feature is in preview status, we might introduce some backward-incompatible changes to the resource specification in the next releases. The feature is disabled by default. To enable it, set the [enable-preview-policies](/nginx-ingress-controller/configuration/global-configuration/command-line-arguments/#cmdoption-enable-preview-policies) command-line argument of the Ingress Controller. > Note: This feature is only available in NGINX Plus. @@ -279,7 +279,7 @@ In this example the Ingress Controller will use the configuration from the first ### IngressMTLS -> **Feature Status**: IngressMTLS is available as a preview feature: it is suitable for experimenting and testing; however, it must be used with caution in production environments. Additionally, while the feature is in preview status, we might introduce some backward-incompatible changes to the resource specification in the next releases. +> **Feature Status**: IngressMTLS is available as a preview feature: it is suitable for experimenting and testing; however, it must be used with caution in production environments. Additionally, while the feature is in preview status, we might introduce some backward-incompatible changes to the resource specification in the next releases. The feature is disabled by default. To enable it, set the [enable-preview-policies](/nginx-ingress-controller/configuration/global-configuration/command-line-arguments/#cmdoption-enable-preview-policies) command-line argument of the Ingress Controller. The IngressMTLS policy configures client certificate verification. @@ -347,7 +347,7 @@ In this example the Ingress Controller will use the configuration from the first ### EgressMTLS -> **Feature Status**: EgressMTLS is available as a preview feature: it is suitable for experimenting and testing; however, it must be used with caution in production environments. Additionally, while the feature is in preview status, we might introduce some backward-incompatible changes to the resource specification in the next releases. +> **Feature Status**: EgressMTLS is available as a preview feature: it is suitable for experimenting and testing; however, it must be used with caution in production environments. Additionally, while the feature is in preview status, we might introduce some backward-incompatible changes to the resource specification in the next releases. The feature is disabled by default. To enable it, set the [enable-preview-policies](/nginx-ingress-controller/configuration/global-configuration/command-line-arguments/#cmdoption-enable-preview-policies) command-line argument of the Ingress Controller. The EgressMTLS policy configures upstreams authentication and certificate verification. diff --git a/docs-web/installation/installation-with-helm.md b/docs-web/installation/installation-with-helm.md index 81e886ae90..0640058e45 100644 --- a/docs-web/installation/installation-with-helm.md +++ b/docs-web/installation/installation-with-helm.md @@ -238,6 +238,9 @@ The following tables lists the configurable parameters of the NGINX Ingress cont * - ``controller.enableCustomResources`` - Enable the custom resources. - true + * - ``controller.enablePreviewPolicies`` + - Enable preview policies. + - false * - ``controller.enableTLSPassthrough`` - Enable TLS Passthrough on port 443. Requires ``controller.enableCustomResources``. - false diff --git a/internal/k8s/controller.go b/internal/k8s/controller.go index a30a7cf418..aeb3c0b3d0 100644 --- a/internal/k8s/controller.go +++ b/internal/k8s/controller.go @@ -171,6 +171,7 @@ type LoadBalancerController struct { controllerNamespace string wildcardTLSSecret string areCustomResourcesEnabled bool + enablePreviewPolicies bool metricsCollector collectors.ControllerCollector globalConfigurationValidator *validation.GlobalConfigurationValidator transportServerValidator *validation.TransportServerValidator @@ -210,6 +211,7 @@ type NewLoadBalancerControllerInput struct { ConfigMaps string GlobalConfiguration string AreCustomResourcesEnabled bool + EnablePreviewPolicies bool MetricsCollector collectors.ControllerCollector GlobalConfigurationValidator *validation.GlobalConfigurationValidator TransportServerValidator *validation.TransportServerValidator @@ -240,6 +242,7 @@ func NewLoadBalancerController(input NewLoadBalancerControllerInput) *LoadBalanc controllerNamespace: input.ControllerNamespace, wildcardTLSSecret: input.WildcardTLSSecret, areCustomResourcesEnabled: input.AreCustomResourcesEnabled, + enablePreviewPolicies: input.EnablePreviewPolicies, metricsCollector: input.MetricsCollector, globalConfigurationValidator: input.GlobalConfigurationValidator, transportServerValidator: input.TransportServerValidator, @@ -843,7 +846,7 @@ func (lbc *LoadBalancerController) syncPolicy(task task) { if polExists { pol := obj.(*conf_v1.Policy) - err := validation.ValidatePolicy(pol, lbc.isNginxPlus) + err := validation.ValidatePolicy(pol, lbc.isNginxPlus, lbc.enablePreviewPolicies) if err != nil { lbc.recorder.Eventf(pol, api_v1.EventTypeWarning, "Rejected", "Policy %v is invalid and was rejected: %v", key, err) } else { @@ -2326,7 +2329,7 @@ func (lbc *LoadBalancerController) getAllPolicies() []*conf_v1.Policy { for _, obj := range lbc.policyLister.List() { pol := obj.(*conf_v1.Policy) - err := validation.ValidatePolicy(pol, lbc.isNginxPlus) + err := validation.ValidatePolicy(pol, lbc.isNginxPlus, lbc.enablePreviewPolicies) if err != nil { glog.V(3).Infof("Skipping invalid Policy %s/%s: %v", pol.Namespace, pol.Name, err) continue @@ -2363,7 +2366,7 @@ func (lbc *LoadBalancerController) getPolicies(policies []conf_v1.PolicyReferenc policy := policyObj.(*conf_v1.Policy) - err = validation.ValidatePolicy(policy, lbc.isNginxPlus) + err = validation.ValidatePolicy(policy, lbc.isNginxPlus, lbc.enablePreviewPolicies) if err != nil { errors = append(errors, fmt.Errorf("Policy %s is invalid: %v", policyKey, err)) continue diff --git a/pkg/apis/configuration/v1/types.go b/pkg/apis/configuration/v1/types.go index 1dd96e1f0f..52e3f3b8c2 100644 --- a/pkg/apis/configuration/v1/types.go +++ b/pkg/apis/configuration/v1/types.go @@ -349,12 +349,14 @@ type PolicyList struct { } // AccessControl defines an access policy based on the source IP of a request. +// policy status: production-ready type AccessControl struct { Allow []string `json:"allow"` Deny []string `json:"deny"` } // RateLimit defines a rate limit policy. +// policy status: preview type RateLimit struct { Rate string `json:"rate"` Key string `json:"key"` @@ -368,6 +370,7 @@ type RateLimit struct { } // JWTAuth holds JWT authentication configuration. +// policy status: preview type JWTAuth struct { Realm string `json:"realm"` Secret string `json:"secret"` @@ -375,6 +378,7 @@ type JWTAuth struct { } // IngressMTLS defines an Ingress MTLS policy. +// policy status: preview type IngressMTLS struct { ClientCertSecret string `json:"clientCertSecret"` VerifyClient string `json:"verifyClient"` @@ -382,6 +386,7 @@ type IngressMTLS struct { } // EgressMTLS defines an Egress MTLS policy. +// policy status: preview type EgressMTLS struct { TLSSecret string `json:"tlsSecret"` VerifyServer bool `json:"verifyServer"` diff --git a/pkg/apis/configuration/validation/policy.go b/pkg/apis/configuration/validation/policy.go index 75d1d6efef..acd87cad7a 100644 --- a/pkg/apis/configuration/validation/policy.go +++ b/pkg/apis/configuration/validation/policy.go @@ -13,12 +13,12 @@ import ( ) // ValidatePolicy validates a Policy. -func ValidatePolicy(policy *v1.Policy, isPlus bool) error { - allErrs := validatePolicySpec(&policy.Spec, field.NewPath("spec"), isPlus) +func ValidatePolicy(policy *v1.Policy, isPlus bool, enablePreviewPolicies bool) error { + allErrs := validatePolicySpec(&policy.Spec, field.NewPath("spec"), isPlus, enablePreviewPolicies) return allErrs.ToAggregate() } -func validatePolicySpec(spec *v1.PolicySpec, fieldPath *field.Path, isPlus bool) field.ErrorList { +func validatePolicySpec(spec *v1.PolicySpec, fieldPath *field.Path, isPlus bool, enablePreviewPolicies bool) field.ErrorList { allErrs := field.ErrorList{} fieldCount := 0 @@ -29,11 +29,19 @@ func validatePolicySpec(spec *v1.PolicySpec, fieldPath *field.Path, isPlus bool) } if spec.RateLimit != nil { + if !enablePreviewPolicies { + return append(allErrs, field.Forbidden(fieldPath.Child("rateLimit"), + "rateLimit is a preview policy. Preview policies must be enabled to use via cli argument -enable-preview-policies")) + } allErrs = append(allErrs, validateRateLimit(spec.RateLimit, fieldPath.Child("rateLimit"), isPlus)...) fieldCount++ } if spec.JWTAuth != nil { + if !enablePreviewPolicies { + allErrs = append(allErrs, field.Forbidden(fieldPath.Child("jwt"), + "jwt is a preview policy. Preview policies must be enabled to use via cli argument -enable-preview-policies")) + } if !isPlus { return append(allErrs, field.Forbidden(fieldPath.Child("jwt"), "jwt secrets are only supported in NGINX Plus")) } @@ -43,11 +51,19 @@ func validatePolicySpec(spec *v1.PolicySpec, fieldPath *field.Path, isPlus bool) } if spec.IngressMTLS != nil { + if !enablePreviewPolicies { + return append(allErrs, field.Forbidden(fieldPath.Child("ingressMTLS"), + "ingressMTLS is a preview policy. Preview policies must be enabled to use via cli argument -enable-preview-policies")) + } allErrs = append(allErrs, validateIngressMTLS(spec.IngressMTLS, fieldPath.Child("ingressMTLS"))...) fieldCount++ } if spec.EgressMTLS != nil { + if !enablePreviewPolicies { + return append(allErrs, field.Forbidden(fieldPath.Child("egressMTLS"), + "egressMTLS is a preview policy. Preview policies must be enabled to use via cli argument -enable-preview-policies")) + } allErrs = append(allErrs, validateEgressMTLS(spec.EgressMTLS, fieldPath.Child("egressMTLS"))...) fieldCount++ } diff --git a/pkg/apis/configuration/validation/policy_test.go b/pkg/apis/configuration/validation/policy_test.go index a739157748..8e81c49ffb 100644 --- a/pkg/apis/configuration/validation/policy_test.go +++ b/pkg/apis/configuration/validation/policy_test.go @@ -8,48 +8,146 @@ import ( ) func TestValidatePolicy(t *testing.T) { - policy := &v1.Policy{ - Spec: v1.PolicySpec{ - AccessControl: &v1.AccessControl{ - Allow: []string{"127.0.0.1"}, + tests := []struct { + policy *v1.Policy + isPlus bool + enablePreviewPolicies bool + msg string + }{ + { + policy: &v1.Policy{ + Spec: v1.PolicySpec{ + AccessControl: &v1.AccessControl{ + Allow: []string{"127.0.0.1"}, + }, + }, + }, + isPlus: false, + enablePreviewPolicies: false, + }, + { + policy: &v1.Policy{ + Spec: v1.PolicySpec{ + JWTAuth: &v1.JWTAuth{ + Realm: "My Product API", + Secret: "my-jwk", + }, + }, }, + isPlus: true, + enablePreviewPolicies: true, + msg: "use jwt(plus only) policy", }, } - isPlus := false - - err := ValidatePolicy(policy, isPlus) - if err != nil { - t.Errorf("ValidatePolicy() returned error %v for valid input", err) + for _, test := range tests { + err := ValidatePolicy(test.policy, test.isPlus, test.enablePreviewPolicies) + if err != nil { + t.Errorf("ValidatePolicy() returned error %v for valid input", err) + } } } - func TestValidatePolicyFails(t *testing.T) { - policy := &v1.Policy{ - Spec: v1.PolicySpec{}, - } - isPlus := false - - err := ValidatePolicy(policy, isPlus) - if err == nil { - t.Errorf("ValidatePolicy() returned no error for invalid input") - } - - multiPolicy := &v1.Policy{ - Spec: v1.PolicySpec{ - AccessControl: &v1.AccessControl{ - Allow: []string{"127.0.0.1"}, + tests := []struct { + policy *v1.Policy + isPlus bool + enablePreviewPolicies bool + msg string + }{ + { + policy: &v1.Policy{ + Spec: v1.PolicySpec{}, }, - RateLimit: &v1.RateLimit{ - Key: "${uri}", - ZoneSize: "10M", - Rate: "10r/s", + isPlus: false, + enablePreviewPolicies: false, + msg: "empty policy spec", + }, + { + policy: &v1.Policy{ + Spec: v1.PolicySpec{ + AccessControl: &v1.AccessControl{ + Allow: []string{"127.0.0.1"}, + }, + RateLimit: &v1.RateLimit{ + Key: "${uri}", + ZoneSize: "10M", + Rate: "10r/s", + }, + }, + }, + isPlus: true, + enablePreviewPolicies: true, + msg: "multiple policies in spec", + }, + { + policy: &v1.Policy{ + Spec: v1.PolicySpec{ + JWTAuth: &v1.JWTAuth{ + Realm: "My Product API", + Secret: "my-jwk", + }, + }, + }, + isPlus: false, + enablePreviewPolicies: true, + msg: "jwt(plus only) policy on OSS", + }, + { + policy: &v1.Policy{ + Spec: v1.PolicySpec{ + RateLimit: &v1.RateLimit{ + Rate: "10r/s", + ZoneSize: "10M", + Key: "${request_uri}", + }, + }, + }, + isPlus: false, + enablePreviewPolicies: false, + msg: "rateLimit policy with preview policies disabled", + }, + { + policy: &v1.Policy{ + Spec: v1.PolicySpec{ + JWTAuth: &v1.JWTAuth{ + Realm: "My Product API", + Secret: "my-jwk", + }, + }, + }, + isPlus: true, + enablePreviewPolicies: false, + msg: "jwt policy with preview policies disabled", + }, + { + policy: &v1.Policy{ + Spec: v1.PolicySpec{ + IngressMTLS: &v1.IngressMTLS{ + ClientCertSecret: "mtls-secret", + }, + }, + }, + isPlus: false, + enablePreviewPolicies: false, + msg: "ingressMTLS policy with preview policies disabled", + }, + { + policy: &v1.Policy{ + Spec: v1.PolicySpec{ + EgressMTLS: &v1.EgressMTLS{ + TLSSecret: "mtls-secret", + }, + }, }, + isPlus: false, + enablePreviewPolicies: false, + msg: "egressMTLS policy with preview policies disabled", }, } - - err = ValidatePolicy(multiPolicy, isPlus) - if err == nil { - t.Errorf("ValidatePolicy() returned no error for invalid input") + for _, test := range tests { + err := ValidatePolicy(test.policy, test.isPlus, test.enablePreviewPolicies) + if err == nil { + t.Errorf("ValidatePolicy() returned no error for invalid input") + } } }