From 402d93e52768e9a076a6712f74c3daa3c23a78b2 Mon Sep 17 00:00:00 2001 From: Steve Harris Date: Sat, 3 Aug 2019 17:05:24 -0400 Subject: [PATCH] Use request Context for admission Webhook handlers --- pkg/webhook/admission/http.go | 3 +-- pkg/webhook/admission/http_test.go | 27 +++++++++++++++++++++++++++ pkg/webhook/admission/webhook.go | 4 ++++ 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/pkg/webhook/admission/http.go b/pkg/webhook/admission/http.go index fa60302adc..5e4e2d699b 100644 --- a/pkg/webhook/admission/http.go +++ b/pkg/webhook/admission/http.go @@ -17,7 +17,6 @@ limitations under the License. package admission import ( - "context" "encoding/json" "errors" "fmt" @@ -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) } diff --git a/pkg/webhook/admission/http_test.go b/pkg/webhook/admission/http_test.go index 975115695f..4f769546bf 100644 --- a/pkg/webhook/admission/http_test.go +++ b/pkg/webhook/admission/http_test.go @@ -19,6 +19,7 @@ package admission import ( "bytes" "context" + "fmt" "io" "net/http" "net/http/httptest" @@ -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)) + }) }) }) diff --git a/pkg/webhook/admission/webhook.go b/pkg/webhook/admission/webhook.go index 9804aa9ba0..8f3430efbf 100644 --- a/pkg/webhook/admission/webhook.go +++ b/pkg/webhook/admission/webhook.go @@ -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 }