Skip to content

Commit 25dad67

Browse files
author
Steve Harris
committed
Use request Context for admission Webhook handlers
1 parent ee41a80 commit 25dad67

File tree

3 files changed

+32
-2
lines changed

3 files changed

+32
-2
lines changed

pkg/webhook/admission/http.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ limitations under the License.
1717
package admission
1818

1919
import (
20-
"context"
2120
"encoding/json"
2221
"errors"
2322
"fmt"
@@ -84,7 +83,7 @@ func (wh *Webhook) ServeHTTP(w http.ResponseWriter, r *http.Request) {
8483
}
8584

8685
// TODO: add panic-recovery for Handle
87-
reviewResponse = wh.Handle(context.Background(), req)
86+
reviewResponse = wh.Handle(r.Context(), req)
8887
wh.writeResponse(w, reviewResponse)
8988
}
9089

pkg/webhook/admission/http_test.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ package admission
1919
import (
2020
"bytes"
2121
"context"
22+
"fmt"
2223
"io"
2324
"net/http"
2425
"net/http/httptest"
@@ -94,6 +95,32 @@ var _ = Describe("Admission Webhooks", func() {
9495
webhook.ServeHTTP(respRecorder, req)
9596
Expect(respRecorder.Body.Bytes()).To(Equal(expected))
9697
})
98+
99+
It("should present the Context from the HTTP request, if any", func() {
100+
req := &http.Request{
101+
Header: http.Header{"Content-Type": []string{"application/json"}},
102+
Body: nopCloser{Reader: bytes.NewBufferString(`{"request":{}}`)},
103+
}
104+
type ctxkey int
105+
const key ctxkey = 1
106+
const value = "from-ctx"
107+
webhook := &Webhook{
108+
Handler: &fakeHandler{
109+
fn: func(ctx context.Context, req Request) Response {
110+
<-ctx.Done()
111+
return Allowed(ctx.Value(key).(string))
112+
},
113+
},
114+
}
115+
116+
expected := []byte(fmt.Sprintf(`{"response":{"uid":"","allowed":true,"status":{"metadata":{},"reason":%q,"code":200}}}
117+
`, value))
118+
119+
ctx, cancel := context.WithCancel(context.WithValue(context.Background(), key, value))
120+
cancel()
121+
webhook.ServeHTTP(respRecorder, req.WithContext(ctx))
122+
Expect(respRecorder.Body.Bytes()).To(Equal(expected))
123+
})
97124
})
98125
})
99126

pkg/webhook/admission/webhook.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,10 @@ func (r *Response) Complete(req Request) error {
9292

9393
// Handler can handle an AdmissionRequest.
9494
type Handler interface {
95+
// Handle yields a response to an AdmissionRequest.
96+
//
97+
// The supplied context is extracted from the received http.Request, if any, allowing wrapping
98+
// http.Handlers to inject values into and control cancelation of downstream request processing.
9599
Handle(context.Context, Request) Response
96100
}
97101

0 commit comments

Comments
 (0)