diff --git a/pkg/webhook/admission/defaulter_custom.go b/pkg/webhook/admission/defaulter_custom.go index a012784e43..d65727e62c 100644 --- a/pkg/webhook/admission/defaulter_custom.go +++ b/pkg/webhook/admission/defaulter_custom.go @@ -19,7 +19,6 @@ package admission import ( "context" "encoding/json" - "errors" "net/http" @@ -61,6 +60,8 @@ func (h *defaulterForType) Handle(ctx context.Context, req Request) Response { panic("object should never be nil") } + ctx = NewContextWithRequest(ctx, req) + // Get the object in the request obj := h.object.DeepCopyObject() if err := h.decoder.Decode(req, obj); err != nil { diff --git a/pkg/webhook/admission/validator_custom.go b/pkg/webhook/admission/validator_custom.go index 38d5565111..33252f1134 100644 --- a/pkg/webhook/admission/validator_custom.go +++ b/pkg/webhook/admission/validator_custom.go @@ -64,6 +64,8 @@ func (h *validatorForType) Handle(ctx context.Context, req Request) Response { panic("object should never be nil") } + ctx = NewContextWithRequest(ctx, req) + // Get the object in the request obj := h.object.DeepCopyObject() diff --git a/pkg/webhook/admission/webhook.go b/pkg/webhook/admission/webhook.go index 3dcff5fadd..cfc46637c3 100644 --- a/pkg/webhook/admission/webhook.go +++ b/pkg/webhook/admission/webhook.go @@ -253,3 +253,21 @@ func StandaloneWebhook(hook *Webhook, opts StandaloneOptions) (http.Handler, err } return metrics.InstrumentedHook(opts.MetricsPath, hook), nil } + +// requestContextKey is how we find the admission.Request in a context.Context. +type requestContextKey struct{} + +// RequestFromContext returns an admission.Request from ctx. +func RequestFromContext(ctx context.Context) (Request, error) { + if v, ok := ctx.Value(requestContextKey{}).(Request); ok { + return v, nil + } + + return Request{}, errors.New("admission.Request not found in context") +} + +// NewContextWithRequest returns a new Context, derived from ctx, which carries the +// provided admission.Request. +func NewContextWithRequest(ctx context.Context, req Request) context.Context { + return context.WithValue(ctx, requestContextKey{}, req) +}