Skip to content

add tests for webhook/admission pkg #123

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

Merged
merged 2 commits into from
Aug 29, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
38 changes: 38 additions & 0 deletions pkg/webhook/admission/admission_suite_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
Copyright 2018 The Kubernetes Authors.

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 admission

import (
"testing"

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

"sigs.k8s.io/controller-runtime/pkg/envtest"
logf "sigs.k8s.io/controller-runtime/pkg/runtime/log"
)

func TestAdmissionWebhook(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecsWithDefaultAndCustomReporters(t, "application Suite", []Reporter{envtest.NewlineReporter{}})
}

var _ = BeforeSuite(func(done Done) {
logf.SetLogger(logf.ZapLoggerTo(GinkgoWriter, true))

close(done)
}, 60)
82 changes: 82 additions & 0 deletions pkg/webhook/admission/decode_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/*
Copyright 2018 The Kubernetes Authors.

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 admission

import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"

admissionv1beta1 "k8s.io/api/admission/v1beta1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/kubernetes/scheme"
)

var _ = Describe("admission webhook decoder", func() {
var decoder Decoder
BeforeEach(func(done Done) {
var err error
decoder, err = NewDecoder(scheme.Scheme)
Expect(err).NotTo(HaveOccurred())
Expect(decoder).NotTo(BeNil())
close(done)
})

Describe("NewDecoder", func() {
It("should return a decoder without an error", func() {
decoder, err := NewDecoder(scheme.Scheme)
Expect(err).NotTo(HaveOccurred())
Expect(decoder).NotTo(BeNil())
})
})

Describe("Decode", func() {
req := Request{
AdmissionRequest: &admissionv1beta1.AdmissionRequest{
Object: runtime.RawExtension{
Raw: []byte(`{
"apiVersion": "v1",
"kind": "Pod",
"metadata": {
"name": "foo",
"namespace": "default"
},
"spec": {
"containers": [
{
"image": "bar",
"name": "bar"
}
]
}
}`),
},
},
}

It("should be able to decode", func() {
err := decoder.Decode(req, &corev1.Pod{})
Expect(err).NotTo(HaveOccurred())
})

It("should return an error if the GVK mismatch", func() {
err := decoder.Decode(req, &corev1.Node{})
Expect(err).To(HaveOccurred())
Expect(err.Error()).Should(ContainSubstring("unable to decode"))
})
})
})
7 changes: 4 additions & 3 deletions pkg/webhook/admission/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ func addToScheme(scheme *runtime.Scheme) {

var _ http.Handler = &Webhook{}

// ContextKey is a type alias of string and is used as the key in context.
type ContextKey string

func (wh *Webhook) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var body []byte
var err error
Expand Down Expand Up @@ -89,13 +92,11 @@ func (wh *Webhook) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}

// TODO: add panic-recovery for Handle
type contextKey string
ctx := context.Background()
for k := range wh.KVMap {
ctx = context.WithValue(ctx, contextKey(k), wh.KVMap[k])
ctx = context.WithValue(ctx, ContextKey(k), wh.KVMap[k])
}
reviewResponse = wh.Handle(ctx, Request{AdmissionRequest: ar.Request})
reviewResponse.Response.UID = ar.Request.UID
writeResponse(w, reviewResponse)
}

Expand Down
175 changes: 175 additions & 0 deletions pkg/webhook/admission/http_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
/*
Copyright 2018 The Kubernetes Authors.

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 admission

import (
"bytes"
"context"
"io"
"net/http"
"net/http/httptest"

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

admissionv1beta1 "k8s.io/api/admission/v1beta1"
"sigs.k8s.io/controller-runtime/pkg/webhook/types"
)

var _ = Describe("admission webhook http handler", func() {
var w *httptest.ResponseRecorder
BeforeEach(func(done Done) {
w = &httptest.ResponseRecorder{
Body: bytes.NewBuffer(nil),
}
close(done)
})

Describe("empty request body", func() {
req := &http.Request{Body: nil}
wh := &Webhook{
Handlers: []Handler{},
}

expected := []byte(`{"response":{"uid":"","allowed":false,"status":{"metadata":{},"message":"request body is empty","code":400}}}
`)
It("should return an error with bad-request status code", func() {
wh.ServeHTTP(w, req)
Expect(w.Body.Bytes()).To(Equal(expected))
})
})

Describe("wrong content type", func() {
req := &http.Request{
Header: http.Header{"Content-Type": []string{"application/foo"}},
Body: nopCloser{Reader: bytes.NewBuffer(nil)},
}
wh := &Webhook{
Handlers: []Handler{},
}
expected := []byte(`{"response":{"uid":"","allowed":false,"status":{"metadata":{},"message":"contentType=application/foo, expect application/json","code":400}}}
`)
It("should return an error with bad-request status code", func() {
wh.ServeHTTP(w, req)
Expect(w.Body.Bytes()).To(Equal(expected))

})
})

Describe("can't decode body", func() {
req := &http.Request{
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: nopCloser{Reader: bytes.NewBufferString("{")},
}
wh := &Webhook{
Type: types.WebhookTypeMutating,
Handlers: []Handler{},
}
expected := []byte(
`{"response":{"uid":"","allowed":false,"status":{"metadata":{},"message":"couldn't get version/kind; json parse error: unexpected end of JSON input","code":400}}}
`)
It("should return an error with bad-request status code", func() {
wh.ServeHTTP(w, req)
Expect(w.Body.Bytes()).To(Equal(expected))

})
})

Describe("empty body after decoding", func() {
req := &http.Request{
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: nopCloser{Reader: bytes.NewBuffer(nil)},
}
wh := &Webhook{
Type: types.WebhookTypeMutating,
Handlers: []Handler{},
}
expected := []byte(`{"response":{"uid":"","allowed":false,"status":{"metadata":{},"message":"got an empty AdmissionRequest","code":400}}}
`)
It("should return an error with bad-request status code", func() {
wh.ServeHTTP(w, req)
Expect(w.Body.Bytes()).To(Equal(expected))
})
})

Describe("no webhook type", func() {
req := &http.Request{
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: nopCloser{Reader: bytes.NewBufferString(`{"request":{}}`)},
}
wh := &Webhook{
Handlers: []Handler{},
}
expected := []byte(`{"response":{"uid":"","allowed":false,"status":{"metadata":{},"message":"you must specify your webhook type","code":500}}}
`)
It("should return an error with internal-error status code", func() {
wh.ServeHTTP(w, req)
Expect(w.Body.Bytes()).To(Equal(expected))

})
})

Describe("handler can be invoked", func() {
req := &http.Request{
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: nopCloser{Reader: bytes.NewBufferString(`{"request":{}}`)},
}
h := &fakeHandler{}
wh := &Webhook{
Type: types.WebhookTypeValidating,
Handlers: []Handler{h},
KVMap: map[string]interface{}{"foo": "bar"},
}
expected := []byte(`{"response":{"uid":"","allowed":true}}
`)
It("should return a response successfully", func() {
wh.ServeHTTP(w, req)
Expect(w.Body.Bytes()).To(Equal(expected))
Expect(h.invoked).To(BeTrue())
Expect(h.valueFromContext).To(Equal("bar"))
})
})
})

type nopCloser struct {
io.Reader
}

func (nopCloser) Close() error { return nil }

type fakeHandler struct {
invoked bool
valueFromContext string
fn func(context.Context, Request) Response
}

func (h *fakeHandler) Handle(ctx context.Context, req Request) Response {
v := ctx.Value(ContextKey("foo"))
if v != nil {
typed, ok := v.(string)
if ok {
h.valueFromContext = typed
}
}
h.invoked = true
if h.fn != nil {
return h.fn(ctx, req)
}
return Response{Response: &admissionv1beta1.AdmissionResponse{
Allowed: true,
}}
}
1 change: 1 addition & 0 deletions pkg/webhook/admission/response.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"net/http"

"github.com/mattbaird/jsonpatch"

admissionv1beta1 "k8s.io/api/admission/v1beta1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
Expand Down
Loading