Skip to content

Commit

Permalink
Merge pull request #2605 from inteon/handle_empty_http_bodies
Browse files Browse the repository at this point in the history
馃悰 Webhook: Handle http.NoBody
  • Loading branch information
k8s-ci-robot committed Dec 3, 2023
2 parents 8d817e7 + cf7eab0 commit 0376af3
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 2 deletions.
2 changes: 1 addition & 1 deletion pkg/webhook/admission/http.go
Expand Up @@ -47,7 +47,7 @@ func (wh *Webhook) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx = wh.WithContextFunc(ctx, r)
}

if r.Body == nil {
if r.Body == nil || r.Body == http.NoBody {
err := errors.New("request body is empty")
wh.getLogger(nil).Error(err, "bad request")
wh.writeResponse(w, Errored(http.StatusBadRequest, err))
Expand Down
13 changes: 13 additions & 0 deletions pkg/webhook/admission/http_test.go
Expand Up @@ -84,6 +84,19 @@ var _ = Describe("Admission Webhooks", func() {
Expect(respRecorder.Body.String()).To(Equal(expected))
})

It("should error when given a NoBody", func() {
req := &http.Request{
Header: http.Header{"Content-Type": []string{"application/json"}},
Method: http.MethodPost,
Body: http.NoBody,
}

expected := `{"response":{"uid":"","allowed":false,"status":{"metadata":{},"message":"request body is empty","code":400}}}
`
webhook.ServeHTTP(respRecorder, req)
Expect(respRecorder.Body.String()).To(Equal(expected))
})

It("should return the response given by the handler with version defaulted to v1", func() {
req := &http.Request{
Header: http.Header{"Content-Type": []string{"application/json"}},
Expand Down
2 changes: 1 addition & 1 deletion pkg/webhook/authentication/http.go
Expand Up @@ -47,7 +47,7 @@ func (wh *Webhook) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx = wh.WithContextFunc(ctx, r)
}

if r.Body == nil {
if r.Body == nil || r.Body == http.NoBody {
err := errors.New("request body is empty")
wh.getLogger(nil).Error(err, "bad request")
wh.writeResponse(w, Errored(err))
Expand Down
13 changes: 13 additions & 0 deletions pkg/webhook/authentication/http_test.go
Expand Up @@ -94,6 +94,19 @@ var _ = Describe("Authentication Webhooks", func() {
Expect(respRecorder.Body.String()).To(Equal(expected))
})

It("should error when given a NoBody", func() {
req := &http.Request{
Header: http.Header{"Content-Type": []string{"application/json"}},
Method: http.MethodPost,
Body: http.NoBody,
}

expected := `{"metadata":{"creationTimestamp":null},"spec":{},"status":{"user":{},"error":"request body is empty"}}
`
webhook.ServeHTTP(respRecorder, req)
Expect(respRecorder.Body.String()).To(Equal(expected))
})

It("should return the response given by the handler with version defaulted to v1", func() {
req := &http.Request{
Header: http.Header{"Content-Type": []string{"application/json"}},
Expand Down

0 comments on commit 0376af3

Please sign in to comment.