├── .circleci └── config.yml ├── .dockerignore ├── .github ├── dependabot.yml ├── pull_request_template.md └── workflows │ ├── pr.yaml │ └── release.yaml ├── Dockerfile ├── LICENSE ├── README.md ├── _config.yml ├── chart └── tugger │ ├── .helmignore │ ├── Chart.yaml │ ├── ci │ └── lint-values.yaml │ ├── templates │ ├── _helpers.tpl │ ├── admission-registration.yaml │ ├── configmap.yaml │ ├── deployment.yaml │ ├── role.yaml │ ├── rolebinding.yaml │ ├── service.yaml │ └── serviceaccount.yaml │ └── values.yaml ├── cmd └── tugger │ ├── go.mod │ ├── go.sum │ ├── main.go │ ├── main_test.go │ ├── policy.go │ └── policy_test.go ├── deployment ├── tugger-deployment.yaml └── tugger-svc.yaml ├── test └── nginx.yaml ├── tls └── gen-cert.sh └── webhook ├── tugger-mutating-webhook-configuration.yaml ├── tugger-validating-webhook-configuration.yaml └── webhook-patch-ca-bundle.sh /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | # Docker CircleCI 2.0 configuration file 2 | # 3 | # Check https://circleci.com/docs/2.0/language-java/ for more details 4 | # 5 | version: 2 6 | jobs: 7 | build: 8 | docker: 9 | # specify the version you desire here 10 | - image: circleci/golang:1.9 11 | 12 | # Specify service dependencies here if necessary 13 | # CircleCI maintains a library of pre-built images 14 | # documented at https://circleci.com/docs/2.0/circleci-images/ 15 | 16 | working_directory: /go/src/github.com/jainishshah17/tugger 17 | 18 | steps: 19 | - checkout 20 | - setup_remote_docker 21 | 22 | - run: | 23 | sudo wget https://github.com/mikefarah/yq/releases/download/v4.4.1/yq_linux_amd64 -O /usr/bin/yq 24 | sudo chmod +x /usr/bin/yq 25 | # Login to docker registry 26 | - run: docker login -u $USER -p $PASSWORD 27 | # Build docker image 28 | - run: docker build --rm=false -t jainishshah17/tugger:$CIRCLE_BUILD_NUM . 29 | - run: docker tag jainishshah17/tugger:$CIRCLE_BUILD_NUM jainishshah17/tugger:latest 30 | - run: | 31 | TARGET_TAG=$(yq e '.appVersion' chart/tugger/Chart.yaml) 32 | docker tag jainishshah17/tugger:$CIRCLE_BUILD_NUM jainishshah17/tugger:$TARGET_TAG 33 | docker push jainishshah17/tugger:$TARGET_TAG 34 | - run: docker push jainishshah17/tugger:$CIRCLE_BUILD_NUM 35 | - run: docker push jainishshah17/tugger:latest 36 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | .git 2 | .circleci 3 | chart 4 | deployment 5 | test 6 | tls 7 | webhook 8 | _config.yml 9 | Dockerfile 10 | LICENSE 11 | *.md 12 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: docker 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | - package-ecosystem: github-actions 8 | directory: "/" 9 | schedule: 10 | interval: "daily" 11 | - package-ecosystem: gomod 12 | directory: "/cmd/tugger" 13 | schedule: 14 | interval: daily 15 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | 8 | 9 | 10 | 11 | ### Checklist 12 | - [ ] Chart version bumped -------------------------------------------------------------------------------- /.github/workflows/pr.yaml: -------------------------------------------------------------------------------- 1 | name: Lint and Test Chart 2 | 3 | on: pull_request 4 | 5 | jobs: 6 | go-test: 7 | runs-on: ubuntu-latest 8 | env: 9 | IMAGE: jainishshah17/tugger 10 | timeout-minutes: 10 11 | steps: 12 | - name: Checkout 13 | uses: actions/checkout@v3 14 | - uses: actions/setup-go@v4 15 | with: 16 | go-version: "^1.13.0" 17 | - name: go test 18 | run: | 19 | cd cmd/tugger 20 | go test . -cover -v 21 | lint-test: 22 | runs-on: ubuntu-latest 23 | env: 24 | IMAGE: jainishshah17/tugger 25 | strategy: 26 | fail-fast: false 27 | matrix: 28 | k8sVersion: 29 | - v1.28.0 30 | - v1.27.3 31 | - v1.26.6 32 | - v1.25.11 33 | - v1.24.15 34 | timeout-minutes: 10 35 | steps: 36 | - name: Checkout 37 | uses: actions/checkout@v3 38 | 39 | - name: Set up Helm 40 | uses: azure/setup-helm@v3.5 41 | 42 | - name: Lint Chart 43 | run: helm lint chart/* -f chart/*/ci/lint-values.yaml 44 | 45 | - name: Build 46 | run: docker build . -t $IMAGE 47 | 48 | - name: Create kind cluster 49 | uses: helm/kind-action@v1.8.0 50 | with: 51 | node_image: kindest/node:${{ matrix.k8sVersion }} 52 | 53 | - name: Install 54 | run: | 55 | kind load docker-image $IMAGE --name=chart-testing 56 | helm install $USER chart/tugger --debug --wait \ 57 | --set=createMutatingWebhook=true \ 58 | --set=image.tag=latest 59 | 60 | - name: Test Mutation 61 | timeout-minutes: 1 62 | run: | 63 | function test_jsonpath() { 64 | until [ "$1" = "$(kubectl -n nginx get po -l test=tugger -o jsonpath="$2")" ] 65 | do 66 | echo "test failed \"$1\" = \"$2\"" 67 | sleep 1 68 | done 69 | } 70 | kubectl apply -f test/nginx.yaml 71 | test_jsonpath "jainishshah17/nginx" '{.items[0].spec.containers[0].image}' 72 | test_jsonpath "original-secret" '{.items[0].spec.imagePullSecrets[0].name}' 73 | test_jsonpath "regsecret" '{.items[0].spec.imagePullSecrets[1].name}' 74 | 75 | - name: Print debug 76 | if: ${{ always() }} 77 | run: | 78 | set +x 79 | while read cmd 80 | do 81 | echo "::group::$cmd" 82 | $cmd 83 | echo "::endgroup::" 84 | done <<< 'git diff 85 | helm list 86 | kubectl get po,rs,svc,ep,secrets,configmap 87 | kubectl describe po 88 | kubectl logs -l app=tugger' 89 | -------------------------------------------------------------------------------- /.github/workflows/release.yaml: -------------------------------------------------------------------------------- 1 | name: Release 2 | on: 3 | push: 4 | branches: 5 | - master 6 | jobs: 7 | tag: 8 | runs-on: ubuntu-latest 9 | env: 10 | upstream: jainishshah17/tugger 11 | steps: 12 | - uses: actions/checkout@v3 13 | - name: create tag 14 | if: github.repository == env.upstream 15 | run: | 16 | set -x 17 | git fetch --all --tags 18 | sudo pip install yq 19 | TARGET_TAG=v$(yq .version -r < chart/tugger/Chart.yaml) 20 | git tag $TARGET_TAG || exit 0 21 | git push origin $TARGET_TAG 22 | - name: sync tags 23 | if: github.repository != env.upstream 24 | run: | 25 | set -x 26 | git fetch --tags https://github.com/${{ env.upstream }}.git 27 | git push --tags 28 | release: 29 | runs-on: ubuntu-latest 30 | steps: 31 | - name: Checkout 32 | uses: actions/checkout@v3 33 | with: 34 | fetch-depth: 0 35 | - name: Configure Git 36 | run: | 37 | git config user.name "$GITHUB_ACTOR" 38 | git config user.email "$GITHUB_ACTOR@users.noreply.github.com" 39 | - name: Install Helm 40 | uses: azure/setup-helm@v3.5 41 | - name: Run chart-releaser 42 | uses: helm/chart-releaser-action@v1.5.0 43 | env: 44 | CR_TOKEN: "${{ secrets.GITHUB_TOKEN }}" 45 | with: 46 | charts_dir: chart 47 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Builder image 2 | FROM golang:1.20.5 as builder 3 | 4 | # Set workspace 5 | WORKDIR /src/jainishshah17/tugger/ 6 | 7 | # Copy source 8 | COPY ./ /src/jainishshah17/tugger/ 9 | 10 | # Build microservices 11 | RUN cd cmd/tugger && CGO_ENABLED=0 go install -ldflags="-extldflags=-static" 12 | 13 | # Runnable image 14 | FROM gcr.io/distroless/base-debian11 15 | 16 | # Copy microservice executable from builder image 17 | COPY --from=builder /go/bin/tugger / 18 | 19 | # Set Entrypoint 20 | CMD ["/tugger"] 21 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Tugger 2 | 3 | ### What does Tugger do? 4 | Tugger is Kubernetes Admission webhook to enforce pulling of docker images from private registry. 5 | 6 | ### Prerequisites 7 | 8 | Kubernetes 1.9.0 or above with the `admissionregistration.k8s.io/v1` API enabled. Verify that by the following command: 9 | ``` 10 | kubectl api-versions | grep admissionregistration.k8s.io/v1beta1 11 | ``` 12 | The result should be: 13 | ``` 14 | admissionregistration.k8s.io/v1beta1 15 | ``` 16 | 17 | In addition, the `MutatingAdmissionWebhook` and `ValidatingAdmissionWebhook` admission controllers should be added and listed in the correct order in the admission-control flag of kube-apiserver. 18 | 19 | ### Build and Push Tugger Docker Image 20 | 21 | ```bash 22 | # Build docker image 23 | docker build -t jainishshah17/tugger:0.1.8 . 24 | 25 | # Push it to Docker Registry 26 | docker push jainishshah17/tugger:0.1.8 27 | ``` 28 | 29 | ### Create [Kubernetes Docker registry secret](https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/) 30 | 31 | ```bash 32 | # Create a Docker registry secret called 'regsecret' 33 | kubectl create secret docker-registry regsecret --docker-server=${DOCKER_REGISTRY} --docker-username=${DOCKER_USER} --docker-password=${DOCKER_PASS} --docker-email=${DOCKER_EMAIL} 34 | ``` 35 | 36 | **Note**: Create Docker registry secret in each non-whitelisted namespaces. 37 | 38 | ### Generate TLS Certs for Tugger 39 | 40 | ```bash 41 | ./tls/gen-cert.sh 42 | ``` 43 | 44 | ### Get CA Bundle 45 | 46 | ```bash 47 | ./webhook/webhook-patch-ca-bundle.sh 48 | ``` 49 | 50 | ### Deploy Tugger to Kubernetes 51 | 52 | #### Deploy using Helm Chart 53 | 54 | The helm chart can generate certificates and configure webhooks in a single step. See the notes on webhooks below for more information. 55 | 56 | ```bash 57 | # Add Tugger Helm repository 58 | helm repo add tugger https://jainishshah17.github.io/tugger 59 | 60 | # Update Helm repository index 61 | helm repo update 62 | ``` 63 | 64 | ```bash 65 | helm install --name tugger \ 66 | --set docker.registrySecret=regsecret, \ 67 | --set docker.registryUrl=jainishshah17, \ 68 | --set whitelistNamespaces={kube-system,default}, \ 69 | --set whitelistRegistries={jainishshah17} \ 70 | --set createValidatingWebhook=true \ 71 | --set createMutatingWebhook=true \ 72 | tugger/tugger 73 | ``` 74 | 75 | #### Deploy using kubectl 76 | 77 | 1. Create deployment and service 78 | 79 | ```bash 80 | # Run deployment 81 | kubectl create -f deployment/tugger-deployment.yaml 82 | 83 | # Create service 84 | kubectl create -f deployment/tugger-svc.yaml 85 | ``` 86 | 87 | 2. Configure `MutatingAdmissionWebhook` and `ValidatingAdmissionWebhook` 88 | 89 | **Note**: Replace `${CA_BUNDLE}` with value generated by running `./webhook/webhook-patch-ca-bundle.sh` 90 | 91 | ```bash 92 | # re MutatingAdmissionWebhook 93 | kubectl create -f webhook/tugger-mutating-webhook ration.yaml 94 | ``` 95 | 96 | Note: Use MutatingAdmissionWebhook only if you want to enforce pulling of docker image from Private Docker Registry e.g [JFrog Artifactory](https://jfrog.com/artifactory/). 97 | If your container image is `nginx` then Tugger will append `REGISTRY_URL` to it. e.g `nginx` will become `jainishshah17/nginx` 98 | 99 | ```bash 100 | # Configure ValidatingWebhookConfiguration 101 | kubectl create -f webhook/tugger-validating-webhook ration.yaml 102 | ``` 103 | 104 | Note: Use ValidatingWebhookConfiguration only if you want to check pulling of docker image from Private Docker Registry e.g [JFrog Artifactory](https://jfrog.com/artifactory/). 105 | If your container image does not contain `REGISTRY_URL` then Tugger will deny request to run that pod. 106 | 107 | ### Test Tugger 108 | 109 | ```bash 110 | # Deploy nginx 111 | kubectl apply -f test/nginx.yaml 112 | ``` 113 | 114 | ## Configure 115 | 116 | The mutation or validation policy can be defined as a list of rules in a YAML file. 117 | 118 | The YALM file can be specified with the command line argument `--policy-file=FILE`, or when using the Helm chart, populate `rules:` in values. 119 | 120 | ### Schema 121 | 122 | ```yaml 123 | rules: 124 | - pattern: regex 125 | replacement: template (optional) 126 | condition: policy (optional) 127 | - ... 128 | ``` 129 | 130 | _pattern_ is a regex pattern 131 | 132 | _replacement_ is a template comprised of the captured groups to use to generate the new image name in the mutating admission controller. When _replacement_ is `null` or undefined, the image name is allowed without patching. Rules with this field are ignored by the validating admission controller, where mutation is not supported. 133 | 134 | _condition_ is a special condition to test before committing the replacement. Initially `Always` and `Exists` will be supported. `Always` is the default and performs the replacement regardless of any condition. `Exists` implements the behavior from #7; it only rewrites the image name if the target name exists in the remote registry. 135 | 136 | Each rule will be evaluated in order, and if the list is exhausted without a match, the admission controller will return `allowed: false`. 137 | 138 | ### Examples 139 | 140 | This example allows all images without rewriting: 141 | ```yaml 142 | rules: 143 | - pattern: .* 144 | ``` 145 | 146 | This example implements the default behavior of rewriting all image names to start with `jainishshah17`: 147 | ```yaml 148 | rules: 149 | - pattern: ^jainishshah17/.* 150 | - pattern: (.*) 151 | replacement: jainishshah17/$1 152 | ``` 153 | 154 | Or the same thing, but only if the image exists in `jainishshah17/`, and allowing all other images: 155 | ```yaml 156 | rules: 157 | - pattern: ^jainishshah17/.* 158 | - pattern: (.*) 159 | replacement: jainishshah17/$1 160 | condition: Exists 161 | - pattern: .* 162 | ``` 163 | 164 | Allow the nginx image, but rewrite everything else: 165 | ```yaml 166 | rules: 167 | - pattern: ^nginx(:.*)?$ 168 | - pattern: (?:jainishshah17)?(.*) 169 | replacement: jainishshah17/$1 170 | ``` 171 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-architect -------------------------------------------------------------------------------- /chart/tugger/.helmignore: -------------------------------------------------------------------------------- 1 | # Patterns to ignore when building packages. 2 | # This supports shell glob matching, relative path matching, and 3 | # negation (prefixed with !). Only one pattern per line. 4 | .DS_Store 5 | # Common VCS dirs 6 | .git/ 7 | .gitignore 8 | .bzr/ 9 | .bzrignore 10 | .hg/ 11 | .hgignore 12 | .svn/ 13 | # Common backup files 14 | *.swp 15 | *.bak 16 | *.tmp 17 | *~ 18 | # Various IDEs 19 | .project 20 | .idea/ 21 | *.tmproj 22 | -------------------------------------------------------------------------------- /chart/tugger/Chart.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | appVersion: "0.1.8" 3 | description: A Helm chart for Tugger 4 | name: tugger 5 | version: 0.4.5 6 | keywords: 7 | - DevOps 8 | - helm 9 | - kubernetes 10 | - docker 11 | home: https://github.com/jainishshah17/tugger 12 | sources: 13 | - https://github.com/jainishshah17/tugger 14 | maintainers: 15 | - name: jainishshah17 16 | email: jainishshah@yahoo.com 17 | icon: https://raw.githubusercontent.com/jainishshah17/containerize-go-microservice/master/static/logo.jpg 18 | -------------------------------------------------------------------------------- /chart/tugger/ci/lint-values.yaml: -------------------------------------------------------------------------------- 1 | # enables optional features in the chart so they will be linted in the PR test 2 | createValidatingWebhook: true 3 | createMutatingWebhook: true 4 | env: prod 5 | docker: 6 | ifExists: true 7 | image: 8 | pullSecret: foo 9 | resources: 10 | limits: 11 | cpu: 100m 12 | memory: 128Mi 13 | requests: 14 | cpu: 100m 15 | memory: 128Mi 16 | rules: 17 | - pattern: ^jainishshah17/.* 18 | - pattern: (.*) 19 | replacement: jainishshah17/$1 20 | slackDedupeTTL: 24h 21 | whitelistRegistries: 22 | - jainishshah17 23 | - 10.110.50.0:5000 24 | - docker.artifactory.com 25 | -------------------------------------------------------------------------------- /chart/tugger/templates/_helpers.tpl: -------------------------------------------------------------------------------- 1 | {{/* vim: set filetype=mustache: */}} 2 | {{/* 3 | Expand the name of the chart. 4 | */}} 5 | {{- define "tugger.name" -}} 6 | {{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}} 7 | {{- end -}} 8 | 9 | {{/* 10 | Create a default fully qualified app name. 11 | We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec). 12 | If release name contains chart name it will be used as a full name. 13 | */}} 14 | {{- define "tugger.fullname" -}} 15 | {{- if .Values.fullnameOverride -}} 16 | {{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" -}} 17 | {{- else -}} 18 | {{- $name := default .Chart.Name .Values.nameOverride -}} 19 | {{- if contains $name .Release.Name -}} 20 | {{- .Release.Name | trunc 63 | trimSuffix "-" -}} 21 | {{- else -}} 22 | {{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}} 23 | {{- end -}} 24 | {{- end -}} 25 | {{- end -}} 26 | 27 | {{/* 28 | Create the name of the service account to use 29 | */}} 30 | {{- define "tugger.serviceAccountName" -}} 31 | {{- if .Values.serviceAccount.create -}} 32 | {{ default (include "tugger.fullname" .) .Values.serviceAccount.name }} 33 | {{- else -}} 34 | {{ default "default" .Values.serviceAccount.name }} 35 | {{- end -}} 36 | {{- end -}} 37 | 38 | {{/* 39 | Create chart name and version as used by the chart label. 40 | */}} 41 | {{- define "tugger.chart" -}} 42 | {{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" -}} 43 | {{- end -}} 44 | 45 | 46 | {{/* 47 | Generate certificates for mutating webhook 48 | */}} 49 | {{- define "tugger.gen-certs" -}} 50 | {{- $ca := genCA "tugger-ca" 3650 }} 51 | {{- $cn := printf "tugger-controller-service" }} 52 | {{- $altName1 := printf "agones-controller-service.%s" .Values.agones.namespace }} 53 | {{- $altName2 := printf "agones-controller-service.%s.svc" .Values.agones.namespace }} 54 | {{- $cert := genSignedCert $cn nil (list $altName1 $altName2) 3650 $ca }} 55 | tls.crt: {{ $cert.Cert | b64enc }} 56 | tls.key: {{ $cert.Key | b64enc }} 57 | ca.crt: {{ $ca.Cert | b64enc }} 58 | {{- end -}} -------------------------------------------------------------------------------- /chart/tugger/templates/admission-registration.yaml: -------------------------------------------------------------------------------- 1 | {{- $serviceName := include "tugger.fullname" . }} 2 | {{- $ca := genCA (printf "%s-mutating-webhook-ca" $serviceName) 1825 }} 3 | {{- $cn := $serviceName }} 4 | {{- $altName1 := printf "%s.%s" $serviceName .Release.Namespace }} 5 | {{- $altName2 := printf "%s.%s.svc" $serviceName .Release.Namespace }} 6 | {{- $cert := genSignedCert $serviceName nil (list $altName1 $altName2) 1825 $ca }} 7 | 8 | # Detect if we should use the user defined CA Certificate or a generated one 9 | {{- $caCert := "" }} 10 | {{- if .Values.tls.caCert }} 11 | {{ $caCert = .Values.tls.caCert }} 12 | {{- else }} 13 | {{ $caCert = $ca.Cert }} 14 | {{- end }} 15 | 16 | {{- if .Values.createValidatingWebhook }} 17 | --- 18 | apiVersion: admissionregistration.k8s.io/v1 19 | kind: ValidatingWebhookConfiguration 20 | metadata: 21 | name: {{ template "tugger.fullname" . }} 22 | labels: 23 | app: {{ template "tugger.name" . }} 24 | chart: {{ template "tugger.chart" . }} 25 | release: {{ .Release.Name }} 26 | heritage: {{ .Release.Service }} 27 | webhooks: 28 | - name: tugger-validate.jainishshah17.com 29 | sideEffects: None 30 | admissionReviewVersions: ["v1beta1"] 31 | {{- with .Values.namespaceSelector }} 32 | namespaceSelector: 33 | {{ . | toYaml | indent 4 }} 34 | {{- end }} 35 | rules: 36 | - apiGroups: 37 | - "" 38 | apiVersions: 39 | - v1 40 | operations: 41 | - CREATE 42 | resources: 43 | - pods 44 | scope: "Namespaced" 45 | failurePolicy: Ignore 46 | clientConfig: 47 | service: 48 | name: {{ $serviceName }} 49 | namespace: {{ .Release.Namespace }} 50 | path: "/validate" 51 | port: {{ .Values.service.port }} 52 | caBundle: {{ b64enc $caCert }} 53 | {{- end }} 54 | 55 | {{- if .Values.createMutatingWebhook }} 56 | --- 57 | apiVersion: admissionregistration.k8s.io/v1 58 | kind: MutatingWebhookConfiguration 59 | metadata: 60 | name: {{ template "tugger.fullname" . }} 61 | labels: 62 | app: {{ template "tugger.name" . }} 63 | chart: {{ template "tugger.chart" . }} 64 | release: {{ .Release.Name }} 65 | heritage: {{ .Release.Service }} 66 | webhooks: 67 | - name: tugger-mutate.jainishshah17.com 68 | sideEffects: None 69 | admissionReviewVersions: ["v1beta1"] 70 | {{- with .Values.namespaceSelector }} 71 | namespaceSelector: 72 | {{ . | toYaml | indent 4 }} 73 | {{- end }} 74 | rules: 75 | - operations: [ "CREATE" ] 76 | apiGroups: [""] 77 | apiVersions: ["v1"] 78 | resources: ["pods"] 79 | failurePolicy: Ignore 80 | clientConfig: 81 | service: 82 | name: {{ $serviceName }} 83 | namespace: {{ .Release.Namespace }} 84 | path: "/mutate" 85 | port: {{ .Values.service.port }} 86 | caBundle: {{ b64enc $caCert }} 87 | {{- end }} 88 | 89 | {{- if not .Values.tls.secretName }} 90 | --- 91 | apiVersion: v1 92 | kind: Secret 93 | metadata: 94 | name: {{ template "tugger.fullname" . }}-cert 95 | labels: 96 | app: {{ template "tugger.name" . }} 97 | chart: {{ template "tugger.chart" . }} 98 | release: {{ .Release.Name }} 99 | heritage: {{ .Release.Service }} 100 | type: kubernetes.io/tls 101 | data: 102 | tls.crt: {{ b64enc $cert.Cert }} 103 | tls.key: {{ b64enc $cert.Key }} 104 | {{- end }} 105 | -------------------------------------------------------------------------------- /chart/tugger/templates/configmap.yaml: -------------------------------------------------------------------------------- 1 | {{- if .Values.rules }} 2 | apiVersion: v1 3 | kind: ConfigMap 4 | metadata: 5 | name: {{ template "tugger.fullname" . }} 6 | labels: 7 | app: {{ template "tugger.name" . }} 8 | chart: {{ template "tugger.chart" . }} 9 | release: {{ .Release.Name }} 10 | heritage: {{ .Release.Service }} 11 | data: 12 | policy.yaml: | 13 | rules: 14 | {{- toYaml .Values.rules | nindent 6 }} 15 | {{- end }} 16 | -------------------------------------------------------------------------------- /chart/tugger/templates/deployment.yaml: -------------------------------------------------------------------------------- 1 | 2 | apiVersion: apps/v1 3 | kind: Deployment 4 | metadata: 5 | name: {{ template "tugger.fullname" . }} 6 | labels: 7 | app: {{ template "tugger.name" . }} 8 | chart: {{ template "tugger.chart" . }} 9 | release: {{ .Release.Name }} 10 | heritage: {{ .Release.Service }} 11 | spec: 12 | replicas: {{ .Values.replicaCount }} 13 | selector: 14 | matchLabels: 15 | app: {{ template "tugger.name" . }} 16 | release: {{ .Release.Name }} 17 | template: 18 | metadata: 19 | labels: 20 | app: {{ template "tugger.name" . }} 21 | release: {{ .Release.Name }} 22 | annotations: 23 | checksum/config: {{ include (print $.Template.BasePath "/admission-registration.yaml") . | sha256sum }} 24 | spec: 25 | {{- with .Values.image.pullSecret }} 26 | imagePullSecrets: 27 | - name: {{ . }} 28 | {{- end }} 29 | {{- with .Values.priorityClassName }} 30 | priorityClassName: {{ . }} 31 | {{- end }} 32 | containers: 33 | - name: {{ .Chart.Name }} 34 | image: "{{ .Values.image.repository }}:{{ default .Chart.AppVersion .Values.image.tag }}" 35 | imagePullPolicy: {{ .Values.image.pullPolicy }} 36 | args: 37 | - /tugger 38 | - --port 39 | - {{ .Values.service.port | quote }} 40 | {{- if .Values.docker.ifExists }} 41 | - --if-exists 42 | {{- end }} 43 | {{- if .Values.rules }} 44 | - --policy-file 45 | - /etc/tugger/policy.yaml 46 | {{- end }} 47 | {{- with .Values.slackDedupeTTL }} 48 | - --slack-dedupe-ttl 49 | - {{ . }} 50 | {{- end }} 51 | env: 52 | {{- with .Values.env }} 53 | - name: ENV 54 | value: {{ . }} 55 | {{- end }} 56 | - name: DOCKER_REGISTRY_URL 57 | value: {{ .Values.docker.registryUrl }} 58 | - name: REGISTRY_SECRET_NAME 59 | value: {{ .Values.docker.registrySecret }} 60 | - name: WHITELIST_NAMESPACES 61 | value: {{ join "," .Values.whitelistNamespaces }} 62 | - name: WHITELIST_REGISTRIES 63 | value: {{ join "," (append .Values.whitelistRegistries .Values.docker.registryUrl) }} 64 | - name: WEBHOOK_URL 65 | value: {{ .Values.webhookUrl }} 66 | ports: 67 | - name: https 68 | containerPort: {{ .Values.service.port }} 69 | protocol: TCP 70 | volumeMounts: 71 | {{- if .Values.rules }} 72 | - name: policy 73 | mountPath: /etc/tugger 74 | {{- end }} 75 | {{- if .Values.image.pullSecret }} 76 | - name: pullsecret 77 | mountPath: /root/.docker/ 78 | {{- end }} 79 | - name: tls 80 | mountPath: /etc/admission-controller/tls 81 | resources: 82 | {{ toYaml .Values.resources | indent 12 }} 83 | {{ with .Values.livenessProbe }} 84 | livenessProbe: 85 | {{ toYaml . | indent 12 }} 86 | {{- end }} 87 | {{- with .Values.readinessProbe }} 88 | readinessProbe: 89 | {{ toYaml . | indent 12 }} 90 | {{- end }} 91 | {{- with .Values.nodeSelector }} 92 | nodeSelector: 93 | {{ toYaml . | indent 8 }} 94 | {{- end }} 95 | {{- with .Values.affinity }} 96 | affinity: 97 | {{ toYaml . | indent 8 }} 98 | {{- end }} 99 | {{- with .Values.tolerations }} 100 | tolerations: 101 | {{ toYaml . | indent 8 }} 102 | {{- end }} 103 | volumes: 104 | {{- if .Values.rules }} 105 | - name: policy 106 | configMap: 107 | name: {{ template "tugger.fullname" . }} 108 | {{- end }} 109 | {{- with .Values.image.pullSecret }} 110 | - name: pullsecret 111 | secret: 112 | secretName: {{ . }} 113 | items: 114 | - key: .dockerconfigjson 115 | path: config.json 116 | {{- end }} 117 | - name: tls 118 | secret: 119 | secretName: {{ default (printf "%s-cert" (include "tugger.fullname" . )) .Values.tls.secretName }} 120 | -------------------------------------------------------------------------------- /chart/tugger/templates/role.yaml: -------------------------------------------------------------------------------- 1 | {{- if .Values.rbac.create }} 2 | apiVersion: rbac.authorization.k8s.io/v1 3 | kind: Role 4 | metadata: 5 | name: {{ template "tugger.fullname" . }} 6 | labels: 7 | app: {{ template "tugger.name" . }} 8 | chart: {{ template "tugger.chart" . }} 9 | heritage: {{ .Release.Service }} 10 | release: {{ .Release.Name }} 11 | ## Rules to create. It follows the role specification 12 | rules: 13 | - apiGroups: 14 | - '' 15 | resources: 16 | - services 17 | - endpoints 18 | - pods 19 | verbs: 20 | - get 21 | - watch 22 | - list 23 | {{- end }} -------------------------------------------------------------------------------- /chart/tugger/templates/rolebinding.yaml: -------------------------------------------------------------------------------- 1 | {{- if .Values.rbac.create }} 2 | apiVersion: rbac.authorization.k8s.io/v1 3 | kind: RoleBinding 4 | metadata: 5 | name: {{ template "tugger.fullname" . }} 6 | labels: 7 | app: {{ template "tugger.name" . }} 8 | chart: {{ template "tugger.chart" . }} 9 | heritage: {{ .Release.Service }} 10 | release: {{ .Release.Name }} 11 | subjects: 12 | - kind: ServiceAccount 13 | name: {{ template "tugger.serviceAccountName" . }} 14 | roleRef: 15 | kind: Role 16 | apiGroup: rbac.authorization.k8s.io 17 | name: {{ template "tugger.fullname" . }} 18 | {{- end }} -------------------------------------------------------------------------------- /chart/tugger/templates/service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: {{ template "tugger.fullname" . }} 5 | labels: 6 | app: {{ template "tugger.name" . }} 7 | chart: {{ template "tugger.chart" . }} 8 | release: {{ .Release.Name }} 9 | heritage: {{ .Release.Service }} 10 | spec: 11 | type: {{ .Values.service.type }} 12 | ports: 13 | - port: {{ .Values.service.port }} 14 | targetPort: https 15 | protocol: TCP 16 | name: https 17 | selector: 18 | app: {{ template "tugger.name" . }} 19 | release: {{ .Release.Name }} 20 | -------------------------------------------------------------------------------- /chart/tugger/templates/serviceaccount.yaml: -------------------------------------------------------------------------------- 1 | {{- if .Values.serviceAccount.create }} 2 | apiVersion: v1 3 | kind: ServiceAccount 4 | metadata: 5 | name: {{ template "tugger.serviceAccountName" . }} 6 | labels: 7 | app: {{ template "tugger.name" . }} 8 | chart: {{ template "tugger.chart" . }} 9 | heritage: {{ .Release.Service }} 10 | release: {{ .Release.Name }} 11 | {{- end }} -------------------------------------------------------------------------------- /chart/tugger/values.yaml: -------------------------------------------------------------------------------- 1 | # Default values for tugger. 2 | # This is a YAML-formatted file. 3 | 4 | replicaCount: 1 5 | 6 | ## Role Based Access Control 7 | ## Ref: https://kubernetes.io/docs/admin/authorization/rbac/ 8 | rbac: 9 | create: true 10 | 11 | ## Service Account 12 | ## Ref: https://kubernetes.io/docs/admin/service-accounts-admin/ 13 | ## 14 | serviceAccount: 15 | create: true 16 | ## The name of the ServiceAccount to use. 17 | ## If not set and create is true, a name is generated using the fullname template 18 | name: 19 | 20 | image: 21 | repository: jainishshah17/tugger 22 | tag: 23 | pullPolicy: IfNotPresent 24 | pullSecret: 25 | 26 | priorityClassName: "" 27 | 28 | service: 29 | type: ClusterIP 30 | port: 443 31 | 32 | docker: 33 | ifExists: false 34 | registryUrl: jainishshah17 35 | registrySecret: regsecret 36 | 37 | # Use regex patterns for image name matching and replacement. See readme. 38 | # Disables/replaces docker.registryUrl and docker.ifExists. 39 | rules: [] 40 | # Disabled for backwards compatibility. 41 | # Configuring this section is recommended for new installations. 42 | # - pattern: ^jainishshah17/.* 43 | # - pattern: (.*) 44 | # replacement: jainishshah17/$1 45 | 46 | # Whitelist namespaces e.g "[kubesystem,default,development]" 47 | whitelistNamespaces: 48 | - kube-system 49 | 50 | # Whitelist docker registries within non-whitelisted namespaces 51 | # e.g "[jainishshah17,10.110.50.0:5000,docker.artifactory.com]" 52 | whitelistRegistries: [] 53 | 54 | tls: 55 | # Optional existing certificate secret to use. 56 | # A certificate is generated if not specified 57 | secretName: 58 | # CA Certificate for cert in secretName (required if using secretName) 59 | caCert: 60 | 61 | # Slack webhook URL e.g "https://hooks.slack.com/services/X1234" 62 | webhookUrl: 63 | slackDedupeTTL: # default: 3m0s, value must be acceptable to time.ParseDuration() https://golang.org/pkg/time/#ParseDuration 64 | 65 | # Optional webhook namespace selector based on labels 66 | # Ref: https://kubernetes.io/docs/reference/access-authn-authz/extensible-admission-controllers/#matching-requests-objectselector 67 | namespaceSelector: 68 | # matchExpressions: 69 | # - key: runlevel 70 | # operator: NotIn 71 | # values: ["0","1"] 72 | 73 | createValidatingWebhook: false 74 | createMutatingWebhook: false 75 | 76 | resources: {} 77 | # We usually recommend not to specify default resources and to leave this as a conscious 78 | # choice for the user. This also increases chances charts run on environments with little 79 | # resources, such as Minikube. If you do want to specify resources, uncomment the following 80 | # lines, adjust them as necessary, and remove the curly braces after 'resources:'. 81 | # limits: 82 | # cpu: 100m 83 | # memory: 128Mi 84 | # requests: 85 | # cpu: 100m 86 | # memory: 128Mi 87 | 88 | nodeSelector: {} 89 | 90 | tolerations: [] 91 | 92 | affinity: {} 93 | 94 | livenessProbe: 95 | httpGet: 96 | scheme: HTTPS 97 | path: /ping 98 | port: https 99 | initialDelaySeconds: 5 100 | periodSeconds: 10 101 | timeoutSeconds: 3 102 | failureThreshold: 12 103 | successThreshold: 1 104 | 105 | readinessProbe: 106 | httpGet: 107 | scheme: HTTPS 108 | path: /ping 109 | port: https 110 | initialDelaySeconds: 5 111 | periodSeconds: 10 112 | timeoutSeconds: 3 113 | failureThreshold: 1 114 | successThreshold: 1 115 | -------------------------------------------------------------------------------- /cmd/tugger/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/jainishshah17/tugger 2 | 3 | go 1.15 4 | 5 | require ( 6 | github.com/google/go-containerregistry v0.15.2 7 | github.com/infobloxopen/atlas-app-toolkit v1.4.0 8 | github.com/jarcoal/httpmock v1.3.0 9 | github.com/patrickmn/go-cache v2.1.0+incompatible 10 | github.com/sirupsen/logrus v1.9.3 11 | google.golang.org/grpc/examples v0.0.0-20210730002332-ea9b7a0a7651 // indirect 12 | gopkg.in/yaml.v2 v2.4.0 13 | k8s.io/api v0.26.2 14 | k8s.io/apimachinery v0.26.2 15 | ) 16 | -------------------------------------------------------------------------------- /cmd/tugger/main.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 Google Inc. All Rights Reserved. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // http://www.apache.org/licenses/LICENSE-2.0 6 | // Unless required by applicable law or agreed to in writing, software 7 | // distributed under the License is distributed on an "AS IS" BASIS, 8 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9 | // See the License for the specific language governing permissions and 10 | // limitations under the License. 11 | 12 | package main 13 | 14 | import ( 15 | "bytes" 16 | "crypto/tls" 17 | "encoding/json" 18 | "flag" 19 | "fmt" 20 | "io/ioutil" 21 | "net/http" 22 | "os" 23 | "strings" 24 | "time" 25 | 26 | "github.com/google/go-containerregistry/pkg/authn" 27 | "github.com/google/go-containerregistry/pkg/name" 28 | "github.com/google/go-containerregistry/pkg/v1/remote" 29 | "github.com/infobloxopen/atlas-app-toolkit/logging" 30 | "github.com/patrickmn/go-cache" 31 | "github.com/sirupsen/logrus" 32 | "k8s.io/api/admission/v1beta1" 33 | v1 "k8s.io/api/core/v1" 34 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 35 | ) 36 | 37 | var ( 38 | ifExists bool 39 | log *logrus.Logger 40 | policy *Policy 41 | listenPort int 42 | tlsCertFile string 43 | tlsKeyFile string 44 | slackDupeCache *cache.Cache 45 | slackDedupeTTL time.Duration 46 | ) 47 | 48 | var ( 49 | env = os.Getenv("ENV") 50 | dockerRegistryUrl = os.Getenv("DOCKER_REGISTRY_URL") 51 | registrySecretName = os.Getenv("REGISTRY_SECRET_NAME") 52 | whitelistRegistries = os.Getenv("WHITELIST_REGISTRIES") 53 | whitelistNamespaces = os.Getenv("WHITELIST_NAMESPACES") 54 | webhookUrl = os.Getenv("WEBHOOK_URL") 55 | whitelistedNamespaces = strings.Split(whitelistNamespaces, ",") 56 | whitelistedRegistries = strings.Split(whitelistRegistries, ",") 57 | ) 58 | 59 | type patch struct { 60 | Op string `json:"op"` 61 | Path string `json:"path"` 62 | Value interface{} `json:"value,omitempty"` 63 | } 64 | 65 | type SlackRequestBody struct { 66 | Text string `json:"text"` 67 | } 68 | 69 | func main() { 70 | flag.BoolVar(&ifExists, "if-exists", false, "makes the mutation conditional on whether the mutated image name exists in the registry") 71 | logLevel := flag.String("log-level", "info", "log verbosity") 72 | policyFile := flag.String("policy-file", "", "YAML file defining allowed image name patterns (see readme)") 73 | flag.IntVar(&listenPort, "port", 443, "HTTPS Port to listen on for webhook requests.") 74 | flag.StringVar(&tlsCertFile, "tls-cert", "/etc/admission-controller/tls/tls.crt", "TLS certificate file.") 75 | flag.StringVar(&tlsKeyFile, "tls-key", "/etc/admission-controller/tls/tls.key", "TLS key file.") 76 | flag.DurationVar(&slackDedupeTTL, "slack-dedupe-ttl", 3*time.Minute, "drops repeat Slack notifications until this amount of time elapses (requires WEBHOOK_URL defined)") 77 | flag.Parse() 78 | 79 | log = logging.New(*logLevel) 80 | 81 | if *policyFile != "" { 82 | var err error 83 | if policy, err = NewPolicy(WithConfigFile(*policyFile)); err != nil { 84 | log.WithError(err).WithField("policy-file", *policyFile).Fatal("failed to load policy file") 85 | } 86 | } 87 | 88 | if webhookUrl != "" && slackDedupeTTL > 0 { 89 | slackDupeCache = cache.New(slackDedupeTTL, 10*time.Minute) 90 | } 91 | 92 | http.HandleFunc("/ping", healthCheck) 93 | http.HandleFunc("/mutate", mutateAdmissionReviewHandler) 94 | http.HandleFunc("/validate", validateAdmissionReviewHandler) 95 | s := http.Server{ 96 | Addr: fmt.Sprintf(":%d", listenPort), 97 | TLSConfig: &tls.Config{ 98 | ClientAuth: tls.NoClientCert, 99 | MinVersion: tls.VersionTLS13, 100 | }, 101 | } 102 | log.Fatal(s.ListenAndServeTLS(tlsCertFile, tlsKeyFile)) 103 | } 104 | 105 | func mutateAdmissionReviewHandler(w http.ResponseWriter, r *http.Request) { 106 | log.Printf("Serving request: %s", r.URL.Path) 107 | //set header 108 | w.Header().Set("Content-Type", "application/json") 109 | 110 | data, err := ioutil.ReadAll(r.Body) 111 | if err != nil { 112 | log.WithError(err).WithField("body", string(data)).Error("could not parse request") 113 | w.WriteHeader(http.StatusBadRequest) 114 | return 115 | } 116 | 117 | log.Debugf(string(data)) 118 | 119 | ar := v1beta1.AdmissionReview{} 120 | if err := json.Unmarshal(data, &ar); err != nil || ar.Request == nil { 121 | log.WithError(err).WithField("body", string(data)).Error("could not parse request") 122 | w.WriteHeader(http.StatusBadRequest) 123 | return 124 | } 125 | 126 | namespace := ar.Request.Namespace 127 | log.Debugf("AdmissionReview Namespace is: %s", namespace) 128 | 129 | admissionResponse := v1beta1.AdmissionResponse{Allowed: false} 130 | patches := []patch{} 131 | 132 | pod := v1.Pod{} 133 | if !contains(whitelistedNamespaces, namespace) { 134 | if err := json.Unmarshal(ar.Request.Object.Raw, &pod); err != nil { 135 | log.WithError(err).WithField("object", ar.Request.Object.Raw).Error("could unmarshal pod spec") 136 | w.WriteHeader(http.StatusBadRequest) 137 | return 138 | } 139 | 140 | // Handle Containers 141 | for i, container := range pod.Spec.Containers { 142 | originalImage := container.Image 143 | if handleContainer(&container, dockerRegistryUrl) { 144 | patches = append( 145 | patches, patch{ 146 | Op: "replace", 147 | Path: fmt.Sprintf("/spec/containers/%d/image", i), 148 | Value: container.Image, 149 | }, 150 | patch{ 151 | Op: "add", 152 | Path: fmt.Sprintf("/metadata/annotations/tugger-original-image-%d", i), 153 | Value: originalImage, 154 | }, 155 | ) 156 | } 157 | } 158 | 159 | // Handle init containers 160 | for i, container := range pod.Spec.InitContainers { 161 | originalImage := container.Image 162 | if handleContainer(&container, dockerRegistryUrl) { 163 | patches = append(patches, 164 | patch{ 165 | Op: "replace", 166 | Path: fmt.Sprintf("/spec/initContainers/%d/image", i), 167 | Value: container.Image, 168 | }, 169 | patch{ 170 | Op: "add", 171 | Path: fmt.Sprintf("/metadata/annotations/tugger-original-init-image-%d", i), 172 | Value: originalImage, 173 | }, 174 | ) 175 | } 176 | } 177 | } else { 178 | log.Printf("Namespace is %s Whitelisted", namespace) 179 | } 180 | 181 | admissionResponse.Allowed = true 182 | if len(patches) > 0 { 183 | 184 | // If the pod doesnt have annotations prepend a patch 185 | // so the annotations map exists before the patches above 186 | if pod.ObjectMeta.Annotations == nil { 187 | patches = append([]patch{patch{ 188 | Op: "add", 189 | Path: "/metadata/annotations", 190 | Value: map[string]string{}, 191 | }}, patches...) 192 | } 193 | 194 | // If the pod doesn't have labels append a patch 195 | if pod.ObjectMeta.Labels == nil { 196 | patches = append(patches, patch{ 197 | Op: "add", 198 | Path: "/metadata/labels", 199 | Value: map[string]string{}, 200 | }) 201 | } 202 | 203 | // Inject image pull secret 204 | if registrySecretName != "" { 205 | imagePullSecrets := pod.Spec.ImagePullSecrets 206 | if imagePullSecrets == nil { 207 | imagePullSecrets = []v1.LocalObjectReference{} 208 | } 209 | imagePullSecrets = append(imagePullSecrets, 210 | v1.LocalObjectReference{ 211 | Name: registrySecretName, 212 | }, 213 | ) 214 | patches = append(patches, patch{ 215 | Op: "add", 216 | Path: "/spec/imagePullSecrets", 217 | Value: imagePullSecrets, 218 | }) 219 | } 220 | 221 | // Add label 222 | patches = append(patches, patch{ 223 | Op: "add", 224 | Path: "/metadata/labels/tugger-modified", 225 | Value: "true", 226 | }) 227 | 228 | patchContent, err := json.Marshal(patches) 229 | if err != nil { 230 | log.WithError(err).WithField("patches", patches).Error("could not marshal patches") 231 | w.WriteHeader(http.StatusInternalServerError) 232 | return 233 | } 234 | 235 | admissionResponse.Patch = patchContent 236 | pt := v1beta1.PatchTypeJSONPatch 237 | admissionResponse.PatchType = &pt 238 | } 239 | 240 | ar = v1beta1.AdmissionReview{ 241 | Response: &admissionResponse, 242 | } 243 | 244 | data, err = json.Marshal(ar) 245 | if err != nil { 246 | log.WithError(err).WithField("resp", ar).Error("could not marshal response") 247 | w.WriteHeader(http.StatusInternalServerError) 248 | return 249 | } 250 | 251 | w.WriteHeader(http.StatusOK) 252 | w.Write(data) 253 | } 254 | 255 | // imageExists verifies an image exists in the remote registry 256 | func imageExists(image string) bool { 257 | ref, err := name.ParseReference(image) 258 | if err != nil { 259 | log.WithError(err).WithField("image", image).Error("could not parse image") 260 | return false 261 | } 262 | 263 | if _, err := remote.Image(ref, remote.WithAuthFromKeychain(authn.DefaultKeychain)); err != nil { 264 | log.WithError(err).WithField("image", image).Error("could not fetch image") 265 | return false 266 | } 267 | 268 | return true 269 | } 270 | 271 | func handleContainer(container *v1.Container, dockerRegistryUrl string) bool { 272 | log.Println("Container Image is", container.Image) 273 | 274 | if policy != nil { 275 | originalImage := container.Image 276 | container.Image, _ = policy.MutateImage(container.Image) 277 | if originalImage != container.Image { 278 | log.Println("Changing image from", originalImage, "to", container.Image) 279 | return true 280 | } 281 | return false 282 | } 283 | 284 | // backwards compatibility when policy is undefined 285 | if containsRegisty(whitelistedRegistries, container.Image) { 286 | log.Printf("Image is being pulled from Private Registry: %s", container.Image) 287 | return false 288 | } 289 | message := fmt.Sprintf("Image is not being pulled from Private Registry: %s", container.Image) 290 | log.Printf(message) 291 | 292 | newImage := dockerRegistryUrl + "/" + container.Image 293 | if ifExists && !imageExists(newImage) { 294 | message := fmt.Sprintf("%s does not exist in private registry, skipping patching of %s", newImage, container.Name) 295 | log.Print(message) 296 | SendSlackNotification(message) 297 | return false 298 | } 299 | 300 | log.Println("Changing image from", container.Image, "to", newImage) 301 | 302 | container.Image = newImage 303 | return true 304 | } 305 | 306 | func validateAdmissionReviewHandler(w http.ResponseWriter, r *http.Request) { 307 | log.Printf("Serving request: %s", r.URL.Path) 308 | //set header 309 | w.Header().Set("Content-Type", "application/json") 310 | 311 | data, err := ioutil.ReadAll(r.Body) 312 | if err != nil { 313 | log.WithError(err).WithField("body", string(data)).Error("could not read request") 314 | w.WriteHeader(http.StatusBadRequest) 315 | return 316 | } 317 | 318 | log.Debugf(string(data)) 319 | 320 | ar := v1beta1.AdmissionReview{} 321 | if err := json.Unmarshal(data, &ar); err != nil { 322 | log.WithError(err).WithField("body", string(data)).Error("could not parse request") 323 | w.WriteHeader(http.StatusBadRequest) 324 | return 325 | } 326 | 327 | namespace := ar.Request.Namespace 328 | log.Debugf("AdmissionReview Namespace is: %s", namespace) 329 | 330 | admissionResponse := v1beta1.AdmissionResponse{Allowed: true} 331 | if !contains(whitelistedNamespaces, namespace) { 332 | pod := v1.Pod{} 333 | if err := json.Unmarshal(ar.Request.Object.Raw, &pod); err != nil { 334 | log.WithError(err).WithField("object", ar.Request.Object.Raw).Error("could unmarshal pod spec") 335 | w.WriteHeader(http.StatusBadRequest) 336 | return 337 | } 338 | 339 | var validateImage func(string) bool 340 | if policy != nil { 341 | validateImage = policy.ValidateImage 342 | } else { 343 | // backwards compatibility when policy is undefined 344 | validateImage = func(image string) bool { 345 | return containsRegisty(whitelistedRegistries, image) 346 | } 347 | } 348 | 349 | // Handle containers 350 | containers := []v1.Container{} 351 | containers = append(containers, pod.Spec.Containers...) 352 | containers = append(containers, pod.Spec.InitContainers...) 353 | for _, container := range containers { 354 | log.Println("Container Image is", container.Image) 355 | if !validateImage(container.Image) { 356 | message := fmt.Sprintf("Image is not being pulled from Private Registry: %s", container.Image) 357 | log.Printf(message) 358 | SendSlackNotification(message) 359 | admissionResponse.Allowed = false 360 | admissionResponse.Result = getInvalidContainerResponse(message) 361 | goto done 362 | } else { 363 | log.Printf("Image is being pulled from Private Registry: %s", container.Image) 364 | admissionResponse.Allowed = true && admissionResponse.Allowed 365 | } 366 | } 367 | } else { 368 | log.Printf("Namespace is %s Whitelisted", namespace) 369 | admissionResponse.Allowed = true && admissionResponse.Allowed 370 | } 371 | 372 | done: 373 | ar = v1beta1.AdmissionReview{ 374 | Response: &admissionResponse, 375 | } 376 | 377 | data, err = json.Marshal(ar) 378 | if err != nil { 379 | log.Println(err) 380 | w.WriteHeader(http.StatusInternalServerError) 381 | return 382 | } 383 | 384 | w.WriteHeader(http.StatusOK) 385 | w.Write(data) 386 | } 387 | 388 | func getInvalidContainerResponse(message string) *metav1.Status { 389 | return &metav1.Status{ 390 | Reason: metav1.StatusReasonInvalid, 391 | Details: &metav1.StatusDetails{ 392 | Causes: []metav1.StatusCause{ 393 | {Message: message}, 394 | }, 395 | }, 396 | } 397 | } 398 | 399 | // if current namespace is part of whitelisted namespaces 400 | func contains(arr []string, str string) bool { 401 | for _, a := range arr { 402 | if a == str || strings.Contains(a, str) { 403 | return true 404 | } 405 | } 406 | return false 407 | } 408 | 409 | // if current registry is part of whitelisted registries 410 | func containsRegisty(arr []string, str string) bool { 411 | for _, a := range arr { 412 | if a == str || strings.Contains(str, a) { 413 | return true 414 | } 415 | } 416 | return false 417 | } 418 | 419 | // ping responds to the request with a plain-text "Ok" message. 420 | func healthCheck(w http.ResponseWriter, r *http.Request) { 421 | log.Debugf("Serving request: %s", r.URL.Path) 422 | fmt.Fprintf(w, "Ok") 423 | } 424 | 425 | // SendSlackNotification will post to an 'Incoming Webook' url setup in Slack Apps. It accepts 426 | // some text and the slack channel is saved within Slack. 427 | func SendSlackNotification(msg string) { 428 | if webhookUrl == "" { 429 | log.Debugln("Slack Webhook URL is not provided") 430 | return 431 | } 432 | 433 | if env != "" { 434 | msg = fmt.Sprintf("[%s] %s", env, msg) 435 | } 436 | 437 | if slackDupeCache != nil { 438 | if err := slackDupeCache.Add(msg, struct{}{}, cache.DefaultExpiration); err != nil { 439 | log.Info("suppressing duplicate Slack message") 440 | return 441 | } 442 | } 443 | 444 | slackBody, _ := json.Marshal(SlackRequestBody{Text: msg}) 445 | req, err := http.NewRequest(http.MethodPost, webhookUrl, bytes.NewBuffer(slackBody)) 446 | if err != nil { 447 | log.WithError(err).Error("unable to build slack request") 448 | return 449 | } 450 | 451 | req.Header.Add("Content-Type", "application/json") 452 | 453 | client := &http.Client{Timeout: 10 * time.Second} 454 | resp, err := client.Do(req) 455 | if err != nil { 456 | log.WithError(err).Error("got error from Slack") 457 | if slackDupeCache != nil { 458 | slackDupeCache.Delete(msg) 459 | } 460 | return 461 | } 462 | defer resp.Body.Close() 463 | 464 | buf := new(bytes.Buffer) 465 | buf.ReadFrom(resp.Body) 466 | if buf.String() != "ok" { 467 | log.WithField("resp", buf.String()).Errorln("Non-ok response returned from Slack") 468 | } 469 | } 470 | -------------------------------------------------------------------------------- /cmd/tugger/main_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 Google Inc. All Rights Reserved. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // http://www.apache.org/licenses/LICENSE-2.0 6 | // Unless required by applicable law or agreed to in writing, software 7 | // distributed under the License is distributed on an "AS IS" BASIS, 8 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9 | // See the License for the specific language governing permissions and 10 | // limitations under the License. 11 | 12 | package main 13 | 14 | import ( 15 | "net/http" 16 | "net/http/httptest" 17 | "strings" 18 | "testing" 19 | "time" 20 | 21 | "github.com/infobloxopen/atlas-app-toolkit/logging" 22 | "github.com/jarcoal/httpmock" 23 | "github.com/patrickmn/go-cache" 24 | ) 25 | 26 | const ( 27 | mockSlackURL = "https://slack/" 28 | trustedRegistry = "private-registry.cluster.local" 29 | trustedAdmissionRequest = ` 30 | { 31 | "kind": "AdmissionReview", 32 | "request": { 33 | "kind": { 34 | "kind": "Pod", 35 | "version": "v1" 36 | }, 37 | "name": "myapp", 38 | "namespace": "foobar", 39 | "object": { 40 | "metadata": { 41 | "name": "myapp", 42 | "namespace": "foobar" 43 | }, 44 | "spec": { 45 | "containers": [ 46 | { 47 | "image": "` + trustedRegistry + `/nginx", 48 | "name": "nginx-frontend" 49 | }, 50 | { 51 | "image": "` + trustedRegistry + `/mysql", 52 | "name": "mysql-backend" 53 | } 54 | ], 55 | "initContainers": [ 56 | { 57 | "image": "` + trustedRegistry + `/nginx", 58 | "name": "nginx-frontend" 59 | }, 60 | { 61 | "image": "` + trustedRegistry + `/mysql", 62 | "name": "mysql-backend" 63 | } 64 | ] 65 | } 66 | } 67 | } 68 | }` 69 | untrustedAdmissionRequest = ` 70 | { 71 | "kind": "AdmissionReview", 72 | "request": { 73 | "kind": { 74 | "kind": "Pod", 75 | "version": "v1" 76 | }, 77 | "name": "myapp", 78 | "namespace": "foobar", 79 | "object": { 80 | "metadata": { 81 | "name": "myapp", 82 | "namespace": "foobar" 83 | }, 84 | "spec": { 85 | "containers": [ 86 | { 87 | "image": "nginx", 88 | "name": "nginx-frontend" 89 | }, 90 | { 91 | "image": "mysql", 92 | "name": "mysql-backend" 93 | } 94 | ], 95 | "initContainers": [ 96 | { 97 | "image": "nginx", 98 | "name": "nginx-frontend" 99 | }, 100 | { 101 | "image": "mysql", 102 | "name": "mysql-backend" 103 | } 104 | ] 105 | } 106 | } 107 | } 108 | }` 109 | mixedTrustAdmissionRequest = ` 110 | { 111 | "kind": "AdmissionReview", 112 | "request": { 113 | "kind": { 114 | "kind": "Pod", 115 | "version": "v1" 116 | }, 117 | "name": "myapp", 118 | "namespace": "foobar", 119 | "object": { 120 | "metadata": { 121 | "name": "myapp", 122 | "namespace": "foobar" 123 | }, 124 | "spec": { 125 | "containers": [ 126 | { 127 | "image": "` + trustedRegistry + `/nginx", 128 | "name": "nginx-frontend" 129 | }, 130 | { 131 | "image": "` + trustedRegistry + `/mysql", 132 | "name": "mysql-backend" 133 | } 134 | ], 135 | "initContainers": [ 136 | { 137 | "image": "` + trustedRegistry + `/nginx", 138 | "name": "nginx-frontend" 139 | }, 140 | { 141 | "image": "mysql", 142 | "name": "mysql-backend" 143 | } 144 | ] 145 | } 146 | } 147 | } 148 | }` 149 | whitelistedAdmissionRequest = ` 150 | { 151 | "kind": "AdmissionReview", 152 | "request": { 153 | "kind": { 154 | "kind": "Pod", 155 | "version": "v1" 156 | }, 157 | "name": "kube-apiserver", 158 | "namespace": "kube-system", 159 | "object": { 160 | "metadata": { 161 | "name": "kube-apiserver", 162 | "namespace": "kube-system" 163 | }, 164 | "spec": { 165 | "containers": [ 166 | { 167 | "image": "apiserver", 168 | "name": "apiserver" 169 | } 170 | ] 171 | } 172 | } 173 | } 174 | }` 175 | ) 176 | 177 | var ( 178 | testCases = []struct { 179 | name string 180 | handler func(http.ResponseWriter, *http.Request) 181 | reqMethod string 182 | reqPath string 183 | reqBody string 184 | expectStatus int 185 | expectBody string 186 | }{ 187 | { 188 | name: "ping", 189 | handler: healthCheck, 190 | expectStatus: http.StatusOK, 191 | expectBody: `Ok`, 192 | }, 193 | { 194 | name: "mutate/empty", 195 | handler: mutateAdmissionReviewHandler, 196 | reqMethod: "POST", 197 | reqPath: "/mutate", 198 | reqBody: `{}`, 199 | expectStatus: http.StatusBadRequest, 200 | }, 201 | { 202 | name: "mutate/happy", 203 | handler: mutateAdmissionReviewHandler, 204 | reqMethod: "POST", 205 | reqPath: "/mutate", 206 | reqBody: string(untrustedAdmissionRequest), 207 | expectStatus: http.StatusOK, 208 | expectBody: `{"response":{"uid":"","allowed":true,"patch":"W3sib3AiOiJhZGQiLCJwYXRoIjoiL21ldGFkYXRhL2Fubm90YXRpb25zIiwidmFsdWUiOnt9fSx7Im9wIjoicmVwbGFjZSIsInBhdGgiOiIvc3BlYy9jb250YWluZXJzLzAvaW1hZ2UiLCJ2YWx1ZSI6InByaXZhdGUtcmVnaXN0cnkuY2x1c3Rlci5sb2NhbC9uZ2lueCJ9LHsib3AiOiJhZGQiLCJwYXRoIjoiL21ldGFkYXRhL2Fubm90YXRpb25zL3R1Z2dlci1vcmlnaW5hbC1pbWFnZS0wIiwidmFsdWUiOiJuZ2lueCJ9LHsib3AiOiJyZXBsYWNlIiwicGF0aCI6Ii9zcGVjL2NvbnRhaW5lcnMvMS9pbWFnZSIsInZhbHVlIjoicHJpdmF0ZS1yZWdpc3RyeS5jbHVzdGVyLmxvY2FsL215c3FsIn0seyJvcCI6ImFkZCIsInBhdGgiOiIvbWV0YWRhdGEvYW5ub3RhdGlvbnMvdHVnZ2VyLW9yaWdpbmFsLWltYWdlLTEiLCJ2YWx1ZSI6Im15c3FsIn0seyJvcCI6InJlcGxhY2UiLCJwYXRoIjoiL3NwZWMvaW5pdENvbnRhaW5lcnMvMC9pbWFnZSIsInZhbHVlIjoicHJpdmF0ZS1yZWdpc3RyeS5jbHVzdGVyLmxvY2FsL25naW54In0seyJvcCI6ImFkZCIsInBhdGgiOiIvbWV0YWRhdGEvYW5ub3RhdGlvbnMvdHVnZ2VyLW9yaWdpbmFsLWluaXQtaW1hZ2UtMCIsInZhbHVlIjoibmdpbngifSx7Im9wIjoicmVwbGFjZSIsInBhdGgiOiIvc3BlYy9pbml0Q29udGFpbmVycy8xL2ltYWdlIiwidmFsdWUiOiJwcml2YXRlLXJlZ2lzdHJ5LmNsdXN0ZXIubG9jYWwvbXlzcWwifSx7Im9wIjoiYWRkIiwicGF0aCI6Ii9tZXRhZGF0YS9hbm5vdGF0aW9ucy90dWdnZXItb3JpZ2luYWwtaW5pdC1pbWFnZS0xIiwidmFsdWUiOiJteXNxbCJ9LHsib3AiOiJhZGQiLCJwYXRoIjoiL21ldGFkYXRhL2xhYmVscyIsInZhbHVlIjp7fX0seyJvcCI6ImFkZCIsInBhdGgiOiIvbWV0YWRhdGEvbGFiZWxzL3R1Z2dlci1tb2RpZmllZCIsInZhbHVlIjoidHJ1ZSJ9XQ==","patchType":"JSONPatch"}}`, 209 | }, 210 | { 211 | name: "mutate/trusted", 212 | handler: mutateAdmissionReviewHandler, 213 | reqMethod: "POST", 214 | reqPath: "/mutate", 215 | reqBody: string(trustedAdmissionRequest), 216 | expectStatus: http.StatusOK, 217 | expectBody: `{"response":{"uid":"","allowed":true}}`, 218 | }, 219 | { 220 | name: "mutate/whitelisted", 221 | handler: mutateAdmissionReviewHandler, 222 | reqMethod: "POST", 223 | reqPath: "/mutate", 224 | reqBody: string(whitelistedAdmissionRequest), 225 | expectStatus: http.StatusOK, 226 | expectBody: `{"response":{"uid":"","allowed":true}}`, 227 | }, 228 | { 229 | name: "validate/untrusted", 230 | handler: validateAdmissionReviewHandler, 231 | reqMethod: "POST", 232 | reqPath: "/validate", 233 | reqBody: string(untrustedAdmissionRequest), 234 | expectStatus: http.StatusOK, 235 | expectBody: `{"response":{"uid":"","allowed":false,"status":{"metadata":{},"reason":"Invalid","details":{"causes":[{"message":"Image is not being pulled from Private Registry: nginx"}]}}}}`, 236 | }, 237 | { 238 | name: "validate/mixedtrust", 239 | handler: validateAdmissionReviewHandler, 240 | reqMethod: "POST", 241 | reqPath: "/validate", 242 | reqBody: string(mixedTrustAdmissionRequest), 243 | expectStatus: http.StatusOK, 244 | expectBody: `{"response":{"uid":"","allowed":false,"status":{"metadata":{},"reason":"Invalid","details":{"causes":[{"message":"Image is not being pulled from Private Registry: mysql"}]}}}}`, 245 | }, 246 | { 247 | name: "validate/trusted", 248 | handler: validateAdmissionReviewHandler, 249 | reqMethod: "POST", 250 | reqPath: "/validate", 251 | reqBody: string(trustedAdmissionRequest), 252 | expectStatus: http.StatusOK, 253 | expectBody: `{"response":{"uid":"","allowed":true}}`, 254 | }, 255 | { 256 | name: "validate/whitelisted", 257 | handler: validateAdmissionReviewHandler, 258 | reqMethod: "POST", 259 | reqPath: "/validate", 260 | reqBody: string(whitelistedAdmissionRequest), 261 | expectStatus: http.StatusOK, 262 | expectBody: `{"response":{"uid":"","allowed":true}}`, 263 | }, 264 | } 265 | ) 266 | 267 | func TestHandlerLegacy(t *testing.T) { 268 | dockerRegistryUrl = trustedRegistry 269 | whitelistRegistries = dockerRegistryUrl 270 | whitelistedRegistries = strings.Split(whitelistRegistries, ",") 271 | testHandler(t) 272 | } 273 | 274 | func TestHandlerPolicy(t *testing.T) { 275 | policy, _ = NewPolicy() 276 | policy.Load([]byte(` 277 | rules: 278 | - pattern: ^` + trustedRegistry + `/.* 279 | - pattern: (.*) 280 | replacement: ` + trustedRegistry + `/$1 281 | `)) 282 | defer func() { 283 | policy = nil 284 | }() 285 | testHandler(t) 286 | } 287 | 288 | func testHandler(t *testing.T) { 289 | whitelistNamespaces = "kube-system" 290 | whitelistedNamespaces = strings.Split(whitelistNamespaces, ",") 291 | for _, tt := range testCases { 292 | t.Run(tt.name, func(t *testing.T) { 293 | req, err := http.NewRequest(tt.reqMethod, tt.reqPath, strings.NewReader(tt.reqBody)) 294 | if err != nil { 295 | t.Fatal(err) 296 | } 297 | 298 | rr := httptest.NewRecorder() 299 | handler := http.HandlerFunc(tt.handler) 300 | 301 | handler.ServeHTTP(rr, req) 302 | 303 | // Check the status code is what we expect. 304 | if status := rr.Code; status != tt.expectStatus { 305 | t.Errorf("handler returned wrong status code: got %v want %v", 306 | status, tt.expectStatus) 307 | } 308 | 309 | // Check the response body is what we expect. 310 | if rr.Body.String() != tt.expectBody { 311 | t.Errorf("handler returned unexpected body: got %v want %v", 312 | rr.Body.String(), tt.expectBody) 313 | } 314 | }) 315 | } 316 | } 317 | 318 | func runMockRegistry() func() { 319 | httpmock.Activate() 320 | httpmock.RegisterResponder("GET", "https://index.docker.io/v2/", 321 | httpmock.NewStringResponder(http.StatusOK, `{}`)) 322 | httpmock.RegisterResponder("GET", "https://index.docker.io/v2/library/nginx/manifests/latest", 323 | httpmock.NewStringResponder(http.StatusOK, `{}`)) 324 | httpmock.RegisterResponder("GET", "https://index.docker.io/v2/jainishshah17/nginx/manifests/latest", 325 | httpmock.NewStringResponder(http.StatusOK, `{}`)) 326 | httpmock.RegisterResponder("GET", "https://index.docker.io/v2/jainishshah17/nginx/manifests/notexist", 327 | httpmock.NewStringResponder(http.StatusNotFound, `{"errors":[{"code":"MANIFEST_UNKNOWN","message":"manifest unknown","detail":{"Tag":"notexist"}}]}`)) 328 | return httpmock.DeactivateAndReset 329 | } 330 | 331 | func Test_imageExists(t *testing.T) { 332 | tests := []struct { 333 | name string 334 | image string 335 | want bool 336 | }{ 337 | { 338 | name: "happy", 339 | image: "nginx", 340 | want: true, 341 | }, 342 | { 343 | name: "doesn't exist", 344 | image: "jainishshah17/nginx:notexist", 345 | want: false, 346 | }, 347 | { 348 | name: "doesn't parse", 349 | image: "doesn't parse", 350 | want: false, 351 | }, 352 | } 353 | defer runMockRegistry()() 354 | for _, tt := range tests { 355 | t.Run(tt.name, func(t *testing.T) { 356 | if got := imageExists(tt.image); got != tt.want { 357 | t.Errorf("imageExists() = %v, want %v", got, tt.want) 358 | } 359 | }) 360 | } 361 | } 362 | 363 | func runMockSlack() func() { 364 | httpmock.Activate() 365 | httpmock.RegisterResponder("POST", mockSlackURL, 366 | httpmock.NewStringResponder(http.StatusOK, `ok`)) 367 | httpmock.RegisterResponder("POST", mockSlackURL+"error", 368 | httpmock.NewStringResponder(http.StatusBadRequest, `invalid arguments`)) 369 | return httpmock.DeactivateAndReset 370 | } 371 | 372 | func TestSendSlackNotification(t *testing.T) { 373 | defaultEnv := env 374 | defaultSlackDupeCache := slackDupeCache 375 | defaultWebhookURL := webhookUrl 376 | sharedDupeCache := cache.New(time.Minute, time.Minute) 377 | tests := []struct { 378 | name string 379 | msg string 380 | env string 381 | slackDupeCache *cache.Cache 382 | webhookURL string 383 | }{ 384 | { 385 | name: "disabled", 386 | webhookURL: "", 387 | }, 388 | { 389 | name: "happy", 390 | msg: "foo does not exist in private registry", 391 | webhookURL: mockSlackURL, 392 | }, 393 | { 394 | name: "with env", 395 | msg: "foo does not exist in private registry", 396 | env: "dev-1", 397 | webhookURL: mockSlackURL, 398 | }, 399 | { 400 | name: "with dupe cache miss", 401 | msg: "foo does not exist in private registry", 402 | slackDupeCache: sharedDupeCache, 403 | webhookURL: mockSlackURL, 404 | }, 405 | { 406 | name: "with dupe cache hit", 407 | msg: "foo does not exist in private registry", 408 | slackDupeCache: sharedDupeCache, 409 | webhookURL: mockSlackURL, 410 | }, 411 | { 412 | name: "slack connection error", 413 | webhookURL: "example.com", 414 | }, 415 | { 416 | name: "slack response error", 417 | webhookURL: mockSlackURL + "error", 418 | }, 419 | { 420 | name: "build request error", 421 | webhookURL: "://", 422 | }, 423 | } 424 | defer runMockSlack()() 425 | for _, tt := range tests { 426 | t.Run(tt.name, func(t *testing.T) { 427 | env = tt.env 428 | slackDupeCache = tt.slackDupeCache 429 | webhookUrl = tt.webhookURL 430 | defer func() { 431 | env = defaultEnv 432 | slackDupeCache = defaultSlackDupeCache 433 | webhookUrl = defaultWebhookURL 434 | }() 435 | SendSlackNotification(tt.msg) 436 | }) 437 | } 438 | } 439 | 440 | func init() { 441 | log = logging.New("debug") 442 | } 443 | -------------------------------------------------------------------------------- /cmd/tugger/policy.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "regexp" 7 | 8 | yaml "gopkg.in/yaml.v2" 9 | ) 10 | 11 | // Pattern defines one rule in a policy 12 | type Pattern struct { 13 | re *regexp.Regexp 14 | Pattern string 15 | Replacement string `yaml:",omitempty"` 16 | Condition string `yaml:",omitempty"` 17 | } 18 | 19 | // Policy defines a policy to mutate image names 20 | type Policy struct { 21 | Rules []*Pattern 22 | } 23 | 24 | // PolicyOption options for NewPolicy() 25 | type PolicyOption func(p *Policy) error 26 | 27 | // Load loads a policy from YAML 28 | func (p *Policy) Load(in []byte) error { 29 | if err := yaml.Unmarshal(in, p); err != nil { 30 | return err 31 | } 32 | if len(p.Rules) == 0 { 33 | return fmt.Errorf("policy rules must be non-empty slice") 34 | } 35 | for _, rule := range p.Rules { 36 | var err error 37 | if rule.re, err = regexp.Compile(rule.Pattern); err != nil { 38 | return err 39 | } 40 | switch rule.Condition { 41 | case "": 42 | case "Always": 43 | case "Exists": 44 | default: 45 | return fmt.Errorf("condition must be null/Always (default) or Exists, not %s", rule.Condition) 46 | } 47 | } 48 | log.WithField("policy", string(in)).Print("loaded policy") 49 | return nil 50 | } 51 | 52 | // MutateImage transforms the image name according to the policy, or returns false if there were no matches 53 | func (p *Policy) MutateImage(image string) (string, bool) { 54 | var msg string 55 | for _, rule := range p.Rules { 56 | if rule.re.MatchString(image) { 57 | image := image 58 | if rule.Replacement != "" { 59 | image = rule.re.ReplaceAllString(image, rule.Replacement) 60 | } 61 | if rule.Condition == "Exists" && !imageExists(image) { 62 | msg = fmt.Sprintf("%s does not exist in private registry", image) 63 | log.Debug(msg) 64 | continue 65 | } 66 | return image, true 67 | } 68 | } 69 | if msg != "" { 70 | log.Print(msg) 71 | SendSlackNotification(msg) 72 | } 73 | return image, false 74 | } 75 | 76 | // ValidateImage checks if an image conforms to any of the patterns in a policy without replacement 77 | func (p *Policy) ValidateImage(image string) bool { 78 | for _, rule := range p.Rules { 79 | if rule.Replacement != "" { 80 | continue 81 | } 82 | if rule.Condition == "Exists" && !imageExists(image) { 83 | continue 84 | } 85 | if rule.re.MatchString(image) { 86 | return true 87 | } 88 | } 89 | return false 90 | } 91 | 92 | // NewPolicy creates a Policy 93 | func NewPolicy(opts ...PolicyOption) (*Policy, error) { 94 | p := &Policy{} 95 | for _, opt := range opts { 96 | if err := opt(p); err != nil { 97 | return nil, err 98 | } 99 | } 100 | return p, nil 101 | } 102 | 103 | // WithConfigFile loads a policy from a yaml file 104 | func WithConfigFile(filename string) PolicyOption { 105 | return func(p *Policy) error { 106 | in, err := ioutil.ReadFile(filename) 107 | if err != nil { 108 | return err 109 | } 110 | return p.Load(in) 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /cmd/tugger/policy_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "io/ioutil" 5 | "os" 6 | "reflect" 7 | "testing" 8 | ) 9 | 10 | var defaultPolicy = ` 11 | rules: 12 | - pattern: ^jainishshah17/.* 13 | condition: Exists 14 | - pattern: always 15 | condition: Always 16 | - pattern: nomatch/(.*) 17 | replacement: jainishshah17/$1 18 | - pattern: (.*) 19 | replacement: jainishshah17/$1 20 | condition: Exists 21 | ` 22 | 23 | var invalidCondition = ` 24 | rules: 25 | - pattern: ^jainishshah17/.* 26 | condition: Always 27 | - pattern: ^foo/.* 28 | condition: bar 29 | - pattern: (.*) 30 | replacement: jainishshah17/$1 31 | ` 32 | 33 | var badRegex = ` 34 | rules: 35 | - pattern: ^jainishsha$(.* 36 | ` 37 | 38 | func TestPolicy_Load(t *testing.T) { 39 | type fields struct { 40 | Rules []*Pattern 41 | } 42 | type args struct { 43 | in []byte 44 | } 45 | tests := []struct { 46 | name string 47 | fields fields 48 | args args 49 | wantErr bool 50 | }{ 51 | { 52 | name: "happy", 53 | args: args{ 54 | in: []byte(defaultPolicy), 55 | }, 56 | wantErr: false, 57 | }, 58 | { 59 | name: "parse error", 60 | args: args{ 61 | in: []byte(`not yaml`), 62 | }, 63 | wantErr: true, 64 | }, 65 | { 66 | name: "invalid condition", 67 | args: args{ 68 | in: []byte(invalidCondition), 69 | }, 70 | wantErr: true, 71 | }, 72 | { 73 | name: "invalid regex", 74 | args: args{ 75 | in: []byte(badRegex), 76 | }, 77 | wantErr: true, 78 | }, 79 | { 80 | name: "empty rules", 81 | args: args{ 82 | in: []byte(`rules: []`), 83 | }, 84 | wantErr: true, 85 | }, 86 | } 87 | for _, tt := range tests { 88 | t.Run(tt.name, func(t *testing.T) { 89 | p := &Policy{ 90 | Rules: tt.fields.Rules, 91 | } 92 | if err := p.Load(tt.args.in); (err != nil) != tt.wantErr { 93 | t.Errorf("Policy.Load() error = %v, wantErr %v", err, tt.wantErr) 94 | } 95 | t.Log(p) 96 | }) 97 | } 98 | } 99 | 100 | func TestPolicy_MutateImage(t *testing.T) { 101 | tests := []struct { 102 | name string 103 | in []byte 104 | image string 105 | want string 106 | allowed bool 107 | }{ 108 | { 109 | name: "happy noop", 110 | in: []byte(defaultPolicy), 111 | image: "jainishshah17/nginx", 112 | want: "jainishshah17/nginx", 113 | allowed: true, 114 | }, 115 | { 116 | name: "happy mutate", 117 | in: []byte(defaultPolicy), 118 | image: "nginx", 119 | want: "jainishshah17/nginx", 120 | allowed: true, 121 | }, 122 | { 123 | name: "happy always", 124 | in: []byte(defaultPolicy), 125 | image: "always", 126 | want: "always", 127 | allowed: true, 128 | }, 129 | { 130 | name: "doesn't exist", 131 | in: []byte(defaultPolicy), 132 | image: "jainishshah17/nginx:notexist", 133 | want: "jainishshah17/nginx:notexist", 134 | allowed: false, 135 | }, 136 | } 137 | defer runMockRegistry()() 138 | for _, tt := range tests { 139 | t.Run(tt.name, func(t *testing.T) { 140 | p, err := NewPolicy() 141 | if err != nil { 142 | t.Error(err) 143 | } 144 | p.Load(tt.in) 145 | got, allowed := p.MutateImage(tt.image) 146 | if got != tt.want { 147 | t.Errorf("Policy.MutateImage() got = %v, want %v", got, tt.want) 148 | } 149 | if allowed != tt.allowed { 150 | t.Errorf("Policy.MutateImage() allowed = %v, want %v", allowed, tt.allowed) 151 | } 152 | }) 153 | } 154 | } 155 | 156 | func TestPolicy_ValidateImage(t *testing.T) { 157 | tests := []struct { 158 | name string 159 | in []byte 160 | image string 161 | want bool 162 | }{ 163 | { 164 | name: "happy", 165 | in: []byte(defaultPolicy), 166 | image: "jainishshah17/nginx", 167 | want: true, 168 | }, 169 | { 170 | name: "deny", 171 | in: []byte(defaultPolicy), 172 | image: "nginx", 173 | want: false, 174 | }, 175 | { 176 | name: "doesn't exist", 177 | in: []byte(defaultPolicy), 178 | image: "jainishshah17/nginx:notexist", 179 | want: false, 180 | }, 181 | } 182 | defer runMockRegistry()() 183 | for _, tt := range tests { 184 | t.Run(tt.name, func(t *testing.T) { 185 | p, err := NewPolicy() 186 | if err != nil { 187 | t.Error(err) 188 | } 189 | p.Load(tt.in) 190 | if got := p.ValidateImage(tt.image); got != tt.want { 191 | t.Errorf("Policy.ValidateImage() = %v, want %v", got, tt.want) 192 | } 193 | }) 194 | } 195 | } 196 | 197 | func TestNewPolicy(t *testing.T) { 198 | tmpfile, err := ioutil.TempFile("", "policy*.yaml") 199 | if err != nil { 200 | t.Fatal(err) 201 | } 202 | defer os.Remove(tmpfile.Name()) // clean up 203 | if _, err := tmpfile.Write([]byte(defaultPolicy)); err != nil { 204 | t.Fatal(err) 205 | } 206 | if err := tmpfile.Close(); err != nil { 207 | t.Fatal(err) 208 | } 209 | p, err := NewPolicy() 210 | if err != nil { 211 | t.Fatal(err) 212 | } 213 | if err := p.Load([]byte(defaultPolicy)); err != nil { 214 | t.Fatal(err) 215 | } 216 | tests := []struct { 217 | name string 218 | opts []PolicyOption 219 | want *Policy 220 | wantErr bool 221 | }{ 222 | { 223 | name: "happy file", 224 | opts: []PolicyOption{WithConfigFile(tmpfile.Name())}, 225 | want: p, 226 | wantErr: false, 227 | }, 228 | { 229 | name: "missing file", 230 | opts: []PolicyOption{WithConfigFile("foo bar.yaml")}, 231 | wantErr: true, 232 | }, 233 | } 234 | for _, tt := range tests { 235 | t.Run(tt.name, func(t *testing.T) { 236 | got, err := NewPolicy(tt.opts...) 237 | if (err != nil) != tt.wantErr { 238 | t.Errorf("NewPolicy() error = %v, wantErr %v", err, tt.wantErr) 239 | return 240 | } 241 | if !reflect.DeepEqual(got, tt.want) { 242 | t.Errorf("NewPolicy() = %v, want %v", got, tt.want) 243 | } 244 | }) 245 | } 246 | } 247 | -------------------------------------------------------------------------------- /deployment/tugger-deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | name: tugger-deployment 5 | labels: 6 | app: tugger 7 | spec: 8 | replicas: 1 9 | selector: 10 | matchLabels: 11 | app: tugger 12 | template: 13 | metadata: 14 | labels: 15 | app: tugger 16 | spec: 17 | containers: 18 | - name: tugger 19 | image: jainishshah17/tugger:0.1.8 20 | imagePullPolicy: Always 21 | env: 22 | - name: DOCKER_REGISTRY_URL 23 | value: "jainishshah17" 24 | - name: REGISTRY_SECRET_NAME 25 | value: 'regsecret' 26 | - name: WHITELIST_NAMESPACES 27 | value: "kube-system,default" 28 | - name: WHITELIST_REGISTRIES 29 | value: "jainishshah17" 30 | - name: WEBHOOK_URL 31 | value: "${WEBHOOK_URL}" 32 | ports: 33 | - containerPort: 443 34 | name: https 35 | volumeMounts: 36 | - name: tls 37 | mountPath: /etc/admission-controller/tls 38 | resources: {} 39 | volumes: 40 | - name: tls 41 | secret: 42 | secretName: tugger-certs 43 | -------------------------------------------------------------------------------- /deployment/tugger-svc.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: tugger 5 | labels: 6 | app: tugger 7 | spec: 8 | type: ClusterIP 9 | ports: 10 | - port: 443 11 | protocol: "TCP" 12 | name: https 13 | selector: 14 | app: tugger -------------------------------------------------------------------------------- /test/nginx.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: v1 3 | kind: Namespace 4 | metadata: 5 | name: nginx 6 | --- 7 | apiVersion: apps/v1 8 | kind: Deployment 9 | metadata: 10 | name: nginx 11 | namespace: nginx 12 | labels: 13 | test: tugger 14 | spec: 15 | replicas: 1 16 | selector: 17 | matchLabels: 18 | test: tugger 19 | template: 20 | metadata: 21 | labels: 22 | test: tugger 23 | spec: 24 | containers: 25 | - name: nginx 26 | image: nginx 27 | imagePullPolicy: IfNotPresent 28 | imagePullSecrets: 29 | - name: original-secret 30 | -------------------------------------------------------------------------------- /tls/gen-cert.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | #title="default" 3 | 4 | #[ -z ${title} ] && service="tugger" 5 | #[ -z ${title} ] && secret="tugger-certs" 6 | #[ -z ${title} ] && namespace="default" 7 | 8 | service="tugger" 9 | secret="tugger-certs" 10 | namespace="default" 11 | 12 | csrName=${service}.${namespace} 13 | echo "csrName is :${csrName}" 14 | tmpdir=$(mktemp -d) 15 | echo "creating certs in tmpdir ${tmpdir} " 16 | 17 | cat <> ${tmpdir}/csr.conf 18 | [req] 19 | req_extensions = v3_req 20 | distinguished_name = req_distinguished_name 21 | [req_distinguished_name] 22 | [ v3_req ] 23 | basicConstraints = CA:FALSE 24 | keyUsage = nonRepudiation, digitalSignature, keyEncipherment 25 | extendedKeyUsage = serverAuth 26 | subjectAltName = @alt_names 27 | [alt_names] 28 | DNS.1 = ${service} 29 | DNS.2 = ${service}.${namespace} 30 | DNS.3 = ${service}.${namespace}.svc 31 | EOF 32 | 33 | openssl genrsa -out ${tmpdir}/server-key.pem 2048 34 | openssl req -new -key ${tmpdir}/server-key.pem -subj "/CN=${service}.${namespace}.svc" -out ${tmpdir}/server.csr -config ${tmpdir}/csr.conf 35 | 36 | # clean-up any previously created CSR for our service. Ignore errors if not present. 37 | kubectl delete csr ${csrName} 2>/dev/null || true 38 | 39 | # create server cert/key CSR and send to k8s API 40 | cat <&2 75 | exit 1 76 | fi 77 | echo ${serverCert} | openssl base64 -d -A -out ${tmpdir}/server-cert.pem 78 | 79 | 80 | # create the secret with CA cert and server cert/key 81 | kubectl create secret tls ${secret} \ 82 | --key=${tmpdir}/server-key.pem \ 83 | --cert=${tmpdir}/server-cert.pem \ 84 | --dry-run -o yaml | 85 | kubectl -n ${namespace} apply -f - 86 | -------------------------------------------------------------------------------- /webhook/tugger-mutating-webhook-configuration.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: admissionregistration.k8s.io/v1beta1 2 | kind: MutatingWebhookConfiguration 3 | metadata: 4 | name: tugger-mutate 5 | webhooks: 6 | - name: tugger-mutate.jainishshah17.com 7 | rules: 8 | - operations: [ "CREATE" ] 9 | apiGroups: [""] 10 | apiVersions: ["v1"] 11 | resources: ["pods"] 12 | failurePolicy: Ignore 13 | clientConfig: 14 | service: 15 | name: tugger 16 | namespace: default 17 | path: "/mutate" 18 | caBundle: ${CA_BUNDLE} -------------------------------------------------------------------------------- /webhook/tugger-validating-webhook-configuration.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: admissionregistration.k8s.io/v1beta1 2 | kind: ValidatingWebhookConfiguration 3 | metadata: 4 | name: tugger-validate 5 | webhooks: 6 | - name: tugger-validate.jainishshah17.com 7 | rules: 8 | - apiGroups: 9 | - "" 10 | apiVersions: 11 | - v1 12 | operations: 13 | - CREATE 14 | resources: 15 | - pods 16 | failurePolicy: Ignore 17 | clientConfig: 18 | service: 19 | name: tugger 20 | namespace: default 21 | path: "/validate" 22 | caBundle: ${CA_BUNDLE} 23 | -------------------------------------------------------------------------------- /webhook/webhook-patch-ca-bundle.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -o errexit 3 | set -o nounset 4 | set -o pipefail 5 | 6 | ROOT=$(cd $(dirname $0)/../../; pwd) 7 | 8 | export CA_BUNDLE=$(kubectl get configmap -n kube-system extension-apiserver-authentication -o=jsonpath='{.data.client-ca-file}' | base64 | tr -d '\n') 9 | 10 | echo "${CA_BUNDLE}" --------------------------------------------------------------------------------