Skip to content

Commit

Permalink
fix: prevent responding with server errors.
Browse files Browse the repository at this point in the history
  • Loading branch information
Justin Bertrand committed Jun 22, 2021
1 parent 6cb4d53 commit 1e26132
Showing 1 changed file with 9 additions and 8 deletions.
17 changes: 9 additions & 8 deletions mutatingwebhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import (
"k8s.io/klog/v2"
)

const internalServerError = "an internal server error has occurred"

// Based on:
// https://medium.com/ovni/writing-a-very-basic-kubernetes-mutating-admission-webhook-398dbbcb63ec
// https://github.com/alex-leonhardt/k8s-mutate-webhook
Expand Down Expand Up @@ -66,23 +68,22 @@ func (mw *mutatingWebhook) handleMutate(w http.ResponseWriter, r *http.Request)

// Decode the request
body, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()

klog.V(5).Infof("request body:\n%s", body)

if err != nil {
klog.Error(err)
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "%s", err)
fmt.Fprintf(w, "%s", internalServerError)
return
}
defer r.Body.Close()

klog.V(5).Infof("request body:\n%s", body)

// Attempt to get the AdmissionReview the request
admissionReview := v1.AdmissionReview{}
if err := json.Unmarshal(body, &admissionReview); err != nil {
klog.Error(err)
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "%s", err)
fmt.Fprintf(w, "%s", internalServerError)
return
}

Expand All @@ -91,7 +92,7 @@ func (mw *mutatingWebhook) handleMutate(w http.ResponseWriter, r *http.Request)
if err != nil {
klog.Error(err)
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "%s", err)
fmt.Fprintf(w, "%s", internalServerError)
return
}

Expand All @@ -102,7 +103,7 @@ func (mw *mutatingWebhook) handleMutate(w http.ResponseWriter, r *http.Request)
if body, err = json.Marshal(reviewResponse); err != nil {
klog.Error(err)
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "%s", err)
fmt.Fprintf(w, "%s", internalServerError)
return
}

Expand Down

0 comments on commit 1e26132

Please sign in to comment.