Skip to content

Commit

Permalink
Merge pull request #387 from MartinBasti/ITS-name-lenght-validation
Browse files Browse the repository at this point in the history
fix(STONEINTG-640): limit ITS name length
  • Loading branch information
MartinBasti authored Nov 1, 2023
2 parents 7eee0a6 + 9bce853 commit fab9d22
Show file tree
Hide file tree
Showing 8 changed files with 179 additions and 54 deletions.
1 change: 1 addition & 0 deletions PROJECT
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,6 @@ resources:
version: v1beta1
webhooks:
conversion: true
validation: true
webhookVersion: v1
version: "3"
50 changes: 44 additions & 6 deletions api/v1beta1/integrationtestscenario_suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,19 @@ package v1beta1

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"
"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"
Expand All @@ -37,6 +43,7 @@ var (
testEnv *envtest.Environment
ctx context.Context
cancel context.CancelFunc
cfg *rest.Config
)

const (
Expand All @@ -56,35 +63,66 @@ var _ = BeforeSuite(func() {

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

cfg, err := testEnv.Start()
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()
Expect(AddToScheme(scheme)).To(Succeed())

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
k8sManager, _ := ctrl.NewManager(cfg, ctrl.Options{
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",
})
k8sClient = k8sManager.GetClient()
Expect(err).NotTo(HaveOccurred())

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

//+kubebuilder:scaffold:webhook

go func() {
defer GinkgoRecover()
err = k8sManager.Start(ctx)
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() {
Expand Down
31 changes: 31 additions & 0 deletions api/v1beta1/integrationtestscenario_webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,42 @@ limitations under the License.
package v1beta1

import (
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/validation"
"k8s.io/apimachinery/pkg/util/validation/field"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/webhook"
)

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

//+kubebuilder:webhook:path=/validate-appstudio-redhat-com-v1beta1-integrationtestscenario,mutating=false,failurePolicy=fail,sideEffects=None,groups=appstudio.redhat.com,resources=integrationtestscenarios,verbs=create;update;delete,versions=v1beta1,name=vintegrationtestscenario.kb.io,admissionReviewVersions=v1

var _ webhook.Validator = &IntegrationTestScenario{}

// ValidateCreate implements webhook.Validator so a webhook will be registered for the type
func (r *IntegrationTestScenario) ValidateCreate() error {
// We use the DNS-1035 format for application names, so ensure it conforms to that specification

if len(validation.IsDNS1035Label(r.Name)) != 0 {
return field.Invalid(field.NewPath("metadata").Child("name"), r.Name,
"an IntegrationTestScenario resource name must start with a lower case "+
"alphabetical character, be under 63 characters, and can only consist "+
"of lower case alphanumeric characters or ‘-’")
}
return nil
}

// ValidateUpdate implements webhook.Validator so a webhook will be registered for the type
func (r *IntegrationTestScenario) ValidateUpdate(old runtime.Object) error {
return nil
}

// ValidateDelete implements webhook.Validator so a webhook will be registered for the type
func (r *IntegrationTestScenario) ValidateDelete() error {
return nil
}
98 changes: 98 additions & 0 deletions api/v1beta1/integrationtestscenario_webhook_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/*
Copyright 2023 Red Hat Inc.
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 (
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"k8s.io/apimachinery/pkg/api/errors"

applicationapiv1alpha1 "github.com/redhat-appstudio/application-api/api/v1alpha1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

var _ = Describe("IntegrationTestScenario webhook", func() {

var integrationTestScenario *IntegrationTestScenario

BeforeEach(func() {
integrationTestScenario = &IntegrationTestScenario{
TypeMeta: metav1.TypeMeta{
APIVersion: "appstudio.redhat.com/v1alpha1",
Kind: "IntegrationTestScenario",
},
ObjectMeta: metav1.ObjectMeta{
Name: "integrationtestscenario",
Namespace: "default",
},
Spec: IntegrationTestScenarioSpec{
Application: "application-sample",
Params: []PipelineParameter{
{
Name: "pipeline-param-name",
Value: "pipeline-param-value",
},
},
Environment: TestEnvironment{
Name: "environment-name",
Type: "POC",
Configuration: &applicationapiv1alpha1.EnvironmentConfiguration{
Env: []applicationapiv1alpha1.EnvVarPair{
{
Name: "env-config-name",
Value: "env-config-value",
},
},
},
},
Contexts: []TestContext{
{
Name: "test-ctx",
Description: "test-ctx-description",
},
},
ResolverRef: ResolverRef{
Resolver: "git",
Params: []ResolverParameter{
{
Name: "url",
Value: "http://url",
},
{
Name: "revision",
Value: "main",
},
{
Name: "pathInRepo",
Value: "pipeline/helloworld.yaml",
},
},
},
},
}
})

AfterEach(func() {
err := k8sClient.Delete(ctx, integrationTestScenario)
Expect(err == nil || errors.IsNotFound(err)).To(BeTrue())
})

It("should fail to create scenario with long name", func() {
integrationTestScenario.Name = "this-name-is-too-long-it-has-64-characters-and-we-allow-max-63ch"
Expect(k8sClient.Create(ctx, integrationTestScenario)).ShouldNot(Succeed())
})
})
2 changes: 1 addition & 1 deletion api/v1beta1/zz_generated.deepcopy.go

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

7 changes: 0 additions & 7 deletions config/default/webhookcainjection_patch.yaml
Original file line number Diff line number Diff line change
@@ -1,13 +1,6 @@
# 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:
name: mutating-webhook-configuration
annotations:
service.beta.openshift.io/inject-cabundle: "true"
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
name: validating-webhook-configuration
Expand Down
7 changes: 0 additions & 7 deletions config/webhook/kustomizeconfig.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,11 @@ nameReference:
- kind: Service
version: v1
fieldSpecs:
- kind: MutatingWebhookConfiguration
group: admissionregistration.k8s.io
path: webhooks/clientConfig/service/name
- kind: ValidatingWebhookConfiguration
group: admissionregistration.k8s.io
path: webhooks/clientConfig/service/name

namespace:
- kind: MutatingWebhookConfiguration
group: admissionregistration.k8s.io
path: webhooks/clientConfig/service/namespace
create: true
- kind: ValidatingWebhookConfiguration
group: admissionregistration.k8s.io
path: webhooks/clientConfig/service/namespace
Expand Down
37 changes: 4 additions & 33 deletions config/webhook/manifests.yaml
Original file line number Diff line number Diff line change
@@ -1,32 +1,3 @@

---
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingWebhookConfiguration
metadata:
creationTimestamp: null
name: mutating-webhook-configuration
webhooks:
- admissionReviewVersions:
- v1alpha1
- v1beta1
clientConfig:
service:
name: webhook-service
namespace: system
path: /mutate-appstudio-redhat-com-v1beta1-integrationtestscenario
failurePolicy: Fail
name: mintegration.kb.io
rules:
- apiGroups:
- appstudio.redhat.com
apiVersions:
- v1beta1
operations:
- CREATE
- UPDATE
resources:
- applications
sideEffects: None
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
Expand All @@ -35,15 +6,14 @@ metadata:
name: validating-webhook-configuration
webhooks:
- admissionReviewVersions:
- v1alpha1
- v1beta1
- v1
clientConfig:
service:
name: webhook-service
namespace: system
path: /validate-appstudio-redhat-com-v1beta1-integrationtestscenario
failurePolicy: Fail
name: vapplication.kb.io
name: vintegrationtestscenario.kb.io
rules:
- apiGroups:
- appstudio.redhat.com
Expand All @@ -52,6 +22,7 @@ webhooks:
operations:
- CREATE
- UPDATE
- DELETE
resources:
- applications
- integrationtestscenarios
sideEffects: None

0 comments on commit fab9d22

Please sign in to comment.