Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add validating webhook for KeptnTaskDefinition #1514

Merged
merged 47 commits into from
Jun 7, 2023
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
47 commits
Select commit Hold shift + click to select a range
e66f2a5
feat: integrate python-runtime into pipelines (#1505)
odubajDT Jun 2, 2023
2af1475
added validating webhook for TaskDefinitions
geoffrey1330 Jun 2, 2023
1f6d09c
added validating webhook for TaskDefinitions
geoffrey1330 Jun 2, 2023
cee0114
Added TaskDefinition validation logic to allow either Function spec o…
geoffrey1330 Jun 2, 2023
184673d
Merge branch 'main' into feat/1486/validating_webhook
geoffrey1330 Jun 2, 2023
7dd8a8c
Merge branch 'feat/1486/validating_webhook' of https://github.com/geo…
geoffrey1330 Jun 2, 2023
42c8193
Added TaskDefinition validation logic to allow either Function spec o…
geoffrey1330 Jun 2, 2023
caca04d
Update operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go
geoffrey1330 Jun 2, 2023
adf509c
Update operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go
geoffrey1330 Jun 2, 2023
658e71e
Update operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go
geoffrey1330 Jun 2, 2023
2f46086
Update operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go
geoffrey1330 Jun 2, 2023
3c45ddb
Update operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go
geoffrey1330 Jun 2, 2023
101f20a
Added TaskDefinition validation logic to allow either Function spec o…
geoffrey1330 Jun 2, 2023
1fd9ff4
added ValidatingWebhookConfiguration manifest
geoffrey1330 Jun 2, 2023
95c8234
added ValidatingWebhookConfiguration manifest
geoffrey1330 Jun 2, 2023
609d75a
deleted webhook_suite_test.go file
geoffrey1330 Jun 2, 2023
dcb52c7
Added neccessary import for keptntaskdefinition_webhook
geoffrey1330 Jun 2, 2023
74f7d39
Update operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go
geoffrey1330 Jun 4, 2023
8ccfa03
Update operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go
geoffrey1330 Jun 4, 2023
f410f6d
Update operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go
geoffrey1330 Jun 4, 2023
fdff589
Added testcase keptntaskdefinition_webhook_test.go for keptntaskdefin…
geoffrey1330 Jun 4, 2023
17a0736
Added testcase keptntaskdefinition_webhook_test.go for keptntaskdefin…
geoffrey1330 Jun 4, 2023
47ecfcd
Added ObjectMeta to the testcase keptntaskdefinition_webhook_test.go …
geoffrey1330 Jun 4, 2023
21cf221
deleted certificate.yaml and webhookcainjection_patch.yaml
geoffrey1330 Jun 4, 2023
b6fa939
deleted config directory
geoffrey1330 Jun 4, 2023
fe86366
reverted back the changes in the imports in main.go and fixed yaml issue
geoffrey1330 Jun 5, 2023
b5e4d78
reverted back the changes in the imports in main.go and fixed yaml issue
geoffrey1330 Jun 5, 2023
afe5d32
reverted back the changes in the imports in main.go and fixed yaml issue
geoffrey1330 Jun 5, 2023
1bf4bbf
reverted back the changes in the imports in main.go and fixed yaml issue
geoffrey1330 Jun 5, 2023
5ab6bc2
Added integration test for validate taskdefinition
geoffrey1330 Jun 5, 2023
6244d04
Added integration test for validate taskdefinition
geoffrey1330 Jun 5, 2023
5870802
Added comment to the integration test for validating taskdefinition
geoffrey1330 Jun 5, 2023
a9e05b4
Added comment to the integration test for validating taskdefinition
geoffrey1330 Jun 5, 2023
16cc385
Added comment to the integration test for validating taskdefinition
geoffrey1330 Jun 5, 2023
c2d4129
Added comment to the integration test for validating taskdefinition
geoffrey1330 Jun 5, 2023
ba845ec
Added comment to the integration test for validating taskdefinition
geoffrey1330 Jun 5, 2023
4528ea8
Added comment to the integration test for validating taskdefinition
geoffrey1330 Jun 5, 2023
682151d
Added tests to cover the Validate[Create/Update/Delete]() methods
geoffrey1330 Jun 5, 2023
eb83821
Added tests to cover the Validate[Create/Update/Delete]() methods
geoffrey1330 Jun 5, 2023
f3cf46a
Added tests to cover the Validate[Create/Update/Delete]() methods
geoffrey1330 Jun 5, 2023
7480936
Added tests to cover the Validate[Create/Update/Delete]() methods
geoffrey1330 Jun 5, 2023
2cc657a
Added tests to cover the Validate[Create/Update/Delete]() methods
geoffrey1330 Jun 5, 2023
1605588
Added tests to cover the Validate[Create/Update/Delete]() methods
geoffrey1330 Jun 5, 2023
8de7acf
Added tests to cover the Validate[Create/Update/Delete]() methods
geoffrey1330 Jun 5, 2023
9b464d8
Added tests to cover the Validate[Create/Update/Delete]() methods
geoffrey1330 Jun 5, 2023
330e3c4
Update operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_t…
geoffrey1330 Jun 6, 2023
0d9daea
Added fixes for tests that covers the Validate[Create/Update/Delete](…
geoffrey1330 Jun 6, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions operator/PROJECT
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# Code generated by tool. DO NOT EDIT.
# This file is used to track the info used to scaffold your project
# and allow the plugins properly work.
# More info: https://book.kubebuilder.io/reference/project-config.html
geoffrey1330 marked this conversation as resolved.
Show resolved Hide resolved
domain: keptn.sh
layout:
- go.kubebuilder.io/v3
Expand Down Expand Up @@ -234,6 +238,9 @@ resources:
kind: KeptnTaskDefinition
path: github.com/keptn/lifecycle-toolkit/operator/apis/lifecycle/v1alpha3
version: v1alpha3
webhooks:
validation: true
webhookVersion: v1
- api:
crdVersion: v1
namespaced: true
Expand Down
87 changes: 87 additions & 0 deletions operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
/*
Copyright 2022.

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 v1alpha3

import (
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/webhook"
)

// log is for logging in this package.
var keptntaskdefinitionlog = logf.Log.WithName("keptntaskdefinition-resource")

func (r *KeptnTaskDefinition) SetupWebhookWithManager(mgr ctrl.Manager) error {
return ctrl.NewWebhookManagedBy(mgr).
For(r).
Complete()
}

// TODO(user): EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN!

// TODO(user): change verbs to "verbs=create;update;delete" if you want to enable deletion validation.
geoffrey1330 marked this conversation as resolved.
Show resolved Hide resolved
//+kubebuilder:webhook:path=/validate-lifecycle-keptn-sh-v1alpha3-keptntaskdefinition,mutating=false,failurePolicy=fail,sideEffects=None,groups=lifecycle.keptn.sh,resources=keptntaskdefinitions,verbs=create;update,versions=v1alpha3,name=vkeptntaskdefinition.kb.io,admissionReviewVersions=v1

var _ webhook.Validator = &KeptnTaskDefinition{}

// ValidateCreate implements webhook.Validator so a webhook will be registered for the type
func (r *KeptnTaskDefinition) ValidateCreate() error {
keptntaskdefinitionlog.Info("validate create", "name", r.Name)

// TODO(user): fill in your validation logic upon object creation.
return nil
geoffrey1330 marked this conversation as resolved.
Show resolved Hide resolved
}

// ValidateUpdate implements webhook.Validator so a webhook will be registered for the type
func (r *KeptnTaskDefinition) ValidateUpdate(old runtime.Object) error {
keptntaskdefinitionlog.Info("validate update", "name", r.Name)

// TODO(user): fill in your validation logic upon object update.
return nil
geoffrey1330 marked this conversation as resolved.
Show resolved Hide resolved
}

// ValidateDelete implements webhook.Validator so a webhook will be registered for the type
func (r *KeptnTaskDefinition) ValidateDelete() error {
keptntaskdefinitionlog.Info("validate delete", "name", r.Name)

// TODO(user): fill in your validation logic upon object deletion.
geoffrey1330 marked this conversation as resolved.
Show resolved Hide resolved
return nil
}

func (r *KeptnTaskDefinition) validateFields() error {
if r.Spec.Function == nil && r.Spec.Container == nil {
return ValidationError{Field: "spec", Message: "Either Function or Container field must be defined"}
}

if r.Spec.Function != nil && r.Spec.Container != nil {
return ValidationError{Field: "spec", Message: "Both Function and Container fields cannot be defined simultaneously"}
}

return nil
}

// ValidationError represents a validation error with a specific field and message
type ValidationError struct {
Field string
Message string
}

// Error returns the validation error message
func (e ValidationError) Error() string {
return e.Message
}
geoffrey1330 marked this conversation as resolved.
Show resolved Hide resolved
132 changes: 132 additions & 0 deletions operator/apis/lifecycle/v1alpha3/webhook_suite_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
/*
Copyright 2022.

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 v1alpha3

import (
"context"
"crypto/tls"
"fmt"
"net"
"path/filepath"
"testing"
"time"

. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"

admissionv1beta1 "k8s.io/api/admission/v1beta1"
//+kubebuilder:scaffold:imports
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/rest"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/envtest"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
)

// These tests use Ginkgo (BDD-style Go testing framework). Refer to
// http://onsi.github.io/ginkgo/ to learn more about Ginkgo.

var cfg *rest.Config
var k8sClient client.Client
var testEnv *envtest.Environment
var ctx context.Context
var cancel context.CancelFunc

func TestAPIs(t *testing.T) {
RegisterFailHandler(Fail)

RunSpecs(t, "Webhook Suite")
}

var _ = BeforeSuite(func() {
logf.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true)))

ctx, cancel = context.WithCancel(context.TODO())

By("bootstrapping test environment")
testEnv = &envtest.Environment{
CRDDirectoryPaths: []string{filepath.Join("..", "..", "..", "config", "crd", "bases")},
ErrorIfCRDPathMissing: false,
WebhookInstallOptions: envtest.WebhookInstallOptions{
Paths: []string{filepath.Join("..", "..", "..", "config", "webhook")},
},
}

var err error
// cfg is defined in this file globally.
cfg, err = testEnv.Start()
Expect(err).NotTo(HaveOccurred())
Expect(cfg).NotTo(BeNil())

scheme := runtime.NewScheme()
err = AddToScheme(scheme)
Expect(err).NotTo(HaveOccurred())

err = admissionv1beta1.AddToScheme(scheme)
Expect(err).NotTo(HaveOccurred())

//+kubebuilder:scaffold:scheme

k8sClient, err = client.New(cfg, client.Options{Scheme: scheme})
Expect(err).NotTo(HaveOccurred())
Expect(k8sClient).NotTo(BeNil())

// start webhook server using Manager
webhookInstallOptions := &testEnv.WebhookInstallOptions
mgr, err := ctrl.NewManager(cfg, ctrl.Options{
Scheme: scheme,
Host: webhookInstallOptions.LocalServingHost,
Port: webhookInstallOptions.LocalServingPort,
CertDir: webhookInstallOptions.LocalServingCertDir,
LeaderElection: false,
MetricsBindAddress: "0",
})
Expect(err).NotTo(HaveOccurred())

err = (&KeptnTaskDefinition{}).SetupWebhookWithManager(mgr)
Expect(err).NotTo(HaveOccurred())

//+kubebuilder:scaffold:webhook

go func() {
defer GinkgoRecover()
err = mgr.Start(ctx)
Expect(err).NotTo(HaveOccurred())
}()

// wait for the webhook server to get ready
dialer := &net.Dialer{Timeout: time.Second}
addrPort := fmt.Sprintf("%s:%d", webhookInstallOptions.LocalServingHost, webhookInstallOptions.LocalServingPort)
Eventually(func() error {
conn, err := tls.DialWithDialer(dialer, "tcp", addrPort, &tls.Config{InsecureSkipVerify: true})
if err != nil {
return err
}
conn.Close()
return nil
}).Should(Succeed())

})

var _ = AfterSuite(func() {
cancel()
By("tearing down the test environment")
err := testEnv.Stop()
Expect(err).NotTo(HaveOccurred())
})

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

39 changes: 39 additions & 0 deletions operator/config/certmanager/certificate.yaml
geoffrey1330 marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# The following manifests contain a self-signed issuer CR and a certificate CR.
# More document can be found at https://docs.cert-manager.io
# WARNING: Targets CertManager v1.0. Check https://cert-manager.io/docs/installation/upgrading/ for breaking changes.
apiVersion: cert-manager.io/v1
kind: Issuer
metadata:
labels:
app.kubernetes.io/name: issuer
app.kubernetes.io/instance: selfsigned-issuer
app.kubernetes.io/component: certificate
app.kubernetes.io/created-by: keptn-lifecycle-toolkit
app.kubernetes.io/part-of: keptn-lifecycle-toolkit
app.kubernetes.io/managed-by: kustomize
name: selfsigned-issuer
namespace: system
spec:
selfSigned: {}
---
apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
labels:
app.kubernetes.io/name: certificate
app.kubernetes.io/instance: serving-cert
app.kubernetes.io/component: certificate
app.kubernetes.io/created-by: keptn-lifecycle-toolkit
app.kubernetes.io/part-of: keptn-lifecycle-toolkit
app.kubernetes.io/managed-by: kustomize
name: serving-cert # this name should match the one appeared in kustomizeconfig.yaml
namespace: system
spec:
# $(SERVICE_NAME) and $(SERVICE_NAMESPACE) will be substituted by kustomize
dnsNames:
- $(SERVICE_NAME).$(SERVICE_NAMESPACE).svc
- $(SERVICE_NAME).$(SERVICE_NAMESPACE).svc.cluster.local
issuerRef:
kind: Issuer
name: selfsigned-issuer
secretName: webhook-server-cert # this secret will not be prefixed, since it's not managed by kustomize
5 changes: 5 additions & 0 deletions operator/config/certmanager/kustomization.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
resources:
- certificate.yaml

configurations:
- kustomizeconfig.yaml
16 changes: 16 additions & 0 deletions operator/config/certmanager/kustomizeconfig.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# This configuration is for teaching kustomize how to update name ref and var substitution
nameReference:
- kind: Issuer
group: cert-manager.io
fieldSpecs:
- kind: Certificate
group: cert-manager.io
path: spec/issuerRef/name

varReference:
- kind: Certificate
group: cert-manager.io
path: spec/commonName
- kind: Certificate
group: cert-manager.io
path: spec/dnsNames
23 changes: 23 additions & 0 deletions operator/config/default/manager_webhook_patch.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: controller-manager
namespace: system
spec:
template:
spec:
containers:
- name: manager
ports:
- containerPort: 9443
name: webhook-server
protocol: TCP
volumeMounts:
- mountPath: /tmp/k8s-webhook-server/serving-certs
name: cert
readOnly: true
volumes:
- name: cert
secret:
defaultMode: 420
secretName: webhook-server-cert
29 changes: 29 additions & 0 deletions operator/config/default/webhookcainjection_patch.yaml
geoffrey1330 marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# This patch add annotation to admission webhook config and
# the variables $(CERTIFICATE_NAMESPACE) and $(CERTIFICATE_NAME) will be substituted by kustomize.
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingWebhookConfiguration
metadata:
labels:
app.kubernetes.io/name: mutatingwebhookconfiguration
app.kubernetes.io/instance: mutating-webhook-configuration
app.kubernetes.io/component: webhook
app.kubernetes.io/created-by: keptn-lifecycle-toolkit
app.kubernetes.io/part-of: keptn-lifecycle-toolkit
app.kubernetes.io/managed-by: kustomize
name: mutating-webhook-configuration
annotations:
cert-manager.io/inject-ca-from: $(CERTIFICATE_NAMESPACE)/$(CERTIFICATE_NAME)
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
labels:
app.kubernetes.io/name: validatingwebhookconfiguration
app.kubernetes.io/instance: validating-webhook-configuration
app.kubernetes.io/component: webhook
app.kubernetes.io/created-by: keptn-lifecycle-toolkit
app.kubernetes.io/part-of: keptn-lifecycle-toolkit
app.kubernetes.io/managed-by: kustomize
name: validating-webhook-configuration
annotations:
cert-manager.io/inject-ca-from: $(CERTIFICATE_NAMESPACE)/$(CERTIFICATE_NAME)
Loading