Skip to content

Commit 936942b

Browse files
committed
return error if more than one For is used on webhook creation
Signed-off-by: Troy Connor <troy0820@users.noreply.github.com>
1 parent 27afc15 commit 936942b

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

pkg/builder/webhook.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ type WebhookBuilder struct {
4444
config *rest.Config
4545
recoverPanic bool
4646
logConstructor func(base logr.Logger, req *admission.Request) logr.Logger
47+
err error
4748
}
4849

4950
// WebhookManagedBy returns a new webhook builder.
@@ -57,6 +58,9 @@ func WebhookManagedBy(m manager.Manager) *WebhookBuilder {
5758
// If the given object implements the admission.Defaulter interface, a MutatingWebhook will be wired for this type.
5859
// If the given object implements the admission.Validator interface, a ValidatingWebhook will be wired for this type.
5960
func (blder *WebhookBuilder) For(apiType runtime.Object) *WebhookBuilder {
61+
if blder.apiType != nil {
62+
blder.err = errors.New("For(...) should only be called once, could not assign multiple objects for webhook registration")
63+
}
6064
blder.apiType = apiType
6165
return blder
6266
}
@@ -142,7 +146,7 @@ func (blder *WebhookBuilder) registerWebhooks() error {
142146
if err != nil {
143147
return err
144148
}
145-
return nil
149+
return blder.err
146150
}
147151

148152
// registerDefaultingWebhook registers a defaulting webhook if necessary.

pkg/builder/webhook_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -662,6 +662,24 @@ func runTests(admissionReviewVersion string) {
662662
ExpectWithOffset(1, w.Body).To(ContainSubstring(`"allowed":true`))
663663
ExpectWithOffset(1, w.Body).To(ContainSubstring(`"code":200`))
664664
})
665+
666+
It("should send an error when trying to register a webhook with more than one For", func() {
667+
By("creating a controller manager")
668+
m, err := manager.New(cfg, manager.Options{})
669+
ExpectWithOffset(1, err).NotTo(HaveOccurred())
670+
671+
By("registering the type in the Scheme")
672+
builder := scheme.Builder{GroupVersion: testDefaulterGVK.GroupVersion()}
673+
builder.Register(&TestDefaulter{}, &TestDefaulterList{})
674+
err = builder.AddToScheme(m.GetScheme())
675+
ExpectWithOffset(1, err).NotTo(HaveOccurred())
676+
677+
err = WebhookManagedBy(m).
678+
For(&TestDefaulter{}).
679+
For(&TestDefaulter{}).
680+
Complete()
681+
Expect(err).To(HaveOccurred())
682+
})
665683
}
666684

667685
// TestDefaulter.

0 commit comments

Comments
 (0)