3 // ========================LICENSE_START=================================
6 // Copyright (C) 2022-2023: Nordix Foundation
8 // Licensed under the Apache License, Version 2.0 (the "License");
9 // you may not use this file except in compliance with the License.
10 // You may obtain a copy of the License at
12 // http://www.apache.org/licenses/LICENSE-2.0
14 // Unless required by applicable law or agreed to in writing, software
15 // distributed under the License is distributed on an "AS IS" BASIS,
16 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 // See the License for the specific language governing permissions and
18 // limitations under the License.
19 // ========================LICENSE_END===================================
28 "k8s.io/api/admission/v1beta1"
29 v1 "k8s.io/api/core/v1"
30 "k8s.io/apimachinery/pkg/runtime"
31 "k8s.io/apimachinery/pkg/runtime/serializer"
36 type ServerParameters struct {
37 port string // webhook server port
38 certFile string // path to the x509 cert
39 keyFile string // path to the x509 private key
43 type patchOperation struct {
45 Path string `json:"path"`
46 Value interface{} `json:"value,omitempty"`
49 var parameters ServerParameters
52 universalDeserializer = serializer.NewCodecFactory(runtime.NewScheme()).UniversalDeserializer()
56 flag.StringVar(¶meters.port, "port", "8443", "Webhook server port.")
57 flag.StringVar(¶meters.certFile, "tlsCertFile", "/certs/tls.crt", "File containing the x509 certificate")
58 flag.StringVar(¶meters.keyFile, "tlsKeyFile", "/certs/tls.key", "File containing the x509 private key")
59 flag.StringVar(¶meters.secret, "secret", "cm-keycloak-client-certs", "Secret containing rapp cert files")
62 http.HandleFunc("/inject-sidecar", HandleSideCarInjection)
63 log.Fatal(http.ListenAndServeTLS(":"+parameters.port, parameters.certFile, parameters.keyFile, nil))
66 func HandleSideCarInjection(w http.ResponseWriter, r *http.Request) {
68 body, err := ioutil.ReadAll(r.Body)
69 err = ioutil.WriteFile("/tmp/request", body, 0644)
74 var admissionReviewReq v1beta1.AdmissionReview
76 if _, _, err := universalDeserializer.Decode(body, nil, &admissionReviewReq); err != nil {
77 w.WriteHeader(http.StatusBadRequest)
78 fmt.Errorf("Could not deserialize request: %v", err)
79 } else if admissionReviewReq.Request == nil {
80 w.WriteHeader(http.StatusBadRequest)
81 errors.New("Malformed admission review - request is empty")
84 fmt.Printf("Received Admission Review Request - Type: %v \t Event: %v \t Name: %v \n",
85 admissionReviewReq.Request.Kind,
86 admissionReviewReq.Request.Operation,
87 admissionReviewReq.Request.Name,
92 err = json.Unmarshal(admissionReviewReq.Request.Object.Raw, &pod)
95 fmt.Errorf("Could not unmarshal pod from admission request: %v", err)
98 var patches []patchOperation
100 labels := pod.ObjectMeta.Labels
101 labels["sidecar-injection-webhook"] = "jwt-proxy"
103 patches = append(patches, patchOperation{
105 Path: "/metadata/labels",
109 var containers []v1.Container
110 containers = append(containers, pod.Spec.Containers...)
111 container := v1.Container{
113 Image: "ktimoney/rapps-jwt",
114 ImagePullPolicy: v1.PullIfNotPresent,
115 Ports: []v1.ContainerPort{
118 Protocol: v1.ProtocolTCP,
122 VolumeMounts: []v1.VolumeMount{
131 containers = append(containers, container)
132 fmt.Println(containers)
134 patches = append(patches, patchOperation{
136 Path: "/spec/containers",
140 var volumes []v1.Volume
141 volumes = append(volumes, pod.Spec.Volumes...)
144 VolumeSource: v1.VolumeSource{
145 Secret: &v1.SecretVolumeSource{
146 SecretName: parameters.secret,
150 volumes = append(volumes, volume)
153 patches = append(patches, patchOperation{
155 Path: "/spec/volumes",
160 patchBytes, err := json.Marshal(patches)
163 fmt.Errorf("Error occurred when trying to marshal JSON patch: %v", err)
166 admissionReviewResponse := v1beta1.AdmissionReview{
167 Response: &v1beta1.AdmissionResponse{
168 UID: admissionReviewReq.Request.UID,
173 admissionReviewResponse.Response.Patch = patchBytes
175 bytes, err := json.Marshal(&admissionReviewResponse)
177 fmt.Errorf("Error occurred when trying to marshal Aadmission Review response: %v", err)