Skip to content

Commit

Permalink
return error if more than one For is used on webhook creation
Browse files Browse the repository at this point in the history
Signed-off-by: Troy Connor <troy0820@users.noreply.github.com>
  • Loading branch information
troy0820 committed Mar 27, 2024
1 parent 27afc15 commit 936942b
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
6 changes: 5 additions & 1 deletion pkg/builder/webhook.go
Expand Up @@ -44,6 +44,7 @@ type WebhookBuilder struct {
config *rest.Config
recoverPanic bool
logConstructor func(base logr.Logger, req *admission.Request) logr.Logger
err error
}

// WebhookManagedBy returns a new webhook builder.
Expand All @@ -57,6 +58,9 @@ func WebhookManagedBy(m manager.Manager) *WebhookBuilder {
// If the given object implements the admission.Defaulter interface, a MutatingWebhook will be wired for this type.
// If the given object implements the admission.Validator interface, a ValidatingWebhook will be wired for this type.
func (blder *WebhookBuilder) For(apiType runtime.Object) *WebhookBuilder {
if blder.apiType != nil {
blder.err = errors.New("For(...) should only be called once, could not assign multiple objects for webhook registration")
}
blder.apiType = apiType
return blder
}
Expand Down Expand Up @@ -142,7 +146,7 @@ func (blder *WebhookBuilder) registerWebhooks() error {
if err != nil {
return err
}
return nil
return blder.err
}

// registerDefaultingWebhook registers a defaulting webhook if necessary.
Expand Down
18 changes: 18 additions & 0 deletions pkg/builder/webhook_test.go
Expand Up @@ -662,6 +662,24 @@ func runTests(admissionReviewVersion string) {
ExpectWithOffset(1, w.Body).To(ContainSubstring(`"allowed":true`))
ExpectWithOffset(1, w.Body).To(ContainSubstring(`"code":200`))
})

It("should send an error when trying to register a webhook with more than one For", func() {
By("creating a controller manager")
m, err := manager.New(cfg, manager.Options{})
ExpectWithOffset(1, err).NotTo(HaveOccurred())

By("registering the type in the Scheme")
builder := scheme.Builder{GroupVersion: testDefaulterGVK.GroupVersion()}
builder.Register(&TestDefaulter{}, &TestDefaulterList{})
err = builder.AddToScheme(m.GetScheme())
ExpectWithOffset(1, err).NotTo(HaveOccurred())

err = WebhookManagedBy(m).
For(&TestDefaulter{}).
For(&TestDefaulter{}).
Complete()
Expect(err).To(HaveOccurred())
})
}

// TestDefaulter.
Expand Down

0 comments on commit 936942b

Please sign in to comment.