From 1e9f38bcb9ab615e62d9ea7a73cdca201ef0acbb Mon Sep 17 00:00:00 2001 From: Mathis Marcotte Date: Tue, 28 Jan 2025 13:56:52 +0000 Subject: [PATCH] Initial commit of kerberos sidecar injector --- .dockerignore | 13 ++ .github/workflows/build.yaml | 100 +++++++++ .github/workflows/publish.yaml | 102 +++++++++ .gitignore | 18 ++ Dockerfile | 31 +++ LICENSE | 201 +++++++++++++++++ README.md | 37 ++++ cmd/cert.go | 90 ++++++++ cmd/main.go | 102 +++++++++ cmd/webhook.go | 380 +++++++++++++++++++++++++++++++++ cmd/webhookconfig.go | 108 ++++++++++ deploy/clusterrole.yaml | 13 ++ deploy/clusterrolebinding.yaml | 14 ++ deploy/configmap.yaml | 64 ++++++ deploy/deployment.yaml | 42 ++++ deploy/kustomization.yaml | 17 ++ deploy/service.yaml | 13 ++ deploy/serviceaccount.yaml | 7 + go.mod | 50 +++++ go.sum | 140 ++++++++++++ prestop.sh | 21 ++ 21 files changed, 1563 insertions(+) create mode 100644 .dockerignore create mode 100644 .github/workflows/build.yaml create mode 100644 .github/workflows/publish.yaml create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 LICENSE create mode 100644 README.md create mode 100644 cmd/cert.go create mode 100644 cmd/main.go create mode 100644 cmd/webhook.go create mode 100644 cmd/webhookconfig.go create mode 100644 deploy/clusterrole.yaml create mode 100644 deploy/clusterrolebinding.yaml create mode 100644 deploy/configmap.yaml create mode 100644 deploy/deployment.yaml create mode 100644 deploy/kustomization.yaml create mode 100644 deploy/service.yaml create mode 100644 deploy/serviceaccount.yaml create mode 100644 go.mod create mode 100644 go.sum create mode 100644 prestop.sh diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..4a146ec --- /dev/null +++ b/.dockerignore @@ -0,0 +1,13 @@ +# Binaries for programs and plugins +*.exe +*.dll +*.so +*.dylib + +# Test binary, build with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +vendor/* diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml new file mode 100644 index 0000000..5d0b3f5 --- /dev/null +++ b/.github/workflows/build.yaml @@ -0,0 +1,100 @@ +# This workflow will build a docker container, publish it to Azure Container Registry, and deploy it to Azure Kubernetes Service using a helm chart. +# +# https://github.com/Azure/actions-workflow-samples/tree/master/Kubernetes +# +# To configure this workflow: +# +# 1. Set up the following secrets in your workspace: +# a. REGISTRY_USERNAME with ACR username +# b. REGISTRY_PASSWORD with ACR Password +# +# 2. Change the values for the REGISTRY_NAME environment variables (below). +name: build +on: + pull_request: + types: + - 'opened' + - 'synchronize' + - 'reopened' + +# Environment variables available to all jobs and steps in this workflow +env: + REGISTRY_NAME: k8scc01covidacr + TRIVY_VERSION: "v0.58.2" + TRIVY_DATABASES: '"ghcr.io/aquasecurity/trivy-db:2","public.ecr.aws/aquasecurity/trivy-db"' + TRIVY_JAVA_DATABASES: '"ghcr.io/aquasecurity/trivy-java-db:1","public.ecr.aws/aquasecurity/trivy-java-db"' + TRIVY_MAX_RETRIES: 5 + TRIVY_RETRY_DELAY: 20 + +jobs: + build: + runs-on: ubuntu-latest + services: + registry: + image: registry:2 + ports: + - 5000:5000 + steps: + - uses: actions/checkout@master + + # Connect to Azure Container registry (ACR) + - uses: azure/docker-login@v1 + with: + login-server: ${{ env.REGISTRY_NAME }}.azurecr.io + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + + # Container build + - run: | + docker build -f Dockerfile -t localhost:5000/kerberos-injector:${{ github.sha }} . + docker push localhost:5000/kerberos-injector:${{ github.sha }} + docker image prune + + # Scan image for vulnerabilities + - name: Aqua Security Trivy image scan + run: | + curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin ${{ env.TRIVY_VERSION }} + + set +e # Lets trivy return an error without it being fatal + + for ((i=0; i<${{ env.TRIVY_MAX_RETRIES }}; i++)); do + echo "Attempt $((i + 1)) of ${{ env.TRIVY_MAX_RETRIES }}..." + + trivy image \ + --db-repository ${{ env.TRIVY_DATABASES }} \ + --java-db-repository ${{ env.TRIVY_JAVA_DATABASES }} \ + localhost:5000/kerberos-injector:${{ github.sha }} \ + --exit-code 10 --timeout=20m --scanners vuln --severity CRITICAL + EXIT_CODE=$? + + if [[ $EXIT_CODE -eq 0 ]]; then + echo "Trivy scan completed successfully." + exit 0 + elif [[ $EXIT_CODE -eq 10 ]]; then + echo "Trivy scan completed successfully. Some vulnerabilities were found." + exit 10 + elif [[ $i -lt $(( ${{ env.TRIVY_MAX_RETRIES }} - 1)) ]]; then + echo "Encountered unexpected error. Retrying in ${{ env.TRIVY_RETRY_DELAY }} seconds..." + sleep ${{ env.TRIVY_RETRY_DELAY }} + else + echo "Unexpected error persists after ${{ env.TRIVY_MAX_RETRIES }} attempts. Exiting." + exit 1 + fi + done + + - name: Test if we should push to ACR + id: should-i-push + if: | + github.event_name == 'push' || + ( + github.event_name == 'pull_request' && + contains( github.event.pull_request.labels.*.name, 'auto-deploy') + ) + run: echo 'boolean=true' >> $GITHUB_OUTPUT + + - name: Push image to registry + if: steps.should-i-push.outputs.boolean == 'true' + run: | + docker pull localhost:5000/kerberos-injector:${{ github.sha }} + docker tag localhost:5000/kerberos-injector:${{ github.sha }} ${{ env.REGISTRY_NAME }}.azurecr.io/kerberos-injector:${{ github.sha }} + docker push ${{ env.REGISTRY_NAME }}.azurecr.io/kerberos-injector:${{ github.sha }} diff --git a/.github/workflows/publish.yaml b/.github/workflows/publish.yaml new file mode 100644 index 0000000..4762359 --- /dev/null +++ b/.github/workflows/publish.yaml @@ -0,0 +1,102 @@ +# This workflow: +# * Builds, tests, and scans all images +# * (optionally) pushes the images to ACR +# +# +# This workflow triggers on: +# * a push to main +# +# Image build/test/scan will run on any of the above events. +# Image push will run only if: +# * this is a push to main +# +# To configure this workflow: +# +# 1. Set up the following secrets in your workspace: +# a. REGISTRY_USERNAME with ACR username +# b. REGISTRY_PASSWORD with ACR Password +# +# 2. Change the values for the REGISTRY_NAME +name: build_and_push +on: + push: + branches: + - 'main' + +jobs: + # Any checks that run pre-build + pre-build-checks: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@master + build-push: + env: + REGISTRY_NAME: k8scc01covidacr + LOCAL_REPO: localhost:5000 + TRIVY_VERSION: "v0.57.0" + TRIVY_DATABASES: '"ghcr.io/aquasecurity/trivy-db:2","public.ecr.aws/aquasecurity/trivy-db"' + TRIVY_JAVA_DATABASES: '"ghcr.io/aquasecurity/trivy-java-db:1","public.ecr.aws/aquasecurity/trivy-java-db"' + TRIVY_MAX_RETRIES: 5 + TRIVY_RETRY_DELAY: 20 + needs: pre-build-checks + runs-on: ubuntu-latest + services: + registry: + image: registry:2 + ports: + - 5000:5000 + steps: + + - uses: actions/checkout@master + + # Connect to Azure Container registry (ACR) + - uses: azure/docker-login@v1 + with: + login-server: ${{ env.REGISTRY_NAME }}.azurecr.io + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + + - name: Build image + id: build-image + run: | + docker build -f Dockerfile -t localhost:5000/kerberos-injector:latest . + docker push localhost:5000/kerberos-injector:latest + docker image prune + + # Scan image for vulnerabilities + - name: Aqua Security Trivy image scan + run: | + curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin ${{ env.TRIVY_VERSION }} + + set +e # Lets trivy return an error without it being fatal + + for ((i=0; i<${{ env.TRIVY_MAX_RETRIES }}; i++)); do + echo "Attempt $((i + 1)) of ${{ env.TRIVY_MAX_RETRIES }}..." + + trivy image \ + --db-repository ${{ env.TRIVY_DATABASES }} \ + --java-db-repository ${{ env.TRIVY_JAVA_DATABASES }} \ + localhost:5000/kerberos-injector:latest \ + --exit-code 10 --timeout=20m --scanners vuln --severity CRITICAL + EXIT_CODE=$? + + if [[ $EXIT_CODE -eq 0 ]]; then + echo "Trivy scan completed successfully." + exit 0 + elif [[ $EXIT_CODE -eq 10 ]]; then + echo "Trivy scan completed successfully. Some vulnerabilities were found." + exit 0 + elif [[ $i -lt $(( ${{ env.TRIVY_MAX_RETRIES }} - 1)) ]]; then + echo "Encountered unexpected error. Retrying in ${{ env.TRIVY_RETRY_DELAY }} seconds..." + sleep ${{ env.TRIVY_RETRY_DELAY }} + else + echo "Unexpected error persists after ${{ env.TRIVY_MAX_RETRIES }} attempts. Exiting." + exit 1 + fi + done + + - name: Push image to registry + run: | + docker pull localhost:5000/kerberos-injector:latest + docker tag localhost:5000/kerberos-injector:latest ${{ env.REGISTRY_NAME }}.azurecr.io/kerberos-injector:${{ github.sha }} + docker push ${{ env.REGISTRY_NAME }}.azurecr.io/kerberos-injector:${{ github.sha }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4b3efd3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,18 @@ +# Binaries for programs and plugins +*.exe +*.dll +*.so +*.dylib + +# Test binary, build with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +vendor/* + +build/_output + +# GOPATH +.go \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..d438790 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,31 @@ +# Build the sidecar-injector binary +FROM golang:1.22 AS builder + +WORKDIR /workspace +# Copy the Go Modules manifests +COPY go.mod go.mod +COPY go.sum go.sum +# cache deps before building and copying source so that we don't need to re-download as much +# and so that source changes don't invalidate our downloaded layer +RUN go mod download + +# Copy the go source +COPY cmd/ cmd/ + +# Build +RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -a -o kerberos-sidecar-injector ./cmd + + +FROM alpine:latest + +# install curl for prestop script +RUN apk --no-cache add curl + +WORKDIR / + +# install binary +COPY --from=builder /workspace/kerberos-sidecar-injector . + +USER 65532:65532 + +ENTRYPOINT ["/kerberos-sidecar-injector"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..5010463 --- /dev/null +++ b/README.md @@ -0,0 +1,37 @@ +# filer-sidecar-injector + +This is forked off of the repo [kube-sidecar-injector](https://github.com/morvencao/kube-sidecar-injector) and was a repo used for [a tutorial at Medium](https://medium.com/ibm-cloud/diving-into-kubernetes-mutatingadmissionwebhook-6ef3c5695f74) to create a Kubernetes [MutatingAdmissionWebhook](https://kubernetes.io/docs/admin/admission-controllers/#mutatingadmissionwebhook-beta-in-19) that injects a nginx sidecar container into pod prior to persistence of the object. + +## Forked for Filer usage +Specifically for use with Filers. + +## Mutating the Pod +This webhook intercepts `pod` create requests and will `jsonpatch` the spec. Whether or not to mutate the pod spec happens in the `mutate` function. If the user namespace does not have an `existing-shares` configmap, or the pod does not have the `notebook-name` label present then it will not mutate and `inject` the filer sidecars. + +## Creating the jsonpatch +This is all done in the `createPatch` function. The very first thing that is done is determine if the pod _already has a volume_. This is because we do not want to overwrite any existing volumes in the `jsonpatch` as adding a new entry is very different from appending one. +From there the `existing-shares` configmap is iterated through in order to create a new sidecar spec for each entry. + +### Getting the values to use in the json patch +For the sidecar spec we have to use the `filer-sidecar-injector-json` configmap object from the `das` namespace, this works as the model / structure that we will modify and inject into the `pod` spec. + +We also need to get the bucket url, name, secret and access key for the particular svm. The bucket url is taken from the `filers-list` cm in the `das` namespace that is read in at injector startup. The bucket name is taken from the `existing-shares` cm and is put through the same hashing function used when creating the bucket in order to mount to the correct one. The secret and access keys are read in from a secret in the user's namespace. If any of these key values are empty then the sidecar will skip as the mounting would just fail. + +### Inserting the values +Using the json template that we deep copy (to avoid modifying the same one over and over again and thus only getting the last changes), we substitute the values in and call various `addX` or `updateX` functions whose only purpose is to return a `[]patchOperation`. These are self explanatory but we will note any exceptional cases below. + +### updateWorkingVolumeMounts +This function adds a volume mount to the user container spec. To determine if we are modifying the correct container we use the `NB_PREFIX` environment variable which is present and if you are testing with a podspec ensure this variable is there. + +### updateUserEnvVars +The sidecar injector will also insert environment variables that users can leverage with the `minio client` or `mc`. These are inserted at the notebook container level so they may use them from within their notebook. This also relies on the `NB_PREFIX` environment variable. + +### Extra Quirks +When retrieving the secrets, we need to replace any `_`'s with `-`'s as k8s resources do not like underscores, however, when creating the user environment variables those need to have underscores, as linux works better with underscores. + +We also must limit the length of the names in the spec. There is a hard 64 character limit and currently to avoid collision we hash the name and use it. A better fix for this will be tracked in [BTIS-528](https://jirab.statcan.ca/browse/BTIS-528) + +We built in a [retry on failure](https://github.com/StatCan/filer-sidecar-injector/pull/13) command for `goofys` as it is currently unclear why goofys sometimes fails to mount, but in general having it retry a few times seems to fix things with more investigation being done in [BTIS-523](https://jirab.statcan.ca/browse/BTIS-523) + +### Building and Deploying for testing +Create a PR with the `auto-deploy` label, and after the image has successfully pushed to the ACR, go to the `netapp` application in das argocd and turn off autosync and update the `filer-sidecar-injector` image tag with the pushed image. Start up a notebook and ensure it patches correctly. diff --git a/cmd/cert.go b/cmd/cert.go new file mode 100644 index 0000000..5749129 --- /dev/null +++ b/cmd/cert.go @@ -0,0 +1,90 @@ +package main + +import ( + "bytes" + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "math/big" + "time" +) + +// generateCert generate a self-signed CA for given organization +// and sign certificate with the CA for given common name and dns names +// it resurns the CA, certificate and private key in PEM format +func generateCert(orgs, dnsNames []string, commonName string) (*bytes.Buffer, *bytes.Buffer, *bytes.Buffer, error) { + // init CA config + ca := &x509.Certificate{ + SerialNumber: big.NewInt(2022), + Subject: pkix.Name{Organization: orgs}, + NotBefore: time.Now(), + NotAfter: time.Now().AddDate(1, 0, 0), // expired in 1 year + IsCA: true, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}, + KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, + BasicConstraintsValid: true, + } + + // generate private key for CA + caPrivateKey, err := rsa.GenerateKey(rand.Reader, 4096) + if err != nil { + return nil, nil, nil, err + } + + // create the CA certificate + caBytes, err := x509.CreateCertificate(rand.Reader, ca, ca, &caPrivateKey.PublicKey, caPrivateKey) + if err != nil { + return nil, nil, nil, err + } + + // CA certificate with PEM encoded + caPEM := new(bytes.Buffer) + _ = pem.Encode(caPEM, &pem.Block{ + Type: "CERTIFICATE", + Bytes: caBytes, + }) + + // new certificate config + newCert := &x509.Certificate{ + DNSNames: dnsNames, + SerialNumber: big.NewInt(1024), + Subject: pkix.Name{ + CommonName: commonName, + Organization: orgs, + }, + NotBefore: time.Now(), + NotAfter: time.Now().AddDate(1, 0, 0), // expired in 1 year + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}, + KeyUsage: x509.KeyUsageDigitalSignature, + } + + // generate new private key + newPrivateKey, err := rsa.GenerateKey(rand.Reader, 4096) + if err != nil { + return nil, nil, nil, err + } + + // sign the new certificate + newCertBytes, err := x509.CreateCertificate(rand.Reader, newCert, ca, &newPrivateKey.PublicKey, caPrivateKey) + if err != nil { + return nil, nil, nil, err + } + + // new certificate with PEM encoded + newCertPEM := new(bytes.Buffer) + _ = pem.Encode(newCertPEM, &pem.Block{ + Type: "CERTIFICATE", + Bytes: newCertBytes, + }) + + // new private key with PEM encoded + newPrivateKeyPEM := new(bytes.Buffer) + _ = pem.Encode(newPrivateKeyPEM, &pem.Block{ + Type: "RSA PRIVATE KEY", + Bytes: x509.MarshalPKCS1PrivateKey(newPrivateKey), + }) + + return caPEM, newCertPEM, newPrivateKeyPEM, nil +} diff --git a/cmd/main.go b/cmd/main.go new file mode 100644 index 0000000..e4e374b --- /dev/null +++ b/cmd/main.go @@ -0,0 +1,102 @@ +package main + +import ( + "context" + "crypto/tls" + "flag" + "fmt" + "log" + "net/http" + "os" + "os/signal" + "syscall" +) + +var ( + infoLogger *log.Logger + warningLogger *log.Logger + errorLogger *log.Logger +) + +var ( + port int + sidecarConfigFile string + webhookNamespace, webhookServiceName string +) + +func init() { + // init loggers + infoLogger = log.New(os.Stderr, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile) + warningLogger = log.New(os.Stderr, "WARNING: ", log.Ldate|log.Ltime|log.Lshortfile) + errorLogger = log.New(os.Stderr, "ERROR: ", log.Ldate|log.Ltime|log.Lshortfile) + + // webhook server running namespace + webhookNamespace = os.Getenv("POD_NAMESPACE") +} + +func main() { + // init command flags + flag.IntVar(&port, "port", 8443, "Webhook server port.") + flag.StringVar(&webhookServiceName, "service-name", "kerberos-sidecar-injector", "Webhook service name.") + flag.StringVar(&sidecarConfigFile, "sidecar-config-file", "/etc/webhook/config/sidecarconfig.json", "Sidecar injector configuration file.") + // flag.StringVar(&certFile, "tlsCertFile", "/etc/webhook/certs/cert.pem", "x509 Certificate file.") + // flag.StringVar(&keyFile, "tlsKeyFile", "/etc/webhook/certs/key.pem", "x509 private key file.") + flag.Parse() + + dnsNames := []string{ + webhookServiceName, + webhookServiceName + "." + webhookNamespace, + webhookServiceName + "." + webhookNamespace + ".svc", + } + commonName := webhookServiceName + "." + webhookNamespace + ".svc" + + org := "das-zone.statcan" + caPEM, certPEM, certKeyPEM, err := generateCert([]string{org}, dnsNames, commonName) + if err != nil { + errorLogger.Fatalf("Failed to generate ca and certificate key pair: %v", err) + } + + pair, err := tls.X509KeyPair(certPEM.Bytes(), certKeyPEM.Bytes()) + if err != nil { + errorLogger.Fatalf("Failed to load certificate key pair: %v", err) + } + + sidecarConfig, err := loadConfig(sidecarConfigFile) + if err != nil { + errorLogger.Fatalf("Failed to load configuration: %v", err) + } + + // create or update the mutatingwebhookconfiguration + err = createOrUpdateMutatingWebhookConfiguration(caPEM, webhookServiceName, webhookNamespace) + if err != nil { + errorLogger.Fatalf("Failed to create or update the mutating webhook configuration: %v", err) + } + + whsvr := &WebhookServer{ + sidecarConfig: sidecarConfig, + server: &http.Server{ + Addr: fmt.Sprintf(":%v", port), + TLSConfig: &tls.Config{Certificates: []tls.Certificate{pair}}, + }, + } + + // define http server and server handler + mux := http.NewServeMux() + mux.HandleFunc(webhookInjectPath, whsvr.serve) + whsvr.server.Handler = mux + + // start webhook server in new rountine + go func() { + if err := whsvr.server.ListenAndServeTLS("", ""); err != nil { + errorLogger.Fatalf("Failed to listen and serve webhook server: %v", err) + } + }() + + // listening OS shutdown singal + signalChan := make(chan os.Signal, 1) + signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM) + <-signalChan + + infoLogger.Printf("Got OS shutdown signal, shutting down webhook server gracefully...") + whsvr.server.Shutdown(context.Background()) +} diff --git a/cmd/webhook.go b/cmd/webhook.go new file mode 100644 index 0000000..bc7081a --- /dev/null +++ b/cmd/webhook.go @@ -0,0 +1,380 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "strings" + + "github.com/barkimedes/go-deepcopy" + admissionv1 "k8s.io/api/admission/v1" + corev1 "k8s.io/api/core/v1" + k8serrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/serializer" + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/rest" +) + +var ( + runtimeScheme = runtime.NewScheme() + codecs = serializer.NewCodecFactory(runtimeScheme) + deserializer = codecs.UniversalDeserializer() +) + +const ( + admissionWebhookAnnotationInjectKey = "kerberos-injector-webhook.das-zone.statcan/inject" + admissionWebhookAnnotationStatusKey = "kerberos-injector-webhook.das-zone.statcan/status" + + kerberosSecret = "kerberos-keytab" +) + +type WebhookServer struct { + sidecarConfig *Config + server *http.Server +} + +// Use for easy adding of values +type M map[string]interface{} + +// Webhook Server parameters +type WhSvrParameters struct { + port int // webhook server port + certFile string // path to the x509 certificate for https + keyFile string // path to the x509 private key matching `CertFile` + sidecarCfgFile string // path to sidecar injector configuration file +} + +type Config struct { + Containers []corev1.Container `json:"containers"` + Volumes []corev1.Volume `json:"volumes"` +} + +type patchOperation struct { + Op string `json:"op"` + Path string `json:"path"` + Value interface{} `json:"value,omitempty"` +} + +func loadConfig(configFile string) (*Config, error) { + data, err := os.ReadFile(configFile) + if err != nil { + return nil, err + } + infoLogger.Printf("New configuration: sha256sum %x", sha256.Sum256(data)) + + var cfg Config + if err := json.Unmarshal(data, &cfg); err != nil { + return nil, err + } + + return &cfg, nil +} + +// Check whether the target resoured need to be mutated +func mutationRequired(metadata *metav1.ObjectMeta) bool { + // Pod must have that label to get picked up + if _, ok := metadata.Labels["notebook-name"]; !ok { + infoLogger.Printf("Skip mutation since not a notebook pod") + return false + } + annotations := metadata.GetAnnotations() + if annotations == nil { + annotations = map[string]string{} + } + + status := annotations[admissionWebhookAnnotationStatusKey] + + // determine whether to perform mutation based on annotation for the target resource + var required bool + if strings.ToLower(status) == "injected" { + required = false + } else { + switch strings.ToLower(annotations[admissionWebhookAnnotationInjectKey]) { + default: + required = true + case "n", "not", "false", "off": + required = false + } + } + + infoLogger.Printf("Mutation policy for %v/%v: status: %q required:%v", metadata.Namespace, metadata.Name, status, required) + return required +} + +func addContainer(target, added []corev1.Container, basePath string) (patch []patchOperation) { + first := len(target) == 0 + var value interface{} + for _, add := range added { + value = add + path := basePath + if first { + first = false + value = []corev1.Container{add} + } else { + path = path + "/-" + } + patch = append(patch, patchOperation{ + Op: "add", + Path: path, + Value: value, + }) + } + return patch +} + +func addVolume(target, added []corev1.Volume, basePath string) (patch []patchOperation) { + first := len(target) == 0 + var value interface{} + for _, add := range added { + value = add + path := basePath + if first { + first = false + value = []corev1.Volume{add} + } else { + path = path + "/-" + } + patch = append(patch, patchOperation{ + Op: "add", + Path: path, + Value: value, + }) + } + return patch +} + +func updateAnnotation(target map[string]string, added map[string]string) (patch []patchOperation) { + for key, value := range added { + if target == nil || target[key] == "" { + target = map[string]string{} + patch = append(patch, patchOperation{ + Op: "add", + Path: "/metadata/annotations", + Value: map[string]string{ + key: value, + }, + }) + } else { + patch = append(patch, patchOperation{ + Op: "replace", + Path: "/metadata/annotations/" + key, + Value: value, + }) + } + } + return patch +} + +// This will ADD a volumeMount to the user container spec +func updateWorkingVolumeMounts(targetContainerSpec []corev1.Container, isFirst bool) (patch []patchOperation) { + for key := range targetContainerSpec { + // if there is an envVar that has NB_PREFIX in it then we are in the right container + for envVars := range targetContainerSpec[key].Env { + if targetContainerSpec[key].Env[envVars].Name == "NB_PREFIX" { + var mapSlice []M + credsCache := M{"name": "kerberos-credential-cache", + "mountPath": "/dev/shm"} + kerbConf := M{"name": "kerberos-conf", + "mountPath": "/etc/krb5.conf", + "subPath": "krb5.conf"} + mapSlice = append(mapSlice, credsCache, kerbConf) + + if isFirst { + patch = append(patch, patchOperation{ + Op: "add", + // the path for only the first value + Path: "/spec/containers/0/volumeMounts", + Value: mapSlice, + }) + } else { + patch = append(patch, patchOperation{ + Op: "add", + // Now that there is one that has created an array, this can just go after it. + Path: "/spec/containers/0/volumeMounts/-", + Value: credsCache, + }) + patch = append(patch, patchOperation{ + Op: "add", + // Now that there is one that has created an array, this can just go after it. + Path: "/spec/containers/0/volumeMounts/-", + Value: kerbConf, + }) + } + } + } + } + return patch +} + +// createPatch function handles the mutation patch creation +func createPatch(pod *corev1.Pod, sidecarConfigTemplate *Config, annotations map[string]string) ([]byte, error) { + var patch []patchOperation + isFirstVol := true + // We don't want to overwrite any mounted volumes + if len(pod.Spec.Volumes) > 0 { + isFirstVol = false + } + + // Deep copy to avoid changes in original sidecar config + tempSidecarConfig, _ := deepcopy.Anything(sidecarConfigTemplate) + sidecarConfig := tempSidecarConfig.(*Config) + + // Add container and volume to the patch + patch = append(patch, addContainer(pod.Spec.Containers, sidecarConfig.Containers, "/spec/containers")...) + patch = append(patch, addVolume(pod.Spec.Volumes, sidecarConfig.Volumes, "/spec/volumes")...) + patch = append(patch, updateAnnotation(pod.Annotations, annotations)...) + patch = append(patch, updateWorkingVolumeMounts(pod.Spec.Containers, isFirstVol)...) + + return json.Marshal(patch) +} + +// main mutation process +func (whsvr *WebhookServer) mutate(ar *admissionv1.AdmissionReview, clientset *kubernetes.Clientset) *admissionv1.AdmissionResponse { + req := ar.Request + var pod corev1.Pod + if err := json.Unmarshal(req.Object.Raw, &pod); err != nil { + warningLogger.Printf("Could not unmarshal raw object: %v", err) + return &admissionv1.AdmissionResponse{ + Result: &metav1.Status{ + Message: err.Error(), + }, + } + } + + infoLogger.Printf("AdmissionReview for Kind=%v, Namespace=%v Name=%v (%v) UID=%v patchOperation=%v UserInfo=%v", + req.Kind, req.Namespace, req.Name, pod.Name, req.UID, req.Operation, req.UserInfo) + + // Retrieve the kerberos secret for pod namespace + _, errKerbSecret := clientset.CoreV1().Secrets(pod.Namespace).Get(context.Background(), kerberosSecret, metav1.GetOptions{}) + + // determine whether to perform mutation + if k8serrors.IsNotFound(errKerbSecret) || !mutationRequired(&pod.ObjectMeta) { + infoLogger.Printf("Skipping mutation for %s/%s due to policy check", pod.Namespace, pod.Name) + return &admissionv1.AdmissionResponse{ + Allowed: true, + } + } + + annotations := map[string]string{admissionWebhookAnnotationStatusKey: "injected"} + patchBytes, err := createPatch(&pod, whsvr.sidecarConfig, annotations) + if err != nil { + return &admissionv1.AdmissionResponse{ + Result: &metav1.Status{ + Message: err.Error(), + }, + } + } + + infoLogger.Printf("AdmissionResponse: patch=%v\n", string(patchBytes)) + return &admissionv1.AdmissionResponse{ + Allowed: true, + Patch: patchBytes, + PatchType: func() *admissionv1.PatchType { + pt := admissionv1.PatchTypeJSONPatch + return &pt + }(), + } +} + +// Serve method for webhook server +func (whsvr *WebhookServer) serve(w http.ResponseWriter, r *http.Request) { + // Creates the in-cluster config + config, err := rest.InClusterConfig() + if err != nil { + panic(err.Error()) + } + + // Creates the clientset + clientset, err := kubernetes.NewForConfig(config) + if err != nil { + panic(err.Error()) + } + + var body []byte + if r.Body != nil { + if data, err := io.ReadAll(r.Body); err == nil { + body = data + } + } + if len(body) == 0 { + warningLogger.Println("empty body") + http.Error(w, "empty body", http.StatusBadRequest) + return + } + + // verify the content type is accurate + contentType := r.Header.Get("Content-Type") + if contentType != "application/json" { + warningLogger.Printf("Content-Type=%s, expect application/json", contentType) + http.Error(w, "invalid Content-Type, expect `application/json`", http.StatusUnsupportedMediaType) + return + } + + var admissionResponse *admissionv1.AdmissionResponse + ar := admissionv1.AdmissionReview{} + if _, _, err := deserializer.Decode(body, nil, &ar); err != nil { + warningLogger.Printf("Can't decode body: %v", err) + admissionResponse = &admissionv1.AdmissionResponse{ + Result: &metav1.Status{ + Message: err.Error(), + }, + } + } else { + admissionResponse = whsvr.mutate(&ar, clientset) + } + + admissionReview := admissionv1.AdmissionReview{ + TypeMeta: metav1.TypeMeta{ + APIVersion: "admission.k8s.io/v1", + Kind: "AdmissionReview", + }, + } + if admissionResponse != nil { + admissionReview.Response = admissionResponse + if ar.Request != nil { + admissionReview.Response.UID = ar.Request.UID + } + } + + resp, err := json.Marshal(admissionReview) + if err != nil { + warningLogger.Printf("Can't encode response: %v", err) + http.Error(w, fmt.Sprintf("could not encode response: %v", err), http.StatusInternalServerError) + } + infoLogger.Printf("Ready to write reponse ...") + if _, err := w.Write(resp); err != nil { + warningLogger.Printf("Can't write response: %v", err) + http.Error(w, fmt.Sprintf("could not write response: %v", err), http.StatusInternalServerError) + } +} + +// func getSvmInfoList(client *kubernetes.Clientset) (map[string]SvmInfo, error) { +// klog.Infof("Getting filers list...") + +// filerListCM, err := client.CoreV1().ConfigMaps("das").Get(context.Background(), "filers-list", metav1.GetOptions{}) +// if err != nil { +// klog.Errorf("Error occured while getting the filers list: %v", err) +// return nil, err +// } + +// var svmInfoList []SvmInfo +// err = json.Unmarshal([]byte(filerListCM.Data["filers"]), &svmInfoList) +// if err != nil { +// klog.Errorf("Error occured while unmarshalling the filers list: %v", err) +// return nil, err +// } + +// //format the data into something a bit more usable +// filerList := map[string]SvmInfo{} +// for _, svm := range svmInfoList { +// filerList[svm.Vserver] = svm +// } + +// return filerList, nil +// } diff --git a/cmd/webhookconfig.go b/cmd/webhookconfig.go new file mode 100644 index 0000000..6af82d0 --- /dev/null +++ b/cmd/webhookconfig.go @@ -0,0 +1,108 @@ +package main + +import ( + "bytes" + "context" + "os" + "reflect" + + admissionregistrationv1 "k8s.io/api/admissionregistration/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/tools/clientcmd" +) + +var ( + webhookConfigName = "kerberos-sidecar-injector-webhook" + webhookInjectPath = "/inject" +) + +func createOrUpdateMutatingWebhookConfiguration(caPEM *bytes.Buffer, webhookService, webhookNamespace string) error { + infoLogger.Println("Initializing the kube client...") + + kubeconfig := os.Getenv("KUBECONFIG") + config, err := clientcmd.BuildConfigFromFlags("", kubeconfig) + if err != nil { + return err + } + clientset, err := kubernetes.NewForConfig(config) + if err != nil { + return err + } + mutatingWebhookConfigV1Client := clientset.AdmissionregistrationV1() + + infoLogger.Printf("Creating or updating the mutatingwebhookconfiguration: %s", webhookConfigName) + fail := admissionregistrationv1.Fail + sideEffect := admissionregistrationv1.SideEffectClassNone + mutatingWebhookConfig := &admissionregistrationv1.MutatingWebhookConfiguration{ + ObjectMeta: metav1.ObjectMeta{ + Name: webhookConfigName, + }, + Webhooks: []admissionregistrationv1.MutatingWebhook{{ + Name: "kerberos-sidecar-injector.das-zone.statcan", + AdmissionReviewVersions: []string{"v1", "v1beta1"}, + SideEffects: &sideEffect, + ClientConfig: admissionregistrationv1.WebhookClientConfig{ + CABundle: caPEM.Bytes(), // self-generated CA for the webhook + Service: &admissionregistrationv1.ServiceReference{ + Name: webhookService, + Namespace: webhookNamespace, + Path: &webhookInjectPath, + }, + }, + Rules: []admissionregistrationv1.RuleWithOperations{ + { + Operations: []admissionregistrationv1.OperationType{ + admissionregistrationv1.Create, + admissionregistrationv1.Update, + }, + Rule: admissionregistrationv1.Rule{ + APIGroups: []string{""}, + APIVersions: []string{"v1"}, + Resources: []string{"pods"}, + }, + }, + }, + NamespaceSelector: &metav1.LabelSelector{ + MatchLabels: map[string]string{ + "kerberos-sidecar-injection": "enabled", + }, + }, + FailurePolicy: &fail, + }}, + } + + foundWebhookConfig, err := mutatingWebhookConfigV1Client.MutatingWebhookConfigurations().Get(context.TODO(), webhookConfigName, metav1.GetOptions{}) + if err != nil && apierrors.IsNotFound(err) { + if _, err := mutatingWebhookConfigV1Client.MutatingWebhookConfigurations().Create(context.TODO(), mutatingWebhookConfig, metav1.CreateOptions{}); err != nil { + warningLogger.Printf("Failed to create the mutatingwebhookconfiguration: %s", webhookConfigName) + return err + } + infoLogger.Printf("Created mutatingwebhookconfiguration: %s", webhookConfigName) + } else if err != nil { + warningLogger.Printf("Failed to check the mutatingwebhookconfiguration: %s", webhookConfigName) + return err + } else { + // there is an existing mutatingWebhookConfiguration + if len(foundWebhookConfig.Webhooks) != len(mutatingWebhookConfig.Webhooks) || + !(foundWebhookConfig.Webhooks[0].Name == mutatingWebhookConfig.Webhooks[0].Name && + reflect.DeepEqual(foundWebhookConfig.Webhooks[0].AdmissionReviewVersions, mutatingWebhookConfig.Webhooks[0].AdmissionReviewVersions) && + reflect.DeepEqual(foundWebhookConfig.Webhooks[0].SideEffects, mutatingWebhookConfig.Webhooks[0].SideEffects) && + reflect.DeepEqual(foundWebhookConfig.Webhooks[0].FailurePolicy, mutatingWebhookConfig.Webhooks[0].FailurePolicy) && + reflect.DeepEqual(foundWebhookConfig.Webhooks[0].Rules, mutatingWebhookConfig.Webhooks[0].Rules) && + reflect.DeepEqual(foundWebhookConfig.Webhooks[0].NamespaceSelector, mutatingWebhookConfig.Webhooks[0].NamespaceSelector) && + reflect.DeepEqual(foundWebhookConfig.Webhooks[0].ClientConfig.CABundle, mutatingWebhookConfig.Webhooks[0].ClientConfig.CABundle) && + reflect.DeepEqual(foundWebhookConfig.Webhooks[0].ClientConfig.Service, mutatingWebhookConfig.Webhooks[0].ClientConfig.Service)) { + mutatingWebhookConfig.ObjectMeta.ResourceVersion = foundWebhookConfig.ObjectMeta.ResourceVersion + if _, err := mutatingWebhookConfigV1Client.MutatingWebhookConfigurations().Update(context.TODO(), mutatingWebhookConfig, metav1.UpdateOptions{}); err != nil { + warningLogger.Printf("Failed to update the mutatingwebhookconfiguration: %s", webhookConfigName) + return err + } + infoLogger.Printf("Updated the mutatingwebhookconfiguration: %s", webhookConfigName) + } + infoLogger.Printf("The mutatingwebhookconfiguration: %s already exists and has no change", webhookConfigName) + } + + return nil +} diff --git a/deploy/clusterrole.yaml b/deploy/clusterrole.yaml new file mode 100644 index 0000000..21e7d87 --- /dev/null +++ b/deploy/clusterrole.yaml @@ -0,0 +1,13 @@ +kind: ClusterRole +apiVersion: rbac.authorization.k8s.io/v1 +metadata: + name: kerberos-sidecar-injector + labels: + app: kerberos-sidecar-injector +rules: +- apiGroups: ["admissionregistration.k8s.io"] + resources: ["mutatingwebhookconfigurations"] + verbs: ["create", "get", "delete", "list", "patch", "update", "watch"] +- apiGroups: [""] + resources: ["secrets"] + verbs: ["get", "list", "watch"] diff --git a/deploy/clusterrolebinding.yaml b/deploy/clusterrolebinding.yaml new file mode 100644 index 0000000..c76ee80 --- /dev/null +++ b/deploy/clusterrolebinding.yaml @@ -0,0 +1,14 @@ +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: kerberos-sidecar-injector + labels: + app: kerberos-sidecar-injector +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: kerberos-sidecar-injector +subjects: +- kind: ServiceAccount + name: kerberos-sidecar-injector + namespace: das diff --git a/deploy/configmap.yaml b/deploy/configmap.yaml new file mode 100644 index 0000000..076c860 --- /dev/null +++ b/deploy/configmap.yaml @@ -0,0 +1,64 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: kerberos-sidecar-injector-json + namespace: das + labels: + app: kerberos-sidecar-injector +data: + sidecarconfig.json: | + { + "containers": [ + { + "name": "kerberos-sidecar", + "image": "artifactory.cloud.statcan.ca/das-aaw-docker/kerberos-sidecar:latest", + "imagePullPolicy": "IfNotPresent", + "volumeMounts": [ + { + "name": "kerberos-credential-cache", + "mountPath": "/dev/shm" + }, + { + "name": "kerberos-conf", + "mountPath": "/etc/krb5.conf", + "subPath": "krb5.conf" + }, + { + "mountPath": "/krb5", + "name": "kerberos-keytab" + } + ], + "livenessProbe": { + "exec": { + "command": [ + "test", + "-f", + "/dev/shm/ccache" + ] + }, + "initialDelaySeconds": 2, + "periodSeconds": 60 + } + } + ], + "volumes": [ + { + "name": "kerberos-credential-cache", + "emptyDir": { + "medium": "Memory" + } + }, + { + "name": "kerberos-keytab", + "secret": { + "secretName": "kerberos-keytab" + } + }, + { + "name": "kerberos-conf", + "configMap": { + "name": "kerberos-sidecar-config" + } + } + ] + } \ No newline at end of file diff --git a/deploy/deployment.yaml b/deploy/deployment.yaml new file mode 100644 index 0000000..349b185 --- /dev/null +++ b/deploy/deployment.yaml @@ -0,0 +1,42 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: kerberos-sidecar-injector + # Must be in a ns without istio + namespace: das + labels: + app: kerberos-sidecar-injector +spec: + replicas: 1 + selector: + matchLabels: + app: kerberos-sidecar-injector + template: + metadata: + labels: + app: kerberos-sidecar-injector + spec: + serviceAccountName: kerberos-sidecar-injector + containers: + - name: kerberos-sidecar-injector + image: artifactory.cloud.statcan.ca/das-aaw-docker/kerberos-injector:latest + imagePullPolicy: Always + args: + - -service-name=kerberos-sidecar-injector + - -sidecar-config-file=/etc/webhook/config/sidecarconfig.json + env: + - name: POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + lifecycle: + preStop: + exec: + command: ["/bin/sh", "-c", "/prestop.sh"] + volumeMounts: + - name: webhook-config + mountPath: /etc/webhook/config + volumes: + - name: webhook-config + configMap: + name: kerberos-sidecar-injector-json \ No newline at end of file diff --git a/deploy/kustomization.yaml b/deploy/kustomization.yaml new file mode 100644 index 0000000..9536585 --- /dev/null +++ b/deploy/kustomization.yaml @@ -0,0 +1,17 @@ +namespace: das + +resources: +- clusterrole.yaml +- clusterrolebinding.yaml +- configmap.yaml +- deployment.yaml +- service.yaml +- serviceaccount.yaml + +images: +- name: kerberos-sidecar-injector +# must update this anways + newName: artifactory.cloud.statcan.ca/das-aaw-docker/kerberos-injector + newTag: latest +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization diff --git a/deploy/service.yaml b/deploy/service.yaml new file mode 100644 index 0000000..1a1e1c1 --- /dev/null +++ b/deploy/service.yaml @@ -0,0 +1,13 @@ +apiVersion: v1 +kind: Service +metadata: + name: kerberos-sidecar-injector + namespace: das + labels: + app: kerberos-sidecar-injector +spec: + ports: + - port: 443 + targetPort: 8443 + selector: + app: kerberos-sidecar-injector diff --git a/deploy/serviceaccount.yaml b/deploy/serviceaccount.yaml new file mode 100644 index 0000000..b67bfe4 --- /dev/null +++ b/deploy/serviceaccount.yaml @@ -0,0 +1,7 @@ +apiVersion: v1 +kind: ServiceAccount +metadata: + name: kerberos-sidecar-injector + namespace: das + labels: + app: kerberos-sidecar-injector diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..256cfb7 --- /dev/null +++ b/go.mod @@ -0,0 +1,50 @@ +module github.com/morvencao/kube-sidecar-injector + +go 1.22.0 + +toolchain go1.22.2 + +require ( + gopkg.in/yaml.v2 v2.4.0 + k8s.io/api v0.30.0 + k8s.io/apimachinery v0.30.0 + k8s.io/client-go v0.30.0 +) + +require ( + github.com/barkimedes/go-deepcopy v0.0.0-20220514131651-17c30cfc62df + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/emicklei/go-restful/v3 v3.12.0 // indirect + github.com/go-logr/logr v1.4.1 // indirect + github.com/go-openapi/jsonpointer v0.21.0 // indirect + github.com/go-openapi/jsonreference v0.21.0 // indirect + github.com/go-openapi/swag v0.23.0 // indirect + github.com/gogo/protobuf v1.3.2 // indirect + github.com/golang/protobuf v1.5.4 // indirect + github.com/google/gnostic-models v0.6.8 // indirect + github.com/google/gofuzz v1.2.0 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/imdario/mergo v0.3.16 // indirect + github.com/josharian/intern v1.0.0 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/mailru/easyjson v0.7.7 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect + github.com/spf13/pflag v1.0.5 // indirect + golang.org/x/net v0.24.0 // indirect + golang.org/x/oauth2 v0.19.0 // indirect + golang.org/x/sys v0.19.0 // indirect + golang.org/x/term v0.19.0 // indirect + golang.org/x/text v0.14.0 // indirect + golang.org/x/time v0.5.0 // indirect + google.golang.org/protobuf v1.34.0 // indirect + gopkg.in/inf.v0 v0.9.1 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect + k8s.io/klog/v2 v2.120.1 // indirect + k8s.io/kube-openapi v0.0.0-20240430033511-f0e62f92d13f // indirect + k8s.io/utils v0.0.0-20240502163921-fe8a2dddb1d0 // indirect + sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect + sigs.k8s.io/structured-merge-diff/v4 v4.4.1 // indirect + sigs.k8s.io/yaml v1.4.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..00b1565 --- /dev/null +++ b/go.sum @@ -0,0 +1,140 @@ +github.com/barkimedes/go-deepcopy v0.0.0-20220514131651-17c30cfc62df h1:GSoSVRLoBaFpOOds6QyY1L8AX7uoY+Ln3BHc22W40X0= +github.com/barkimedes/go-deepcopy v0.0.0-20220514131651-17c30cfc62df/go.mod h1:hiVxq5OP2bUGBRNS3Z/bt/reCLFNbdcST6gISi1fiOM= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/emicklei/go-restful/v3 v3.12.0 h1:y2DdzBAURM29NFF94q6RaY4vjIH1rtwDapwQtU84iWk= +github.com/emicklei/go-restful/v3 v3.12.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= +github.com/go-logr/logr v1.4.1 h1:pKouT5E8xu9zeFC39JXRDukb6JFQPXM5p5I91188VAQ= +github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ= +github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY= +github.com/go-openapi/jsonreference v0.21.0 h1:Rs+Y7hSXT83Jacb7kFyjn4ijOuVGSvOdF2+tg1TRrwQ= +github.com/go-openapi/jsonreference v0.21.0/go.mod h1:LmZmgsrTkVg9LG4EaHeY8cBDslNPMo06cago5JNLkm4= +github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE= +github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ= +github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 h1:tfuBGBXKqDEevZMzYi5KSi8KkcZtzBcTgAUUtapy0OI= +github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= +github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= +github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/google/gnostic-models v0.6.8 h1:yo/ABAfM5IMRsS1VnXjTBvUb61tFIHozhlYvRgGre9I= +github.com/google/gnostic-models v0.6.8/go.mod h1:5n7qKqH0f5wFt+aWF8CW6pZLLNOfYuF5OpfBSENuI8U= +github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= +github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/pprof v0.0.0-20240424215950-a892ee059fd6 h1:k7nVchz72niMH6YLQNvHSdIE7iqsQxK1P41mySCvssg= +github.com/google/pprof v0.0.0-20240424215950-a892ee059fd6/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/imdario/mergo v0.3.16 h1:wwQJbIsHYGMUyLSPrEq1CT16AhnhNJQ51+4fdHUnCl4= +github.com/imdario/mergo v0.3.16/go.mod h1:WBLT9ZmE3lPoWsEzCh9LPo3TiwVN+ZKEjmz+hD27ysY= +github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= +github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= +github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= +github.com/onsi/ginkgo/v2 v2.17.2 h1:7eMhcy3GimbsA3hEnVKdw/PQM9XN9krpKVXsZdph0/g= +github.com/onsi/ginkgo/v2 v2.17.2/go.mod h1:nP2DPOQoNsQmsVyv5rDA8JkXQoCs6goXIvr/PRJ1eCc= +github.com/onsi/gomega v1.33.1 h1:dsYjIxxSR755MDmKVsaFQTE22ChNBcuuTWgkUDSubOk= +github.com/onsi/gomega v1.33.1/go.mod h1:U4R44UsT+9eLIaYRB2a5qajjtQYn0hauxvRm16AVYg0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= +github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w= +golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8= +golang.org/x/oauth2 v0.19.0 h1:9+E/EZBCbTLNrbN35fHv/a/d/mOBatymz1zbtQrXpIg= +golang.org/x/oauth2 v0.19.0/go.mod h1:vYi7skDa1x015PmRRYZ7+s1cWyPgrPiSYRe4rnsexc8= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o= +golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/term v0.19.0 h1:+ThwsDv+tYfnJFhF4L8jITxu1tdTWRTZpdsWgEgjL6Q= +golang.org/x/term v0.19.0/go.mod h1:2CuTdWZ7KHSQwUzKva0cbMg6q2DMI3Mmxp+gKJbskEk= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk= +golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.20.0 h1:hz/CVckiOxybQvFw6h7b/q80NTr9IUQb4s1IIzW7KNY= +golang.org/x/tools v0.20.0/go.mod h1:WvitBU7JJf6A4jOdg4S1tviW9bhUxkgeCui/0JHctQg= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/protobuf v1.34.0 h1:Qo/qEd2RZPCf2nKuorzksSknv0d3ERwp1vFG38gSmH4= +google.golang.org/protobuf v1.34.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= +gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +k8s.io/api v0.30.0 h1:siWhRq7cNjy2iHssOB9SCGNCl2spiF1dO3dABqZ8niA= +k8s.io/api v0.30.0/go.mod h1:OPlaYhoHs8EQ1ql0R/TsUgaRPhpKNxIMrKQfWUp8QSE= +k8s.io/apimachinery v0.30.0 h1:qxVPsyDM5XS96NIh9Oj6LavoVFYff/Pon9cZeDIkHHA= +k8s.io/apimachinery v0.30.0/go.mod h1:iexa2somDaxdnj7bha06bhb43Zpa6eWH8N8dbqVjTUc= +k8s.io/client-go v0.30.0 h1:sB1AGGlhY/o7KCyCEQ0bPWzYDL0pwOZO4vAtTSh/gJQ= +k8s.io/client-go v0.30.0/go.mod h1:g7li5O5256qe6TYdAMyX/otJqMhIiGgTapdLchhmOaY= +k8s.io/klog/v2 v2.120.1 h1:QXU6cPEOIslTGvZaXvFWiP9VKyeet3sawzTOvdXb4Vw= +k8s.io/klog/v2 v2.120.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE= +k8s.io/kube-openapi v0.0.0-20240430033511-f0e62f92d13f h1:0LQagt0gDpKqvIkAMPaRGcXawNMouPECM1+F9BVxEaM= +k8s.io/kube-openapi v0.0.0-20240430033511-f0e62f92d13f/go.mod h1:S9tOR0FxgyusSNR+MboCuiDpVWkAifZvaYI1Q2ubgro= +k8s.io/utils v0.0.0-20240502163921-fe8a2dddb1d0 h1:jgGTlFYnhF1PM1Ax/lAlxUPE+KfCIXHaathvJg1C3ak= +k8s.io/utils v0.0.0-20240502163921-fe8a2dddb1d0/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= +sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd h1:EDPBXCAspyGV4jQlpZSudPeMmr1bNJefnuqLsRAsHZo= +sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd/go.mod h1:B8JuhiUyNFVKdsE8h686QcCxMaH6HrOAZj4vswFpcB0= +sigs.k8s.io/structured-merge-diff/v4 v4.4.1 h1:150L+0vs/8DA78h1u02ooW1/fFq/Lwr+sGiqlzvrtq4= +sigs.k8s.io/structured-merge-diff/v4 v4.4.1/go.mod h1:N8hJocpFajUSSeSJ9bOZ77VzejKZaXsTtZo4/u7Io08= +sigs.k8s.io/yaml v1.4.0 h1:Mk1wCc2gy/F0THH0TAp1QYyJNzRm2KCLy3o5ASXVI5E= +sigs.k8s.io/yaml v1.4.0/go.mod h1:Ejl7/uTz7PSA4eKMyQCUTnhZYNmLIl+5c2lQPGR2BPY= diff --git a/prestop.sh b/prestop.sh new file mode 100644 index 0000000..7ecfbb8 --- /dev/null +++ b/prestop.sh @@ -0,0 +1,21 @@ +set -exo pipefail + +# Point to the internal API server hostname +APISERVER=https://kubernetes.default.svc + +# Path to ServiceAccount token +SERVICEACCOUNT=/var/run/secrets/kubernetes.io/serviceaccount + +# Read this Pod's namespace +NAMESPACE=$(cat ${SERVICEACCOUNT}/namespace) + +# Read the ServiceAccount bearer token +TOKEN=$(cat ${SERVICEACCOUNT}/token) + +# Reference the internal certificate authority (CA) +CACERT=${SERVICEACCOUNT}/ca.crt + +MutatingWebhookConfigurationName=sidecar-injector-webhook + +# Delete the validatingwebhookconfiguration with TOKEN +curl --cacert ${CACERT} --header "Authorization: Bearer ${TOKEN}" -X DELETE ${APISERVER}/apis/admissionregistration.k8s.io/v1/mutatingwebhookconfigurations/${MutatingWebhookConfigurationName}