Skip to content

Commit

Permalink
Provide access to admission.Request in custom validator/defaulter
Browse files Browse the repository at this point in the history
  • Loading branch information
sbueringer committed Jul 6, 2022
1 parent 365ae09 commit 608fd80
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
3 changes: 2 additions & 1 deletion pkg/webhook/admission/defaulter_custom.go
Expand Up @@ -19,7 +19,6 @@ package admission
import (
"context"
"encoding/json"

"errors"
"net/http"

Expand Down Expand Up @@ -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 {
Expand Down
2 changes: 2 additions & 0 deletions pkg/webhook/admission/validator_custom.go
Expand Up @@ -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()

Expand Down
18 changes: 18 additions & 0 deletions pkg/webhook/admission/webhook.go
Expand Up @@ -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)
}

0 comments on commit 608fd80

Please sign in to comment.