diff --git a/.gitignore b/.gitignore index 4154dc8a131..7f7f1a7e50a 100644 --- a/.gitignore +++ b/.gitignore @@ -16,7 +16,7 @@ bin *.out # Manager image patch file -config/manager_image_patch.yaml +overlays/dev/manager_image_patch.yaml # Kubernetes Generated files - skip generated files, except for vendored files diff --git a/Gopkg.lock b/Gopkg.lock index e2a3dec61c3..f63c5354aaa 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -444,18 +444,20 @@ [[projects]] branch = "master" - digest = "1:8e448f89b6d2feb0057f1c327ea24499c02275a6967749316adbb67f12e47884" + digest = "1:97900dffeb853bb5d97edaf13d4830d0275f901c6f5c559d8164ac7a24f49e5a" name = "github.com/open-policy-agent/frameworks" packages = [ "constraint/pkg/apis/templates/v1alpha1", + "constraint/pkg/apis/templates/v1beta1", "constraint/pkg/client", "constraint/pkg/client/drivers", "constraint/pkg/client/drivers/local", "constraint/pkg/client/regolib", + "constraint/pkg/core/templates", "constraint/pkg/types", ] pruneopts = "" - revision = "3586b8572da369f6d9a2ffba19c35a7a429e00ca" + revision = "33c568209f31d5f0198d7dad9ad06d9995646302" [[projects]] digest = "1:37eca0e6103236bc41d65f3d31a3a756f0ed1c96427a6a63746dae208ce1726a" @@ -1148,8 +1150,10 @@ "github.com/onsi/ginkgo", "github.com/onsi/gomega", "github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1alpha1", + "github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1", "github.com/open-policy-agent/frameworks/constraint/pkg/client", "github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/local", + "github.com/open-policy-agent/frameworks/constraint/pkg/core/templates", "github.com/open-policy-agent/frameworks/constraint/pkg/types", "github.com/open-policy-agent/opa/ast", "github.com/pkg/errors", @@ -1158,6 +1162,7 @@ "k8s.io/api/admissionregistration/v1beta1", "k8s.io/api/authentication/v1", "k8s.io/api/core/v1", + "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions", "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1", "k8s.io/apimachinery/pkg/api/errors", "k8s.io/apimachinery/pkg/api/meta", diff --git a/Makefile b/Makefile index b3c5050300e..705cea6eea8 100644 --- a/Makefile +++ b/Makefile @@ -62,14 +62,16 @@ install: manifests # Deploy controller in the configured Kubernetes cluster in ~/.kube/config deploy: manifests - touch -a ./config/manager_image_patch.yaml + touch -a ./overlays/dev/manager_image_patch.yaml kubectl apply -f config/crds - kubectl apply -f vendor/github.com/open-policy-agent/frameworks/constraint/config/crds - kustomize build config | kubectl apply -f - + kubectl apply -f vendor/github.com/open-policy-agent/frameworks/constraint/deploy + kustomize build overlays/dev | kubectl apply -f - # Generate manifests e.g. CRD, RBAC etc. manifests: go run vendor/sigs.k8s.io/controller-tools/cmd/controller-gen/main.go all + kustomize build config -o deploy/gatekeeper.yaml + bash -c 'for x in vendor/github.com/open-policy-agent/frameworks/constraint/deploy/*.yaml ; do echo --- >> deploy/gatekeeper.yaml ; cat $${x} >> deploy/gatekeeper.yaml ; done' # Run go fmt against code fmt: @@ -94,7 +96,7 @@ docker-tag-dev: # Tag for Dev docker-tag-release: @docker tag $(IMG) $(REPOSITORY):$(VERSION) - @docker tag $(IMG) $(REPOSITORY):latest + @docker tag $(IMG) $(REPOSITORY):latest # Push for Dev docker-push-dev: docker-tag-dev @@ -110,9 +112,9 @@ docker-build: docker build . -t ${IMG} @echo "updating kustomize image patch file for manager resource" - @test -s ./config/manager_image_patch.yaml || bash -c 'echo -e ${MANAGER_IMAGE_PATCH} > ./config/manager_image_patch.yaml' + @test -s ./overlays/dev/manager_image_patch.yaml || bash -c 'echo -e ${MANAGER_IMAGE_PATCH} > ./overlays/dev/manager_image_patch.yaml' - @sed -i'' -e 's@image: .*@image: '"${IMG}"'@' ./config/manager_image_patch.yaml + @sed -i'' -e 's@image: .*@image: '"${IMG}"'@' ./overlays/dev/manager_image_patch.yaml docker-build-ci: docker build . -t $(IMG) -f Dockerfile_ci diff --git a/README.md b/README.md index ffc5183adee..206f3d25636 100644 --- a/README.md +++ b/README.md @@ -144,7 +144,7 @@ spec: violation[{"msg": msg, "details": {"missing_labels": missing}}] { provided := {label | input.review.object.metadata.labels[label]} - required := {label | label := input.constraint.spec.parameters.labels[_]} + required := {label | label := input.parameters.labels[_]} missing := required - provided count(missing) > 0 msg := sprintf("you must provide labels: %v", [missing]) diff --git a/cmd/manager/main.go b/cmd/manager/main.go index cc4d7de1378..fc452f1d5e9 100644 --- a/cmd/manager/main.go +++ b/cmd/manager/main.go @@ -21,6 +21,7 @@ import ( "github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/local" "github.com/open-policy-agent/gatekeeper/pkg/apis" "github.com/open-policy-agent/gatekeeper/pkg/audit" + "github.com/open-policy-agent/gatekeeper/pkg/upgrade" "github.com/open-policy-agent/gatekeeper/pkg/controller" "github.com/open-policy-agent/gatekeeper/pkg/target" "github.com/open-policy-agent/gatekeeper/pkg/webhook" @@ -95,6 +96,12 @@ func main() { os.Exit(1) } + log.Info("setting up upgrade") + if err := upgrade.AddToManager(mgr); err != nil { + log.Error(err, "unable to register upgrade to the manager") + os.Exit(1) + } + // Start the Cmd log.Info("Starting the Cmd.") if err := mgr.Start(signals.SetupSignalHandler()); err != nil { diff --git a/config/kustomization.yaml b/config/kustomization.yaml index 892a1032c41..3d5e6d4466b 100644 --- a/config/kustomization.yaml +++ b/config/kustomization.yaml @@ -21,9 +21,7 @@ resources: - rbac/rbac_role.yaml - rbac/rbac_role_binding.yaml - manager/manager.yaml - -patches: -- manager_image_patch.yaml +- crds/config_v1alpha1_config.yaml vars: - name: WEBHOOK_SECRET_NAME diff --git a/config/manager/manager.yaml b/config/manager/manager.yaml index 4d105e23e27..f3bef999941 100644 --- a/config/manager/manager.yaml +++ b/config/manager/manager.yaml @@ -2,6 +2,7 @@ apiVersion: v1 kind: Namespace metadata: labels: + control-plane: controller-manager controller-tools.k8s.io: "1.0" name: system --- @@ -43,17 +44,19 @@ spec: containers: - command: - /root/manager - # args: + args: + - "--auditInterval=30" # - "--alsologtostderr" # - "--stderrthreshold=INFO" # - "-v=100" - image: controller:latest + image: quay.io/open-policy-agent/gatekeeper:v3.0.4-alpha.0 imagePullPolicy: Always name: manager env: - name: POD_NAMESPACE valueFrom: fieldRef: + apiVersion: v1 fieldPath: metadata.namespace - name: POD_NAME valueFrom: @@ -69,7 +72,7 @@ spec: cpu: 100m memory: 256Mi ports: - - containerPort: 9876 + - containerPort: 443 name: webhook-server protocol: TCP volumeMounts: diff --git a/demo/agilebank/constraints/containers_must_be_limited.yaml b/demo/agilebank/constraints/containers_must_be_limited.yaml index e99879ff1db..2b06fd8d18a 100644 --- a/demo/agilebank/constraints/containers_must_be_limited.yaml +++ b/demo/agilebank/constraints/containers_must_be_limited.yaml @@ -1,4 +1,4 @@ -apiVersion: constraints.gatekeeper.sh/v1alpha1 +apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sContainerLimits metadata: name: container-must-have-limits diff --git a/demo/agilebank/constraints/owner_must_be_provided.yaml b/demo/agilebank/constraints/owner_must_be_provided.yaml index 4bcfbd7b1e7..806e9862ffc 100644 --- a/demo/agilebank/constraints/owner_must_be_provided.yaml +++ b/demo/agilebank/constraints/owner_must_be_provided.yaml @@ -1,4 +1,4 @@ -apiVersion: constraints.gatekeeper.sh/v1alpha1 +apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sRequiredLabels metadata: name: all-must-have-owner diff --git a/demo/agilebank/constraints/prod_repo_is_openpolicyagent.yaml b/demo/agilebank/constraints/prod_repo_is_openpolicyagent.yaml index 4dd7fe933bd..68c9bd31762 100644 --- a/demo/agilebank/constraints/prod_repo_is_openpolicyagent.yaml +++ b/demo/agilebank/constraints/prod_repo_is_openpolicyagent.yaml @@ -1,4 +1,4 @@ -apiVersion: constraints.gatekeeper.sh/v1alpha1 +apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sAllowedRepos metadata: name: prod-repo-is-openpolicyagent diff --git a/demo/agilebank/constraints/unique_service_selector.yaml b/demo/agilebank/constraints/unique_service_selector.yaml index 0fdb7f8d701..3a00cd8b1bd 100644 --- a/demo/agilebank/constraints/unique_service_selector.yaml +++ b/demo/agilebank/constraints/unique_service_selector.yaml @@ -1,4 +1,4 @@ -apiVersion: constraints.gatekeeper.sh/v1alpha1 +apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sUniqueServiceSelector metadata: name: unique-service-selector diff --git a/demo/agilebank/remediation/ban_latest_tag.yaml b/demo/agilebank/remediation/ban_latest_tag.yaml index 2ad7c348715..0d1edf19993 100644 --- a/demo/agilebank/remediation/ban_latest_tag.yaml +++ b/demo/agilebank/remediation/ban_latest_tag.yaml @@ -1,4 +1,4 @@ -apiVersion: constraints.gatekeeper.sh/v1alpha1 +apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sBannedImageTags metadata: name: ban-latest-tag diff --git a/demo/agilebank/remediation/k8sbannedimagetags_template.yaml b/demo/agilebank/remediation/k8sbannedimagetags_template.yaml index 23785f7eb40..1e104503005 100644 --- a/demo/agilebank/remediation/k8sbannedimagetags_template.yaml +++ b/demo/agilebank/remediation/k8sbannedimagetags_template.yaml @@ -1,4 +1,4 @@ -apiVersion: templates.gatekeeper.sh/v1alpha1 +apiVersion: templates.gatekeeper.sh/v1beta1 kind: ConstraintTemplate metadata: name: k8sbannedimagetags diff --git a/demo/agilebank/templates/k8sallowedrepos_template.yaml b/demo/agilebank/templates/k8sallowedrepos_template.yaml index a3c1dc30be8..2cc68e33fd1 100644 --- a/demo/agilebank/templates/k8sallowedrepos_template.yaml +++ b/demo/agilebank/templates/k8sallowedrepos_template.yaml @@ -1,4 +1,4 @@ -apiVersion: templates.gatekeeper.sh/v1alpha1 +apiVersion: templates.gatekeeper.sh/v1beta1 kind: ConstraintTemplate metadata: name: k8sallowedrepos @@ -25,7 +25,7 @@ spec: violation[{"msg": msg}] { container := input.review.object.spec.containers[_] - satisfied := [good | repo = input.constraint.spec.parameters.repos[_] ; good = startswith(container.image, repo)] + satisfied := [good | repo = input.parameters.repos[_] ; good = startswith(container.image, repo)] not any(satisfied) - msg := sprintf("container <%v> has an invalid image repo <%v>, allowed repos are %v", [container.name, container.image, input.constraint.spec.parameters.repos]) + msg := sprintf("container <%v> has an invalid image repo <%v>, allowed repos are %v", [container.name, container.image, input.parameters.repos]) } diff --git a/demo/agilebank/templates/k8scontainterlimits_template.yaml b/demo/agilebank/templates/k8scontainterlimits_template.yaml index c9e19f9d587..d7627d28227 100644 --- a/demo/agilebank/templates/k8scontainterlimits_template.yaml +++ b/demo/agilebank/templates/k8scontainterlimits_template.yaml @@ -1,4 +1,4 @@ -apiVersion: templates.gatekeeper.sh/v1alpha1 +apiVersion: templates.gatekeeper.sh/v1beta1 kind: ConstraintTemplate metadata: name: k8scontainerlimits @@ -166,7 +166,7 @@ spec: container := input.review.object.spec.containers[_] cpu_orig := container.resources.limits.cpu cpu := canonify_cpu(cpu_orig) - max_cpu_orig := input.constraint.spec.parameters.cpu + max_cpu_orig := input.parameters.cpu max_cpu := canonify_cpu(max_cpu_orig) cpu > max_cpu msg := sprintf("container <%v> cpu limit <%v> is higher than the maximum allowed of <%v>", [container.name, cpu_orig, max_cpu_orig]) @@ -176,7 +176,7 @@ spec: container := input.review.object.spec.containers[_] mem_orig := container.resources.limits.memory mem := canonify_mem(mem_orig) - max_mem_orig := input.constraint.spec.parameters.memory + max_mem_orig := input.parameters.memory max_mem := canonify_mem(max_mem_orig) mem > max_mem msg := sprintf("container <%v> memory limit <%v> is higher than the maximum allowed of <%v>", [container.name, mem_orig, max_mem_orig]) diff --git a/demo/agilebank/templates/k8srequiredlabels_template.yaml b/demo/agilebank/templates/k8srequiredlabels_template.yaml index d739f1ad2ba..133ff4fbd1d 100644 --- a/demo/agilebank/templates/k8srequiredlabels_template.yaml +++ b/demo/agilebank/templates/k8srequiredlabels_template.yaml @@ -1,4 +1,4 @@ -apiVersion: templates.gatekeeper.sh/v1alpha1 +apiVersion: templates.gatekeeper.sh/v1beta1 kind: ConstraintTemplate metadata: name: k8srequiredlabels @@ -30,31 +30,31 @@ spec: rego: | package k8srequiredlabels - get_message(constraint, _default) = msg { - not constraint.spec.parameters.message + get_message(parameters, _default) = msg { + not parameters.message msg := _default } - get_message(constraint, _default) = msg { - msg := constraint.spec.parameters.message + get_message(parameters, _default) = msg { + msg := parameters.message } violation[{"msg": msg, "details": {"missing_labels": missing}}] { provided := {label | input.review.object.metadata.labels[label]} - required := {label | label := input.constraint.spec.parameters.labels[_].key} + required := {label | label := input.parameters.labels[_].key} missing := required - provided count(missing) > 0 def_msg := sprintf("you must provide labels: %v", [missing]) - msg := get_message(input.constraint, def_msg) + msg := get_message(input.parameters, def_msg) } violation[{"msg": msg}] { value := input.review.object.metadata.labels[key] - expected := input.constraint.spec.parameters.labels[_] + expected := input.parameters.labels[_] expected.key == key # do not match if allowedRegex is not defined, or is an empty string expected.allowedRegex != "" not re_match(expected.allowedRegex, value) def_msg := sprintf("Label <%v: %v> does not satisfy allowed regex: %v", [key, value, expected.allowedRegex]) - msg := get_message(input.constraint, def_msg) + msg := get_message(input.parameters, def_msg) } diff --git a/demo/agilebank/templates/k8suniqueserviceselector_template.yaml b/demo/agilebank/templates/k8suniqueserviceselector_template.yaml index 61e93dbb5ae..a7e868ac547 100644 --- a/demo/agilebank/templates/k8suniqueserviceselector_template.yaml +++ b/demo/agilebank/templates/k8suniqueserviceselector_template.yaml @@ -1,4 +1,4 @@ -apiVersion: templates.gatekeeper.sh/v1alpha1 +apiVersion: templates.gatekeeper.sh/v1beta1 kind: ConstraintTemplate metadata: name: k8suniqueserviceselector diff --git a/demo/basic/bad/bad_constraint_labelselector.yaml b/demo/basic/bad/bad_constraint_labelselector.yaml index 15b470c93fe..5a3f3865425 100644 --- a/demo/basic/bad/bad_constraint_labelselector.yaml +++ b/demo/basic/bad/bad_constraint_labelselector.yaml @@ -1,4 +1,4 @@ -apiVersion: constraints.gatekeeper.sh/v1alpha1 +apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sUniqueLabel metadata: name: ns-gk-label-unique diff --git a/demo/basic/bad/bad_schema.yaml b/demo/basic/bad/bad_schema.yaml index 46bc69f0b23..c5d8c2e6c16 100644 --- a/demo/basic/bad/bad_schema.yaml +++ b/demo/basic/bad/bad_schema.yaml @@ -1,4 +1,4 @@ -apiVersion: constraints.gatekeeper.sh/v1alpha1 +apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sRequiredLabel metadata: name: bad-schema diff --git a/demo/basic/bad/bad_schema2.yaml b/demo/basic/bad/bad_schema2.yaml index bb5f616d633..2771a177abe 100644 --- a/demo/basic/bad/bad_schema2.yaml +++ b/demo/basic/bad/bad_schema2.yaml @@ -1,4 +1,4 @@ -apiVersion: constraints.gatekeeper.sh/v1alpha1 +apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sRequiredLabel metadata: name: bad-schema diff --git a/demo/basic/bad/bad_schema3.yaml b/demo/basic/bad/bad_schema3.yaml index 2c19fc8b4c3..4149b422b7d 100644 --- a/demo/basic/bad/bad_schema3.yaml +++ b/demo/basic/bad/bad_schema3.yaml @@ -1,4 +1,4 @@ -apiVersion: constraints.gatekeeper.sh/v1alpha1 +apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sRequiredLabel metadata: name: bad-schema diff --git a/demo/basic/bad/bad_template.yaml b/demo/basic/bad/bad_template.yaml index d26340b4ad4..e3702d9dfbe 100644 --- a/demo/basic/bad/bad_template.yaml +++ b/demo/basic/bad/bad_template.yaml @@ -1,4 +1,4 @@ -apiVersion: templates.gatekeeper.sh/v1alpha1 +apiVersion: templates.gatekeeper.sh/v1beta1 kind: ConstraintTemplate metadata: name: k8suniquelabels diff --git a/demo/basic/constraints/all_ns_gatekeeper_label_unique.yaml b/demo/basic/constraints/all_ns_gatekeeper_label_unique.yaml index 606e9c8cc08..6cc519765fa 100644 --- a/demo/basic/constraints/all_ns_gatekeeper_label_unique.yaml +++ b/demo/basic/constraints/all_ns_gatekeeper_label_unique.yaml @@ -1,4 +1,4 @@ -apiVersion: constraints.gatekeeper.sh/v1alpha1 +apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sUniqueLabel metadata: name: ns-gk-label-unique diff --git a/demo/basic/constraints/all_ns_must_have_gatekeeper.yaml b/demo/basic/constraints/all_ns_must_have_gatekeeper.yaml index eb7962b2715..0c3c5b4f51d 100644 --- a/demo/basic/constraints/all_ns_must_have_gatekeeper.yaml +++ b/demo/basic/constraints/all_ns_must_have_gatekeeper.yaml @@ -1,4 +1,4 @@ -apiVersion: constraints.gatekeeper.sh/v1alpha1 +apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sRequiredLabels metadata: name: ns-must-have-gk diff --git a/demo/basic/demo.sh b/demo/basic/demo.sh index 3ff00e66343..38c9f2999ae 100755 --- a/demo/basic/demo.sh +++ b/demo/basic/demo.sh @@ -22,9 +22,9 @@ pe "cat good/good_ns.yaml" pe "kubectl apply -f good/good_ns.yaml" -pe "cat templates/k8suniquelabels_template.yaml" +pe "cat templates/k8suniquelabel_template.yaml" -pe "kubectl apply -f templates/k8suniquelabels_template.yaml" +pe "kubectl apply -f templates/k8suniquelabel_template.yaml" pe "kubectl apply -f constraints/all_ns_gatekeeper_label_unique.yaml" diff --git a/demo/basic/templates/k8srequiredlabels_template.yaml b/demo/basic/templates/k8srequiredlabels_template.yaml index 8b220d29695..1ddaddf55f1 100644 --- a/demo/basic/templates/k8srequiredlabels_template.yaml +++ b/demo/basic/templates/k8srequiredlabels_template.yaml @@ -1,4 +1,4 @@ -apiVersion: templates.gatekeeper.sh/v1alpha1 +apiVersion: templates.gatekeeper.sh/v1beta1 kind: ConstraintTemplate metadata: name: k8srequiredlabels @@ -24,7 +24,7 @@ spec: violation[{"msg": msg, "details": {"missing_labels": missing}}] { provided := {label | input.review.object.metadata.labels[label]} - required := {label | label := input.constraint.spec.parameters.labels[_]} + required := {label | label := input.parameters.labels[_]} missing := required - provided count(missing) > 0 msg := sprintf("you must provide labels: %v", [missing]) diff --git a/demo/basic/templates/k8srequiredlabels_template_external_data.yaml b/demo/basic/templates/k8srequiredlabels_template_external_data.yaml index c66925ed2b4..dfe04945bb5 100644 --- a/demo/basic/templates/k8srequiredlabels_template_external_data.yaml +++ b/demo/basic/templates/k8srequiredlabels_template_external_data.yaml @@ -1,4 +1,4 @@ -apiVersion: templates.gatekeeper.sh/v1alpha1 +apiVersion: templates.gatekeeper.sh/v1beta1 kind: ConstraintTemplate metadata: name: k8srequiredlabels @@ -24,7 +24,7 @@ spec: violation[{"msg": msg, "details": {"missing_labels": missing}}] { provided := {label | input.review.object.metadata.labels[label]} - required := {label | label := input.constraint.spec.parameters.labels[_]} + required := {label | label := input.parameters.labels[_]} missing := required - provided count(missing) > 0 ns := [n | data.inventory.cluster.v1.Namespace[n]] diff --git a/demo/basic/templates/k8suniquelabel_template.yaml b/demo/basic/templates/k8suniquelabel_template.yaml index 0dea310ead8..8c048a355c9 100644 --- a/demo/basic/templates/k8suniquelabel_template.yaml +++ b/demo/basic/templates/k8suniquelabel_template.yaml @@ -1,4 +1,4 @@ -apiVersion: templates.gatekeeper.sh/v1alpha1 +apiVersion: templates.gatekeeper.sh/v1beta1 kind: ConstraintTemplate metadata: name: k8suniquelabel @@ -47,7 +47,7 @@ spec: } violation[{"msg": msg, "details": {"value": val, "label": label}}] { - label := input.constraint.spec.parameters.label + label := input.parameters.label val := input.review.object.metadata.labels[label] cluster_objs := [o | o = data.inventory.cluster[_][_][_]; not identical_cluster(o, input.review)] ns_objs := [o | o = data.inventory.namespace[_][_][_][_]; not identical_namespace(o, input.review)] diff --git a/deploy/gatekeeper.yaml b/deploy/gatekeeper.yaml index 24d06a06f02..04cd74cfa05 100644 --- a/deploy/gatekeeper.yaml +++ b/deploy/gatekeeper.yaml @@ -1,29 +1,124 @@ apiVersion: v1 kind: Namespace metadata: - name: gatekeeper-system labels: control-plane: controller-manager + controller-tools.k8s.io: "1.0" + name: gatekeeper-system --- -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRoleBinding +apiVersion: apiextensions.k8s.io/v1beta1 +kind: CustomResourceDefinition metadata: creationTimestamp: null - name: manager-rolebinding -roleRef: - apiGroup: rbac.authorization.k8s.io - kind: ClusterRole - name: manager-role -subjects: -- kind: ServiceAccount - name: default - namespace: gatekeeper-system + labels: + controller-tools.k8s.io: "1.0" + name: configs.config.gatekeeper.sh +spec: + group: config.gatekeeper.sh + names: + kind: Config + plural: configs + scope: Namespaced + validation: + openAPIV3Schema: + properties: + apiVersion: + description: 'APIVersion defines the versioned schema of this representation + of an object. Servers should convert recognized schemas to the latest + internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources' + type: string + kind: + description: 'Kind is a string value representing the REST resource this + object represents. Servers may infer this from the endpoint the client + submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds' + type: string + metadata: + type: object + spec: + properties: + sync: + description: Configuration for syncing k8s objects + properties: + syncOnly: + description: If non-empty, only entries on this list will be replicated + into OPA + items: + properties: + group: + type: string + kind: + type: string + version: + type: string + type: object + type: array + type: object + validation: + description: Configuration for validation + properties: + traces: + description: List of requests to trace. Both "user" and "kinds" + must be specified + items: + properties: + dump: + description: Also dump the state of OPA with the trace. Set + to `All` to dump everything. + type: string + kind: + description: Only trace requests of the following GroupVersionKind + properties: + group: + type: string + kind: + type: string + version: + type: string + type: object + user: + description: Only trace requests from the specified user + type: string + type: object + type: array + type: object + type: object + status: + properties: + byPod: + description: List of statuses as seen by individual pods + items: + properties: + allFinalizers: + description: List of Group/Version/Kinds with finalizers + items: + properties: + group: + type: string + kind: + type: string + version: + type: string + type: object + type: array + id: + description: a unique identifier for the pod that wrote the status + type: string + type: object + type: array + type: object + version: v1alpha1 +status: + acceptedNames: + kind: "" + plural: "" + conditions: [] + storedVersions: [] --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: creationTimestamp: null - name: manager-role + name: gatekeeper-manager-role rules: - apiGroups: - '*' @@ -99,6 +194,18 @@ rules: - get - update - patch +- apiGroups: + - constraints.gatekeeper.sh + resources: + - '*' + verbs: + - get + - list + - watch + - create + - update + - patch + - delete - apiGroups: - '*' resources: @@ -157,6 +264,41 @@ rules: - patch - delete --- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + creationTimestamp: null + name: gatekeeper-manager-rolebinding +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: gatekeeper-manager-role +subjects: +- kind: ServiceAccount + name: default + namespace: gatekeeper-system +--- +apiVersion: v1 +kind: Secret +metadata: + name: gatekeeper-webhook-server-secret + namespace: gatekeeper-system +--- +apiVersion: v1 +kind: Service +metadata: + labels: + control-plane: controller-manager + controller-tools.k8s.io: "1.0" + name: gatekeeper-controller-manager-service + namespace: gatekeeper-system +spec: + ports: + - port: 443 + selector: + control-plane: controller-manager + controller-tools.k8s.io: "1.0" +--- apiVersion: apps/v1 kind: StatefulSet metadata: @@ -178,11 +320,10 @@ spec: controller-tools.k8s.io: "1.0" spec: containers: - - name: manager + - args: + - --auditInterval=30 command: - /root/manager - args: - - "--auditInterval=30" env: - name: POD_NAMESPACE valueFrom: @@ -197,17 +338,18 @@ spec: value: gatekeeper-webhook-server-secret image: quay.io/open-policy-agent/gatekeeper:v3.0.4-alpha.0 imagePullPolicy: Always + name: manager ports: - containerPort: 443 name: webhook-server protocol: TCP resources: limits: - cpu: 1 - memory: 500Mi + cpu: 100m + memory: 512Mi requests: cpu: 100m - memory: 300Mi + memory: 256Mi volumeMounts: - mountPath: /certs name: cert @@ -219,32 +361,6 @@ spec: defaultMode: 420 secretName: gatekeeper-webhook-server-secret --- -apiVersion: v1 -kind: Service -metadata: - name: gatekeeper-controller-manager-service - namespace: gatekeeper-system - labels: - control-plane: controller-manager - controller-tools.k8s.io: "1.0" -spec: - selector: - control-plane: controller-manager - controller-tools.k8s.io: "1.0" - ports: - - port: 443 ---- -apiVersion: v1 -kind: Secret -metadata: - name: gatekeeper-webhook-server-secret - namespace: gatekeeper-system ---- -apiVersion: admissionregistration.k8s.io/v1beta1 -kind: ValidatingWebhookConfiguration -metadata: - name: validation.gatekeeper.sh ---- apiVersion: apiextensions.k8s.io/v1beta1 kind: CustomResourceDefinition metadata: @@ -280,6 +396,9 @@ spec: spec: properties: names: + properties: + kind: + type: string type: object validation: type: object @@ -297,83 +416,39 @@ spec: type: object status: properties: - created: - type: boolean - error: - type: string - type: object - version: v1alpha1 -status: - acceptedNames: - kind: "" - plural: "" - conditions: [] - storedVersions: [] ---- -apiVersion: apiextensions.k8s.io/v1beta1 -kind: CustomResourceDefinition -metadata: - creationTimestamp: null - labels: - controller-tools.k8s.io: "1.0" - name: configs.config.gatekeeper.sh -spec: - group: config.gatekeeper.sh - names: - kind: Config - plural: configs - scope: Namespaced - validation: - openAPIV3Schema: - properties: - apiVersion: - description: 'APIVersion defines the versioned schema of this representation - of an object. Servers should convert recognized schemas to the latest - internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources' - type: string - kind: - description: 'Kind is a string value representing the REST resource this - object represents. Servers may infer this from the endpoint the client - submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds' - type: string - metadata: - type: object - spec: - properties: - sync: - description: Configuration for syncing k8s objects - properties: - syncOnly: - description: If non-empty, only entries on this list will be replicated - into OPA - items: - properties: - group: - type: string - kind: - type: string - version: - type: string - type: object - type: array - type: object - type: object - status: - properties: - allFinalizers: - description: List of Group/Version/Kinds with finalizers + byPod: items: properties: - group: - type: string - kind: - type: string - version: + errors: + items: + properties: + code: + type: string + location: + type: string + message: + type: string + required: + - code + - message + type: object + type: array + id: + description: a unique identifier for the pod that wrote the status type: string type: object type: array + created: + type: boolean type: object - version: v1alpha1 + version: v1beta1 + versions: + - name: v1beta1 + served: true + storage: true + - name: v1alpha1 + served: true + storage: false status: acceptedNames: kind: "" diff --git a/overlays/dev/kustomization.yaml b/overlays/dev/kustomization.yaml new file mode 100644 index 00000000000..7d9bf4d8e7f --- /dev/null +++ b/overlays/dev/kustomization.yaml @@ -0,0 +1,8 @@ +# Adds namespace to all resources. +namespace: gatekeeper-system + +resources: + - ../../config + +patchesStrategicMerge: +- manager_image_patch.yaml diff --git a/pkg/apis/addtoscheme_constrainttemplate_v1beta1.go b/pkg/apis/addtoscheme_constrainttemplate_v1beta1.go new file mode 100644 index 00000000000..7a5a503f856 --- /dev/null +++ b/pkg/apis/addtoscheme_constrainttemplate_v1beta1.go @@ -0,0 +1,25 @@ +/* + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package apis + +import ( + "github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1" +) + +func init() { + // Register the types with the Scheme so the components can map objects to GroupVersionKinds and back + AddToSchemes = append(AddToSchemes, v1beta1.SchemeBuilder.AddToScheme) +} diff --git a/pkg/audit/manager.go b/pkg/audit/manager.go index 1ec77a09f7d..a3d9b86164d 100644 --- a/pkg/audit/manager.go +++ b/pkg/audit/manager.go @@ -26,7 +26,7 @@ var log = logf.Log.WithName("controller").WithValues("metaKind", "audit") const ( crdName = "constrainttemplates.templates.gatekeeper.sh" - constraintsGV = "constraints.gatekeeper.sh/v1alpha1" + constraintsGV = "constraints.gatekeeper.sh/v1beta1" msgSize = 256 ) diff --git a/pkg/controller/constrainttemplate/constrainttemplate_controller.go b/pkg/controller/constrainttemplate/constrainttemplate_controller.go index 6a8e0f026e4..aa19ddea180 100644 --- a/pkg/controller/constrainttemplate/constrainttemplate_controller.go +++ b/pkg/controller/constrainttemplate/constrainttemplate_controller.go @@ -20,13 +20,15 @@ import ( "fmt" "reflect" - "github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1alpha1" + "github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1" opa "github.com/open-policy-agent/frameworks/constraint/pkg/client" + "github.com/open-policy-agent/frameworks/constraint/pkg/core/templates" "github.com/open-policy-agent/gatekeeper/pkg/controller/constraint" "github.com/open-policy-agent/gatekeeper/pkg/util" "github.com/open-policy-agent/gatekeeper/pkg/watch" "github.com/open-policy-agent/opa/ast" errorpkg "github.com/pkg/errors" + "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" @@ -97,7 +99,7 @@ func add(mgr manager.Manager, r reconcile.Reconciler) error { } // Watch for changes to ConstraintTemplate - err = c.Watch(&source.Kind{Type: &v1alpha1.ConstraintTemplate{}}, &handler.EnqueueRequestForObject{}) + err = c.Watch(&source.Kind{Type: &v1beta1.ConstraintTemplate{}}, &handler.EnqueueRequestForObject{}) if err != nil { return err } @@ -123,7 +125,7 @@ type ReconcileConstraintTemplate struct { // +kubebuilder:rbac:groups=templates.gatekeeper.sh,resources=constrainttemplates/status,verbs=get;update;patch func (r *ReconcileConstraintTemplate) Reconcile(request reconcile.Request) (reconcile.Result, error) { // Fetch the ConstraintTemplate instance - instance := &v1alpha1.ConstraintTemplate{} + instance := &v1beta1.ConstraintTemplate{} err := r.Get(context.TODO(), request.NamespacedName, instance) if err != nil { if errors.IsNotFound(err) { @@ -137,16 +139,21 @@ func (r *ReconcileConstraintTemplate) Reconcile(request reconcile.Request) (reco status := util.GetCTHAStatus(instance) status.Errors = nil - crd, err := r.opa.CreateCRD(context.Background(), instance) + versionless := &templates.ConstraintTemplate{} + if err := r.scheme.Convert(instance, versionless, nil); err != nil { + log.Error(err, "conversion error") + return reconcile.Result{Requeue: true}, nil + } + crd, err := r.opa.CreateCRD(context.Background(), versionless) if err != nil { - var createErr *v1alpha1.CreateCRDError + var createErr *v1beta1.CreateCRDError if parseErrs, ok := err.(ast.Errors); ok { for i := 0; i < len(parseErrs); i++ { - createErr = &v1alpha1.CreateCRDError{Code: parseErrs[i].Code, Message: parseErrs[i].Message, Location: parseErrs[i].Location.String()} + createErr = &v1beta1.CreateCRDError{Code: parseErrs[i].Code, Message: parseErrs[i].Message, Location: parseErrs[i].Location.String()} status.Errors = append(status.Errors, createErr) } } else { - createErr = &v1alpha1.CreateCRDError{Code: "create_error", Message: err.Error()} + createErr = &v1beta1.CreateCRDError{Code: "create_error", Message: err.Error()} status.Errors = append(status.Errors, createErr) } @@ -172,7 +179,12 @@ func (r *ReconcileConstraintTemplate) Reconcile(request reconcile.Request) (reco return reconcile.Result{}, err } else { - return r.handleUpdate(instance, crd, found) + unversionedCRD := &apiextensions.CustomResourceDefinition{} + if err := r.scheme.Convert(found, unversionedCRD, nil); err != nil { + log.Error(err, "conversion error") + return reconcile.Result{Requeue: true}, nil + } + return r.handleUpdate(instance, crd, unversionedCRD) } } @@ -180,21 +192,26 @@ func (r *ReconcileConstraintTemplate) Reconcile(request reconcile.Request) (reco } func (r *ReconcileConstraintTemplate) handleCreate( - instance *v1alpha1.ConstraintTemplate, - crd *apiextensionsv1beta1.CustomResourceDefinition) (reconcile.Result, error) { + instance *v1beta1.ConstraintTemplate, + crd *apiextensions.CustomResourceDefinition) (reconcile.Result, error) { name := crd.GetName() log := log.WithValues("name", name) log.Info("creating constraint") if !containsString(finalizerName, instance.GetFinalizers()) { instance.SetFinalizers(append(instance.GetFinalizers(), finalizerName)) if err := r.Update(context.Background(), instance); err != nil { - log.Error(err, "update error", err) + log.Error(err, "update error") return reconcile.Result{Requeue: true}, nil } } log.Info("loading code into OPA") - if _, err := r.opa.AddTemplate(context.Background(), instance); err != nil { - updateErr := &v1alpha1.CreateCRDError{Code: "update_error", Message: fmt.Sprintf("Could not update CRD: %s", err)} + versionless := &templates.ConstraintTemplate{} + if err := r.scheme.Convert(instance, versionless, nil); err != nil { + log.Error(err, "conversion error") + return reconcile.Result{Requeue: true}, nil + } + if _, err := r.opa.AddTemplate(context.Background(), versionless); err != nil { + updateErr := &v1beta1.CreateCRDError{Code: "update_error", Message: fmt.Sprintf("Could not update CRD: %s", err)} status := util.GetCTHAStatus(instance) status.Errors = append(status.Errors, updateErr) util.SetCTHAStatus(instance, status) @@ -209,10 +226,15 @@ func (r *ReconcileConstraintTemplate) handleCreate( } // To support HA deployments, only one pod should be able to create CRDs log.Info("creating constraint CRD") - if err := r.Create(context.TODO(), crd); err != nil { + crdv1beta1 := &apiextensionsv1beta1.CustomResourceDefinition{} + if err := r.scheme.Convert(crd, crdv1beta1, nil); err != nil { + log.Error(err, "conversion error") + return reconcile.Result{Requeue: true}, nil + } + if err := r.Create(context.TODO(), crdv1beta1); err != nil { status := util.GetCTHAStatus(instance) - status.Errors = []*v1alpha1.CreateCRDError{} - createErr := &v1alpha1.CreateCRDError{Code: "create_error", Message: fmt.Sprintf("Could not create CRD: %s", err)} + status.Errors = []*v1beta1.CreateCRDError{} + createErr := &v1beta1.CreateCRDError{Code: "create_error", Message: fmt.Sprintf("Could not create CRD: %s", err)} status.Errors = append(status.Errors, createErr) util.SetCTHAStatus(instance, status) if err2 := r.Update(context.Background(), instance); err2 != nil { @@ -228,8 +250,8 @@ func (r *ReconcileConstraintTemplate) handleCreate( } func (r *ReconcileConstraintTemplate) handleUpdate( - instance *v1alpha1.ConstraintTemplate, - crd, found *apiextensionsv1beta1.CustomResourceDefinition) (reconcile.Result, error) { + instance *v1beta1.ConstraintTemplate, + crd, found *apiextensions.CustomResourceDefinition) (reconcile.Result, error) { // TODO: We may want to only check in code if it has changed. This is harder to do than it sounds // because even if the hash hasn't changed, OPA may have been restarted and needs code re-loaded // anyway. We should see if the OPA server is smart enough to look for changes on its own, otherwise @@ -237,8 +259,13 @@ func (r *ReconcileConstraintTemplate) handleUpdate( name := crd.GetName() log := log.WithValues("name", instance.GetName(), "crdName", name) log.Info("loading constraint code into OPA") - if _, err := r.opa.AddTemplate(context.Background(), instance); err != nil { - updateErr := &v1alpha1.CreateCRDError{Code: "update_error", Message: fmt.Sprintf("Could not update CRD: %s", err)} + versionless := &templates.ConstraintTemplate{} + if err := r.scheme.Convert(instance, versionless, nil); err != nil { + log.Error(err, "conversion error") + return reconcile.Result{Requeue: true}, nil + } + if _, err := r.opa.AddTemplate(context.Background(), versionless); err != nil { + updateErr := &v1beta1.CreateCRDError{Code: "update_error", Message: fmt.Sprintf("Could not update CRD: %s", err)} status := util.GetCTHAStatus(instance) status.Errors = append(status.Errors, updateErr) util.SetCTHAStatus(instance, status) @@ -255,25 +282,35 @@ func (r *ReconcileConstraintTemplate) handleUpdate( if !reflect.DeepEqual(crd.Spec, found.Spec) { log.Info("difference in spec found, updating") found.Spec = crd.Spec - if err := r.Update(context.Background(), found); err != nil { + crdv1beta1 := &apiextensionsv1beta1.CustomResourceDefinition{} + if err := r.scheme.Convert(found, crdv1beta1, nil); err != nil { + log.Error(err, "conversion error") + return reconcile.Result{Requeue: true}, nil + } + if err := r.Update(context.Background(), crdv1beta1); err != nil { return reconcile.Result{}, err } } if err := r.Update(context.Background(), instance); err != nil { - log.Error(err, "update error", err) + log.Error(err, "update error") return reconcile.Result{Requeue: true}, nil } return reconcile.Result{}, nil } func (r *ReconcileConstraintTemplate) handleDelete( - instance *v1alpha1.ConstraintTemplate, - crd *apiextensionsv1beta1.CustomResourceDefinition) (reconcile.Result, error) { + instance *v1beta1.ConstraintTemplate, + crd *apiextensions.CustomResourceDefinition) (reconcile.Result, error) { name := crd.GetName() namespace := crd.GetNamespace() log := log.WithValues("name", instance.GetName(), "crdName", name) if containsString(finalizerName, instance.GetFinalizers()) { - if err := r.Delete(context.Background(), crd); err != nil && !errors.IsNotFound(err) { + crdv1beta1 := &apiextensionsv1beta1.CustomResourceDefinition{} + if err := r.scheme.Convert(crd, crdv1beta1, nil); err != nil { + log.Error(err, "conversion error") + return reconcile.Result{Requeue: true}, nil + } + if err := r.Delete(context.Background(), crdv1beta1); err != nil && !errors.IsNotFound(err) { return reconcile.Result{}, err } found := &apiextensionsv1beta1.CustomResourceDefinition{} @@ -292,7 +329,12 @@ func (r *ReconcileConstraintTemplate) handleDelete( if err := r.watcher.RemoveWatch(makeGvk(instance.Spec.CRD.Spec.Names.Kind)); err != nil { return reconcile.Result{}, err } - if _, err := r.opa.RemoveTemplate(context.Background(), instance); err != nil { + versionless := &templates.ConstraintTemplate{} + if err := r.scheme.Convert(instance, versionless, nil); err != nil { + log.Error(err, "conversion error") + return reconcile.Result{Requeue: true}, nil + } + if _, err := r.opa.RemoveTemplate(context.Background(), versionless); err != nil { return reconcile.Result{}, err } instance.SetFinalizers(removeString(finalizerName, instance.GetFinalizers())) @@ -306,7 +348,7 @@ func (r *ReconcileConstraintTemplate) handleDelete( func makeGvk(kind string) schema.GroupVersionKind { return schema.GroupVersionKind{ Group: "constraints.gatekeeper.sh", - Version: "v1alpha1", + Version: "v1beta1", Kind: kind, } } diff --git a/pkg/controller/constrainttemplate/constrainttemplate_controller_suite_test.go b/pkg/controller/constrainttemplate/constrainttemplate_controller_suite_test.go index 870e83b4399..03eff7c365a 100644 --- a/pkg/controller/constrainttemplate/constrainttemplate_controller_suite_test.go +++ b/pkg/controller/constrainttemplate/constrainttemplate_controller_suite_test.go @@ -37,7 +37,7 @@ func TestMain(m *testing.M) { t := &envtest.Environment{ CRDDirectoryPaths: []string{ filepath.Join("..", "..", "..", "config", "crds"), - filepath.Join("..", "..", "..", "vendor", "github.com", "open-policy-agent", "frameworks", "constraint", "config", "crds"), + filepath.Join("..", "..", "..", "vendor", "github.com", "open-policy-agent", "frameworks", "constraint", "deploy"), }, } apis.AddToScheme(scheme.Scheme) @@ -46,6 +46,7 @@ func TestMain(m *testing.M) { if cfg, err = t.Start(); err != nil { stdlog.Fatal(err) } + stdlog.Print("STARTED") code := m.Run() t.Stop() diff --git a/pkg/controller/constrainttemplate/constrainttemplate_controller_test.go b/pkg/controller/constrainttemplate/constrainttemplate_controller_test.go index 37bf9774791..2c849f05116 100644 --- a/pkg/controller/constrainttemplate/constrainttemplate_controller_test.go +++ b/pkg/controller/constrainttemplate/constrainttemplate_controller_test.go @@ -23,7 +23,7 @@ import ( "time" "github.com/onsi/gomega" - "github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1alpha1" + "github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1" opa "github.com/open-policy-agent/frameworks/constraint/pkg/client" "github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/local" "github.com/open-policy-agent/gatekeeper/pkg/target" @@ -55,17 +55,17 @@ const timeout = time.Second * 5 func TestReconcile(t *testing.T) { g := gomega.NewGomegaWithT(t) - instance := &v1alpha1.ConstraintTemplate{ + instance := &v1beta1.ConstraintTemplate{ ObjectMeta: metav1.ObjectMeta{Name: "denyall"}, - Spec: v1alpha1.ConstraintTemplateSpec{ - CRD: v1alpha1.CRD{ - Spec: v1alpha1.CRDSpec{ - Names: v1alpha1.Names{ + Spec: v1beta1.ConstraintTemplateSpec{ + CRD: v1beta1.CRD{ + Spec: v1beta1.CRDSpec{ + Names: v1beta1.Names{ Kind: "DenyAll", }, }, }, - Targets: []v1alpha1.Target{ + Targets: []v1beta1.Target{ { Target: "admission.k8s.gatekeeper.sh", Rego: ` @@ -122,7 +122,7 @@ violation[{"msg": "denied!"}] { if err := c.Get(context.TODO(), types.NamespacedName{Name: "denyall.constraints.gatekeeper.sh"}, crd); err != nil { return err } - rs, err := clientset.Discovery().ServerResourcesForGroupVersion("constraints.gatekeeper.sh/v1alpha1") + rs, err := clientset.Discovery().ServerResourcesForGroupVersion("constraints.gatekeeper.sh/v1beta1") if err != nil { return err } @@ -137,7 +137,7 @@ violation[{"msg": "denied!"}] { cstr := &unstructured.Unstructured{} cstr.SetGroupVersionKind(schema.GroupVersionKind{ Group: "constraints.gatekeeper.sh", - Version: "v1alpha1", + Version: "v1beta1", Kind: "DenyAll", }) cstr.SetName("denyall") @@ -149,14 +149,14 @@ violation[{"msg": "denied!"}] { g.Expect(err).NotTo(gomega.HaveOccurred()) dynamic := dynamic.NewForConfigOrDie(cfg) - cstrClient := dynamic.Resource(schema.GroupVersionResource{Group: "constraints.gatekeeper.sh", Version: "v1alpha1", Resource: "denyall"}) + cstrClient := dynamic.Resource(schema.GroupVersionResource{Group: "constraints.gatekeeper.sh", Version: "v1beta1", Resource: "denyall"}) _, err = cstrClient.Create(cstr, metav1.CreateOptions{}) g.Expect(err).NotTo(gomega.HaveOccurred()) defer c.Delete(context.TODO(), cstr) g.Eventually(func() error { - o, err := cstrClient.Get("denyall", metav1.GetOptions{TypeMeta: metav1.TypeMeta{Kind: "DenyAll", APIVersion: "constraints.gatekeeper.sh/v1alpha1"}}) + o, err := cstrClient.Get("denyall", metav1.GetOptions{TypeMeta: metav1.TypeMeta{Kind: "DenyAll", APIVersion: "constraints.gatekeeper.sh/v1beta1"}}) if err != nil { return err } @@ -201,17 +201,17 @@ violation[{"msg": "denied!"}] { g.Expect(len(resp.Results())).Should(gomega.Equal(1)) // Create template with invalid rego, should populate parse error in status - instanceInvalidRego := &v1alpha1.ConstraintTemplate{ + instanceInvalidRego := &v1beta1.ConstraintTemplate{ ObjectMeta: metav1.ObjectMeta{Name: "invalidrego"}, - Spec: v1alpha1.ConstraintTemplateSpec{ - CRD: v1alpha1.CRD{ - Spec: v1alpha1.CRDSpec{ - Names: v1alpha1.Names{ + Spec: v1beta1.ConstraintTemplateSpec{ + CRD: v1beta1.CRD{ + Spec: v1beta1.CRDSpec{ + Names: v1beta1.Names{ Kind: "InvalidRego", }, }, }, - Targets: []v1alpha1.Target{ + Targets: []v1beta1.Target{ { Target: "admission.k8s.gatekeeper.sh", Rego: ` @@ -232,7 +232,7 @@ anyrule[}}}//invalid//rego g.Eventually(requests, timeout).Should(gomega.Receive(gomega.Equal(expectedRequestInvalidRego))) g.Eventually(func() error { - ct := &v1alpha1.ConstraintTemplate{} + ct := &v1beta1.ConstraintTemplate{} if err := c.Get(context.TODO(), types.NamespacedName{Name: "invalidrego"}, ct); err != nil { return err } diff --git a/pkg/target/target.go b/pkg/target/target.go index ebc8f039c92..bcf7df5c8d8 100644 --- a/pkg/target/target.go +++ b/pkg/target/target.go @@ -11,7 +11,7 @@ import ( "github.com/open-policy-agent/frameworks/constraint/pkg/types" "github.com/pkg/errors" admissionv1beta1 "k8s.io/api/admission/v1beta1" - apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" + "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/apis/meta/v1/validation" @@ -368,96 +368,64 @@ func (h *K8sValidationTarget) HandleViolation(result *types.Result) error { return nil } -func (h *K8sValidationTarget) MatchSchema() apiextensionsv1beta1.JSONSchemaProps { - stringList := &apiextensionsv1beta1.JSONSchemaPropsOrArray{ - Schema: &apiextensionsv1beta1.JSONSchemaProps{Type: "string"}} - return apiextensionsv1beta1.JSONSchemaProps{ - Properties: map[string]apiextensionsv1beta1.JSONSchemaProps{ - "kinds": apiextensionsv1beta1.JSONSchemaProps{ +func (h *K8sValidationTarget) MatchSchema() apiextensions.JSONSchemaProps { + stringList := &apiextensions.JSONSchemaPropsOrArray{ + Schema: &apiextensions.JSONSchemaProps{Type: "string"}} + labelSelectorSchema := apiextensions.JSONSchemaProps{ + Properties: map[string]apiextensions.JSONSchemaProps{ + // Map schema validation will only work in kubernetes versions > 1.10. See https://github.com/kubernetes/kubernetes/pull/62333 + //"matchLabels": apiextensions.JSONSchemaProps{ + // AdditionalProperties: &apiextensions.JSONSchemaPropsOrBool{ + // Allows: true, + // Schema: &apiextensions.JSONSchemaProps{Type: "string"}, + // }, + //}, + "matchExpressions": apiextensions.JSONSchemaProps{ Type: "array", - Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{ - Schema: &apiextensionsv1beta1.JSONSchemaProps{ - Properties: map[string]apiextensionsv1beta1.JSONSchemaProps{ - "apiGroups": {Items: stringList}, - "kinds": {Items: stringList}, - }, - }, - }, - }, - "namespaces": apiextensionsv1beta1.JSONSchemaProps{ - Type: "array", - Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{ - Schema: &apiextensionsv1beta1.JSONSchemaProps{Type: "string"}}}, - "labelSelector": apiextensionsv1beta1.JSONSchemaProps{ - Properties: map[string]apiextensionsv1beta1.JSONSchemaProps{ - // Map schema validation will only work in kubernetes versions > 1.10. See https://github.com/kubernetes/kubernetes/pull/62333 - //"matchLabels": apiextensionsv1beta1.JSONSchemaProps{ - // AdditionalProperties: &apiextensionsv1beta1.JSONSchemaPropsOrBool{ - // Allows: true, - // Schema: &apiextensionsv1beta1.JSONSchemaProps{Type: "string"}, - // }, - //}, - "matchExpressions": apiextensionsv1beta1.JSONSchemaProps{ - Type: "array", - Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{ - Schema: &apiextensionsv1beta1.JSONSchemaProps{ - Properties: map[string]apiextensionsv1beta1.JSONSchemaProps{ - "key": apiextensionsv1beta1.JSONSchemaProps{Type: "string"}, - "operator": apiextensionsv1beta1.JSONSchemaProps{ - Type: "string", - Enum: []apiextensionsv1beta1.JSON{ - apiextensionsv1beta1.JSON{Raw: []byte(`"In"`)}, - apiextensionsv1beta1.JSON{Raw: []byte(`"NotIn"`)}, - apiextensionsv1beta1.JSON{Raw: []byte(`"Exists"`)}, - apiextensionsv1beta1.JSON{Raw: []byte(`"DoesNotExist"`)}, - }}, - "values": apiextensionsv1beta1.JSONSchemaProps{ - Type: "array", - Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{ - Schema: &apiextensionsv1beta1.JSONSchemaProps{Type: "string"}, - }, - }, + Items: &apiextensions.JSONSchemaPropsOrArray{ + Schema: &apiextensions.JSONSchemaProps{ + Properties: map[string]apiextensions.JSONSchemaProps{ + "key": apiextensions.JSONSchemaProps{Type: "string"}, + "operator": apiextensions.JSONSchemaProps{ + Type: "string", + Enum: []apiextensions.JSON{ + "In", + "NotIn", + "Exists", + "DoesNotExist", + }, + }, + "values": apiextensions.JSONSchemaProps{ + Type: "array", + Items: &apiextensions.JSONSchemaPropsOrArray{ + Schema: &apiextensions.JSONSchemaProps{Type: "string"}, }, }, }, }, }, }, - "namespaceSelector": apiextensionsv1beta1.JSONSchemaProps{ - Properties: map[string]apiextensionsv1beta1.JSONSchemaProps{ - // Map schema validation will only work in kubernetes versions > 1.10. See https://github.com/kubernetes/kubernetes/pull/62333 - //"matchLabels": apiextensionsv1beta1.JSONSchemaProps{ - // AdditionalProperties: &apiextensionsv1beta1.JSONSchemaPropsOrBool{ - // Allows: true, - // Schema: &apiextensionsv1beta1.JSONSchemaProps{Type: "string"}, - // }, - //}, - "matchExpressions": apiextensionsv1beta1.JSONSchemaProps{ - Type: "array", - Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{ - Schema: &apiextensionsv1beta1.JSONSchemaProps{ - Properties: map[string]apiextensionsv1beta1.JSONSchemaProps{ - "key": apiextensionsv1beta1.JSONSchemaProps{Type: "string"}, - "operator": apiextensionsv1beta1.JSONSchemaProps{ - Type: "string", - Enum: []apiextensionsv1beta1.JSON{ - apiextensionsv1beta1.JSON{Raw: []byte(`"In"`)}, - apiextensionsv1beta1.JSON{Raw: []byte(`"NotIn"`)}, - apiextensionsv1beta1.JSON{Raw: []byte(`"Exists"`)}, - apiextensionsv1beta1.JSON{Raw: []byte(`"DoesNotExist"`)}, - }}, - "values": apiextensionsv1beta1.JSONSchemaProps{ - Type: "array", - Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{ - Schema: &apiextensionsv1beta1.JSONSchemaProps{Type: "string"}, - }, - }, - }, - }, + }, + } + return apiextensions.JSONSchemaProps{ + Properties: map[string]apiextensions.JSONSchemaProps{ + "kinds": apiextensions.JSONSchemaProps{ + Type: "array", + Items: &apiextensions.JSONSchemaPropsOrArray{ + Schema: &apiextensions.JSONSchemaProps{ + Properties: map[string]apiextensions.JSONSchemaProps{ + "apiGroups": {Items: stringList}, + "kinds": {Items: stringList}, }, }, }, }, + "namespaces": apiextensions.JSONSchemaProps{ + Type: "array", + Items: &apiextensions.JSONSchemaPropsOrArray{ + Schema: &apiextensions.JSONSchemaProps{Type: "string"}}}, + "labelSelector": labelSelectorSchema, + "namespaceSelector": labelSelectorSchema, }, } } diff --git a/pkg/target/target_test.go b/pkg/target/target_test.go index fa1be3096a6..e6f6746b928 100644 --- a/pkg/target/target_test.go +++ b/pkg/target/target_test.go @@ -36,7 +36,7 @@ func TestValidateConstraint(t *testing.T) { Name: "No LabelSelector", Constraint: ` { - "apiVersion": "constraints.gatekeeper.sh/v1alpha1", + "apiVersion": "constraints.gatekeeper.sh/v1beta1", "kind": "K8sRequiredLabel", "metadata": { "name": "ns-must-have-gk" @@ -62,7 +62,7 @@ func TestValidateConstraint(t *testing.T) { Name: "Valid LabelSelector", Constraint: ` { - "apiVersion": "constraints.gatekeeper.sh/v1alpha1", + "apiVersion": "constraints.gatekeeper.sh/v1beta1", "kind": "K8sRequiredLabel", "metadata": { "name": "ns-must-have-gk" @@ -95,7 +95,7 @@ func TestValidateConstraint(t *testing.T) { Name: "Invalid LabelSelector", Constraint: ` { - "apiVersion": "constraints.gatekeeper.sh/v1alpha1", + "apiVersion": "constraints.gatekeeper.sh/v1beta1", "kind": "K8sRequiredLabel", "metadata": { "name": "ns-must-have-gk" @@ -128,7 +128,7 @@ func TestValidateConstraint(t *testing.T) { Name: "No NamespaceSelector", Constraint: ` { - "apiVersion": "constraints.gatekeeper.sh/v1alpha1", + "apiVersion": "constraints.gatekeeper.sh/v1beta1", "kind": "K8sAllowedRepos", "metadata": { "name": "prod-nslabels-is-openpolicyagent" @@ -160,7 +160,7 @@ func TestValidateConstraint(t *testing.T) { Name: "Valid NamespaceSelector", Constraint: ` { - "apiVersion": "constraints.gatekeeper.sh/v1alpha1", + "apiVersion": "constraints.gatekeeper.sh/v1beta1", "kind": "K8sAllowedRepos", "metadata": { "name": "prod-nslabels-is-openpolicyagent" @@ -192,7 +192,7 @@ func TestValidateConstraint(t *testing.T) { Name: "Invalid NamespaceSelector", Constraint: ` { - "apiVersion": "constraints.gatekeeper.sh/v1alpha1", + "apiVersion": "constraints.gatekeeper.sh/v1beta1", "kind": "K8sAllowedRepos", "metadata": { "name": "prod-nslabels-is-openpolicyagent" @@ -345,18 +345,18 @@ func TestProcessData(t *testing.T) { }{ { Name: "Cluster Object", - JSON: `{"apiVersion": "v1alpha1", "kind": "Rock", "metadata": {"name": "myrock"}}`, - ExpectedPath: "cluster/v1alpha1/Rock/myrock", + JSON: `{"apiVersion": "v1beta1", "kind": "Rock", "metadata": {"name": "myrock"}}`, + ExpectedPath: "cluster/v1beta1/Rock/myrock", }, { Name: "Namespace Object", - JSON: `{"apiVersion": "v1alpha1", "kind": "Rock", "metadata": {"name": "myrock", "namespace": "foo"}}`, - ExpectedPath: "namespace/foo/v1alpha1/Rock/myrock", + JSON: `{"apiVersion": "v1beta1", "kind": "Rock", "metadata": {"name": "myrock", "namespace": "foo"}}`, + ExpectedPath: "namespace/foo/v1beta1/Rock/myrock", }, { Name: "Grouped Object", - JSON: `{"apiVersion": "mygroup/v1alpha1", "kind": "Rock", "metadata": {"name": "myrock"}}`, - ExpectedPath: "cluster/mygroup%2Fv1alpha1/Rock/myrock", + JSON: `{"apiVersion": "mygroup/v1beta1", "kind": "Rock", "metadata": {"name": "myrock"}}`, + ExpectedPath: "cluster/mygroup%2Fv1beta1/Rock/myrock", }, { Name: "No Version", diff --git a/pkg/upgrade/controller.go b/pkg/upgrade/controller.go new file mode 100644 index 00000000000..9fae489f842 --- /dev/null +++ b/pkg/upgrade/controller.go @@ -0,0 +1,28 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 + Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package upgrade + +import ( + "context" + + "sigs.k8s.io/controller-runtime/pkg/manager" +) + +// AddToManager adds upgrade manager to the Manager +func AddToManager(m manager.Manager) error { + am, err := New(context.Background(), m.GetConfig()) + if err != nil { + return err + } + return m.Add(am) +} diff --git a/pkg/upgrade/manager.go b/pkg/upgrade/manager.go new file mode 100644 index 00000000000..5c2278df442 --- /dev/null +++ b/pkg/upgrade/manager.go @@ -0,0 +1,209 @@ +package upgrade + +// TODO consider whether this needs to exist after https://github.com/kubernetes/kubernetes/pull/79495 +// is merged, or we make the minimum supported version of k8s v1.14 + +import ( + "context" + "strings" + "time" + + apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/wait" + "k8s.io/client-go/discovery" + "k8s.io/client-go/rest" + "sigs.k8s.io/controller-runtime/pkg/client" + logf "sigs.k8s.io/controller-runtime/pkg/runtime/log" +) + +var log = logf.Log.WithName("controller").WithValues("metaKind", "upgrade") + +const ( + crdName = "constrainttemplates.templates.gatekeeper.sh" +) + +// UpgradeManager allows us to upgrade resources on startup +type UpgradeManager struct { + client client.Client + cfg *rest.Config + ctx context.Context +} + +// New creates a new manager for audit +func New(ctx context.Context, cfg *rest.Config) (*UpgradeManager, error) { + am := &UpgradeManager{ + cfg: cfg, + ctx: ctx, + } + return am, nil +} + + +// Start implements the Runnable interface +func (um *UpgradeManager) Start(stop <-chan struct{}) error { + log.Info("Starting Upgrade Manager") + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + defer log.Info("Stopping upgrade manager workers") + errCh := make(chan error) + go func() {errCh <- um.upgrade(ctx)}() + select { + case <-stop: + return nil + case err := <-errCh: + if err != nil { + return err + } + } + // We must block indefinitely or manager will exit + <-stop + return nil +} + +func (um *UpgradeManager) ensureCRDExists(ctx context.Context) error { + crd := &apiextensionsv1beta1.CustomResourceDefinition{} + return um.client.Get(ctx, types.NamespacedName{Name: crdName}, crd) +} + +func (um *UpgradeManager) getAllKinds(groupVersion string) (*metav1.APIResourceList, error) { + discoveryClient, err := discovery.NewDiscoveryClientForConfig(um.cfg) + if err != nil { + return nil, err + } + return discoveryClient.ServerResourcesForGroupVersion(groupVersion) +} + +func (um *UpgradeManager) upgrade(ctx context.Context) error { + gvs := []string{ + "constraints.gatekeeper.sh/v1alpha1", + "templates.gatekeeper.sh/v1alpha1", + } + for _, gv := range gvs { + if err := um.upgradeGroupVersion(ctx, gv); err != nil { + return err + } + } + return nil +} + +// upgradeGroupVersion touches each resource in a given groupVersion, incrementing its storage version +func (um *UpgradeManager) upgradeGroupVersion(ctx context.Context, groupVersion string) error { + // new client to get updated restmapper + c, err := client.New(um.cfg, client.Options{Scheme: nil, Mapper: nil}) + if err != nil { + return err + } + um.client = c + if err := um.ensureCRDExists(ctx); err != nil { + log.Info("required crd has not been deployed ", "CRD", crdName) + return err + } + // get all resource kinds + resourceList, err := um.getAllKinds(groupVersion) + if err != nil { + // If the resource doesn't exist, it doesn't need upgrading + if errors.IsNotFound(err) { + return nil + } + return err + } + + resourceGV := strings.Split(resourceList.GroupVersion, "/") + group := resourceGV[0] + version := resourceGV[1] + + // get resource for each Kind + for _, r := range resourceList.APIResources { + log.Info("resource", "kind", r.Kind) + resourceGvk := schema.GroupVersionKind{ + Group: group, + Version: version, + Kind: r.Kind + "List", + } + instanceList := &unstructured.UnstructuredList{} + instanceList.SetGroupVersionKind(resourceGvk) + err := um.client.List(ctx, &client.ListOptions{}, instanceList) + if err != nil { + return err + } + log.Info("resoure", "count of resources", len(instanceList.Items)) + updateResources := make(map[string]unstructured.Unstructured, len(instanceList.Items)) + // get each resourcet + for _, item := range instanceList.Items { + updateResources[item.GetSelfLink()] = item + } + + if len(updateResources) > 0 { + urloop := &updateResourceLoop{ + ur: updateResources, + client: um.client, + stop: make(chan struct{}), + stopped: make(chan struct{}), + } + log.Info("starting update resources loop", "updateResources", updateResources) + go urloop.update() + } + } + return nil +} + +type updateResourceLoop struct { + ur map[string]unstructured.Unstructured + client client.Client + stop chan struct{} + stopped chan struct{} +} + +func (urloop *updateResourceLoop) update() { + defer close(urloop.stopped) + updateLoop := func() (bool, error) { + for _, item := range urloop.ur { + select { + case <-urloop.stop: + return true, nil + default: + failure := false + ctx := context.Background() + var latestItem unstructured.Unstructured + item.DeepCopyInto(&latestItem) + name := latestItem.GetName() + namespace := latestItem.GetNamespace() + namespacedName := types.NamespacedName{ + Name: name, + Namespace: namespace, + } + // get the latest constraint + err := urloop.client.Get(ctx, namespacedName, &latestItem) + if err != nil { + failure = true + log.Error(err, "could not get latest resource during update", "name", name, "namespace", namespace) + } + if err := urloop.client.Update(ctx, &latestItem); err != nil { + failure = true + log.Error(err, "could not update resource", "name", name, "namespace", namespace) + } + if !failure { + delete(urloop.ur, latestItem.GetSelfLink()) + } + } + } + if len(urloop.ur) == 0 { + return true, nil + } + return false, nil + } + + if err := wait.ExponentialBackoff(wait.Backoff{ + Duration: 1 * time.Second, + Factor: 2, + Jitter: 1, + Steps: 5, + }, updateLoop); err != nil { + log.Error(err, "could not update resource reached max retries", "remaining update resources", urloop.ur) + } +} diff --git a/pkg/util/ha_status.go b/pkg/util/ha_status.go index bb506c2696d..5592f10101d 100644 --- a/pkg/util/ha_status.go +++ b/pkg/util/ha_status.go @@ -3,10 +3,11 @@ package util import ( "os" - "github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1alpha1" - configv1alpha1 "github.com/open-policy-agent/gatekeeper/pkg/apis/config/v1alpha1" + "github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1" "github.com/pkg/errors" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + + configv1alpha1 "github.com/open-policy-agent/gatekeeper/pkg/apis/config/v1alpha1" ) func getID() string { @@ -19,17 +20,17 @@ func blankStatus(id string) map[string]interface{} { } } -func GetCTHAStatus(template *v1alpha1.ConstraintTemplate) *v1alpha1.ByPodStatus { +func GetCTHAStatus(template *v1beta1.ConstraintTemplate) *v1beta1.ByPodStatus { id := getID() for _, status := range template.Status.ByPod { if status.ID == id { return status } } - return &v1alpha1.ByPodStatus{ID: id} + return &v1beta1.ByPodStatus{ID: id} } -func SetCTHAStatus(template *v1alpha1.ConstraintTemplate, status *v1alpha1.ByPodStatus) { +func SetCTHAStatus(template *v1beta1.ConstraintTemplate, status *v1beta1.ByPodStatus) { id := getID() status.ID = id for i, status := range template.Status.ByPod { diff --git a/pkg/util/ha_status_test.go b/pkg/util/ha_status_test.go index a65c57ad4cb..98827404e14 100644 --- a/pkg/util/ha_status_test.go +++ b/pkg/util/ha_status_test.go @@ -6,7 +6,7 @@ import ( "reflect" "testing" - "github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1alpha1" + "github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1" configv1alpha1 "github.com/open-policy-agent/gatekeeper/pkg/apis/config/v1alpha1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" ) @@ -175,31 +175,31 @@ func TestCTHAStatus(t *testing.T) { tc := []struct { Name string // One error per pretend Pod - Errors []*v1alpha1.CreateCRDError + Errors []*v1beta1.CreateCRDError }{ { Name: "One Status", - Errors: []*v1alpha1.CreateCRDError{{Message: "one_status"}}, + Errors: []*v1beta1.CreateCRDError{{Message: "one_status"}}, }, { Name: "Two Statuses", - Errors: []*v1alpha1.CreateCRDError{{Message: "one"}, {Message: "two"}}, + Errors: []*v1beta1.CreateCRDError{{Message: "one"}, {Message: "two"}}, }, { Name: "Three Statuses", - Errors: []*v1alpha1.CreateCRDError{{Message: "one"}, {Message: "two"}, {Message: "three"}}, + Errors: []*v1beta1.CreateCRDError{{Message: "one"}, {Message: "two"}, {Message: "three"}}, }, } for _, tt := range tc { t.Run(tt.Name, func(t *testing.T) { - obj := &v1alpha1.ConstraintTemplate{} + obj := &v1beta1.ConstraintTemplate{} for i, e := range tt.Errors { pod := fmt.Sprintf("Pod%d", i) if err := os.Setenv("POD_NAME", pod); err != nil { t.Fatal(err) } st := GetCTHAStatus(obj) - es := []*v1alpha1.CreateCRDError{e} + es := []*v1beta1.CreateCRDError{e} st.Errors = es SetCTHAStatus(obj, st) st2 := GetCTHAStatus(obj) @@ -219,7 +219,7 @@ func TestCTHAStatus(t *testing.T) { if err := os.Setenv("POD_NAME", pod); err != nil { t.Fatal(err) } - es := []*v1alpha1.CreateCRDError{e} + es := []*v1beta1.CreateCRDError{e} st2 := GetCTHAStatus(obj) if st2.ID != pod { t.Errorf("t2: id = %v; want %v", st2.ID, pod) diff --git a/pkg/webhook/policy.go b/pkg/webhook/policy.go index 7e31538d02c..b1188fcce5e 100644 --- a/pkg/webhook/policy.go +++ b/pkg/webhook/policy.go @@ -8,11 +8,9 @@ import ( "net/http" "strings" - templv1alpha1 "github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1alpha1" opa "github.com/open-policy-agent/frameworks/constraint/pkg/client" + "github.com/open-policy-agent/frameworks/constraint/pkg/core/templates" rtypes "github.com/open-policy-agent/frameworks/constraint/pkg/types" - "github.com/open-policy-agent/gatekeeper/pkg/apis/config/v1alpha1" - "github.com/open-policy-agent/gatekeeper/pkg/controller/config" admissionv1beta1 "k8s.io/api/admission/v1beta1" admissionregistrationv1beta1 "k8s.io/api/admissionregistration/v1beta1" authenticationv1 "k8s.io/api/authentication/v1" @@ -28,10 +26,15 @@ import ( "sigs.k8s.io/controller-runtime/pkg/webhook/admission" "sigs.k8s.io/controller-runtime/pkg/webhook/admission/builder" atypes "sigs.k8s.io/controller-runtime/pkg/webhook/admission/types" + + "github.com/open-policy-agent/gatekeeper/pkg/apis" + "github.com/open-policy-agent/gatekeeper/pkg/apis/config/v1alpha1" + "github.com/open-policy-agent/gatekeeper/pkg/controller/config" ) func init() { AddToManagerFuncs = append(AddToManagerFuncs, AddPolicyWebhook) + apis.AddToScheme(runtimeScheme) } const ( @@ -219,11 +222,15 @@ func (h *validationHandler) validateGatekeeperResources(ctx context.Context, req } func (h *validationHandler) validateTemplate(ctx context.Context, req atypes.Request) (bool, error) { - templ := &templv1alpha1.ConstraintTemplate{} - if _, _, err := deserializer.Decode(req.AdmissionRequest.Object.Raw, nil, templ); err != nil { + templ, _, err := deserializer.Decode(req.AdmissionRequest.Object.Raw, nil, nil) + if err != nil { + return false, err + } + unversioned := &templates.ConstraintTemplate{} + if err := runtimeScheme.Convert(templ, unversioned, nil); err != nil { return false, err } - if _, err := h.opa.CreateCRD(ctx, templ); err != nil { + if _, err := h.opa.CreateCRD(ctx, unversioned); err != nil { return true, err } return false, nil diff --git a/pkg/webhook/policy_test.go b/pkg/webhook/policy_test.go index fb8840d4317..de389f079c7 100644 --- a/pkg/webhook/policy_test.go +++ b/pkg/webhook/policy_test.go @@ -5,9 +5,10 @@ import ( "testing" "github.com/ghodss/yaml" - templv1alpha1 "github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1alpha1" + templv1beta1 "github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1" "github.com/open-policy-agent/frameworks/constraint/pkg/client" "github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/local" + "github.com/open-policy-agent/frameworks/constraint/pkg/core/templates" "github.com/open-policy-agent/gatekeeper/pkg/apis/config/v1alpha1" "github.com/open-policy-agent/gatekeeper/pkg/target" admissionv1beta1 "k8s.io/api/admission/v1beta1" @@ -19,7 +20,7 @@ import ( const ( bad_rego_template = ` -apiVersion: templates.gatekeeper.sh/v1alpha1 +apiVersion: templates.gatekeeper.sh/v1beta1 kind: ConstraintTemplate metadata: name: k8sbadrego @@ -41,7 +42,7 @@ spec: ` good_rego_template = ` -apiVersion: templates.gatekeeper.sh/v1alpha1 +apiVersion: templates.gatekeeper.sh/v1beta1 kind: ConstraintTemplate metadata: name: k8sgoodrego @@ -64,7 +65,7 @@ spec: ` bad_labelselector = ` -apiVersion: constraints.gatekeeper.sh/v1alpha1 +apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sGoodRego metadata: name: bad-labelselector @@ -80,7 +81,7 @@ spec: ` good_labelselector = ` -apiVersion: constraints.gatekeeper.sh/v1alpha1 +apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sGoodRego metadata: name: good-labelselector @@ -97,7 +98,7 @@ spec: ` bad_namespaceselector = ` -apiVersion: constraints.gatekeeper.sh/v1alpha1 +apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sGoodRego metadata: name: bad-namespaceselector @@ -113,7 +114,7 @@ spec: ` good_namespaceselector = ` -apiVersion: constraints.gatekeeper.sh/v1alpha1 +apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sGoodRego metadata: name: good-namespaceselector @@ -176,7 +177,7 @@ func TestTemplateValidation(t *testing.T) { AdmissionRequest: &admissionv1beta1.AdmissionRequest{ Kind: metav1.GroupVersionKind{ Group: "templates.gatekeeper.sh", - Version: "v1alpha1", + Version: "v1beta1", Kind: "ConstraintTemplate", }, Object: runtime.RawExtension{ @@ -233,11 +234,15 @@ func TestConstraintValidation(t *testing.T) { if err != nil { t.Fatalf("Could not initialize OPA: %s", err) } - cstr := &templv1alpha1.ConstraintTemplate{} + cstr := &templv1beta1.ConstraintTemplate{} if err := yaml.Unmarshal([]byte(tt.Template), cstr); err != nil { t.Fatalf("Could not instantiate template: %s", err) } - if _, err := opa.AddTemplate(context.Background(), cstr); err != nil { + unversioned := &templates.ConstraintTemplate{} + if err := runtimeScheme.Convert(cstr, unversioned, nil); err != nil { + t.Fatalf("Could not convert to unversioned: %v", err) + } + if _, err := opa.AddTemplate(context.Background(), unversioned); err != nil { t.Fatalf("Could not add template: %s", err) } handler := validationHandler{opa: opa} @@ -249,7 +254,7 @@ func TestConstraintValidation(t *testing.T) { AdmissionRequest: &admissionv1beta1.AdmissionRequest{ Kind: metav1.GroupVersionKind{ Group: "constraints.gatekeeper.sh", - Version: "v1alpha1", + Version: "v1beta1", Kind: "K8sGoodRego", }, Object: runtime.RawExtension{ @@ -349,11 +354,15 @@ func TestTracing(t *testing.T) { if err != nil { t.Fatalf("Could not initialize OPA: %s", err) } - cstr := &templv1alpha1.ConstraintTemplate{} + cstr := &templv1beta1.ConstraintTemplate{} if err := yaml.Unmarshal([]byte(tt.Template), cstr); err != nil { t.Fatalf("Could not instantiate template: %s", err) } - if _, err := opa.AddTemplate(context.Background(), cstr); err != nil { + unversioned := &templates.ConstraintTemplate{} + if err := runtimeScheme.Convert(cstr, unversioned, nil); err != nil { + t.Fatalf("Could not convert to unversioned: %v", err) + } + if _, err := opa.AddTemplate(context.Background(), unversioned); err != nil { t.Fatalf("Could not add template: %s", err) } handler := validationHandler{opa: opa, injectedConfig: tt.Cfg} diff --git a/test/Dockerfile b/test/Dockerfile index 5d4ff61331e..0774171258d 100644 --- a/test/Dockerfile +++ b/test/Dockerfile @@ -13,6 +13,13 @@ RUN tar -zxvf kubebuilder_${version}_linux_${arch}.tar.gz RUN mv kubebuilder_${version}_linux_${arch} kubebuilder && mv kubebuilder /usr/local/ ENV PATH=$PATH:/usr/local/kubebuilder/bin:/usr/bin +# Install kustomize +ENV version=3.0.2 +ENV arch=amd64 +RUN curl -L -O "https://github.com/kubernetes-sigs/kustomize/releases/download/v${version}/kustomize_${version}_linux_${arch}" +RUN mv kustomize_${version}_linux_${arch} /usr/bin/kustomize +RUN chmod u+x /usr/bin/kustomize + # Copy in the go src WORKDIR /go/src/github.com/open-policy-agent/gatekeeper COPY . . diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/Dockerfile b/vendor/github.com/open-policy-agent/frameworks/constraint/Dockerfile index b4b0baae1b5..c17970c87ed 100644 --- a/vendor/github.com/open-policy-agent/frameworks/constraint/Dockerfile +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/Dockerfile @@ -13,6 +13,13 @@ RUN tar -zxvf kubebuilder_${version}_linux_${arch}.tar.gz RUN mv kubebuilder_${version}_linux_${arch} kubebuilder && mv kubebuilder /usr/local/ ENV PATH=$PATH:/usr/local/kubebuilder/bin:/usr/bin +# Install kustomize +ENV version=3.0.2 +ENV arch=amd64 +RUN curl -L -O "https://github.com/kubernetes-sigs/kustomize/releases/download/v${version}/kustomize_${version}_linux_${arch}" +RUN mv kustomize_${version}_linux_${arch} /usr/bin/kustomize +RUN chmod u+x /usr/bin/kustomize + # Install OPA WORKDIR /usr/bin RUN curl -L -o opa https://github.com/open-policy-agent/opa/releases/download/v0.10.5/opa_linux_amd64 diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/Gopkg.lock b/vendor/github.com/open-policy-agent/frameworks/constraint/Gopkg.lock index 4a85016467c..602bc5a5653 100644 --- a/vendor/github.com/open-policy-agent/frameworks/constraint/Gopkg.lock +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/Gopkg.lock @@ -238,6 +238,20 @@ pruneopts = "UT" revision = "4030bb1f1f0c35b30ca7009e9ebd06849dd45306" +[[projects]] + digest = "1:bf40199583e5143d1472fc34d10d6f4b69d97572142acf343b3e43136da40823" + name = "github.com/google/go-cmp" + packages = [ + "cmp", + "cmp/internal/diff", + "cmp/internal/flags", + "cmp/internal/function", + "cmp/internal/value", + ] + pruneopts = "UT" + revision = "6f77996f0c42f7b84e5a2b252227263f93432e9b" + version = "v0.3.0" + [[projects]] digest = "1:41bfd4219241b7f7d6e6fdb13fc712576f1337e68e6b895136283b76928fdd66" name = "github.com/google/gofuzz" @@ -984,7 +998,7 @@ [[projects]] branch = "master" - digest = "1:5b9abf55561501223ba793d8be3884e220441fc5f36bb2da5a45c1b58927d9fe" + digest = "1:5ea5791e694c4ba8be90bd095bb34c29ba4db126563b90f349695b269d941669" name = "k8s.io/code-generator" packages = [ "cmd/client-gen", @@ -995,13 +1009,16 @@ "cmd/client-gen/generators/util", "cmd/client-gen/path", "cmd/client-gen/types", + "cmd/conversion-gen", + "cmd/conversion-gen/args", + "cmd/conversion-gen/generators", "cmd/deepcopy-gen", "cmd/deepcopy-gen/args", "pkg/namer", "pkg/util", ] pruneopts = "UT" - revision = "e4c2b1329cf785363b23612eebf93bb4c2affdb4" + revision = "93d7507fc8ffb4c860e4dd6f9a51a5e1985aebcd" [[projects]] branch = "master" @@ -1105,6 +1122,7 @@ analyzer-version = 1 input-imports = [ "github.com/davecgh/go-spew/spew", + "github.com/google/go-cmp/cmp", "github.com/onsi/gomega", "github.com/open-policy-agent/opa/ast", "github.com/open-policy-agent/opa/rego", @@ -1119,6 +1137,7 @@ "k8s.io/apiextensions-apiserver/pkg/apiserver/validation", "k8s.io/apimachinery/pkg/apis/meta/v1", "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured", + "k8s.io/apimachinery/pkg/conversion", "k8s.io/apimachinery/pkg/runtime", "k8s.io/apimachinery/pkg/runtime/schema", "k8s.io/apimachinery/pkg/types", @@ -1126,6 +1145,7 @@ "k8s.io/client-go/kubernetes/scheme", "k8s.io/client-go/rest", "k8s.io/code-generator/cmd/client-gen", + "k8s.io/code-generator/cmd/conversion-gen", "k8s.io/code-generator/cmd/deepcopy-gen", "sigs.k8s.io/controller-runtime/pkg/client", "sigs.k8s.io/controller-runtime/pkg/envtest", diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/Gopkg.toml b/vendor/github.com/open-policy-agent/frameworks/constraint/Gopkg.toml index 6cbf6140ad5..11ce16dc015 100644 --- a/vendor/github.com/open-policy-agent/frameworks/constraint/Gopkg.toml +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/Gopkg.toml @@ -28,6 +28,7 @@ required = [ "github.com/onsi/gomega", # for test matchers "k8s.io/code-generator/cmd/client-gen", # for go generate "k8s.io/code-generator/cmd/deepcopy-gen", # for go generate + "k8s.io/code-generator/cmd/conversion-gen", # for go generate "sigs.k8s.io/controller-tools/cmd/controller-gen", # for crd/rbac generation "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1", ] @@ -63,3 +64,7 @@ required = [ [prune] go-tests = true unused-packages = true + +[[constraint]] + name = "github.com/google/go-cmp" + version = "0.3.0" diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/Makefile b/vendor/github.com/open-policy-agent/frameworks/constraint/Makefile index 52d25d0effe..b3f845cb58c 100644 --- a/vendor/github.com/open-policy-agent/frameworks/constraint/Makefile +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/Makefile @@ -20,6 +20,7 @@ install: manifests # Generate manifests e.g. CRD, RBAC etc. manifests: go run vendor/sigs.k8s.io/controller-tools/cmd/controller-gen/main.go all + kustomize build config -o deploy/crds.yaml # Run go fmt against code fmt: diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/README.md b/vendor/github.com/open-policy-agent/frameworks/constraint/README.md index db6b5244a8a..55b8998e126 100644 --- a/vendor/github.com/open-policy-agent/frameworks/constraint/README.md +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/README.md @@ -10,7 +10,7 @@ I want to make sure that every object has a `billing` label, I might write the following constraint YAML: ```yaml -apiVersion: constraints.gatekeeper.sh/v1alpha1 +apiVersion: constraints.gatekeeper.sh/v1beta1 kind: FooSystemRequiredLabel metadata: name: require-billing-label @@ -39,7 +39,7 @@ intent. For example, to define the `FooSystemRequiredLabel` constraint kind implemented above, I might write the following template YAML: ```yaml -apiVersion: gatekeeper.sh/v1alpha1 +apiVersion: gatekeeper.sh/v1beta1 kind: ConstraintTemplate metadata: name: foosystemrequiredlabels @@ -48,9 +48,6 @@ spec: spec: names: kind: FooSystemRequiredLabel - listKind: FooSystemRequiredLabelsList - plural: foosystemrequiredlabels - singular: foosystemrequiredlabel validation: # Schema for the `parameters` field openAPIV3Schema: @@ -63,7 +60,7 @@ spec: rego: | violation[{"msg": msg, "details": {"missing_labels": missing}}] { provided := {label | input.request.object.metadata.labels[label]} - required := {label | label := input.constraint.spec.parameters.labels[_]} + required := {label | label := input.parameters.labels[_]} missing := required - provided count(missing) > 0 msg := sprintf("you must provide labels: %v", [missing]) @@ -152,7 +149,7 @@ type TargetHandler interface { GetName() string // MatchSchema returns the JSON Schema for the `match` field of a constraint - MatchSchema() apiextensionsv1beta1.JSONSchemaProps + MatchSchema() apiextensions.JSONSchemaProps // Library returns the pieces of Rego code required to stitch together constraint evaluation // for the target. Current required libraries are `matching_constraints` and // `matching_reviews_and_constraints` @@ -206,11 +203,12 @@ text template that forms a Rego module with at least two rules: * `matching_constraints[constraint]` * Returns all `constraint` objects that satisfy the `match` criteria for - a given `input`. This `constraint` will be assigned to `input.constraint`. + a given `input`. This `perameters` of this `constraint` will be assigned + to `input.parameters`. * `matching_reviews_and_constraints[[review, constraint]]` * Returns a `review` that corresponds to all cached data for the target. It also returns a `constraint` for every constraint relevant to a review. - Values will be made available to constraint rules as `input.constraint` and + Values will be made available to constraint rules as `input.parameters` and `input.review`. Note that the `Library()` module will be sandboxed much like how constraint rules @@ -245,9 +243,9 @@ type Client interface { AddData(context.Context, interface{}) (*types.Responses, error) RemoveData(context.Context, interface{}) (*types.Responses, error) - CreateCRD(context.Context, *v1alpha1.ConstraintTemplate) (*apiextensionsv1beta1.CustomResourceDefinition, error) - AddTemplate(context.Context, *v1alpha1.ConstraintTemplate) (*types.Responses, error) - RemoveTemplate(context.Context, *v1alpha1.ConstraintTemplate) (*types.Responses, error) + CreateCRD(context.Context, *templates.ConstraintTemplate) (*apiextensions.CustomResourceDefinition, error) + AddTemplate(context.Context, *templates.ConstraintTemplate) (*types.Responses, error) + RemoveTemplate(context.Context, *templates.ConstraintTemplate) (*types.Responses, error) AddConstraint(context.Context, *unstructured.Unstructured) (*types.Responses, error) RemoveConstraint(context.Context, *unstructured.Unstructured) (*types.Responses, error) @@ -325,4 +323,4 @@ There are three helpful levers for debugging: * `Client.Dump()` returns all data cached in OPA and every module created in OPA * Drivers can be initialized with a tracing option like so: `local.New(local.Tracing(true))`. These traces can then be viewed by calling `TraceDump()` on the response. - * Traces can be performed on a per-request basis for `Audit()` and `Review()` requests by providing the `client.Tracing(true)` option argument. Example: `results_with_tracing := c.Audit(context.Background(), client.Tracing(true))` \ No newline at end of file + * Traces can be performed on a per-request basis for `Audit()` and `Review()` requests by providing the `client.Tracing(true)` option argument. Example: `results_with_tracing := c.Audit(context.Background(), client.Tracing(true))` diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/config/crd_patch.yaml b/vendor/github.com/open-policy-agent/frameworks/constraint/config/crd_patch.yaml new file mode 100644 index 00000000000..894deeb21c7 --- /dev/null +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/config/crd_patch.yaml @@ -0,0 +1,12 @@ +apiVersion: apiextensions.k8s.io/v1beta1 +kind: CustomResourceDefinition +metadata: + name: constrainttemplates.templates.gatekeeper.sh +spec: + versions: + - name: v1beta1 + served: true + storage: true + - name: v1alpha1 + served: true + storage: false diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/config/crds/templates_v1beta1_constrainttemplate.yaml b/vendor/github.com/open-policy-agent/frameworks/constraint/config/crds/templates_v1beta1_constrainttemplate.yaml new file mode 100644 index 00000000000..043e75484e5 --- /dev/null +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/config/crds/templates_v1beta1_constrainttemplate.yaml @@ -0,0 +1,87 @@ +apiVersion: apiextensions.k8s.io/v1beta1 +kind: CustomResourceDefinition +metadata: + creationTimestamp: null + labels: + controller-tools.k8s.io: "1.0" + name: constrainttemplates.templates.gatekeeper.sh +spec: + group: templates.gatekeeper.sh + names: + kind: ConstraintTemplate + plural: constrainttemplates + scope: Cluster + validation: + openAPIV3Schema: + properties: + apiVersion: + description: 'APIVersion defines the versioned schema of this representation + of an object. Servers should convert recognized schemas to the latest + internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources' + type: string + kind: + description: 'Kind is a string value representing the REST resource this + object represents. Servers may infer this from the endpoint the client + submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds' + type: string + metadata: + type: object + spec: + properties: + crd: + properties: + spec: + properties: + names: + properties: + kind: + type: string + type: object + validation: + type: object + type: object + type: object + targets: + items: + properties: + rego: + type: string + target: + type: string + type: object + type: array + type: object + status: + properties: + byPod: + items: + properties: + errors: + items: + properties: + code: + type: string + location: + type: string + message: + type: string + required: + - code + - message + type: object + type: array + id: + description: a unique identifier for the pod that wrote the status + type: string + type: object + type: array + created: + type: boolean + type: object + version: v1beta1 +status: + acceptedNames: + kind: "" + plural: "" + conditions: [] + storedVersions: [] diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/config/kustomization.yaml b/vendor/github.com/open-policy-agent/frameworks/constraint/config/kustomization.yaml new file mode 100644 index 00000000000..1fa9e51ad6d --- /dev/null +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/config/kustomization.yaml @@ -0,0 +1,9 @@ +# create a multi-version CRD via kustomize because Kubebuilder v1 doesn't support multi-version +# CRDs + +resources: +- crds/templates_v1beta1_constrainttemplate.yaml + +patchesStrategicMerge: +- crd_patch.yaml + diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/config/samples/templates_v1beta1_constrainttemplate.yaml b/vendor/github.com/open-policy-agent/frameworks/constraint/config/samples/templates_v1beta1_constrainttemplate.yaml new file mode 100644 index 00000000000..9b36faa01cc --- /dev/null +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/config/samples/templates_v1beta1_constrainttemplate.yaml @@ -0,0 +1,9 @@ +apiVersion: templates.gatekeeper.sh/v1beta1 +kind: ConstraintTemplate +metadata: + labels: + controller-tools.k8s.io: "1.0" + name: constrainttemplate-sample +spec: + # Add fields here + foo: bar diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/deploy/crds.yaml b/vendor/github.com/open-policy-agent/frameworks/constraint/deploy/crds.yaml new file mode 100644 index 00000000000..a3715ba2e3a --- /dev/null +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/deploy/crds.yaml @@ -0,0 +1,94 @@ +apiVersion: apiextensions.k8s.io/v1beta1 +kind: CustomResourceDefinition +metadata: + creationTimestamp: null + labels: + controller-tools.k8s.io: "1.0" + name: constrainttemplates.templates.gatekeeper.sh +spec: + group: templates.gatekeeper.sh + names: + kind: ConstraintTemplate + plural: constrainttemplates + scope: Cluster + validation: + openAPIV3Schema: + properties: + apiVersion: + description: 'APIVersion defines the versioned schema of this representation + of an object. Servers should convert recognized schemas to the latest + internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources' + type: string + kind: + description: 'Kind is a string value representing the REST resource this + object represents. Servers may infer this from the endpoint the client + submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds' + type: string + metadata: + type: object + spec: + properties: + crd: + properties: + spec: + properties: + names: + properties: + kind: + type: string + type: object + validation: + type: object + type: object + type: object + targets: + items: + properties: + rego: + type: string + target: + type: string + type: object + type: array + type: object + status: + properties: + byPod: + items: + properties: + errors: + items: + properties: + code: + type: string + location: + type: string + message: + type: string + required: + - code + - message + type: object + type: array + id: + description: a unique identifier for the pod that wrote the status + type: string + type: object + type: array + created: + type: boolean + type: object + version: v1beta1 + versions: + - name: v1beta1 + served: true + storage: true + - name: v1alpha1 + served: true + storage: false +status: + acceptedNames: + kind: "" + plural: "" + conditions: [] + storedVersions: [] diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/addtoscheme_templates_v1alpha1.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/addtoscheme_templates_v1alpha1.go index b03b444c891..be307783c09 100644 --- a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/addtoscheme_templates_v1alpha1.go +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/addtoscheme_templates_v1alpha1.go @@ -21,5 +21,5 @@ import ( func init() { // Register the types with the Scheme so the components can map objects to GroupVersionKinds and back - AddToSchemes = append(AddToSchemes, v1alpha1.SchemeBuilder.AddToScheme) + AddToSchemes = append(AddToSchemes, v1alpha1.AddToSchemes...) } diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/addtoscheme_templates_v1beta1.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/addtoscheme_templates_v1beta1.go new file mode 100644 index 00000000000..938df734eec --- /dev/null +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/addtoscheme_templates_v1beta1.go @@ -0,0 +1,25 @@ +/* + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package apis + +import ( + "github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1" +) + +func init() { + // Register the types with the Scheme so the components can map objects to GroupVersionKinds and back + AddToSchemes = append(AddToSchemes, v1beta1.AddToSchemes...) +} diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/apis.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/apis.go index 15ccbf9c8a5..e0b391d8f30 100644 --- a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/apis.go +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/apis.go @@ -15,6 +15,7 @@ limitations under the License. // Generate deepcopy for apis //go:generate go run ../../vendor/k8s.io/code-generator/cmd/deepcopy-gen/main.go -O zz_generated.deepcopy -i ./... -h ../../hack/boilerplate.go.txt +//go:generate go run ../../vendor/k8s.io/code-generator/cmd/conversion-gen/main.go -O zz_generated.conversion -i ./... -h ../../hack/boilerplate.go.txt // Package apis contains Kubernetes API groups. package apis diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1alpha1/constrainttemplate_types_test.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1alpha1/constrainttemplate_types_test.go index db80accaf83..7b5adeed7bb 100644 --- a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1alpha1/constrainttemplate_types_test.go +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1alpha1/constrainttemplate_types_test.go @@ -16,11 +16,16 @@ limitations under the License. package v1alpha1 import ( + "reflect" "testing" + "github.com/google/go-cmp/cmp" "github.com/onsi/gomega" + "github.com/open-policy-agent/frameworks/constraint/pkg/core/templates" "golang.org/x/net/context" + apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" ) @@ -53,3 +58,66 @@ func TestStorageConstraintTemplate(t *testing.T) { g.Expect(c.Delete(context.TODO(), fetched)).NotTo(gomega.HaveOccurred()) g.Expect(c.Get(context.TODO(), key, fetched)).To(gomega.HaveOccurred()) } + +func TestTypeConversion(t *testing.T) { + scheme := runtime.NewScheme() + AddToSchemes.AddToScheme(scheme) + + versioned := &ConstraintTemplate{ + TypeMeta: metav1.TypeMeta{ + Kind: "ConstraintTemplate", + APIVersion: "templates.gatekeeper.sh/v1alpha1", + }, + ObjectMeta: metav1.ObjectMeta{ + Name: "MustHaveMoreCats", + }, + Spec: ConstraintTemplateSpec{ + CRD: CRD{ + Spec: CRDSpec{ + Names: Names{ + Kind: "MustHaveMoreCats", + }, + Validation: &Validation{ + OpenAPIV3Schema: &apiextensionsv1beta1.JSONSchemaProps{ + Properties: map[string]apiextensionsv1beta1.JSONSchemaProps{ + "message": apiextensionsv1beta1.JSONSchemaProps{ + Type: "string", + }, + "labels": apiextensionsv1beta1.JSONSchemaProps{ + Type: "array", + Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{ + Schema: &apiextensionsv1beta1.JSONSchemaProps{ + Type: "object", + Properties: map[string]apiextensionsv1beta1.JSONSchemaProps{ + "key": apiextensionsv1beta1.JSONSchemaProps{Type: "string"}, + "allowedRegex": apiextensionsv1beta1.JSONSchemaProps{Type: "string"}, + }, + }, + }, + }, + }, + }, + }, + }, + }, + Targets: []Target{ + { + Target: "sometarget", + Rego: `package hello ; violation[{"msg": "msg"}] { true }`, + }, + }, + }, + } + versionedCopy := versioned.DeepCopy() + // Kind and API Version do not survive the conversion process + versionedCopy.Kind = "" + versionedCopy.APIVersion = "" + + unversioned := &templates.ConstraintTemplate{} + scheme.Convert(versioned, unversioned, nil) + recast := &ConstraintTemplate{} + scheme.Convert(unversioned, recast, nil) + if !reflect.DeepEqual(versionedCopy, recast) { + t.Error(cmp.Diff(versionedCopy, recast)) + } +} diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1alpha1/doc.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1alpha1/doc.go index e48e833dff1..eafa12af163 100644 --- a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1alpha1/doc.go +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1alpha1/doc.go @@ -16,7 +16,7 @@ limitations under the License. // Package v1alpha1 contains API Schema definitions for the templates v1alpha1 API group // +k8s:openapi-gen=true // +k8s:deepcopy-gen=package,register -// +k8s:conversion-gen=github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates +// +k8s:conversion-gen=github.com/open-policy-agent/frameworks/constraint/pkg/core/templates // +k8s:defaulter-gen=TypeMeta // +groupName=templates.gatekeeper.sh package v1alpha1 diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1alpha1/register.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1alpha1/register.go index 3101a607658..8d448fa9f25 100644 --- a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1alpha1/register.go +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1alpha1/register.go @@ -24,6 +24,7 @@ limitations under the License. package v1alpha1 import ( + "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "sigs.k8s.io/controller-runtime/pkg/runtime/scheme" ) @@ -35,8 +36,8 @@ var ( // SchemeBuilder is used to add go types to the GroupVersionKind scheme SchemeBuilder = &scheme.Builder{GroupVersion: SchemeGroupVersion} - // AddToScheme is required by pkg/client/... - AddToScheme = SchemeBuilder.AddToScheme + AddToSchemes = runtime.NewSchemeBuilder(SchemeBuilder.AddToScheme) + localSchemeBuilder = AddToSchemes ) // Resource is required by pkg/client/listers/... diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1alpha1/v1alpha1_suite_test.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1alpha1/v1alpha1_suite_test.go index 5b24577908e..f6bf3ac0a2b 100644 --- a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1alpha1/v1alpha1_suite_test.go +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1alpha1/v1alpha1_suite_test.go @@ -32,7 +32,7 @@ var c client.Client func TestMain(m *testing.M) { t := &envtest.Environment{ - CRDDirectoryPaths: []string{filepath.Join("..", "..", "..", "..", "config", "crds")}, + CRDDirectoryPaths: []string{filepath.Join("..", "..", "..", "..", "deploy")}, } err := SchemeBuilder.AddToScheme(scheme.Scheme) diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1alpha1/zz_generated.conversion.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1alpha1/zz_generated.conversion.go new file mode 100644 index 00000000000..38b05e8684b --- /dev/null +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1alpha1/zz_generated.conversion.go @@ -0,0 +1,463 @@ +// +build !ignore_autogenerated + +/* + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +// Code generated by main. DO NOT EDIT. + +package v1alpha1 + +import ( + unsafe "unsafe" + + templates "github.com/open-policy-agent/frameworks/constraint/pkg/core/templates" + apiextensions "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" + v1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" + conversion "k8s.io/apimachinery/pkg/conversion" + runtime "k8s.io/apimachinery/pkg/runtime" +) + +func init() { + localSchemeBuilder.Register(RegisterConversions) +} + +// RegisterConversions adds conversion functions to the given scheme. +// Public to allow building arbitrary schemes. +func RegisterConversions(s *runtime.Scheme) error { + if err := s.AddGeneratedConversionFunc((*ByPodStatus)(nil), (*templates.ByPodStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1alpha1_ByPodStatus_To_templates_ByPodStatus(a.(*ByPodStatus), b.(*templates.ByPodStatus), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*templates.ByPodStatus)(nil), (*ByPodStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_templates_ByPodStatus_To_v1alpha1_ByPodStatus(a.(*templates.ByPodStatus), b.(*ByPodStatus), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*CRD)(nil), (*templates.CRD)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1alpha1_CRD_To_templates_CRD(a.(*CRD), b.(*templates.CRD), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*templates.CRD)(nil), (*CRD)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_templates_CRD_To_v1alpha1_CRD(a.(*templates.CRD), b.(*CRD), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*CRDSpec)(nil), (*templates.CRDSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1alpha1_CRDSpec_To_templates_CRDSpec(a.(*CRDSpec), b.(*templates.CRDSpec), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*templates.CRDSpec)(nil), (*CRDSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_templates_CRDSpec_To_v1alpha1_CRDSpec(a.(*templates.CRDSpec), b.(*CRDSpec), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*ConstraintTemplate)(nil), (*templates.ConstraintTemplate)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1alpha1_ConstraintTemplate_To_templates_ConstraintTemplate(a.(*ConstraintTemplate), b.(*templates.ConstraintTemplate), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*templates.ConstraintTemplate)(nil), (*ConstraintTemplate)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_templates_ConstraintTemplate_To_v1alpha1_ConstraintTemplate(a.(*templates.ConstraintTemplate), b.(*ConstraintTemplate), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*ConstraintTemplateList)(nil), (*templates.ConstraintTemplateList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1alpha1_ConstraintTemplateList_To_templates_ConstraintTemplateList(a.(*ConstraintTemplateList), b.(*templates.ConstraintTemplateList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*templates.ConstraintTemplateList)(nil), (*ConstraintTemplateList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_templates_ConstraintTemplateList_To_v1alpha1_ConstraintTemplateList(a.(*templates.ConstraintTemplateList), b.(*ConstraintTemplateList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*ConstraintTemplateSpec)(nil), (*templates.ConstraintTemplateSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1alpha1_ConstraintTemplateSpec_To_templates_ConstraintTemplateSpec(a.(*ConstraintTemplateSpec), b.(*templates.ConstraintTemplateSpec), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*templates.ConstraintTemplateSpec)(nil), (*ConstraintTemplateSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_templates_ConstraintTemplateSpec_To_v1alpha1_ConstraintTemplateSpec(a.(*templates.ConstraintTemplateSpec), b.(*ConstraintTemplateSpec), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*ConstraintTemplateStatus)(nil), (*templates.ConstraintTemplateStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1alpha1_ConstraintTemplateStatus_To_templates_ConstraintTemplateStatus(a.(*ConstraintTemplateStatus), b.(*templates.ConstraintTemplateStatus), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*templates.ConstraintTemplateStatus)(nil), (*ConstraintTemplateStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_templates_ConstraintTemplateStatus_To_v1alpha1_ConstraintTemplateStatus(a.(*templates.ConstraintTemplateStatus), b.(*ConstraintTemplateStatus), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*CreateCRDError)(nil), (*templates.CreateCRDError)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1alpha1_CreateCRDError_To_templates_CreateCRDError(a.(*CreateCRDError), b.(*templates.CreateCRDError), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*templates.CreateCRDError)(nil), (*CreateCRDError)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_templates_CreateCRDError_To_v1alpha1_CreateCRDError(a.(*templates.CreateCRDError), b.(*CreateCRDError), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*Names)(nil), (*templates.Names)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1alpha1_Names_To_templates_Names(a.(*Names), b.(*templates.Names), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*templates.Names)(nil), (*Names)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_templates_Names_To_v1alpha1_Names(a.(*templates.Names), b.(*Names), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*Target)(nil), (*templates.Target)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1alpha1_Target_To_templates_Target(a.(*Target), b.(*templates.Target), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*templates.Target)(nil), (*Target)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_templates_Target_To_v1alpha1_Target(a.(*templates.Target), b.(*Target), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*Validation)(nil), (*templates.Validation)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1alpha1_Validation_To_templates_Validation(a.(*Validation), b.(*templates.Validation), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*templates.Validation)(nil), (*Validation)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_templates_Validation_To_v1alpha1_Validation(a.(*templates.Validation), b.(*Validation), scope) + }); err != nil { + return err + } + return nil +} + +func autoConvert_v1alpha1_ByPodStatus_To_templates_ByPodStatus(in *ByPodStatus, out *templates.ByPodStatus, s conversion.Scope) error { + out.ID = in.ID + out.Errors = *(*[]*templates.CreateCRDError)(unsafe.Pointer(&in.Errors)) + return nil +} + +// Convert_v1alpha1_ByPodStatus_To_templates_ByPodStatus is an autogenerated conversion function. +func Convert_v1alpha1_ByPodStatus_To_templates_ByPodStatus(in *ByPodStatus, out *templates.ByPodStatus, s conversion.Scope) error { + return autoConvert_v1alpha1_ByPodStatus_To_templates_ByPodStatus(in, out, s) +} + +func autoConvert_templates_ByPodStatus_To_v1alpha1_ByPodStatus(in *templates.ByPodStatus, out *ByPodStatus, s conversion.Scope) error { + out.ID = in.ID + out.Errors = *(*[]*CreateCRDError)(unsafe.Pointer(&in.Errors)) + return nil +} + +// Convert_templates_ByPodStatus_To_v1alpha1_ByPodStatus is an autogenerated conversion function. +func Convert_templates_ByPodStatus_To_v1alpha1_ByPodStatus(in *templates.ByPodStatus, out *ByPodStatus, s conversion.Scope) error { + return autoConvert_templates_ByPodStatus_To_v1alpha1_ByPodStatus(in, out, s) +} + +func autoConvert_v1alpha1_CRD_To_templates_CRD(in *CRD, out *templates.CRD, s conversion.Scope) error { + if err := Convert_v1alpha1_CRDSpec_To_templates_CRDSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + return nil +} + +// Convert_v1alpha1_CRD_To_templates_CRD is an autogenerated conversion function. +func Convert_v1alpha1_CRD_To_templates_CRD(in *CRD, out *templates.CRD, s conversion.Scope) error { + return autoConvert_v1alpha1_CRD_To_templates_CRD(in, out, s) +} + +func autoConvert_templates_CRD_To_v1alpha1_CRD(in *templates.CRD, out *CRD, s conversion.Scope) error { + if err := Convert_templates_CRDSpec_To_v1alpha1_CRDSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + return nil +} + +// Convert_templates_CRD_To_v1alpha1_CRD is an autogenerated conversion function. +func Convert_templates_CRD_To_v1alpha1_CRD(in *templates.CRD, out *CRD, s conversion.Scope) error { + return autoConvert_templates_CRD_To_v1alpha1_CRD(in, out, s) +} + +func autoConvert_v1alpha1_CRDSpec_To_templates_CRDSpec(in *CRDSpec, out *templates.CRDSpec, s conversion.Scope) error { + if err := Convert_v1alpha1_Names_To_templates_Names(&in.Names, &out.Names, s); err != nil { + return err + } + if in.Validation != nil { + in, out := &in.Validation, &out.Validation + *out = new(templates.Validation) + if err := Convert_v1alpha1_Validation_To_templates_Validation(*in, *out, s); err != nil { + return err + } + } else { + out.Validation = nil + } + return nil +} + +// Convert_v1alpha1_CRDSpec_To_templates_CRDSpec is an autogenerated conversion function. +func Convert_v1alpha1_CRDSpec_To_templates_CRDSpec(in *CRDSpec, out *templates.CRDSpec, s conversion.Scope) error { + return autoConvert_v1alpha1_CRDSpec_To_templates_CRDSpec(in, out, s) +} + +func autoConvert_templates_CRDSpec_To_v1alpha1_CRDSpec(in *templates.CRDSpec, out *CRDSpec, s conversion.Scope) error { + if err := Convert_templates_Names_To_v1alpha1_Names(&in.Names, &out.Names, s); err != nil { + return err + } + if in.Validation != nil { + in, out := &in.Validation, &out.Validation + *out = new(Validation) + if err := Convert_templates_Validation_To_v1alpha1_Validation(*in, *out, s); err != nil { + return err + } + } else { + out.Validation = nil + } + return nil +} + +// Convert_templates_CRDSpec_To_v1alpha1_CRDSpec is an autogenerated conversion function. +func Convert_templates_CRDSpec_To_v1alpha1_CRDSpec(in *templates.CRDSpec, out *CRDSpec, s conversion.Scope) error { + return autoConvert_templates_CRDSpec_To_v1alpha1_CRDSpec(in, out, s) +} + +func autoConvert_v1alpha1_ConstraintTemplate_To_templates_ConstraintTemplate(in *ConstraintTemplate, out *templates.ConstraintTemplate, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + if err := Convert_v1alpha1_ConstraintTemplateSpec_To_templates_ConstraintTemplateSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + if err := Convert_v1alpha1_ConstraintTemplateStatus_To_templates_ConstraintTemplateStatus(&in.Status, &out.Status, s); err != nil { + return err + } + return nil +} + +// Convert_v1alpha1_ConstraintTemplate_To_templates_ConstraintTemplate is an autogenerated conversion function. +func Convert_v1alpha1_ConstraintTemplate_To_templates_ConstraintTemplate(in *ConstraintTemplate, out *templates.ConstraintTemplate, s conversion.Scope) error { + return autoConvert_v1alpha1_ConstraintTemplate_To_templates_ConstraintTemplate(in, out, s) +} + +func autoConvert_templates_ConstraintTemplate_To_v1alpha1_ConstraintTemplate(in *templates.ConstraintTemplate, out *ConstraintTemplate, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + if err := Convert_templates_ConstraintTemplateSpec_To_v1alpha1_ConstraintTemplateSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + if err := Convert_templates_ConstraintTemplateStatus_To_v1alpha1_ConstraintTemplateStatus(&in.Status, &out.Status, s); err != nil { + return err + } + return nil +} + +// Convert_templates_ConstraintTemplate_To_v1alpha1_ConstraintTemplate is an autogenerated conversion function. +func Convert_templates_ConstraintTemplate_To_v1alpha1_ConstraintTemplate(in *templates.ConstraintTemplate, out *ConstraintTemplate, s conversion.Scope) error { + return autoConvert_templates_ConstraintTemplate_To_v1alpha1_ConstraintTemplate(in, out, s) +} + +func autoConvert_v1alpha1_ConstraintTemplateList_To_templates_ConstraintTemplateList(in *ConstraintTemplateList, out *templates.ConstraintTemplateList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]templates.ConstraintTemplate, len(*in)) + for i := range *in { + if err := Convert_v1alpha1_ConstraintTemplate_To_templates_ConstraintTemplate(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil +} + +// Convert_v1alpha1_ConstraintTemplateList_To_templates_ConstraintTemplateList is an autogenerated conversion function. +func Convert_v1alpha1_ConstraintTemplateList_To_templates_ConstraintTemplateList(in *ConstraintTemplateList, out *templates.ConstraintTemplateList, s conversion.Scope) error { + return autoConvert_v1alpha1_ConstraintTemplateList_To_templates_ConstraintTemplateList(in, out, s) +} + +func autoConvert_templates_ConstraintTemplateList_To_v1alpha1_ConstraintTemplateList(in *templates.ConstraintTemplateList, out *ConstraintTemplateList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ConstraintTemplate, len(*in)) + for i := range *in { + if err := Convert_templates_ConstraintTemplate_To_v1alpha1_ConstraintTemplate(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil +} + +// Convert_templates_ConstraintTemplateList_To_v1alpha1_ConstraintTemplateList is an autogenerated conversion function. +func Convert_templates_ConstraintTemplateList_To_v1alpha1_ConstraintTemplateList(in *templates.ConstraintTemplateList, out *ConstraintTemplateList, s conversion.Scope) error { + return autoConvert_templates_ConstraintTemplateList_To_v1alpha1_ConstraintTemplateList(in, out, s) +} + +func autoConvert_v1alpha1_ConstraintTemplateSpec_To_templates_ConstraintTemplateSpec(in *ConstraintTemplateSpec, out *templates.ConstraintTemplateSpec, s conversion.Scope) error { + if err := Convert_v1alpha1_CRD_To_templates_CRD(&in.CRD, &out.CRD, s); err != nil { + return err + } + out.Targets = *(*[]templates.Target)(unsafe.Pointer(&in.Targets)) + return nil +} + +// Convert_v1alpha1_ConstraintTemplateSpec_To_templates_ConstraintTemplateSpec is an autogenerated conversion function. +func Convert_v1alpha1_ConstraintTemplateSpec_To_templates_ConstraintTemplateSpec(in *ConstraintTemplateSpec, out *templates.ConstraintTemplateSpec, s conversion.Scope) error { + return autoConvert_v1alpha1_ConstraintTemplateSpec_To_templates_ConstraintTemplateSpec(in, out, s) +} + +func autoConvert_templates_ConstraintTemplateSpec_To_v1alpha1_ConstraintTemplateSpec(in *templates.ConstraintTemplateSpec, out *ConstraintTemplateSpec, s conversion.Scope) error { + if err := Convert_templates_CRD_To_v1alpha1_CRD(&in.CRD, &out.CRD, s); err != nil { + return err + } + out.Targets = *(*[]Target)(unsafe.Pointer(&in.Targets)) + return nil +} + +// Convert_templates_ConstraintTemplateSpec_To_v1alpha1_ConstraintTemplateSpec is an autogenerated conversion function. +func Convert_templates_ConstraintTemplateSpec_To_v1alpha1_ConstraintTemplateSpec(in *templates.ConstraintTemplateSpec, out *ConstraintTemplateSpec, s conversion.Scope) error { + return autoConvert_templates_ConstraintTemplateSpec_To_v1alpha1_ConstraintTemplateSpec(in, out, s) +} + +func autoConvert_v1alpha1_ConstraintTemplateStatus_To_templates_ConstraintTemplateStatus(in *ConstraintTemplateStatus, out *templates.ConstraintTemplateStatus, s conversion.Scope) error { + out.Created = in.Created + out.ByPod = *(*[]*templates.ByPodStatus)(unsafe.Pointer(&in.ByPod)) + return nil +} + +// Convert_v1alpha1_ConstraintTemplateStatus_To_templates_ConstraintTemplateStatus is an autogenerated conversion function. +func Convert_v1alpha1_ConstraintTemplateStatus_To_templates_ConstraintTemplateStatus(in *ConstraintTemplateStatus, out *templates.ConstraintTemplateStatus, s conversion.Scope) error { + return autoConvert_v1alpha1_ConstraintTemplateStatus_To_templates_ConstraintTemplateStatus(in, out, s) +} + +func autoConvert_templates_ConstraintTemplateStatus_To_v1alpha1_ConstraintTemplateStatus(in *templates.ConstraintTemplateStatus, out *ConstraintTemplateStatus, s conversion.Scope) error { + out.Created = in.Created + out.ByPod = *(*[]*ByPodStatus)(unsafe.Pointer(&in.ByPod)) + return nil +} + +// Convert_templates_ConstraintTemplateStatus_To_v1alpha1_ConstraintTemplateStatus is an autogenerated conversion function. +func Convert_templates_ConstraintTemplateStatus_To_v1alpha1_ConstraintTemplateStatus(in *templates.ConstraintTemplateStatus, out *ConstraintTemplateStatus, s conversion.Scope) error { + return autoConvert_templates_ConstraintTemplateStatus_To_v1alpha1_ConstraintTemplateStatus(in, out, s) +} + +func autoConvert_v1alpha1_CreateCRDError_To_templates_CreateCRDError(in *CreateCRDError, out *templates.CreateCRDError, s conversion.Scope) error { + out.Code = in.Code + out.Message = in.Message + out.Location = in.Location + return nil +} + +// Convert_v1alpha1_CreateCRDError_To_templates_CreateCRDError is an autogenerated conversion function. +func Convert_v1alpha1_CreateCRDError_To_templates_CreateCRDError(in *CreateCRDError, out *templates.CreateCRDError, s conversion.Scope) error { + return autoConvert_v1alpha1_CreateCRDError_To_templates_CreateCRDError(in, out, s) +} + +func autoConvert_templates_CreateCRDError_To_v1alpha1_CreateCRDError(in *templates.CreateCRDError, out *CreateCRDError, s conversion.Scope) error { + out.Code = in.Code + out.Message = in.Message + out.Location = in.Location + return nil +} + +// Convert_templates_CreateCRDError_To_v1alpha1_CreateCRDError is an autogenerated conversion function. +func Convert_templates_CreateCRDError_To_v1alpha1_CreateCRDError(in *templates.CreateCRDError, out *CreateCRDError, s conversion.Scope) error { + return autoConvert_templates_CreateCRDError_To_v1alpha1_CreateCRDError(in, out, s) +} + +func autoConvert_v1alpha1_Names_To_templates_Names(in *Names, out *templates.Names, s conversion.Scope) error { + out.Kind = in.Kind + return nil +} + +// Convert_v1alpha1_Names_To_templates_Names is an autogenerated conversion function. +func Convert_v1alpha1_Names_To_templates_Names(in *Names, out *templates.Names, s conversion.Scope) error { + return autoConvert_v1alpha1_Names_To_templates_Names(in, out, s) +} + +func autoConvert_templates_Names_To_v1alpha1_Names(in *templates.Names, out *Names, s conversion.Scope) error { + out.Kind = in.Kind + return nil +} + +// Convert_templates_Names_To_v1alpha1_Names is an autogenerated conversion function. +func Convert_templates_Names_To_v1alpha1_Names(in *templates.Names, out *Names, s conversion.Scope) error { + return autoConvert_templates_Names_To_v1alpha1_Names(in, out, s) +} + +func autoConvert_v1alpha1_Target_To_templates_Target(in *Target, out *templates.Target, s conversion.Scope) error { + out.Target = in.Target + out.Rego = in.Rego + return nil +} + +// Convert_v1alpha1_Target_To_templates_Target is an autogenerated conversion function. +func Convert_v1alpha1_Target_To_templates_Target(in *Target, out *templates.Target, s conversion.Scope) error { + return autoConvert_v1alpha1_Target_To_templates_Target(in, out, s) +} + +func autoConvert_templates_Target_To_v1alpha1_Target(in *templates.Target, out *Target, s conversion.Scope) error { + out.Target = in.Target + out.Rego = in.Rego + return nil +} + +// Convert_templates_Target_To_v1alpha1_Target is an autogenerated conversion function. +func Convert_templates_Target_To_v1alpha1_Target(in *templates.Target, out *Target, s conversion.Scope) error { + return autoConvert_templates_Target_To_v1alpha1_Target(in, out, s) +} + +func autoConvert_v1alpha1_Validation_To_templates_Validation(in *Validation, out *templates.Validation, s conversion.Scope) error { + if in.OpenAPIV3Schema != nil { + in, out := &in.OpenAPIV3Schema, &out.OpenAPIV3Schema + *out = new(apiextensions.JSONSchemaProps) + // TODO: Inefficient conversion - can we improve it? + if err := s.Convert(*in, *out, 0); err != nil { + return err + } + } else { + out.OpenAPIV3Schema = nil + } + return nil +} + +// Convert_v1alpha1_Validation_To_templates_Validation is an autogenerated conversion function. +func Convert_v1alpha1_Validation_To_templates_Validation(in *Validation, out *templates.Validation, s conversion.Scope) error { + return autoConvert_v1alpha1_Validation_To_templates_Validation(in, out, s) +} + +func autoConvert_templates_Validation_To_v1alpha1_Validation(in *templates.Validation, out *Validation, s conversion.Scope) error { + if in.OpenAPIV3Schema != nil { + in, out := &in.OpenAPIV3Schema, &out.OpenAPIV3Schema + *out = new(v1beta1.JSONSchemaProps) + // TODO: Inefficient conversion - can we improve it? + if err := s.Convert(*in, *out, 0); err != nil { + return err + } + } else { + out.OpenAPIV3Schema = nil + } + return nil +} + +// Convert_templates_Validation_To_v1alpha1_Validation is an autogenerated conversion function. +func Convert_templates_Validation_To_v1alpha1_Validation(in *templates.Validation, out *Validation, s conversion.Scope) error { + return autoConvert_templates_Validation_To_v1alpha1_Validation(in, out, s) +} diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1/constrainttemplate_types.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1/constrainttemplate_types.go new file mode 100644 index 00000000000..3ad7b3cafa5 --- /dev/null +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1/constrainttemplate_types.go @@ -0,0 +1,102 @@ +/* + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta1 + +import ( + apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! +// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. + +// ConstraintTemplateSpec defines the desired state of ConstraintTemplate +type ConstraintTemplateSpec struct { + CRD CRD `json:"crd,omitempty"` + Targets []Target `json:"targets,omitempty"` +} + +type CRD struct { + Spec CRDSpec `json:"spec,omitempty"` +} + +type CRDSpec struct { + Names Names `json:"names,omitempty"` + Validation *Validation `json:"validation,omitempty"` +} + +type Names struct { + Kind string `json:"kind,omitempty"` +} + +type Validation struct { + OpenAPIV3Schema *apiextensionsv1beta1.JSONSchemaProps `json:"openAPIV3Schema,omitempty"` +} + +type Target struct { + Target string `json:"target,omitempty"` + Rego string `json:"rego,omitempty"` +} + +// CreateCRDError represents a single error caught during parsing, compiling, etc. +type CreateCRDError struct { + Code string `json:"code"` + Message string `json:"message"` + Location string `json:"location,omitempty"` +} + +// ByPodStatus defines the observed state of ConstraintTemplate as seen by +// an individual controller +type ByPodStatus struct { + // a unique identifier for the pod that wrote the status + ID string `json:"id,omitempty"` + Errors []*CreateCRDError `json:"errors,omitempty"` +} + +// ConstraintTemplateStatus defines the observed state of ConstraintTemplate +type ConstraintTemplateStatus struct { + Created bool `json:"created,omitempty"` + ByPod []*ByPodStatus `json:"byPod,omitempty"` + // INSERT ADDITIONAL STATUS FIELD - define observed state of cluster + // Important: Run "make" to regenerate code after modifying this file +} + +// +genclient +// +genclient:nonNamespaced +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// ConstraintTemplate is the Schema for the constrainttemplates API +// +k8s:openapi-gen=true +type ConstraintTemplate struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec ConstraintTemplateSpec `json:"spec,omitempty"` + Status ConstraintTemplateStatus `json:"status,omitempty"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// ConstraintTemplateList contains a list of ConstraintTemplate +type ConstraintTemplateList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []ConstraintTemplate `json:"items"` +} + +func init() { + SchemeBuilder.Register(&ConstraintTemplate{}, &ConstraintTemplateList{}) +} diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1/constrainttemplate_types_test.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1/constrainttemplate_types_test.go new file mode 100644 index 00000000000..e8b44a9bd37 --- /dev/null +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1/constrainttemplate_types_test.go @@ -0,0 +1,123 @@ +/* + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta1 + +import ( + "reflect" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/onsi/gomega" + "github.com/open-policy-agent/frameworks/constraint/pkg/core/templates" + "golang.org/x/net/context" + apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" +) + +func TestStorageConstraintTemplate(t *testing.T) { + key := types.NamespacedName{ + Name: "foo", + } + created := &ConstraintTemplate{ + ObjectMeta: metav1.ObjectMeta{ + Name: "foo", + }} + g := gomega.NewGomegaWithT(t) + + // Test Create + fetched := &ConstraintTemplate{} + g.Expect(c.Create(context.TODO(), created)).NotTo(gomega.HaveOccurred()) + + g.Expect(c.Get(context.TODO(), key, fetched)).NotTo(gomega.HaveOccurred()) + g.Expect(fetched).To(gomega.Equal(created)) + + // Test Updating the Labels + updated := fetched.DeepCopy() + updated.Labels = map[string]string{"hello": "world"} + g.Expect(c.Update(context.TODO(), updated)).NotTo(gomega.HaveOccurred()) + + g.Expect(c.Get(context.TODO(), key, fetched)).NotTo(gomega.HaveOccurred()) + g.Expect(fetched).To(gomega.Equal(updated)) + + // Test Delete + g.Expect(c.Delete(context.TODO(), fetched)).NotTo(gomega.HaveOccurred()) + g.Expect(c.Get(context.TODO(), key, fetched)).To(gomega.HaveOccurred()) +} + +func TestTypeConversion(t *testing.T) { + scheme := runtime.NewScheme() + AddToSchemes.AddToScheme(scheme) + + versioned := &ConstraintTemplate{ + TypeMeta: metav1.TypeMeta{ + Kind: "ConstraintTemplate", + APIVersion: "templates.gatekeeper.sh/v1beta1", + }, + ObjectMeta: metav1.ObjectMeta{ + Name: "MustHaveMoreCats", + }, + Spec: ConstraintTemplateSpec{ + CRD: CRD{ + Spec: CRDSpec{ + Names: Names{ + Kind: "MustHaveMoreCats", + }, + Validation: &Validation{ + OpenAPIV3Schema: &apiextensionsv1beta1.JSONSchemaProps{ + Properties: map[string]apiextensionsv1beta1.JSONSchemaProps{ + "message": apiextensionsv1beta1.JSONSchemaProps{ + Type: "string", + }, + "labels": apiextensionsv1beta1.JSONSchemaProps{ + Type: "array", + Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{ + Schema: &apiextensionsv1beta1.JSONSchemaProps{ + Type: "object", + Properties: map[string]apiextensionsv1beta1.JSONSchemaProps{ + "key": apiextensionsv1beta1.JSONSchemaProps{Type: "string"}, + "allowedRegex": apiextensionsv1beta1.JSONSchemaProps{Type: "string"}, + }, + }, + }, + }, + }, + }, + }, + }, + }, + Targets: []Target{ + { + Target: "sometarget", + Rego: `package hello ; violation[{"msg": "msg"}] { true }`, + }, + }, + }, + } + versionedCopy := versioned.DeepCopy() + // Kind and API Version do not survive the conversion process + versionedCopy.Kind = "" + versionedCopy.APIVersion = "" + + unversioned := &templates.ConstraintTemplate{} + scheme.Convert(versioned, unversioned, nil) + recast := &ConstraintTemplate{} + scheme.Convert(unversioned, recast, nil) + if !reflect.DeepEqual(versionedCopy, recast) { + t.Error(cmp.Diff(versionedCopy, recast)) + } +} diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1/doc.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1/doc.go new file mode 100644 index 00000000000..139acc07e87 --- /dev/null +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1/doc.go @@ -0,0 +1,22 @@ +/* + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package v1beta1 contains API Schema definitions for the templates v1beta1 API group +// +k8s:openapi-gen=true +// +k8s:deepcopy-gen=package,register +// +k8s:conversion-gen=github.com/open-policy-agent/frameworks/constraint/pkg/core/templates +// +k8s:defaulter-gen=TypeMeta +// +groupName=templates.gatekeeper.sh +package v1beta1 diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1/register.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1/register.go new file mode 100644 index 00000000000..c4b56280f7f --- /dev/null +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1/register.go @@ -0,0 +1,46 @@ +/* + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// NOTE: Boilerplate only. Ignore this file. + +// Package v1beta1 contains API Schema definitions for the templates v1beta1 API group +// +k8s:openapi-gen=true +// +k8s:deepcopy-gen=package,register +// +k8s:conversion-gen=github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates +// +k8s:defaulter-gen=TypeMeta +// +groupName=templates.gatekeeper.sh +package v1beta1 + +import ( + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "sigs.k8s.io/controller-runtime/pkg/runtime/scheme" +) + +var ( + // SchemeGroupVersion is group version used to register these objects + SchemeGroupVersion = schema.GroupVersion{Group: "templates.gatekeeper.sh", Version: "v1beta1"} + + // SchemeBuilder is used to add go types to the GroupVersionKind scheme + SchemeBuilder = &scheme.Builder{GroupVersion: SchemeGroupVersion} + + AddToSchemes = runtime.NewSchemeBuilder(SchemeBuilder.AddToScheme) + localSchemeBuilder = AddToSchemes +) + +// Resource is required by pkg/client/listers/... +func Resource(resource string) schema.GroupResource { + return SchemeGroupVersion.WithResource(resource).GroupResource() +} diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1/v1beta1_suite_test.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1/v1beta1_suite_test.go new file mode 100644 index 00000000000..e335de3dce6 --- /dev/null +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1/v1beta1_suite_test.go @@ -0,0 +1,54 @@ +/* + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta1 + +import ( + "log" + "os" + "path/filepath" + "testing" + + "k8s.io/client-go/kubernetes/scheme" + "k8s.io/client-go/rest" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" +) + +var cfg *rest.Config +var c client.Client + +func TestMain(m *testing.M) { + t := &envtest.Environment{ + CRDDirectoryPaths: []string{filepath.Join("..", "..", "..", "..", "deploy")}, + } + + err := SchemeBuilder.AddToScheme(scheme.Scheme) + if err != nil { + log.Fatal(err) + } + + if cfg, err = t.Start(); err != nil { + log.Fatal(err) + } + + if c, err = client.New(cfg, client.Options{Scheme: scheme.Scheme}); err != nil { + log.Fatal(err) + } + + code := m.Run() + t.Stop() + os.Exit(code) +} diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1/zz_generated.conversion.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1/zz_generated.conversion.go new file mode 100644 index 00000000000..dc5b6e8ee53 --- /dev/null +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1/zz_generated.conversion.go @@ -0,0 +1,463 @@ +// +build !ignore_autogenerated + +/* + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +// Code generated by main. DO NOT EDIT. + +package v1beta1 + +import ( + unsafe "unsafe" + + templates "github.com/open-policy-agent/frameworks/constraint/pkg/core/templates" + apiextensions "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" + apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" + conversion "k8s.io/apimachinery/pkg/conversion" + runtime "k8s.io/apimachinery/pkg/runtime" +) + +func init() { + localSchemeBuilder.Register(RegisterConversions) +} + +// RegisterConversions adds conversion functions to the given scheme. +// Public to allow building arbitrary schemes. +func RegisterConversions(s *runtime.Scheme) error { + if err := s.AddGeneratedConversionFunc((*ByPodStatus)(nil), (*templates.ByPodStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_ByPodStatus_To_templates_ByPodStatus(a.(*ByPodStatus), b.(*templates.ByPodStatus), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*templates.ByPodStatus)(nil), (*ByPodStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_templates_ByPodStatus_To_v1beta1_ByPodStatus(a.(*templates.ByPodStatus), b.(*ByPodStatus), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*CRD)(nil), (*templates.CRD)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_CRD_To_templates_CRD(a.(*CRD), b.(*templates.CRD), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*templates.CRD)(nil), (*CRD)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_templates_CRD_To_v1beta1_CRD(a.(*templates.CRD), b.(*CRD), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*CRDSpec)(nil), (*templates.CRDSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_CRDSpec_To_templates_CRDSpec(a.(*CRDSpec), b.(*templates.CRDSpec), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*templates.CRDSpec)(nil), (*CRDSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_templates_CRDSpec_To_v1beta1_CRDSpec(a.(*templates.CRDSpec), b.(*CRDSpec), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*ConstraintTemplate)(nil), (*templates.ConstraintTemplate)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_ConstraintTemplate_To_templates_ConstraintTemplate(a.(*ConstraintTemplate), b.(*templates.ConstraintTemplate), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*templates.ConstraintTemplate)(nil), (*ConstraintTemplate)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_templates_ConstraintTemplate_To_v1beta1_ConstraintTemplate(a.(*templates.ConstraintTemplate), b.(*ConstraintTemplate), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*ConstraintTemplateList)(nil), (*templates.ConstraintTemplateList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_ConstraintTemplateList_To_templates_ConstraintTemplateList(a.(*ConstraintTemplateList), b.(*templates.ConstraintTemplateList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*templates.ConstraintTemplateList)(nil), (*ConstraintTemplateList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_templates_ConstraintTemplateList_To_v1beta1_ConstraintTemplateList(a.(*templates.ConstraintTemplateList), b.(*ConstraintTemplateList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*ConstraintTemplateSpec)(nil), (*templates.ConstraintTemplateSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_ConstraintTemplateSpec_To_templates_ConstraintTemplateSpec(a.(*ConstraintTemplateSpec), b.(*templates.ConstraintTemplateSpec), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*templates.ConstraintTemplateSpec)(nil), (*ConstraintTemplateSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_templates_ConstraintTemplateSpec_To_v1beta1_ConstraintTemplateSpec(a.(*templates.ConstraintTemplateSpec), b.(*ConstraintTemplateSpec), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*ConstraintTemplateStatus)(nil), (*templates.ConstraintTemplateStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_ConstraintTemplateStatus_To_templates_ConstraintTemplateStatus(a.(*ConstraintTemplateStatus), b.(*templates.ConstraintTemplateStatus), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*templates.ConstraintTemplateStatus)(nil), (*ConstraintTemplateStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_templates_ConstraintTemplateStatus_To_v1beta1_ConstraintTemplateStatus(a.(*templates.ConstraintTemplateStatus), b.(*ConstraintTemplateStatus), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*CreateCRDError)(nil), (*templates.CreateCRDError)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_CreateCRDError_To_templates_CreateCRDError(a.(*CreateCRDError), b.(*templates.CreateCRDError), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*templates.CreateCRDError)(nil), (*CreateCRDError)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_templates_CreateCRDError_To_v1beta1_CreateCRDError(a.(*templates.CreateCRDError), b.(*CreateCRDError), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*Names)(nil), (*templates.Names)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_Names_To_templates_Names(a.(*Names), b.(*templates.Names), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*templates.Names)(nil), (*Names)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_templates_Names_To_v1beta1_Names(a.(*templates.Names), b.(*Names), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*Target)(nil), (*templates.Target)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_Target_To_templates_Target(a.(*Target), b.(*templates.Target), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*templates.Target)(nil), (*Target)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_templates_Target_To_v1beta1_Target(a.(*templates.Target), b.(*Target), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*Validation)(nil), (*templates.Validation)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_Validation_To_templates_Validation(a.(*Validation), b.(*templates.Validation), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*templates.Validation)(nil), (*Validation)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_templates_Validation_To_v1beta1_Validation(a.(*templates.Validation), b.(*Validation), scope) + }); err != nil { + return err + } + return nil +} + +func autoConvert_v1beta1_ByPodStatus_To_templates_ByPodStatus(in *ByPodStatus, out *templates.ByPodStatus, s conversion.Scope) error { + out.ID = in.ID + out.Errors = *(*[]*templates.CreateCRDError)(unsafe.Pointer(&in.Errors)) + return nil +} + +// Convert_v1beta1_ByPodStatus_To_templates_ByPodStatus is an autogenerated conversion function. +func Convert_v1beta1_ByPodStatus_To_templates_ByPodStatus(in *ByPodStatus, out *templates.ByPodStatus, s conversion.Scope) error { + return autoConvert_v1beta1_ByPodStatus_To_templates_ByPodStatus(in, out, s) +} + +func autoConvert_templates_ByPodStatus_To_v1beta1_ByPodStatus(in *templates.ByPodStatus, out *ByPodStatus, s conversion.Scope) error { + out.ID = in.ID + out.Errors = *(*[]*CreateCRDError)(unsafe.Pointer(&in.Errors)) + return nil +} + +// Convert_templates_ByPodStatus_To_v1beta1_ByPodStatus is an autogenerated conversion function. +func Convert_templates_ByPodStatus_To_v1beta1_ByPodStatus(in *templates.ByPodStatus, out *ByPodStatus, s conversion.Scope) error { + return autoConvert_templates_ByPodStatus_To_v1beta1_ByPodStatus(in, out, s) +} + +func autoConvert_v1beta1_CRD_To_templates_CRD(in *CRD, out *templates.CRD, s conversion.Scope) error { + if err := Convert_v1beta1_CRDSpec_To_templates_CRDSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + return nil +} + +// Convert_v1beta1_CRD_To_templates_CRD is an autogenerated conversion function. +func Convert_v1beta1_CRD_To_templates_CRD(in *CRD, out *templates.CRD, s conversion.Scope) error { + return autoConvert_v1beta1_CRD_To_templates_CRD(in, out, s) +} + +func autoConvert_templates_CRD_To_v1beta1_CRD(in *templates.CRD, out *CRD, s conversion.Scope) error { + if err := Convert_templates_CRDSpec_To_v1beta1_CRDSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + return nil +} + +// Convert_templates_CRD_To_v1beta1_CRD is an autogenerated conversion function. +func Convert_templates_CRD_To_v1beta1_CRD(in *templates.CRD, out *CRD, s conversion.Scope) error { + return autoConvert_templates_CRD_To_v1beta1_CRD(in, out, s) +} + +func autoConvert_v1beta1_CRDSpec_To_templates_CRDSpec(in *CRDSpec, out *templates.CRDSpec, s conversion.Scope) error { + if err := Convert_v1beta1_Names_To_templates_Names(&in.Names, &out.Names, s); err != nil { + return err + } + if in.Validation != nil { + in, out := &in.Validation, &out.Validation + *out = new(templates.Validation) + if err := Convert_v1beta1_Validation_To_templates_Validation(*in, *out, s); err != nil { + return err + } + } else { + out.Validation = nil + } + return nil +} + +// Convert_v1beta1_CRDSpec_To_templates_CRDSpec is an autogenerated conversion function. +func Convert_v1beta1_CRDSpec_To_templates_CRDSpec(in *CRDSpec, out *templates.CRDSpec, s conversion.Scope) error { + return autoConvert_v1beta1_CRDSpec_To_templates_CRDSpec(in, out, s) +} + +func autoConvert_templates_CRDSpec_To_v1beta1_CRDSpec(in *templates.CRDSpec, out *CRDSpec, s conversion.Scope) error { + if err := Convert_templates_Names_To_v1beta1_Names(&in.Names, &out.Names, s); err != nil { + return err + } + if in.Validation != nil { + in, out := &in.Validation, &out.Validation + *out = new(Validation) + if err := Convert_templates_Validation_To_v1beta1_Validation(*in, *out, s); err != nil { + return err + } + } else { + out.Validation = nil + } + return nil +} + +// Convert_templates_CRDSpec_To_v1beta1_CRDSpec is an autogenerated conversion function. +func Convert_templates_CRDSpec_To_v1beta1_CRDSpec(in *templates.CRDSpec, out *CRDSpec, s conversion.Scope) error { + return autoConvert_templates_CRDSpec_To_v1beta1_CRDSpec(in, out, s) +} + +func autoConvert_v1beta1_ConstraintTemplate_To_templates_ConstraintTemplate(in *ConstraintTemplate, out *templates.ConstraintTemplate, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + if err := Convert_v1beta1_ConstraintTemplateSpec_To_templates_ConstraintTemplateSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + if err := Convert_v1beta1_ConstraintTemplateStatus_To_templates_ConstraintTemplateStatus(&in.Status, &out.Status, s); err != nil { + return err + } + return nil +} + +// Convert_v1beta1_ConstraintTemplate_To_templates_ConstraintTemplate is an autogenerated conversion function. +func Convert_v1beta1_ConstraintTemplate_To_templates_ConstraintTemplate(in *ConstraintTemplate, out *templates.ConstraintTemplate, s conversion.Scope) error { + return autoConvert_v1beta1_ConstraintTemplate_To_templates_ConstraintTemplate(in, out, s) +} + +func autoConvert_templates_ConstraintTemplate_To_v1beta1_ConstraintTemplate(in *templates.ConstraintTemplate, out *ConstraintTemplate, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + if err := Convert_templates_ConstraintTemplateSpec_To_v1beta1_ConstraintTemplateSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + if err := Convert_templates_ConstraintTemplateStatus_To_v1beta1_ConstraintTemplateStatus(&in.Status, &out.Status, s); err != nil { + return err + } + return nil +} + +// Convert_templates_ConstraintTemplate_To_v1beta1_ConstraintTemplate is an autogenerated conversion function. +func Convert_templates_ConstraintTemplate_To_v1beta1_ConstraintTemplate(in *templates.ConstraintTemplate, out *ConstraintTemplate, s conversion.Scope) error { + return autoConvert_templates_ConstraintTemplate_To_v1beta1_ConstraintTemplate(in, out, s) +} + +func autoConvert_v1beta1_ConstraintTemplateList_To_templates_ConstraintTemplateList(in *ConstraintTemplateList, out *templates.ConstraintTemplateList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]templates.ConstraintTemplate, len(*in)) + for i := range *in { + if err := Convert_v1beta1_ConstraintTemplate_To_templates_ConstraintTemplate(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil +} + +// Convert_v1beta1_ConstraintTemplateList_To_templates_ConstraintTemplateList is an autogenerated conversion function. +func Convert_v1beta1_ConstraintTemplateList_To_templates_ConstraintTemplateList(in *ConstraintTemplateList, out *templates.ConstraintTemplateList, s conversion.Scope) error { + return autoConvert_v1beta1_ConstraintTemplateList_To_templates_ConstraintTemplateList(in, out, s) +} + +func autoConvert_templates_ConstraintTemplateList_To_v1beta1_ConstraintTemplateList(in *templates.ConstraintTemplateList, out *ConstraintTemplateList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ConstraintTemplate, len(*in)) + for i := range *in { + if err := Convert_templates_ConstraintTemplate_To_v1beta1_ConstraintTemplate(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil +} + +// Convert_templates_ConstraintTemplateList_To_v1beta1_ConstraintTemplateList is an autogenerated conversion function. +func Convert_templates_ConstraintTemplateList_To_v1beta1_ConstraintTemplateList(in *templates.ConstraintTemplateList, out *ConstraintTemplateList, s conversion.Scope) error { + return autoConvert_templates_ConstraintTemplateList_To_v1beta1_ConstraintTemplateList(in, out, s) +} + +func autoConvert_v1beta1_ConstraintTemplateSpec_To_templates_ConstraintTemplateSpec(in *ConstraintTemplateSpec, out *templates.ConstraintTemplateSpec, s conversion.Scope) error { + if err := Convert_v1beta1_CRD_To_templates_CRD(&in.CRD, &out.CRD, s); err != nil { + return err + } + out.Targets = *(*[]templates.Target)(unsafe.Pointer(&in.Targets)) + return nil +} + +// Convert_v1beta1_ConstraintTemplateSpec_To_templates_ConstraintTemplateSpec is an autogenerated conversion function. +func Convert_v1beta1_ConstraintTemplateSpec_To_templates_ConstraintTemplateSpec(in *ConstraintTemplateSpec, out *templates.ConstraintTemplateSpec, s conversion.Scope) error { + return autoConvert_v1beta1_ConstraintTemplateSpec_To_templates_ConstraintTemplateSpec(in, out, s) +} + +func autoConvert_templates_ConstraintTemplateSpec_To_v1beta1_ConstraintTemplateSpec(in *templates.ConstraintTemplateSpec, out *ConstraintTemplateSpec, s conversion.Scope) error { + if err := Convert_templates_CRD_To_v1beta1_CRD(&in.CRD, &out.CRD, s); err != nil { + return err + } + out.Targets = *(*[]Target)(unsafe.Pointer(&in.Targets)) + return nil +} + +// Convert_templates_ConstraintTemplateSpec_To_v1beta1_ConstraintTemplateSpec is an autogenerated conversion function. +func Convert_templates_ConstraintTemplateSpec_To_v1beta1_ConstraintTemplateSpec(in *templates.ConstraintTemplateSpec, out *ConstraintTemplateSpec, s conversion.Scope) error { + return autoConvert_templates_ConstraintTemplateSpec_To_v1beta1_ConstraintTemplateSpec(in, out, s) +} + +func autoConvert_v1beta1_ConstraintTemplateStatus_To_templates_ConstraintTemplateStatus(in *ConstraintTemplateStatus, out *templates.ConstraintTemplateStatus, s conversion.Scope) error { + out.Created = in.Created + out.ByPod = *(*[]*templates.ByPodStatus)(unsafe.Pointer(&in.ByPod)) + return nil +} + +// Convert_v1beta1_ConstraintTemplateStatus_To_templates_ConstraintTemplateStatus is an autogenerated conversion function. +func Convert_v1beta1_ConstraintTemplateStatus_To_templates_ConstraintTemplateStatus(in *ConstraintTemplateStatus, out *templates.ConstraintTemplateStatus, s conversion.Scope) error { + return autoConvert_v1beta1_ConstraintTemplateStatus_To_templates_ConstraintTemplateStatus(in, out, s) +} + +func autoConvert_templates_ConstraintTemplateStatus_To_v1beta1_ConstraintTemplateStatus(in *templates.ConstraintTemplateStatus, out *ConstraintTemplateStatus, s conversion.Scope) error { + out.Created = in.Created + out.ByPod = *(*[]*ByPodStatus)(unsafe.Pointer(&in.ByPod)) + return nil +} + +// Convert_templates_ConstraintTemplateStatus_To_v1beta1_ConstraintTemplateStatus is an autogenerated conversion function. +func Convert_templates_ConstraintTemplateStatus_To_v1beta1_ConstraintTemplateStatus(in *templates.ConstraintTemplateStatus, out *ConstraintTemplateStatus, s conversion.Scope) error { + return autoConvert_templates_ConstraintTemplateStatus_To_v1beta1_ConstraintTemplateStatus(in, out, s) +} + +func autoConvert_v1beta1_CreateCRDError_To_templates_CreateCRDError(in *CreateCRDError, out *templates.CreateCRDError, s conversion.Scope) error { + out.Code = in.Code + out.Message = in.Message + out.Location = in.Location + return nil +} + +// Convert_v1beta1_CreateCRDError_To_templates_CreateCRDError is an autogenerated conversion function. +func Convert_v1beta1_CreateCRDError_To_templates_CreateCRDError(in *CreateCRDError, out *templates.CreateCRDError, s conversion.Scope) error { + return autoConvert_v1beta1_CreateCRDError_To_templates_CreateCRDError(in, out, s) +} + +func autoConvert_templates_CreateCRDError_To_v1beta1_CreateCRDError(in *templates.CreateCRDError, out *CreateCRDError, s conversion.Scope) error { + out.Code = in.Code + out.Message = in.Message + out.Location = in.Location + return nil +} + +// Convert_templates_CreateCRDError_To_v1beta1_CreateCRDError is an autogenerated conversion function. +func Convert_templates_CreateCRDError_To_v1beta1_CreateCRDError(in *templates.CreateCRDError, out *CreateCRDError, s conversion.Scope) error { + return autoConvert_templates_CreateCRDError_To_v1beta1_CreateCRDError(in, out, s) +} + +func autoConvert_v1beta1_Names_To_templates_Names(in *Names, out *templates.Names, s conversion.Scope) error { + out.Kind = in.Kind + return nil +} + +// Convert_v1beta1_Names_To_templates_Names is an autogenerated conversion function. +func Convert_v1beta1_Names_To_templates_Names(in *Names, out *templates.Names, s conversion.Scope) error { + return autoConvert_v1beta1_Names_To_templates_Names(in, out, s) +} + +func autoConvert_templates_Names_To_v1beta1_Names(in *templates.Names, out *Names, s conversion.Scope) error { + out.Kind = in.Kind + return nil +} + +// Convert_templates_Names_To_v1beta1_Names is an autogenerated conversion function. +func Convert_templates_Names_To_v1beta1_Names(in *templates.Names, out *Names, s conversion.Scope) error { + return autoConvert_templates_Names_To_v1beta1_Names(in, out, s) +} + +func autoConvert_v1beta1_Target_To_templates_Target(in *Target, out *templates.Target, s conversion.Scope) error { + out.Target = in.Target + out.Rego = in.Rego + return nil +} + +// Convert_v1beta1_Target_To_templates_Target is an autogenerated conversion function. +func Convert_v1beta1_Target_To_templates_Target(in *Target, out *templates.Target, s conversion.Scope) error { + return autoConvert_v1beta1_Target_To_templates_Target(in, out, s) +} + +func autoConvert_templates_Target_To_v1beta1_Target(in *templates.Target, out *Target, s conversion.Scope) error { + out.Target = in.Target + out.Rego = in.Rego + return nil +} + +// Convert_templates_Target_To_v1beta1_Target is an autogenerated conversion function. +func Convert_templates_Target_To_v1beta1_Target(in *templates.Target, out *Target, s conversion.Scope) error { + return autoConvert_templates_Target_To_v1beta1_Target(in, out, s) +} + +func autoConvert_v1beta1_Validation_To_templates_Validation(in *Validation, out *templates.Validation, s conversion.Scope) error { + if in.OpenAPIV3Schema != nil { + in, out := &in.OpenAPIV3Schema, &out.OpenAPIV3Schema + *out = new(apiextensions.JSONSchemaProps) + // TODO: Inefficient conversion - can we improve it? + if err := s.Convert(*in, *out, 0); err != nil { + return err + } + } else { + out.OpenAPIV3Schema = nil + } + return nil +} + +// Convert_v1beta1_Validation_To_templates_Validation is an autogenerated conversion function. +func Convert_v1beta1_Validation_To_templates_Validation(in *Validation, out *templates.Validation, s conversion.Scope) error { + return autoConvert_v1beta1_Validation_To_templates_Validation(in, out, s) +} + +func autoConvert_templates_Validation_To_v1beta1_Validation(in *templates.Validation, out *Validation, s conversion.Scope) error { + if in.OpenAPIV3Schema != nil { + in, out := &in.OpenAPIV3Schema, &out.OpenAPIV3Schema + *out = new(apiextensionsv1beta1.JSONSchemaProps) + // TODO: Inefficient conversion - can we improve it? + if err := s.Convert(*in, *out, 0); err != nil { + return err + } + } else { + out.OpenAPIV3Schema = nil + } + return nil +} + +// Convert_templates_Validation_To_v1beta1_Validation is an autogenerated conversion function. +func Convert_templates_Validation_To_v1beta1_Validation(in *templates.Validation, out *Validation, s conversion.Scope) error { + return autoConvert_templates_Validation_To_v1beta1_Validation(in, out, s) +} diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1/zz_generated.deepcopy.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1/zz_generated.deepcopy.go new file mode 100644 index 00000000000..42f06893ed9 --- /dev/null +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1/zz_generated.deepcopy.go @@ -0,0 +1,267 @@ +// +build !ignore_autogenerated + +/* + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +// Code generated by main. DO NOT EDIT. + +package v1beta1 + +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 *ByPodStatus) DeepCopyInto(out *ByPodStatus) { + *out = *in + if in.Errors != nil { + in, out := &in.Errors, &out.Errors + *out = make([]*CreateCRDError, len(*in)) + for i := range *in { + if (*in)[i] != nil { + in, out := &(*in)[i], &(*out)[i] + *out = new(CreateCRDError) + **out = **in + } + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ByPodStatus. +func (in *ByPodStatus) DeepCopy() *ByPodStatus { + if in == nil { + return nil + } + out := new(ByPodStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CRD) DeepCopyInto(out *CRD) { + *out = *in + in.Spec.DeepCopyInto(&out.Spec) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CRD. +func (in *CRD) DeepCopy() *CRD { + if in == nil { + return nil + } + out := new(CRD) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CRDSpec) DeepCopyInto(out *CRDSpec) { + *out = *in + out.Names = in.Names + if in.Validation != nil { + in, out := &in.Validation, &out.Validation + *out = new(Validation) + (*in).DeepCopyInto(*out) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CRDSpec. +func (in *CRDSpec) DeepCopy() *CRDSpec { + if in == nil { + return nil + } + out := new(CRDSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ConstraintTemplate) DeepCopyInto(out *ConstraintTemplate) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConstraintTemplate. +func (in *ConstraintTemplate) DeepCopy() *ConstraintTemplate { + if in == nil { + return nil + } + out := new(ConstraintTemplate) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ConstraintTemplate) 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 *ConstraintTemplateList) DeepCopyInto(out *ConstraintTemplateList) { + *out = *in + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ConstraintTemplate, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConstraintTemplateList. +func (in *ConstraintTemplateList) DeepCopy() *ConstraintTemplateList { + if in == nil { + return nil + } + out := new(ConstraintTemplateList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ConstraintTemplateList) 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 *ConstraintTemplateSpec) DeepCopyInto(out *ConstraintTemplateSpec) { + *out = *in + in.CRD.DeepCopyInto(&out.CRD) + if in.Targets != nil { + in, out := &in.Targets, &out.Targets + *out = make([]Target, len(*in)) + copy(*out, *in) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConstraintTemplateSpec. +func (in *ConstraintTemplateSpec) DeepCopy() *ConstraintTemplateSpec { + if in == nil { + return nil + } + out := new(ConstraintTemplateSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ConstraintTemplateStatus) DeepCopyInto(out *ConstraintTemplateStatus) { + *out = *in + if in.ByPod != nil { + in, out := &in.ByPod, &out.ByPod + *out = make([]*ByPodStatus, len(*in)) + for i := range *in { + if (*in)[i] != nil { + in, out := &(*in)[i], &(*out)[i] + *out = new(ByPodStatus) + (*in).DeepCopyInto(*out) + } + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConstraintTemplateStatus. +func (in *ConstraintTemplateStatus) DeepCopy() *ConstraintTemplateStatus { + if in == nil { + return nil + } + out := new(ConstraintTemplateStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CreateCRDError) DeepCopyInto(out *CreateCRDError) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CreateCRDError. +func (in *CreateCRDError) DeepCopy() *CreateCRDError { + if in == nil { + return nil + } + out := new(CreateCRDError) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Names) DeepCopyInto(out *Names) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Names. +func (in *Names) DeepCopy() *Names { + if in == nil { + return nil + } + out := new(Names) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Target) DeepCopyInto(out *Target) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Target. +func (in *Target) DeepCopy() *Target { + if in == nil { + return nil + } + out := new(Target) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Validation) DeepCopyInto(out *Validation) { + *out = *in + if in.OpenAPIV3Schema != nil { + in, out := &in.OpenAPIV3Schema, &out.OpenAPIV3Schema + *out = (*in).DeepCopy() + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Validation. +func (in *Validation) DeepCopy() *Validation { + if in == nil { + return nil + } + out := new(Validation) + in.DeepCopyInto(out) + return out +} diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/zz_generated.deepcopy.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/zz_generated.deepcopy.go new file mode 100644 index 00000000000..f1958b88148 --- /dev/null +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/zz_generated.deepcopy.go @@ -0,0 +1,19 @@ +// +build !ignore_autogenerated + +/* + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +// Code generated by main. DO NOT EDIT. + +package templates diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/client.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/client.go index ceff4fc4875..ee9dd4e7348 100644 --- a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/client.go +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/client.go @@ -11,11 +11,11 @@ import ( "sync" "text/template" - "github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1alpha1" "github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers" "github.com/open-policy-agent/frameworks/constraint/pkg/client/regolib" + "github.com/open-policy-agent/frameworks/constraint/pkg/core/templates" "github.com/open-policy-agent/frameworks/constraint/pkg/types" - apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" + "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" ) @@ -25,9 +25,9 @@ type Client interface { AddData(context.Context, interface{}) (*types.Responses, error) RemoveData(context.Context, interface{}) (*types.Responses, error) - CreateCRD(context.Context, *v1alpha1.ConstraintTemplate) (*apiextensionsv1beta1.CustomResourceDefinition, error) - AddTemplate(context.Context, *v1alpha1.ConstraintTemplate) (*types.Responses, error) - RemoveTemplate(context.Context, *v1alpha1.ConstraintTemplate) (*types.Responses, error) + CreateCRD(context.Context, *templates.ConstraintTemplate) (*apiextensions.CustomResourceDefinition, error) + AddTemplate(context.Context, *templates.ConstraintTemplate) (*types.Responses, error) + RemoveTemplate(context.Context, *templates.ConstraintTemplate) (*types.Responses, error) AddConstraint(context.Context, *unstructured.Unstructured) (*types.Responses, error) RemoveConstraint(context.Context, *unstructured.Unstructured) (*types.Responses, error) @@ -97,7 +97,7 @@ func Targets(ts ...TargetHandler) ClientOpt { type MatchSchemaProvider interface { // MatchSchema returns the JSON Schema for the `match` field of a constraint - MatchSchema() apiextensionsv1beta1.JSONSchemaProps + MatchSchema() apiextensions.JSONSchemaProps } type TargetHandler interface { @@ -137,7 +137,7 @@ type TargetHandler interface { var _ Client = &client{} type constraintEntry struct { - CRD *apiextensionsv1beta1.CustomResourceDefinition + CRD *apiextensions.CustomResourceDefinition Targets []string } @@ -213,7 +213,7 @@ func createTemplatePath(target, name string) string { } // CreateCRD creates a CRD from template -func (c *client) CreateCRD(ctx context.Context, templ *v1alpha1.ConstraintTemplate) (*apiextensionsv1beta1.CustomResourceDefinition, error) { +func (c *client) CreateCRD(ctx context.Context, templ *templates.ConstraintTemplate) (*apiextensions.CustomResourceDefinition, error) { if err := validateTargets(templ); err != nil { return nil, err } @@ -236,9 +236,15 @@ func (c *client) CreateCRD(ctx context.Context, templ *v1alpha1.ConstraintTempla src = v.Rego } - schema := createSchema(templ, target) - crd := c.backend.crd.createCRD(templ, schema) - if err := c.backend.crd.validateCRD(crd); err != nil { + schema, err := c.backend.crd.createSchema(templ, target) + if err != nil { + return nil, err + } + crd, err := c.backend.crd.createCRD(templ, schema) + if err != nil { + return nil, err + } + if err = c.backend.crd.validateCRD(crd); err != nil { return nil, err } @@ -251,7 +257,7 @@ func (c *client) CreateCRD(ctx context.Context, templ *v1alpha1.ConstraintTempla return nil, fmt.Errorf("Invalid rego: %s", err) } - _, err := ensureRegoConformance(crd.Spec.Names.Kind, path, src) + _, err = ensureRegoConformance(crd.Spec.Names.Kind, path, src) if err != nil { return nil, err } @@ -262,7 +268,7 @@ func (c *client) CreateCRD(ctx context.Context, templ *v1alpha1.ConstraintTempla // AddTemplate adds the template source code to OPA and registers the CRD with the client for // schema validation on calls to AddConstraint. It also returns a copy of the CRD describing // the constraint. -func (c *client) AddTemplate(ctx context.Context, templ *v1alpha1.ConstraintTemplate) (*types.Responses, error) { +func (c *client) AddTemplate(ctx context.Context, templ *templates.ConstraintTemplate) (*types.Responses, error) { resp := types.NewResponses() crd, err := c.CreateCRD(ctx, templ) if err != nil { @@ -301,7 +307,7 @@ func (c *client) AddTemplate(ctx context.Context, templ *v1alpha1.ConstraintTemp // RemoveTemplate removes the template source code from OPA and removes the CRD from the validation // registry. -func (c *client) RemoveTemplate(ctx context.Context, templ *v1alpha1.ConstraintTemplate) (*types.Responses, error) { +func (c *client) RemoveTemplate(ctx context.Context, templ *templates.ConstraintTemplate) (*types.Responses, error) { resp := types.NewResponses() if err := validateTargets(templ); err != nil { return resp, err @@ -317,8 +323,14 @@ func (c *client) RemoveTemplate(ctx context.Context, templ *v1alpha1.ConstraintT target = t } - schema := createSchema(templ, target) - crd := c.backend.crd.createCRD(templ, schema) + schema, err := c.backend.crd.createSchema(templ, target) + if err != nil { + return resp, err + } + crd, err := c.backend.crd.createCRD(templ, schema) + if err != nil { + return resp, err + } if err := c.backend.crd.validateCRD(crd); err != nil { return resp, err } @@ -327,7 +339,7 @@ func (c *client) RemoveTemplate(ctx context.Context, templ *v1alpha1.ConstraintT c.constraintsMux.Lock() defer c.constraintsMux.Unlock() - _, err := c.backend.driver.DeleteModule(ctx, path) + _, err = c.backend.driver.DeleteModule(ctx, path) if err != nil { return resp, err } @@ -345,13 +357,10 @@ func createConstraintPath(target string, constraint *unstructured.Unstructured) if gvk.Group == "" { return "", fmt.Errorf("Empty group for the constrant named %s", constraint.GetName()) } - if gvk.Version == "" { - return "", fmt.Errorf("Empty version for the constraint named %s", constraint.GetName()) - } if gvk.Kind == "" { return "", fmt.Errorf("Empty kind for the constraint named %s", constraint.GetName()) } - return "/" + path.Join("constraints", target, "cluster", gvk.Group, gvk.Version, gvk.Kind, constraint.GetName()), nil + return "/" + path.Join("constraints", target, "cluster", gvk.Group, gvk.Kind, constraint.GetName()), nil } // getConstraintEntry returns the constraint entry for a given constraint @@ -481,7 +490,7 @@ func (c *client) init() error { } libBuf := &bytes.Buffer{} if err := libTempl.Execute(libBuf, map[string]string{ - "ConstraintsRoot": fmt.Sprintf(`data.constraints["%s"].cluster["%s"].v1alpha1`, t.GetName(), constraintGroup), + "ConstraintsRoot": fmt.Sprintf(`data.constraints["%s"].cluster["%s"]`, t.GetName(), constraintGroup), "DataRoot": fmt.Sprintf(`data.external["%s"]`, t.GetName()), }); err != nil { return err diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/client_test.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/client_test.go index bd26980357a..e61f8840ef8 100644 --- a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/client_test.go +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/client_test.go @@ -7,10 +7,10 @@ import ( "testing" "text/template" - "github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1alpha1" "github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/local" + "github.com/open-policy-agent/frameworks/constraint/pkg/core/templates" "github.com/open-policy-agent/frameworks/constraint/pkg/types" - apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" + "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" ) @@ -53,8 +53,8 @@ matching_constraints[c] {c = data.c} matching_reviews_and_constraints[[r,c]] {r = data.r; c = data.c}`)) } -func (h *badHandler) MatchSchema() apiextensionsv1beta1.JSONSchemaProps { - return apiextensionsv1beta1.JSONSchemaProps{} +func (h *badHandler) MatchSchema() apiextensions.JSONSchemaProps { + return apiextensions.JSONSchemaProps{} } func (h *badHandler) ProcessData(obj interface{}) (bool, string, interface{}, error) { @@ -314,7 +314,7 @@ some_rule[r] { tc := []struct { Name string Handler TargetHandler - Template *v1alpha1.ConstraintTemplate + Template *templates.ConstraintTemplate ErrorExpected bool }{ { @@ -400,7 +400,7 @@ func TestRemoveTemplate(t *testing.T) { tc := []struct { Name string Handler TargetHandler - Template *v1alpha1.ConstraintTemplate + Template *templates.ConstraintTemplate ErrorExpected bool }{ { diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/crd_helpers.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/crd_helpers.go index 4f3c71aac84..d4c1838253c 100644 --- a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/crd_helpers.go +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/crd_helpers.go @@ -6,6 +6,8 @@ import ( "strings" "github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1alpha1" + "github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1" + "github.com/open-policy-agent/frameworks/constraint/pkg/core/templates" "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" apiextensionsvalidation "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation" @@ -15,8 +17,13 @@ import ( apivalidation "k8s.io/apimachinery/pkg/util/validation" ) +var supportedVersions = map[string]bool{ + v1alpha1.SchemeGroupVersion.Version: true, + v1beta1.SchemeGroupVersion.Version: true, +} + // validateTargets ensures that the targets field has the appropriate values -func validateTargets(templ *v1alpha1.ConstraintTemplate) error { +func validateTargets(templ *templates.ConstraintTemplate) error { if len(templ.Spec.Targets) > 1 { return errors.New("Multi-target templates are not currently supported") } else if templ.Spec.Targets == nil { @@ -29,21 +36,25 @@ func validateTargets(templ *v1alpha1.ConstraintTemplate) error { // createSchema combines the schema of the match target and the ConstraintTemplate parameters // to form the schema of the actual constraint resource -func createSchema(templ *v1alpha1.ConstraintTemplate, target MatchSchemaProvider) *apiextensionsv1beta1.JSONSchemaProps { - props := map[string]apiextensionsv1beta1.JSONSchemaProps{ +func (h *crdHelper) createSchema(templ *templates.ConstraintTemplate, target MatchSchemaProvider) (*apiextensions.JSONSchemaProps, error) { + props := map[string]apiextensions.JSONSchemaProps{ "match": target.MatchSchema(), } if templ.Spec.CRD.Spec.Validation != nil && templ.Spec.CRD.Spec.Validation.OpenAPIV3Schema != nil { - props["parameters"] = *templ.Spec.CRD.Spec.Validation.OpenAPIV3Schema + internalSchema := &apiextensions.JSONSchemaProps{} + if err := h.scheme.Convert(templ.Spec.CRD.Spec.Validation.OpenAPIV3Schema, internalSchema, nil); err != nil { + return nil, err + } + props["parameters"] = *internalSchema } - schema := &apiextensionsv1beta1.JSONSchemaProps{ - Properties: map[string]apiextensionsv1beta1.JSONSchemaProps{ - "spec": apiextensionsv1beta1.JSONSchemaProps{ + schema := &apiextensions.JSONSchemaProps{ + Properties: map[string]apiextensions.JSONSchemaProps{ + "spec": apiextensions.JSONSchemaProps{ Properties: props, }, }, } - return schema + return schema, nil } // crdHelper builds the scheme for handling CRDs. It is necessary to build crdHelper at runtime as @@ -60,36 +71,53 @@ func newCRDHelper() *crdHelper { // createCRD takes a template and a schema and converts it to a CRD func (h *crdHelper) createCRD( - templ *v1alpha1.ConstraintTemplate, - schema *apiextensionsv1beta1.JSONSchemaProps) *apiextensionsv1beta1.CustomResourceDefinition { - crd := &apiextensionsv1beta1.CustomResourceDefinition{ - Spec: apiextensionsv1beta1.CustomResourceDefinitionSpec{ + templ *templates.ConstraintTemplate, + schema *apiextensions.JSONSchemaProps) (*apiextensions.CustomResourceDefinition, error) { + crd := &apiextensions.CustomResourceDefinition{ + Spec: apiextensions.CustomResourceDefinitionSpec{ Group: constraintGroup, - Names: apiextensionsv1beta1.CustomResourceDefinitionNames{ + Names: apiextensions.CustomResourceDefinitionNames{ Kind: templ.Spec.CRD.Spec.Names.Kind, ListKind: templ.Spec.CRD.Spec.Names.Kind + "List", Plural: strings.ToLower(templ.Spec.CRD.Spec.Names.Kind), Singular: strings.ToLower(templ.Spec.CRD.Spec.Names.Kind), }, - Validation: &apiextensionsv1beta1.CustomResourceValidation{ + Validation: &apiextensions.CustomResourceValidation{ OpenAPIV3Schema: schema, }, Scope: "Cluster", - Version: v1alpha1.SchemeGroupVersion.Version, + Version: v1beta1.SchemeGroupVersion.Version, + Versions: []apiextensions.CustomResourceDefinitionVersion{ + { + Name: v1beta1.SchemeGroupVersion.Version, + Storage: true, + Served: true, + }, + { + Name: v1alpha1.SchemeGroupVersion.Version, + Storage: false, + Served: true, + }, + }, }, } - h.scheme.Default(crd) - crd.ObjectMeta.Name = fmt.Sprintf("%s.%s", crd.Spec.Names.Plural, constraintGroup) - return crd + // Defaulting functions only exist for v1beta1 + v1b1 := &apiextensionsv1beta1.CustomResourceDefinition{} + if err := h.scheme.Convert(crd, v1b1, nil); err != nil { + return nil, err + } + h.scheme.Default(v1b1) + crd2 := &apiextensions.CustomResourceDefinition{} + if err := h.scheme.Convert(v1b1, crd2, nil); err != nil { + return nil, err + } + crd2.ObjectMeta.Name = fmt.Sprintf("%s.%s", crd.Spec.Names.Plural, constraintGroup) + return crd2, nil } // validateCRD calls the CRD package's validation on an internal representation of the CRD -func (h *crdHelper) validateCRD(crd *apiextensionsv1beta1.CustomResourceDefinition) error { - internalCRD := &apiextensions.CustomResourceDefinition{} - if err := h.scheme.Convert(crd, internalCRD, nil); err != nil { - return err - } - errors := apiextensionsvalidation.ValidateCustomResourceDefinition(internalCRD) +func (h *crdHelper) validateCRD(crd *apiextensions.CustomResourceDefinition) error { + errors := apiextensionsvalidation.ValidateCustomResourceDefinition(crd) if len(errors) > 0 { return errors.ToAggregate() } @@ -97,12 +125,8 @@ func (h *crdHelper) validateCRD(crd *apiextensionsv1beta1.CustomResourceDefiniti } // validateCR validates the provided custom resource against its CustomResourceDefinition -func (h *crdHelper) validateCR(cr *unstructured.Unstructured, crd *apiextensionsv1beta1.CustomResourceDefinition) error { - internalCRD := &apiextensions.CustomResourceDefinition{} - if err := h.scheme.Convert(crd, internalCRD, nil); err != nil { - return err - } - validator, _, err := validation.NewSchemaValidator(internalCRD.Spec.Validation) +func (h *crdHelper) validateCR(cr *unstructured.Unstructured, crd *apiextensions.CustomResourceDefinition) error { + validator, _, err := validation.NewSchemaValidator(crd.Spec.Validation) if err != nil { return err } @@ -118,8 +142,8 @@ func (h *crdHelper) validateCR(cr *unstructured.Unstructured, crd *apiextensions if cr.GroupVersionKind().Group != constraintGroup { return fmt.Errorf("Wrong group for constraint %s. Have %s, want %s", cr.GetName(), cr.GroupVersionKind().Group, constraintGroup) } - if cr.GroupVersionKind().Version != crd.Spec.Version { - return fmt.Errorf("Wrong version for constraint %s. Have %s, want %s", cr.GetName(), cr.GroupVersionKind().Version, crd.Spec.Version) + if !supportedVersions[cr.GroupVersionKind().Version] { + return fmt.Errorf("Wrong version for constraint %s. Have %s, supported: %v", cr.GetName(), cr.GroupVersionKind().Version, supportedVersions) } return nil } diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/crd_helpers_test.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/crd_helpers_test.go index b36ce3f9ed5..b960aa44a2e 100644 --- a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/crd_helpers_test.go +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/crd_helpers_test.go @@ -6,25 +6,25 @@ import ( "reflect" "testing" - "github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1alpha1" - apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" + "github.com/open-policy-agent/frameworks/constraint/pkg/core/templates" + "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" k8schema "k8s.io/apimachinery/pkg/runtime/schema" ) // helpers for creating a ConstraintTemplate for test -type tmplArg func(*v1alpha1.ConstraintTemplate) +type tmplArg func(*templates.ConstraintTemplate) func name(name string) tmplArg { - return func(tmpl *v1alpha1.ConstraintTemplate) { + return func(tmpl *templates.ConstraintTemplate) { tmpl.ObjectMeta.Name = name } } func crdNames(kind string) tmplArg { - return func(tmpl *v1alpha1.ConstraintTemplate) { - tmpl.Spec.CRD.Spec.Names = v1alpha1.Names{ + return func(tmpl *templates.ConstraintTemplate) { + tmpl.Spec.CRD.Spec.Names = templates.Names{ Kind: kind, } } @@ -32,25 +32,25 @@ func crdNames(kind string) tmplArg { func schema(pm propMap) tmplArg { p := prop(pm) - return func(tmpl *v1alpha1.ConstraintTemplate) { - tmpl.Spec.CRD.Spec.Validation = &v1alpha1.Validation{} + return func(tmpl *templates.ConstraintTemplate) { + tmpl.Spec.CRD.Spec.Validation = &templates.Validation{} tmpl.Spec.CRD.Spec.Validation.OpenAPIV3Schema = &p } } func targets(ts ...string) tmplArg { - targets := make([]v1alpha1.Target, len(ts)) + targets := make([]templates.Target, len(ts)) for i, t := range ts { - targets[i] = v1alpha1.Target{Target: t, Rego: `package hello violation[{"msg": msg}] {msg = "hello"}`} + targets[i] = templates.Target{Target: t, Rego: `package hello violation[{"msg": msg}] {msg = "hello"}`} } - return func(tmpl *v1alpha1.ConstraintTemplate) { + return func(tmpl *templates.ConstraintTemplate) { tmpl.Spec.Targets = targets } } -func createTemplate(args ...tmplArg) *v1alpha1.ConstraintTemplate { - tmpl := &v1alpha1.ConstraintTemplate{} +func createTemplate(args ...tmplArg) *templates.ConstraintTemplate { + tmpl := &templates.ConstraintTemplate{} for _, arg := range args { arg(tmpl) } @@ -70,7 +70,7 @@ func matchSchema(pm propMap) targetHandlerArg { var _ MatchSchemaProvider = &testTargetHandler{} type testTargetHandler struct { - matchSchema apiextensionsv1beta1.JSONSchemaProps + matchSchema apiextensions.JSONSchemaProps } func createTestTargetHandler(args ...targetHandlerArg) MatchSchemaProvider { @@ -81,28 +81,28 @@ func createTestTargetHandler(args ...targetHandlerArg) MatchSchemaProvider { return h } -func (h testTargetHandler) MatchSchema() apiextensionsv1beta1.JSONSchemaProps { +func (h testTargetHandler) MatchSchema() apiextensions.JSONSchemaProps { return h.matchSchema } // schema Helpers -type propMap map[string]apiextensionsv1beta1.JSONSchemaProps +type propMap map[string]apiextensions.JSONSchemaProps // prop currently expects 0 or 1 prop map. More is unsupported. -func prop(pm ...map[string]apiextensionsv1beta1.JSONSchemaProps) apiextensionsv1beta1.JSONSchemaProps { +func prop(pm ...map[string]apiextensions.JSONSchemaProps) apiextensions.JSONSchemaProps { if len(pm) == 0 { - return apiextensionsv1beta1.JSONSchemaProps{} + return apiextensions.JSONSchemaProps{} } - return apiextensionsv1beta1.JSONSchemaProps{Properties: pm[0]} + return apiextensions.JSONSchemaProps{Properties: pm[0]} } // tProp creates a typed property -func tProp(t string) apiextensionsv1beta1.JSONSchemaProps { - return apiextensionsv1beta1.JSONSchemaProps{Type: t} +func tProp(t string) apiextensions.JSONSchemaProps { + return apiextensions.JSONSchemaProps{Type: t} } -func expectedSchema(pm propMap) *apiextensionsv1beta1.JSONSchemaProps { +func expectedSchema(pm propMap) *apiextensions.JSONSchemaProps { p := prop(propMap{"spec": prop(pm)}) return &p } @@ -118,7 +118,7 @@ func gvk(group, version, kind string) customResourceArg { } func kind(kind string) customResourceArg { - return gvk(constraintGroup, "v1alpha1", kind) + return gvk(constraintGroup, "v1beta1", kind) } func params(s string) customResourceArg { @@ -159,10 +159,10 @@ func createCR(args ...customResourceArg) *unstructured.Unstructured { type crdTestCase struct { Name string - Template *v1alpha1.ConstraintTemplate + Template *templates.ConstraintTemplate Handler MatchSchemaProvider CR *unstructured.Unstructured - ExpectedSchema *apiextensionsv1beta1.JSONSchemaProps + ExpectedSchema *apiextensions.JSONSchemaProps ErrorExpected bool } @@ -239,8 +239,12 @@ func TestCreateSchema(t *testing.T) { }, } for _, tc := range tests { + h := newCRDHelper() t.Run(tc.Name, func(t *testing.T) { - schema := createSchema(tc.Template, tc.Handler) + schema, err := h.createSchema(tc.Template, tc.Handler) + if err != nil { + t.Errorf("error = %v; want nil", err) + } if !reflect.DeepEqual(schema, tc.ExpectedSchema) { t.Errorf("createSchema(%#v) = \n%#v; \nwant %#v", tc.Template, *schema, *tc.ExpectedSchema) } @@ -299,9 +303,15 @@ func TestCRDCreationAndValidation(t *testing.T) { h := newCRDHelper() for _, tc := range tests { t.Run(tc.Name, func(t *testing.T) { - schema := createSchema(tc.Template, tc.Handler) - crd := h.createCRD(tc.Template, schema) - err := h.validateCRD(crd) + schema, err := h.createSchema(tc.Template, tc.Handler) + if err != nil { + t.Errorf("err = %v; want nil", err) + } + crd, err := h.createCRD(tc.Template, schema) + if err != nil { + t.Errorf("err = %v; want nil", err) + } + err = h.validateCRD(crd) if (err == nil) && tc.ErrorExpected { t.Errorf("err = nil; want non-nil") } @@ -434,12 +444,18 @@ func TestCRValidation(t *testing.T) { h := newCRDHelper() for _, tc := range tests { t.Run(tc.Name, func(t *testing.T) { - schema := createSchema(tc.Template, tc.Handler) - crd := h.createCRD(tc.Template, schema) + schema, err := h.createSchema(tc.Template, tc.Handler) + if err != nil { + t.Errorf("err = %v; want nil", err) + } + crd, err := h.createCRD(tc.Template, schema) + if err != nil { + t.Errorf("err = %v; want nil", err) + } if err := h.validateCRD(crd); err != nil { t.Errorf("Bad test setup: Bad CRD: %s", err) } - err := h.validateCR(tc.CR, crd) + err = h.validateCR(tc.CR, crd) if (err == nil) && tc.ErrorExpected { t.Errorf("err = nil; want non-nil") } diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/e2e_tests.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/e2e_tests.go index 8aa2dae44a6..255f2461529 100644 --- a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/e2e_tests.go +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/e2e_tests.go @@ -8,10 +8,10 @@ import ( "strings" "github.com/davecgh/go-spew/spew" - "github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1alpha1" + "github.com/open-policy-agent/frameworks/constraint/pkg/core/templates" "github.com/open-policy-agent/frameworks/constraint/pkg/types" "github.com/pkg/errors" - apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" + "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" k8schema "k8s.io/apimachinery/pkg/runtime/schema" @@ -19,26 +19,26 @@ import ( var ctx = context.Background() -func newConstraintTemplate(name, rego string) *v1alpha1.ConstraintTemplate { - return &v1alpha1.ConstraintTemplate{ +func newConstraintTemplate(name, rego string) *templates.ConstraintTemplate { + return &templates.ConstraintTemplate{ ObjectMeta: metav1.ObjectMeta{Name: strings.ToLower(name)}, - Spec: v1alpha1.ConstraintTemplateSpec{ - CRD: v1alpha1.CRD{ - Spec: v1alpha1.CRDSpec{ - Names: v1alpha1.Names{ + Spec: templates.ConstraintTemplateSpec{ + CRD: templates.CRD{ + Spec: templates.CRDSpec{ + Names: templates.Names{ Kind: name, }, - Validation: &v1alpha1.Validation{ - OpenAPIV3Schema: &apiextensionsv1beta1.JSONSchemaProps{ - Properties: map[string]apiextensionsv1beta1.JSONSchemaProps{ - "expected": apiextensionsv1beta1.JSONSchemaProps{Type: "string"}, + Validation: &templates.Validation{ + OpenAPIV3Schema: &apiextensions.JSONSchemaProps{ + Properties: map[string]apiextensions.JSONSchemaProps{ + "expected": apiextensions.JSONSchemaProps{Type: "string"}, }, }, }, }, }, - Targets: []v1alpha1.Target{ - v1alpha1.Target{Target: "test.target", Rego: rego}, + Targets: []templates.Target{ + templates.Target{Target: "test.target", Rego: rego}, }, }, } @@ -101,6 +101,48 @@ violation[{"msg": "DENIED", "details": {}}] { return nil }, + "Deny By Parameter": func(c Client) error { + _, err := c.AddTemplate(ctx, newConstraintTemplate("Foo", `package foo +violation[{"msg": "DENIED", "details": {}}] { + input.parameters.name == input.review.Name +}`)) + if err != nil { + return errors.Wrap(err, "AddTemplate") + } + cstr := newConstraint("Foo", "ph", map[string]string{"name": "deny_me"}) + if _, err := c.AddConstraint(ctx, cstr); err != nil { + return errors.Wrap(err, "AddConstraint") + } + rsps, err := c.Review(ctx, targetData{Name: "deny_me", ForConstraint: "Foo"}) + if err != nil { + return errors.Wrap(err, "Review") + } + if len(rsps.ByTarget) == 0 { + return errors.New("No responses returned") + } + if len(rsps.Results()) != 1 { + return e("Bad number of results", rsps) + } + if !reflect.DeepEqual(rsps.Results()[0].Constraint, cstr) { + return e(fmt.Sprintf("Constraint %s != %s", spew.Sdump(rsps.Results()[0].Constraint), spew.Sdump(cstr)), rsps) + } + if rsps.Results()[0].Msg != "DENIED" { + return e(fmt.Sprintf("res.Msg = %s; wanted DENIED", rsps.Results()[0].Msg), rsps) + } + + rsps, err = c.Review(ctx, targetData{Name: "Sara", ForConstraint: "Foo"}) + if err != nil { + return errors.Wrap(err, "Review") + } + if len(rsps.ByTarget) == 0 { + return errors.New("No responses returned for second test") + } + if len(rsps.Results()) != 0 { + return e("Expected no results", rsps) + } + return nil + }, + "Deny All Audit x2": func(c Client) error { _, err := c.AddTemplate(ctx, newConstraintTemplate("Foo", `package foo violation[{"msg": "DENIED", "details": {}}] { diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/regolib/src.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/regolib/src.go index ce8049fc7f3..9f545373271 100644 --- a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/regolib/src.go +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/regolib/src.go @@ -21,7 +21,7 @@ violation[response] { review := get_default(input, "review", {}) inp := { "review": review, - "constraint": constraint + "parameters": get_default(get_default(constraint, "spec", {}), "parameters", {}), } inventory[inv] data.templates["{{.Target}}"][constraint.kind].violation[r] with input as inp with data.inventory as inv @@ -39,7 +39,7 @@ audit[response] { data.hooks["{{.Target}}"].library.matching_reviews_and_constraints[[review, constraint]] inp := { "review": review, - "constraint": constraint, + "parameters": get_default(get_default(constraint, "spec", {}), "parameters", {}), } inventory[inv] data.templates["{{.Target}}"][constraint.kind].violation[r] with input as inp with data.inventory as inv diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/test_handler.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/test_handler.go index 09f245adc9b..adfd9a4e375 100644 --- a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/test_handler.go +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/test_handler.go @@ -5,7 +5,7 @@ import ( "text/template" "github.com/open-policy-agent/frameworks/constraint/pkg/types" - apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" + "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" ) @@ -100,10 +100,10 @@ func (h *handler) HandleViolation(result *types.Result) error { return nil } -func (h *handler) MatchSchema() apiextensionsv1beta1.JSONSchemaProps { - return apiextensionsv1beta1.JSONSchemaProps{ - Properties: map[string]apiextensionsv1beta1.JSONSchemaProps{ - "label": apiextensionsv1beta1.JSONSchemaProps{Type: "string"}, +func (h *handler) MatchSchema() apiextensions.JSONSchemaProps { + return apiextensions.JSONSchemaProps{ + Properties: map[string]apiextensions.JSONSchemaProps{ + "label": apiextensions.JSONSchemaProps{Type: "string"}, }, } } diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/core/templates/constrainttemplate_types.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/core/templates/constrainttemplate_types.go new file mode 100644 index 00000000000..bae101e9b6d --- /dev/null +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/core/templates/constrainttemplate_types.go @@ -0,0 +1,101 @@ +/* + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Generate deepcopy for apis +//go:generate go run ../../../vendor/k8s.io/code-generator/cmd/deepcopy-gen/main.go -O zz_generated.deepcopy -i ./... -h ../../../hack/boilerplate.go.txt + +package templates + +import ( + "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! +// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. + +// ConstraintTemplateSpec defines the desired state of ConstraintTemplate +type ConstraintTemplateSpec struct { + CRD CRD `json:"crd,omitempty"` + Targets []Target `json:"targets,omitempty"` +} + +type CRD struct { + Spec CRDSpec `json:"spec,omitempty"` +} + +type CRDSpec struct { + Names Names `json:"names,omitempty"` + Validation *Validation `json:"validation,omitempty"` +} + +type Names struct { + Kind string `json:"kind,omitempty"` +} + +type Validation struct { + OpenAPIV3Schema *apiextensions.JSONSchemaProps `json:"openAPIV3Schema,omitempty"` +} + +type Target struct { + Target string `json:"target,omitempty"` + Rego string `json:"rego,omitempty"` +} + +// CreateCRDError represents a single error caught during parsing, compiling, etc. +type CreateCRDError struct { + Code string `json:"code"` + Message string `json:"message"` + Location string `json:"location,omitempty"` +} + +// ByPodStatus defines the observed state of ConstraintTemplate as seen by +// an individual controller +type ByPodStatus struct { + // a unique identifier for the pod that wrote the status + ID string `json:"id,omitempty"` + Errors []*CreateCRDError `json:"errors,omitempty"` +} + +// ConstraintTemplateStatus defines the observed state of ConstraintTemplate +type ConstraintTemplateStatus struct { + Created bool `json:"created,omitempty"` + ByPod []*ByPodStatus `json:"byPod,omitempty"` + // INSERT ADDITIONAL STATUS FIELD - define observed state of cluster + // Important: Run "make" to regenerate code after modifying this file +} + +// +genclient +// +genclient:nonNamespaced +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// ConstraintTemplate is the Schema for the constrainttemplates API +// +k8s:openapi-gen=true +type ConstraintTemplate struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec ConstraintTemplateSpec `json:"spec,omitempty"` + Status ConstraintTemplateStatus `json:"status,omitempty"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// ConstraintTemplateList contains a list of ConstraintTemplate +type ConstraintTemplateList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []ConstraintTemplate `json:"items"` +} diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/core/templates/doc.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/core/templates/doc.go new file mode 100644 index 00000000000..44daf26d59e --- /dev/null +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/core/templates/doc.go @@ -0,0 +1,18 @@ +/* + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package templates contains API Schema definitions for the templates API group +// +k8s:deepcopy-gen=package +package templates diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/core/templates/zz_generated.deepcopy.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/core/templates/zz_generated.deepcopy.go new file mode 100644 index 00000000000..a4617a4348d --- /dev/null +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/core/templates/zz_generated.deepcopy.go @@ -0,0 +1,267 @@ +// +build !ignore_autogenerated + +/* + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +// Code generated by main. DO NOT EDIT. + +package templates + +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 *ByPodStatus) DeepCopyInto(out *ByPodStatus) { + *out = *in + if in.Errors != nil { + in, out := &in.Errors, &out.Errors + *out = make([]*CreateCRDError, len(*in)) + for i := range *in { + if (*in)[i] != nil { + in, out := &(*in)[i], &(*out)[i] + *out = new(CreateCRDError) + **out = **in + } + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ByPodStatus. +func (in *ByPodStatus) DeepCopy() *ByPodStatus { + if in == nil { + return nil + } + out := new(ByPodStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CRD) DeepCopyInto(out *CRD) { + *out = *in + in.Spec.DeepCopyInto(&out.Spec) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CRD. +func (in *CRD) DeepCopy() *CRD { + if in == nil { + return nil + } + out := new(CRD) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CRDSpec) DeepCopyInto(out *CRDSpec) { + *out = *in + out.Names = in.Names + if in.Validation != nil { + in, out := &in.Validation, &out.Validation + *out = new(Validation) + (*in).DeepCopyInto(*out) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CRDSpec. +func (in *CRDSpec) DeepCopy() *CRDSpec { + if in == nil { + return nil + } + out := new(CRDSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ConstraintTemplate) DeepCopyInto(out *ConstraintTemplate) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConstraintTemplate. +func (in *ConstraintTemplate) DeepCopy() *ConstraintTemplate { + if in == nil { + return nil + } + out := new(ConstraintTemplate) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ConstraintTemplate) 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 *ConstraintTemplateList) DeepCopyInto(out *ConstraintTemplateList) { + *out = *in + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ConstraintTemplate, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConstraintTemplateList. +func (in *ConstraintTemplateList) DeepCopy() *ConstraintTemplateList { + if in == nil { + return nil + } + out := new(ConstraintTemplateList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ConstraintTemplateList) 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 *ConstraintTemplateSpec) DeepCopyInto(out *ConstraintTemplateSpec) { + *out = *in + in.CRD.DeepCopyInto(&out.CRD) + if in.Targets != nil { + in, out := &in.Targets, &out.Targets + *out = make([]Target, len(*in)) + copy(*out, *in) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConstraintTemplateSpec. +func (in *ConstraintTemplateSpec) DeepCopy() *ConstraintTemplateSpec { + if in == nil { + return nil + } + out := new(ConstraintTemplateSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ConstraintTemplateStatus) DeepCopyInto(out *ConstraintTemplateStatus) { + *out = *in + if in.ByPod != nil { + in, out := &in.ByPod, &out.ByPod + *out = make([]*ByPodStatus, len(*in)) + for i := range *in { + if (*in)[i] != nil { + in, out := &(*in)[i], &(*out)[i] + *out = new(ByPodStatus) + (*in).DeepCopyInto(*out) + } + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConstraintTemplateStatus. +func (in *ConstraintTemplateStatus) DeepCopy() *ConstraintTemplateStatus { + if in == nil { + return nil + } + out := new(ConstraintTemplateStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CreateCRDError) DeepCopyInto(out *CreateCRDError) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CreateCRDError. +func (in *CreateCRDError) DeepCopy() *CreateCRDError { + if in == nil { + return nil + } + out := new(CreateCRDError) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Names) DeepCopyInto(out *Names) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Names. +func (in *Names) DeepCopy() *Names { + if in == nil { + return nil + } + out := new(Names) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Target) DeepCopyInto(out *Target) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Target. +func (in *Target) DeepCopy() *Target { + if in == nil { + return nil + } + out := new(Target) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Validation) DeepCopyInto(out *Validation) { + *out = *in + if in.OpenAPIV3Schema != nil { + in, out := &in.OpenAPIV3Schema, &out.OpenAPIV3Schema + *out = (*in).DeepCopy() + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Validation. +func (in *Validation) DeepCopy() *Validation { + if in == nil { + return nil + } + out := new(Validation) + in.DeepCopyInto(out) + return out +}