Skip to content

Commit

Permalink
Use request Context for admission Webhook handlers
Browse files Browse the repository at this point in the history
  • Loading branch information
Steve Harris committed Aug 4, 2019
1 parent ee41a80 commit 402d93e
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
3 changes: 1 addition & 2 deletions pkg/webhook/admission/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ limitations under the License.
package admission

import (
"context"
"encoding/json"
"errors"
"fmt"
Expand Down Expand Up @@ -84,7 +83,7 @@ func (wh *Webhook) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}

// TODO: add panic-recovery for Handle
reviewResponse = wh.Handle(context.Background(), req)
reviewResponse = wh.Handle(r.Context(), req)
wh.writeResponse(w, reviewResponse)
}

Expand Down
27 changes: 27 additions & 0 deletions pkg/webhook/admission/http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package admission
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
Expand Down Expand Up @@ -94,6 +95,32 @@ var _ = Describe("Admission Webhooks", func() {
webhook.ServeHTTP(respRecorder, req)
Expect(respRecorder.Body.Bytes()).To(Equal(expected))
})

It("should present the Context from the HTTP request, if any", func() {
req := &http.Request{
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: nopCloser{Reader: bytes.NewBufferString(`{"request":{}}`)},
}
type ctxkey int
const key ctxkey = 1
const value = "from-ctx"
webhook := &Webhook{
Handler: &fakeHandler{
fn: func(ctx context.Context, req Request) Response {
<-ctx.Done()
return Allowed(ctx.Value(key).(string))
},
},
}

expected := []byte(fmt.Sprintf(`{"response":{"uid":"","allowed":true,"status":{"metadata":{},"reason":%q,"code":200}}}
`, value))

ctx, cancel := context.WithCancel(context.WithValue(context.Background(), key, value))
cancel()
webhook.ServeHTTP(respRecorder, req.WithContext(ctx))
Expect(respRecorder.Body.Bytes()).To(Equal(expected))
})
})
})

Expand Down
4 changes: 4 additions & 0 deletions pkg/webhook/admission/webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,10 @@ func (r *Response) Complete(req Request) error {

// Handler can handle an AdmissionRequest.
type Handler interface {
// Handle yields a response to an AdmissionRequest.
//
// The supplied context is extracted from the received http.Request, allowing wrapping
// http.Handlers to inject values into and control cancelation of downstream request processing.
Handle(context.Context, Request) Response
}

Expand Down

0 comments on commit 402d93e

Please sign in to comment.