main.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. /*
  2. Copyright 2018 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package webhook
  14. import (
  15. "encoding/json"
  16. "fmt"
  17. "io/ioutil"
  18. "net/http"
  19. "github.com/spf13/cobra"
  20. v1 "k8s.io/api/admission/v1"
  21. "k8s.io/api/admission/v1beta1"
  22. "k8s.io/apimachinery/pkg/runtime"
  23. "k8s.io/klog"
  24. // TODO: try this library to see if it generates correct json patch
  25. // https://github.com/mattbaird/jsonpatch
  26. )
  27. var (
  28. certFile string
  29. keyFile string
  30. port int
  31. sidecarImage string
  32. )
  33. // CmdWebhook is used by agnhost Cobra.
  34. var CmdWebhook = &cobra.Command{
  35. Use: "webhook",
  36. Short: "Starts a HTTP server, useful for testing MutatingAdmissionWebhook and ValidatingAdmissionWebhook",
  37. Long: `Starts a HTTP server, useful for testing MutatingAdmissionWebhook and ValidatingAdmissionWebhook.
  38. After deploying it to Kubernetes cluster, the Administrator needs to create a ValidatingWebhookConfiguration
  39. in the Kubernetes cluster to register remote webhook admission controllers.`,
  40. Args: cobra.MaximumNArgs(0),
  41. Run: main,
  42. }
  43. func init() {
  44. CmdWebhook.Flags().StringVar(&certFile, "tls-cert-file", "",
  45. "File containing the default x509 Certificate for HTTPS. (CA cert, if any, concatenated after server cert).")
  46. CmdWebhook.Flags().StringVar(&keyFile, "tls-private-key-file", "",
  47. "File containing the default x509 private key matching --tls-cert-file.")
  48. CmdWebhook.Flags().IntVar(&port, "port", 443,
  49. "Secure port that the webhook listens on")
  50. CmdWebhook.Flags().StringVar(&sidecarImage, "sidecar-image", "",
  51. "Image to be used as the injected sidecar")
  52. }
  53. // admitv1beta1Func handles a v1beta1 admission
  54. type admitv1beta1Func func(v1beta1.AdmissionReview) *v1beta1.AdmissionResponse
  55. // admitv1beta1Func handles a v1 admission
  56. type admitv1Func func(v1.AdmissionReview) *v1.AdmissionResponse
  57. // admitHandler is a handler, for both validators and mutators, that supports multiple admission review versions
  58. type admitHandler struct {
  59. v1beta1 admitv1beta1Func
  60. v1 admitv1Func
  61. }
  62. func newDelegateToV1AdmitHandler(f admitv1Func) admitHandler {
  63. return admitHandler{
  64. v1beta1: delegateV1beta1AdmitToV1(f),
  65. v1: f,
  66. }
  67. }
  68. func delegateV1beta1AdmitToV1(f admitv1Func) admitv1beta1Func {
  69. return func(review v1beta1.AdmissionReview) *v1beta1.AdmissionResponse {
  70. in := v1.AdmissionReview{Request: convertAdmissionRequestToV1(review.Request)}
  71. out := f(in)
  72. return convertAdmissionResponseToV1beta1(out)
  73. }
  74. }
  75. // serve handles the http portion of a request prior to handing to an admit
  76. // function
  77. func serve(w http.ResponseWriter, r *http.Request, admit admitHandler) {
  78. var body []byte
  79. if r.Body != nil {
  80. if data, err := ioutil.ReadAll(r.Body); err == nil {
  81. body = data
  82. }
  83. }
  84. // verify the content type is accurate
  85. contentType := r.Header.Get("Content-Type")
  86. if contentType != "application/json" {
  87. klog.Errorf("contentType=%s, expect application/json", contentType)
  88. return
  89. }
  90. klog.V(2).Info(fmt.Sprintf("handling request: %s", body))
  91. deserializer := codecs.UniversalDeserializer()
  92. obj, gvk, err := deserializer.Decode(body, nil, nil)
  93. if err != nil {
  94. msg := fmt.Sprintf("Request could not be decoded: %v", err)
  95. klog.Error(msg)
  96. http.Error(w, msg, http.StatusBadRequest)
  97. return
  98. }
  99. var responseObj runtime.Object
  100. switch *gvk {
  101. case v1beta1.SchemeGroupVersion.WithKind("AdmissionReview"):
  102. requestedAdmissionReview, ok := obj.(*v1beta1.AdmissionReview)
  103. if !ok {
  104. klog.Errorf("Expected v1beta1.AdmissionReview but got: %T", obj)
  105. return
  106. }
  107. responseAdmissionReview := &v1beta1.AdmissionReview{}
  108. responseAdmissionReview.SetGroupVersionKind(*gvk)
  109. responseAdmissionReview.Response = admit.v1beta1(*requestedAdmissionReview)
  110. responseAdmissionReview.Response.UID = requestedAdmissionReview.Request.UID
  111. responseObj = responseAdmissionReview
  112. case v1.SchemeGroupVersion.WithKind("AdmissionReview"):
  113. requestedAdmissionReview, ok := obj.(*v1.AdmissionReview)
  114. if !ok {
  115. klog.Errorf("Expected v1.AdmissionReview but got: %T", obj)
  116. return
  117. }
  118. responseAdmissionReview := &v1.AdmissionReview{}
  119. responseAdmissionReview.SetGroupVersionKind(*gvk)
  120. responseAdmissionReview.Response = admit.v1(*requestedAdmissionReview)
  121. responseAdmissionReview.Response.UID = requestedAdmissionReview.Request.UID
  122. responseObj = responseAdmissionReview
  123. default:
  124. msg := fmt.Sprintf("Unsupported group version kind: %v", gvk)
  125. klog.Error(msg)
  126. http.Error(w, msg, http.StatusBadRequest)
  127. return
  128. }
  129. klog.V(2).Info(fmt.Sprintf("sending response: %v", responseObj))
  130. respBytes, err := json.Marshal(responseObj)
  131. if err != nil {
  132. klog.Error(err)
  133. http.Error(w, err.Error(), http.StatusInternalServerError)
  134. return
  135. }
  136. w.Header().Set("Content-Type", "application/json")
  137. if _, err := w.Write(respBytes); err != nil {
  138. klog.Error(err)
  139. }
  140. }
  141. func serveAlwaysAllowDelayFiveSeconds(w http.ResponseWriter, r *http.Request) {
  142. serve(w, r, newDelegateToV1AdmitHandler(alwaysAllowDelayFiveSeconds))
  143. }
  144. func serveAlwaysDeny(w http.ResponseWriter, r *http.Request) {
  145. serve(w, r, newDelegateToV1AdmitHandler(alwaysDeny))
  146. }
  147. func serveAddLabel(w http.ResponseWriter, r *http.Request) {
  148. serve(w, r, newDelegateToV1AdmitHandler(addLabel))
  149. }
  150. func servePods(w http.ResponseWriter, r *http.Request) {
  151. serve(w, r, newDelegateToV1AdmitHandler(admitPods))
  152. }
  153. func serveAttachingPods(w http.ResponseWriter, r *http.Request) {
  154. serve(w, r, newDelegateToV1AdmitHandler(denySpecificAttachment))
  155. }
  156. func serveMutatePods(w http.ResponseWriter, r *http.Request) {
  157. serve(w, r, newDelegateToV1AdmitHandler(mutatePods))
  158. }
  159. func serveMutatePodsSidecar(w http.ResponseWriter, r *http.Request) {
  160. serve(w, r, newDelegateToV1AdmitHandler(mutatePodsSidecar))
  161. }
  162. func serveConfigmaps(w http.ResponseWriter, r *http.Request) {
  163. serve(w, r, newDelegateToV1AdmitHandler(admitConfigMaps))
  164. }
  165. func serveMutateConfigmaps(w http.ResponseWriter, r *http.Request) {
  166. serve(w, r, newDelegateToV1AdmitHandler(mutateConfigmaps))
  167. }
  168. func serveCustomResource(w http.ResponseWriter, r *http.Request) {
  169. serve(w, r, newDelegateToV1AdmitHandler(admitCustomResource))
  170. }
  171. func serveMutateCustomResource(w http.ResponseWriter, r *http.Request) {
  172. serve(w, r, newDelegateToV1AdmitHandler(mutateCustomResource))
  173. }
  174. func serveCRD(w http.ResponseWriter, r *http.Request) {
  175. serve(w, r, newDelegateToV1AdmitHandler(admitCRD))
  176. }
  177. func main(cmd *cobra.Command, args []string) {
  178. config := Config{
  179. CertFile: certFile,
  180. KeyFile: keyFile,
  181. }
  182. http.HandleFunc("/always-allow-delay-5s", serveAlwaysAllowDelayFiveSeconds)
  183. http.HandleFunc("/always-deny", serveAlwaysDeny)
  184. http.HandleFunc("/add-label", serveAddLabel)
  185. http.HandleFunc("/pods", servePods)
  186. http.HandleFunc("/pods/attach", serveAttachingPods)
  187. http.HandleFunc("/mutating-pods", serveMutatePods)
  188. http.HandleFunc("/mutating-pods-sidecar", serveMutatePodsSidecar)
  189. http.HandleFunc("/configmaps", serveConfigmaps)
  190. http.HandleFunc("/mutating-configmaps", serveMutateConfigmaps)
  191. http.HandleFunc("/custom-resource", serveCustomResource)
  192. http.HandleFunc("/mutating-custom-resource", serveMutateCustomResource)
  193. http.HandleFunc("/crd", serveCRD)
  194. http.HandleFunc("/readyz", func(w http.ResponseWriter, req *http.Request) { w.Write([]byte("ok")) })
  195. server := &http.Server{
  196. Addr: fmt.Sprintf(":%d", port),
  197. TLSConfig: configTLS(config),
  198. }
  199. err := server.ListenAndServeTLS("", "")
  200. if err != nil {
  201. panic(err)
  202. }
  203. }