├── .circleci └── config.yml ├── .dockerignore ├── .github └── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── .gitignore ├── .goreleaser.yml ├── .pipelines ├── any-branch.yml ├── pr.yml └── release.yml ├── Dockerfile ├── LICENSE ├── Makefile ├── README.md ├── benchmark ├── benchmark.sh ├── mutate_body └── validate_body ├── chart └── kubenab │ ├── .helmignore │ ├── Chart.yaml │ ├── templates │ ├── NOTES.txt │ ├── _helpers.tpl │ ├── deployment.yaml │ ├── hpa.yaml │ ├── metrics.yaml │ ├── mutating-webhook.yaml │ ├── pki.yaml │ ├── role.yaml │ ├── rolebinding.yaml │ ├── service.yaml │ ├── serviceaccount.yaml │ └── validating-webhook.yaml │ └── values.yaml ├── cmd └── kubenab │ ├── admissions.go │ ├── go.mod │ ├── go.sum │ ├── log │ ├── log.go │ ├── log_debug.go │ └── log_release.go │ ├── main.go │ └── version.go ├── deployment ├── kubenab-deployment.yaml └── kubenab-svc.yaml ├── test └── nginx.yaml ├── tls └── gen-cert.sh └── webhook ├── kubenab-mutating-webhook-configuration.yaml ├── kubenab-validating-webhook-configuration.yaml └── webhook-patch-ca-bundle.sh /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | jobs: 3 | untagged-build: 4 | docker: 5 | - image: circleci/golang:1.13 6 | working_directory: /go/src/github.com/jfrog/kubenab 7 | steps: 8 | - checkout 9 | - run: make build 10 | workflows: 11 | version: 2 12 | untagged-build: 13 | jobs: 14 | - untagged-build 15 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | tmp 2 | .idea 3 | README.md 4 | hooks 5 | chart 6 | build.sh 7 | .pipeline 8 | bin 9 | tmp 10 | 11 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | 11 | 12 | **Describe the bug** 13 | A clear and concise description of what the bug is. 14 | 15 | **To Reproduce** 16 | Steps to reproduce the behavior (example below): 17 | 1. Install `kubenab` with those Settings: _XXX_ 18 | 2. Create a new Pod 19 | 3. Check status with `kubectl describe [POD]` 20 | 21 | **Expected behavior** 22 | A clear and concise description of what you expected to happen. 23 | 24 | **Logs** 25 | Please add the related Logs to better understand your problem. (_Note: Please use Markdown to format the Log!_) 26 | 27 | **Additional context** 28 | Add any other context about the problem here. 29 | 30 | 31 | ### Versions 32 | 33 | * **Helm**: 34 | * **Helm Chart Version**: 35 | * **Kubernetes Cluster Version**: 36 | * **`kubenab` Version**: 37 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | bin/ 2 | files/ 3 | tmp/ 4 | credentials/ 5 | override-values.yaml 6 | artifactory.creds* 7 | SUBSTITUTIONS 8 | .idea 9 | .vscode 10 | *.swp 11 | -------------------------------------------------------------------------------- /.goreleaser.yml: -------------------------------------------------------------------------------- 1 | env: 2 | - GO111MODULE=on 3 | - GOPROXY=https://gocenter.io 4 | builds: 5 | - main: cmd/kubenab/main.go 6 | binary: kubenab 7 | env: 8 | - CGO_ENABLED=0 9 | goos: 10 | - darwin 11 | - linux 12 | - windows 13 | goarch: 14 | - amd64 15 | flags: 16 | - -tags 'strip_debug' 17 | archives: 18 | - format: tar.gz 19 | name_template: "kubenab_{{ .Version }}_{{ .Os }}_{{ .Arch }}" 20 | files: 21 | - LICENSE 22 | - README.md 23 | checksum: 24 | name_template: 'checksums.txt' 25 | -------------------------------------------------------------------------------- /.pipelines/any-branch.yml: -------------------------------------------------------------------------------- 1 | 2 | resources: 3 | - name: kubenab_any_branch 4 | type: GitRepo 5 | configuration: 6 | gitProvider: jfrogsolutionsci_github 7 | path: jfrog/kubenab 8 | files: 9 | exclude: .pipelines/.*.yml$ 10 | branches: 11 | exclude: master 12 | 13 | pipelines: 14 | - name: kubenabAnyBranch 15 | steps: 16 | - name: build_image 17 | type: DockerBuild 18 | configuration: 19 | dockerFileLocation: . 20 | dockerFileName: Dockerfile 21 | dockerImageName: kubenab 22 | dockerImageTag: $run_number 23 | inputResources: 24 | - name: kubenab_any_branch 25 | integrations: 26 | - name: cpe_pipeline_slack 27 | execution: 28 | onStart: 29 | - send_notification cpe_pipeline_slack --text "Starting kubenabAnyBranch branch ${res_kubenab_any_branch_branchName} ${step_name}_buildNumber=${run_number}" 30 | onSuccess: 31 | - send_notification cpe_pipeline_slack --text "kubenabAnyBranch branch ${res_kubenab_any_branch_branchName} ${step_name}_buildNumber=${run_number} - SUCCESS" 32 | onFailure: 33 | - send_notification cpe_pipeline_slack --text "kubenabAnyBranch branch ${res_kubenab_any_branch_branchName} ${step_name}_buildNumber=${run_number} - FAILED" 34 | -------------------------------------------------------------------------------- /.pipelines/pr.yml: -------------------------------------------------------------------------------- 1 | resources: 2 | - name: kubenab_pr 3 | type: GitRepo 4 | configuration: 5 | gitProvider: jfrogsolutionsci_github 6 | path: jfrog/kubenab 7 | files: 8 | exclude: .pipelines/.*.yml$ 9 | branches: 10 | exclude: master 11 | buildOn: 12 | commit: false 13 | pullRequestCreate: true 14 | 15 | pipelines: 16 | - name: kubenabPr 17 | steps: 18 | - name: build_image_pr 19 | type: DockerBuild 20 | configuration: 21 | dockerFileLocation: . 22 | dockerFileName: Dockerfile 23 | dockerImageName: kubenab 24 | dockerImageTag: $run_number 25 | inputResources: 26 | - name: kubenab_pr 27 | integrations: 28 | - name: cpe_pipeline_slack 29 | execution: 30 | onStart: 31 | - send_notification cpe_pipeline_slack --text "Starting kubenabPr ${step_name}_buildNumber=${run_number}" 32 | onSuccess: 33 | - send_notification cpe_pipeline_slack --text "kubenabPr ${step_name}_buildNumber=${run_number} - SUCCESS" 34 | onFailure: 35 | - send_notification cpe_pipeline_slack --text "kubenabPr ${step_name}_buildNumber=${run_number} - FAILED" 36 | -------------------------------------------------------------------------------- /.pipelines/release.yml: -------------------------------------------------------------------------------- 1 | resources: 2 | - name: kubenab_release 3 | type: GitRepo 4 | configuration: 5 | gitProvider: jfrogsolutionsci_github 6 | path: jfrog/kubenab 7 | files: 8 | exclude: .pipelines/.*.yml$ 9 | branches: 10 | include: master 11 | tags: 12 | include: .*.*.* 13 | buildOn: 14 | commit: false 15 | tagCreate: true 16 | 17 | pipelines: 18 | - name: kubenabRelease 19 | steps: 20 | - name: build_image 21 | type: DockerBuild 22 | configuration: 23 | affinityGroup: bldGroup 24 | dockerFileLocation: . 25 | dockerFileName: Dockerfile 26 | dockerImageName: kubenab 27 | dockerImageTag: $res_kubenab_release_gitTagName 28 | inputResources: 29 | - name: kubenab_release 30 | integrations: 31 | - name: cpe_pipeline_slack 32 | execution: 33 | onStart: 34 | - send_notification cpe_pipeline_slack --text "Starting kubenabRelease v$res_kubenab_release_gitTagName ${step_name}_buildNumber=${run_number}" 35 | onSuccess: 36 | - send_notification cpe_pipeline_slack --text "kubenabRelease v$res_kubenab_release_gitTagName ${step_name}_buildNumber=${run_number} - SUCCESS" 37 | onFailure: 38 | - send_notification cpe_pipeline_slack --text "kubenabRelease v$res_kubenab_release_gitTagName ${step_name}_buildNumber=${run_number} - FAILED" 39 | - name: push_image 40 | type: Bash 41 | configuration: 42 | affinityGroup: bldGroup 43 | environmentVariables: 44 | TAG_NAME: $res_kubenab_release_gitTagName 45 | BINTRAY_REPO: ${int_jfrogsolutionsci_bintray_repo//_/-}.bintray.io 46 | inputResources: 47 | - name: kubenab_release 48 | trigger: false 49 | integrations: 50 | - name: jfrogsolutionsci_bintray 51 | - name: cpe_pipeline_slack 52 | inputSteps: 53 | - name: build_image 54 | execution: 55 | onStart: 56 | - send_notification cpe_pipeline_slack --text "Starting kubenabRelease of docker image ${step_name}_buildNumber=${run_number}" 57 | onExecute: 58 | - docker login -u=${int_jfrogsolutionsci_bintray_user} -p=${int_jfrogsolutionsci_bintray_password} ${BINTRAY_REPO} 59 | - docker tag kubenab:${TAG_NAME} ${BINTRAY_REPO}/kubenab:${TAG_NAME} 60 | - docker push ${BINTRAY_REPO}/kubenab:${TAG_NAME} 61 | onSuccess: 62 | - send_notification cpe_pipeline_slack --text "kubenabRelease of docker image v${TAG_NAME} ${step_name}_buildNumber=${run_number} - SUCCESS" 63 | onFailure: 64 | - send_notification cpe_pipeline_slack --text "kubenabRelease of docker image v${TAG_NAME} ${step_name}_buildNumber=${run_number} - FAILED" 65 | - name: goreleaser 66 | type: Bash 67 | configuration: 68 | runtime: 69 | type: image 70 | image: 71 | auto: 72 | language: go 73 | versions: 74 | - "1.12.5" 75 | environmentVariables: 76 | TAG_NAME: $res_kubenab_release_gitTagName 77 | GITHUB_TOKEN: ${int_jfrogsolutionsci_github_token} 78 | inputResources: 79 | - name: kubenab_release 80 | trigger: false 81 | integrations: 82 | - name: jfrogsolutionsci_github 83 | - name: cpe_pipeline_slack 84 | inputSteps: 85 | - name: build_image 86 | execution: 87 | onStart: 88 | - send_notification cpe_pipeline_slack --text "Starting kubenabRelease goreleaser v${TAG_NAME} ${step_name}_buildNumber=${run_number}" 89 | onExecute: 90 | - cd $res_kubenab_release_resourcePath 91 | - ls 92 | - pwd 93 | - curl -sL https://raw.githubusercontent.com/goreleaser/get/master/get | VERSION=v0.115.0 bash 94 | - echo "goreleaser finished!!!" 95 | onSuccess: 96 | - send_notification cpe_pipeline_slack --text "kubenabRelease goreleaser v${TAG_NAME} ${step_name}_buildNumber=${run_number} - SUCCESS" 97 | onFailure: 98 | - send_notification cpe_pipeline_slack --text "kubenabRelease goreleaser v${TAG_NAME} ${step_name}_buildNumber=${run_number} - FAILED" 99 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Builder image 2 | FROM golang:1.13-alpine as builder 3 | 4 | # Copy source 5 | ADD ./cmd/kubenab /root/app 6 | 7 | # Install dependencies 8 | RUN apk add --no-cache git 9 | 10 | # Download modules 11 | RUN ls -alh /root/app && cd /root/app && \ 12 | GO111MODULE=on GOPROXY=https://gocenter.io go mod download 13 | 14 | # Build microservices 15 | RUN cd /root/app && \ 16 | CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build 17 | 18 | FROM gcr.io/distroless/static 19 | 20 | # Copy microservice executable from builder image 21 | COPY --from=builder /root/app/kubenab /bin/kubenab 22 | 23 | # Set runtime user to non-root 24 | USER 1000 25 | 26 | # Set Entrypoint 27 | CMD ["kubenab"] 28 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # 'strip_debug' will increase the Performance of kubenab 2 | # You can disable this by setting `STRIP_DEBUG=""` 3 | STRIP_DEBUG ?=-tags 'strip_debug' 4 | LDFLAGS := "-X main.version=${VERSION}" 5 | # OUT_DIR sets the Path where the kubenab Build Artifact will be puttet 6 | OUT_DIR ?=../../bin 7 | GIT_HASH=$(shell git rev-parse HEAD) 8 | BUILD_DATE=$(shell date -u '+%Y-%m-%d_%I:%M:%S%p') 9 | APP_VERSION=$(shell git describe --abbrev=0 --tags) 10 | 11 | .PHONY: image 12 | image: 13 | @echo "++ Building kubenab docker image..." 14 | docker build -t kubenab . 15 | 16 | .PHONY: build 17 | build: export GOARCH=amd64 18 | build: export CGO_ENABLED=0 19 | build: export GO111MODULE=on 20 | build: export GOPROXY=https://gocenter.io 21 | build: 22 | @echo "++ Building kubenab go binary..." 23 | mkdir -p bin 24 | cd cmd/kubenab && go mod download && \ 25 | go build $(STRIP_DEBUG) -ldflags $(LDFLAGS) -o $(OUT_DIR)/kubenab 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Kubenab 2 | 3 | [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) 4 | [![Go Report Card](https://goreportcard.com/badge/github.com/jfrog/kubenab?style=flat-square)](https://goreportcard.com/report/github.com/jfrog/kubenab) 5 | [![Go Doc](https://img.shields.io/badge/godoc-reference-blue.svg?style=flat-square)](http://godoc.org/github.com/jfrog/kubenab) 6 | [![CircleCI](https://circleci.com/gh/jfrog/kubenab/tree/master.svg?style=svg)](https://circleci.com/gh/jfrog/kubenab/tree/master) 7 | [![Release](https://img.shields.io/github/release/jfrog/kubenab.svg?style=flat-square)](https://github.com/jfrog/kubenab/releases/latest) 8 | 9 | ### What does Kubenab do? 10 | Kubenab is Kubernetes Admission webhook to enforce pulling of docker images from private registry. 11 | 12 | ### Prerequisites 13 | 14 | Kubernetes 1.12.0 or above with the `admissionregistration.k8s.io/v1beta1` API enabled. Verify that by the following command: 15 | ``` 16 | kubectl api-versions | grep admissionregistration.k8s.io/v1beta1 17 | ``` 18 | The result should be: 19 | ``` 20 | admissionregistration.k8s.io/v1beta1 21 | ``` 22 | 23 | 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. 24 | 25 | ### Build and Push Kubenab Docker Image 26 | 27 | ```bash 28 | # Build docker image 29 | docker build -t my-registry/kubenab:0.3.3 . 30 | 31 | # Push it to Docker Registry 32 | docker push my-registry/kubenab:0.3.3 33 | ``` 34 | 35 | ### Create [Kubernetes Docker registry secret](https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/) 36 | 37 | ```bash 38 | # Create a Docker registry secret called 'regsecret' 39 | kubectl create secret docker-registry regsecret --docker-server=${DOCKER_REGISTRY} --docker-username=${DOCKER_USER} --docker-password=${DOCKER_PASS} --docker-email=${DOCKER_EMAIL} 40 | ``` 41 | 42 | **Note**: Create Docker registry secret in each non-whitelisted namespaces. 43 | 44 | ### Generate TLS Certs for Kubenab 45 | 46 | ```bash 47 | ./tls/gen-cert.sh 48 | ``` 49 | 50 | ### Get CA Bundle 51 | 52 | ```bash 53 | ./webhook/webhook-patch-ca-bundle.sh 54 | ``` 55 | 56 | **Note:** You can skip this step and use Helm chart install with TLS certs generated by the [cert-manager](https://github.com/jetstack/cert-manager) 57 | 58 | ### Deploy Kubenab to Kubernetes with self generated TLS Certs 59 | 60 | * Deploy using kubectl 61 | ```bash 62 | # Run deployment 63 | kubectl create -f deployment/kubenab-deployment.yaml 64 | 65 | # Create service 66 | kubectl create -f deployment/kubenab-svc.yaml 67 | ``` 68 | 69 | * Deploy using Helm Chart 70 | ```bash 71 | helm install --name kubenab --set docker.registrySecret=regsecret,docker.registryUrl=jfrog,whitelistNamespaces="kube-system,default",whitelistRegistries="jfrog",tls.secretName=kubenab-certs chart/kubenab/ 72 | ``` 73 | 74 | #### Configure `MutatingAdmissionWebhook` and `ValidatingAdmissionWebhook` 75 | 76 | **Note**: Replace `${CA_BUNDLE}` with value generated by running `./webhook/webhook-patch-ca-bundle.sh` 77 | 78 | ```bash 79 | # Configure MutatingAdmissionWebhook 80 | kubectl create -f webhook/kubenab-mutating-webhook-configuration.yaml 81 | ``` 82 | 83 | 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/). 84 | If your container image is `nginx` then Kubenab will append `REGISTRY_URL` to it. e.g `nginx` will become `jfrog/nginx` 85 | 86 | ```bash 87 | # Configure ValidatingAdmissionWebhook 88 | kubectl create -f webhook/kubenab-validating-webhook-configuration.yaml 89 | ``` 90 | 91 | Note: Use ValidatingAdmissionWebhook only if you want to check pulling of docker image from Private Docker Registry e.g [JFrog Artifactory](https://jfrog.com/artifactory/). 92 | If your container image does not contain `REGISTRY_URL` then Kubenab will deny request to run that pod. 93 | 94 | 95 | ### Deploy Kubenab to Kubernetes with cert-manager generated TLS Certs 96 | 97 | * Deploy using Helm Chart 98 | ```bash 99 | helm install --name kubenab --set docker.registrySecret=regsecret,docker.registryUrl=jfrog,whitelistNamespaces="kube-system,default",whitelistRegistries="jfrog" chart/kubenab/ 100 | ``` 101 | 102 | `ValidatingAdmissionWebhook` is enabled by default, use `mutatingWebhook.enabled="true"` to enable `MutatingAdmissionWebhook`. 103 | 104 | 105 | ### Test Kubenab 106 | 107 | ```bash 108 | # Deploy nginx 109 | kubectl apply -f test/nginx.yaml 110 | ``` 111 | 112 | 113 | ## Benchmark 114 | 115 | Run the `benchmark.sh` Script in [`benchmark/`](./benchmark/), you only need 116 | `go`, `docker` and `openssl`. 117 | 118 | ### Benchmark Results 119 | 120 | ```bash 121 | ==> Mutate Webhook 122 | 123 | 124 | 1000000 / 1000000 [=====================================================================================================================] 100.00% 6850/s 2m25s 125 | Done! 126 | Statistics Avg Stdev Max 127 | Reqs/sec 6906,14 612,30 7957,42 128 | Latency 285,93us 171,41us 27,91ms 129 | Latency Distribution 130 | 50% 257,00us 131 | 75% 309,00us 132 | 90% 376,00us 133 | 95% 440,00us 134 | 99% 764,00us 135 | HTTP codes: 136 | 1xx - 0, 2xx - 100000, 3xx - 0, 4xx - 0, 5xx - 0 137 | others - 0 138 | Throughput: 15.05MB/s 139 | 140 | 141 | ==> Validate Webhook 142 | 143 | 144 | 1000000 / 1000000 [=====================================================================================================================] 100.00% 6669/s 2m29s 145 | Done! 146 | Statistics Avg Stdev Max 147 | Reqs/sec 6675.83 515.18 8017.83 148 | Latency 295.81us 99.07us 22.86ms 149 | Latency Distribution 150 | 50% 267.00us 151 | 75% 319.00us 152 | 90% 388.00us 153 | 95% 453.00us 154 | 99% 759.00us 155 | HTTP codes: 156 | 1xx - 0, 2xx - 1000000, 3xx - 0, 4xx - 0, 5xx - 0 157 | others - 0 158 | Throughput: 16.20MB/s 159 | ``` 160 | 161 | **ATTENTION:** This Benchmark was done on an _non_ optimized Laptop! 162 | (Intel(R) Core(TM) i5-3230M CPU @ 2.60GHz **;** 8GB RAM) 163 | -------------------------------------------------------------------------------- /benchmark/benchmark.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash - 2 | #=============================================================================== 3 | # 4 | # FILE: benchmark.sh 5 | # 6 | # USAGE: ./benchmark.sh 7 | # 8 | # DESCRIPTION: Runs a benchmark against the kubenab-Server 9 | # 10 | # OPTIONS: --- 11 | # REQUIREMENTS: go, docker, openssl 12 | # BUGS: --- 13 | # NOTES: --- 14 | # AUTHOR: Francesco Emanuel Bennici 15 | # ORGANIZATION: 16 | # CREATED: 28.09.2019 00:32:08 17 | # REVISION: --- 18 | #=============================================================================== 19 | 20 | set -o nounset # Treat unset variables as an error 21 | 22 | DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" 23 | tmp=$(mktemp -d) 24 | curr=$(pwd) 25 | 26 | ## ===> Compile `kubenab` <=== 27 | 28 | echo "[i] Generating Self-Signed Certificates" 29 | openssl req -x509 -newkey rsa:4096 -sha256 -days 3650 -nodes \ 30 | -keyout ${tmp}/tls.key -out ${tmp}/tls.crt -extensions san -config \ 31 | <(echo "[req]"; 32 | echo distinguished_name=req; 33 | echo "[san]"; 34 | echo subjectAltName=DNS:localhost,IP:127.0.0.1 35 | ) \ 36 | -subj "/CN=localhost" 37 | 38 | 39 | echo "[i] Compiling kubenab" 40 | cd ${DIR}/../ 41 | docker build -t temp/build:kubenab . 42 | id=$(docker run -p 8443:443 \ 43 | -v ${tmp}:/etc/admission-controller/tls \ 44 | -d --env "DOCKER_REGISTRY_URL=jfrog" --env "REPLACE_REGISTRY_URL=false" \ 45 | temp/build:kubenab) 46 | cd ${curr} 47 | 48 | ## ==> Benchmark <==# 49 | 50 | echo "[i] Installing bombardier" 51 | go get -u github.com/codesenberg/bombardier 52 | 53 | echo "###########################" 54 | echo "### Starting bombardier ###" 55 | echo -e "###########################\n" 56 | 57 | echo -e "==> Mutate Webhook\n\n" 58 | bombardier -c 125 -n 10000000 --insecure --latencies \ 59 | --fasthttp --body $(cat ${DIR}/mutate_body) \ 60 | --print 'i,p,r' --method POST https://localhost:8443/mutate 61 | 62 | echo -e "\n\n==> Validate Webhook\n\n" 63 | bombardier -c 125 -n 10000000 --insecure --latencies \ 64 | --fasthttp --body $(cat ${DIR}/validate_body) \ 65 | --print 'i,p,r' --method POST https://localhost:8443/validate 66 | 67 | 68 | ## Cleaning Up 69 | docker rm --force --volumes ${id} 70 | rm -rf ${tmp} 71 | -------------------------------------------------------------------------------- /benchmark/mutate_body: -------------------------------------------------------------------------------- 1 | {"kind":"AdmissionReview","apiVersion":"admission.k8s.io/v1beta1","request":{"uid":"eae55fa6-d3f5-41f2-bafe-ecb34af1a2d0","kind":{"group":"","version":"v1","kind":"Pod"},"resource":{"group":"","version":"v1","resource":"pods"},"requestKind":{"group":"","version":"v1","kind":"Pod"},"requestResource":{"group":"","version":"v1","resource":"pods"},"namespace":"nginx","operation":"CREATE","userInfo":{"username":"system:serviceaccount:kube-system:replicaset-controller","uid":"76e1a4a5-f75a-40fe-a7a0-876619472d2f","groups":["system:serviceaccounts","system:serviceaccounts:kube-system","system:authenticated"]},"object":{"kind":"Pod","apiVersion":"v1","metadata":{"generateName":"nginx-69844dfc86-","creationTimestamp":null,"labels":{"pod-template-hash":"69844dfc86","test":"kubenab"},"ownerReferences":[{"apiVersion":"apps/v1","kind":"ReplicaSet","name":"nginx-69844dfc86","uid":"5ddf2df2-66e4-4287-869a-e349b0777966","controller":true,"blockOwnerDeletion":true}]},"spec":{"volumes":[{"name":"default-token-mc7dh","secret":{"secretName":"default-token-mc7dh"}}],"containers":[{"name":"nginx","image":"nginx","resources":{},"volumeMounts":[{"name":"default-token-mc7dh","readOnly":true,"mountPath":"/var/run/secrets/kubernetes.io/serviceaccount"}],"terminationMessagePath":"/dev/termination-log","terminationMessagePolicy":"File","imagePullPolicy":"IfNotPresent"}],"restartPolicy":"Always","terminationGracePeriodSeconds":30,"dnsPolicy":"ClusterFirst","serviceAccountName":"default","serviceAccount":"default","securityContext":{},"schedulerName":"default-scheduler","tolerations":[{"key":"node.kubernetes.io/not-ready","operator":"Exists","effect":"NoExecute","tolerationSeconds":300},{"key":"node.kubernetes.io/unreachable","operator":"Exists","effect":"NoExecute","tolerationSeconds":300}],"priority":0,"enableServiceLinks":true},"status":{}},"oldObject":null,"dryRun":false,"options":{"kind":"CreateOptions","apiVersion":"meta.k8s.io/v1"}}} 2 | -------------------------------------------------------------------------------- /benchmark/validate_body: -------------------------------------------------------------------------------- 1 | {"kind":"AdmissionReview","apiVersion":"admission.k8s.io/v1beta1","request":{"uid":"1f19a6d5-949a-4379-a0f9-a34e52faee18","kind":{"group":"","version":"v1","kind":"Pod"},"resource":{"group":"","version":"v1","resource":"pods"},"requestKind":{"group":"","version":"v1","kind":"Pod"},"requestResource":{"group":"","version":"v1","resource":"pods"},"name":"nginx-69844dfc86-n5vbr","namespace":"nginx","operation":"CREATE","userInfo":{"username":"system:serviceaccount:kube-system:replicaset-controller","uid":"76e1a4a5-f75a-40fe-a7a0-876619472d2f","groups":["system:serviceaccounts","system:serviceaccounts:kube-system","system:authenticated"]},"object":{"kind":"Pod","apiVersion":"v1","metadata":{"name":"nginx-69844dfc86-n5vbr","generateName":"nginx-69844dfc86-","namespace":"nginx","uid":"7be27643-cdb7-438b-a32f-47e5844ad7a8","creationTimestamp":"2019-09-27T22:30:55Z","labels":{"pod-template-hash":"69844dfc86","test":"kubenab"},"ownerReferences":[{"apiVersion":"apps/v1","kind":"ReplicaSet","name":"nginx-69844dfc86","uid":"5ddf2df2-66e4-4287-869a-e349b0777966","controller":true,"blockOwnerDeletion":true}]},"spec":{"volumes":[{"name":"default-token-mc7dh","secret":{"secretName":"default-token-mc7dh","defaultMode":420}}],"containers":[{"name":"nginx","image":"kubenab/nginx","resources":{},"volumeMounts":[{"name":"default-token-mc7dh","readOnly":true,"mountPath":"/var/run/secrets/kubernetes.io/serviceaccount"}],"terminationMessagePath":"/dev/termination-log","terminationMessagePolicy":"File","imagePullPolicy":"IfNotPresent"}],"restartPolicy":"Always","terminationGracePeriodSeconds":30,"dnsPolicy":"ClusterFirst","serviceAccountName":"default","serviceAccount":"default","securityContext":{},"imagePullSecrets":[{"name":"regsecret"}],"schedulerName":"default-scheduler","tolerations":[{"key":"node.kubernetes.io/not-ready","operator":"Exists","effect":"NoExecute","tolerationSeconds":300},{"key":"node.kubernetes.io/unreachable","operator":"Exists","effect":"NoExecute","tolerationSeconds":300}],"priority":0,"enableServiceLinks":true},"status":{"phase":"Pending","qosClass":"BestEffort"}},"oldObject":null,"dryRun":false,"options":{"kind":"CreateOptions","apiVersion":"meta.k8s.io/v1"}}} 2 | -------------------------------------------------------------------------------- /chart/kubenab/.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 | .vscode/ 23 | -------------------------------------------------------------------------------- /chart/kubenab/Chart.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | name: kubenab 3 | version: 0.0.12 4 | appVersion: 0.3.3 5 | home: https://github.com/jfrog/kubenab 6 | kubeVersion: ">=1.12.0" 7 | description: Kubenab Helm chart 8 | keywords: 9 | - devops 10 | - helm 11 | - kubernetes 12 | - docker 13 | - jfrog 14 | - security 15 | sources: 16 | - https://github.com/jfrog/kubenab 17 | maintainers: 18 | - name: rimusz 19 | email: rimasm@jfrog.com 20 | icon: https://raw.githubusercontent.com/jfrog/artifactory-dcos/master/images/jfrog_med.png 21 | -------------------------------------------------------------------------------- /chart/kubenab/templates/NOTES.txt: -------------------------------------------------------------------------------- 1 | {{- if not .Values.docker.registryUrl }} 2 | 3 | ############################################################# 4 | #### ERROR: You did not provide Private Registry RUL #### 5 | ############################################################# 6 | 7 | All pods do not go to the running state if the instances 8 | settings were not provided. 9 | 10 | {{- end }} 11 | 12 | 1. Get the application URL by running these commands: 13 | {{- if contains "NodePort" .Values.service.type }} 14 | export NODE_PORT=$(kubectl get --namespace {{ .Release.Namespace }} -o jsonpath="{.spec.ports[0].nodePort}" services {{ include "kubenab.fullname" . }}) 15 | export NODE_IP=$(kubectl get nodes --namespace {{ .Release.Namespace }} -o jsonpath="{.items[0].status.addresses[0].address}") 16 | echo http://$NODE_IP:$NODE_PORT 17 | {{- else if contains "ClusterIP" .Values.service.type }} 18 | export POD_NAME=$(kubectl get pods --namespace {{ .Release.Namespace }} -l "app.kubernetes.io/name={{ include "kubenab.name" . }},app.kubernetes.io/instance={{ .Release.Name }}" -o jsonpath="{.items[0].metadata.name}") 19 | echo "Visit http://127.0.0.1:8080 to use your application" 20 | kubectl port-forward $POD_NAME 8080:80 21 | {{- end }} 22 | 23 | {{/* 24 | Print Config that needs to be added to the ConfigMap of the prometheus-adapter 25 | if Prometheus Metrics are enabled. 26 | */}} 27 | {{- if .Values.metrics.enable }} 28 | Please add the following Data to the prometheus-adapter ConfigMap. 29 | If you don't do this the HPA will not work! 30 | 31 | {{/* ~~~~~ Response Latency Metric ~~~~~ */}} 32 | {{- if .Values.hpa.metrics.latency }} 33 | - seriesQuery: '{namespace!="",pod!=""}' 34 | name: 35 | matches: "^(.*)_milliseconds_bucket" 36 | as: "http_request_duration" 37 | resources: 38 | overrides: 39 | namespace: {resource: "namespace"} 40 | pod: {resource: "pod"} 41 | metricsQuery: 'histogram_quantile(0.99, sum(rate(<<.Series>>[5m])) by (le, api_method, endpoint, <<.GroupBy>>))' 42 | {{- end }} 43 | 44 | {{/* ~~~~~ HTTP Requests Metric ~~~~~ */}} 45 | {{- if .Values.hpa.metrics.httpRequests }} 46 | - seriesQuery: 'http_requests_total{namespace!="",pod!=""}' 47 | resources: 48 | overrides: 49 | namespace: {resource: "namespace"} 50 | pod: {resource: "pod"} 51 | name: 52 | matches: "^(.*)_total" 53 | as: "${1}_per_second" 54 | metricsQuery: 'sum(rate(<<.Series>>{<<.LabelMatchers>>}[2m])) by (<<.GroupBy>>)' 55 | {{- end }} 56 | {{- end }} 57 | -------------------------------------------------------------------------------- /chart/kubenab/templates/_helpers.tpl: -------------------------------------------------------------------------------- 1 | {{/* vim: set filetype=mustache: */}} 2 | {{/* 3 | Expand the name of the chart. 4 | */}} 5 | {{- define "kubenab.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 "kubenab.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 chart name and version as used by the chart label. 29 | */}} 30 | {{- define "kubenab.chart" -}} 31 | {{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" -}} 32 | {{- end -}} 33 | 34 | {{/* 35 | Common labels 36 | */}} 37 | {{- define "kubenab.labels" -}} 38 | app.kubernetes.io/name: {{ include "kubenab.name" . }} 39 | helm.sh/chart: {{ include "kubenab.chart" . }} 40 | app.kubernetes.io/instance: {{ .Release.Name }} 41 | {{- if .Chart.AppVersion }} 42 | app.kubernetes.io/version: {{ .Chart.AppVersion | quote }} 43 | {{- end }} 44 | app.kubernetes.io/managed-by: {{ .Release.Service }} 45 | {{- end -}} 46 | 47 | {{- define "kubenab.selfSignedIssuer" -}} 48 | {{ printf "%s-selfsign" (include "kubenab.fullname" .) }} 49 | {{- end -}} 50 | 51 | {{- define "kubenab.rootCAIssuer" -}} 52 | {{ printf "%s-ca" (include "kubenab.fullname" .) }} 53 | {{- end -}} 54 | 55 | {{- define "kubenab.rootCACertificate" -}} 56 | {{ printf "%s-ca" (include "kubenab.fullname" .) }} 57 | {{- end -}} 58 | 59 | {{- define "kubenab.servingCertificate" -}} 60 | {{ printf "%s-kubenab-tls" (include "kubenab.fullname" .) }} 61 | {{- end -}} 62 | -------------------------------------------------------------------------------- /chart/kubenab/templates/deployment.yaml: -------------------------------------------------------------------------------- 1 | {{- if .Values.docker.registryUrl }} 2 | {{- if .Capabilities.APIVersions.Has "apps/v1" }} 3 | apiVersion: apps/v1 4 | {{- else }} 5 | apiVersion: extensions/v1beta1 6 | {{- end }} 7 | kind: Deployment 8 | metadata: 9 | name: {{ include "kubenab.fullname" . }} 10 | labels: 11 | {{ include "kubenab.labels" . | indent 4 }} 12 | spec: 13 | replicas: {{ .Values.replicaCount }} 14 | selector: 15 | matchLabels: 16 | app.kubernetes.io/name: {{ include "kubenab.name" . }} 17 | app.kubernetes.io/instance: {{ .Release.Name }} 18 | template: 19 | metadata: 20 | labels: 21 | {{ include "kubenab.labels" . | indent 8 }} 22 | spec: 23 | {{- if .Values.priorityClass.enabled }} 24 | priorityClassName: {{ .Values.priorityClass.name | default "system-cluster-critical" }} 25 | {{- end }} 26 | serviceAccountName: {{ include "kubenab.fullname" . }} 27 | {{- if .Values.imagePullSecrets }} 28 | imagePullSecrets: 29 | - name: {{ .Values.imagePullSecrets }} 30 | {{- end }} 31 | containers: 32 | - name: {{ .Chart.Name }} 33 | image: "{{ .Values.image.repository }}:{{ default .Chart.AppVersion .Values.image.tag }}" 34 | imagePullPolicy: {{ .Values.image.pullPolicy }} 35 | env: 36 | - name: DOCKER_REGISTRY_URL 37 | value: {{ .Values.docker.registryUrl }} 38 | - name: REGISTRY_SECRET_NAME 39 | value: {{ .Values.docker.registrySecret }} 40 | - name: WHITELIST_NAMESPACES 41 | value: {{ .Values.whitelistNamespaces }} 42 | - name: WHITELIST_REGISTRIES 43 | value: {{ .Values.whitelistRegistries }} 44 | - name: REPLACE_REGISTRY_URL 45 | value: {{ .Values.docker.replaceRegistryUrl }} 46 | - name: PORT 47 | value: {{ .Values.image.port }} 48 | ports: 49 | - name: https 50 | containerPort: {{ .Values.image.port }} 51 | protocol: TCP 52 | volumeMounts: 53 | - name: tls 54 | mountPath: /etc/admission-controller/tls 55 | resources: 56 | {{- toYaml .Values.resources | nindent 12 }} 57 | {{- if .Values.securityContext.enabled }} 58 | securityContext: 59 | {{- omit .Values.securityContext "enabled" | toYaml | nindent 12 }} 60 | {{- end }} 61 | {{- if .Values.livenessProbe.enabled }} 62 | livenessProbe: 63 | {{- omit .Values.livenessProbe "enabled" | toYaml | nindent 12 }} 64 | {{- end }} 65 | {{- if .Values.readinessProbe.enabled }} 66 | readinessProbe: 67 | {{- omit .Values.readinessProbe "enabled" | toYaml | nindent 12 }} 68 | {{- end }} 69 | {{- with .Values.nodeSelector }} 70 | nodeSelector: 71 | {{- toYaml . | nindent 8 }} 72 | {{- end }} 73 | {{- with .Values.affinity }} 74 | affinity: 75 | {{- toYaml . | nindent 8 }} 76 | {{- end }} 77 | {{- with .Values.tolerations }} 78 | tolerations: 79 | {{- toYaml . | nindent 8 }} 80 | {{- end }} 81 | volumes: 82 | - name: tls 83 | secret: 84 | secretName: {{ .Values.tls.secretName | default (printf "%s" ( include "kubenab.servingCertificate" .)) }} 85 | {{- end }} 86 | -------------------------------------------------------------------------------- /chart/kubenab/templates/hpa.yaml: -------------------------------------------------------------------------------- 1 | {{- if .Values.hpa.enabled }} 2 | apiVersion: autoscaling/v2beta2 3 | kind: HorizontalPodAutoscaler 4 | metadata: 5 | name: {{ include "kubenab.fullname" . }} 6 | labels: 7 | {{ include "kubenab.labels" . | indent 4 }} 8 | spec: 9 | scaleTargetRef: 10 | {{- if .Capabilities.APIVersions.Has "apps/v1" }} 11 | apiVersion: apps/v1 12 | {{- else }} 13 | apiVersion: extensions/v1beta1 14 | {{- end }} 15 | kind: Deployment 16 | name: {{ include "kubenab.fullname" . }} 17 | minReplicas: {{ .Values.hpa.minReplicas }} 18 | maxReplicas: {{ .Values.hpa.maxReplicas }} 19 | metrics: 20 | {{- if .Values.hpa.metrics.cpuUtilization.enabled }} 21 | - type: Resource 22 | resource: 23 | name: cpu 24 | target: 25 | type: Utilization 26 | averageUtilization: {{ .Values.hpa.metrics.cpuUtilization.averageUtilization }} 27 | {{- end }} 28 | {{- if .Values.metrics.enable }} 29 | {{- if .Values.hpa.metrics.httpRequests }} 30 | - type: Pods 31 | pods: 32 | metric: 33 | name: http_requests_per_second 34 | target: 35 | type: "AverageValue" 36 | averageValue: "{{ .Values.hpa.metrics.httpRequests.targetAvg }}" 37 | {{- end }} 38 | {{- if .Values.hpa.metrics.latency }} 39 | - type: Pods 40 | pods: 41 | metric: 42 | name: http_request_duration 43 | target: 44 | type: "AverageValue" 45 | averageValue: "{{ .Values.hpa.metrics.latency.targetAvg }}" 46 | {{- end }} 47 | {{- end }} 48 | {{- end }} 49 | -------------------------------------------------------------------------------- /chart/kubenab/templates/metrics.yaml: -------------------------------------------------------------------------------- 1 | {{ if .Values.metrics.enable }} 2 | apiVersion: monitoring.coreos.com/v1 3 | kind: ServiceMonitor 4 | metadata: 5 | name: {{ include "kubenab.fullname" . }}-monitor 6 | labels: 7 | {{ include "kubenab.labels" . | indent 4 }} 8 | spec: 9 | jobLabel: {{ include "kubenab.fullname" . }}-metrics 10 | selector: 11 | matchLabels: 12 | {{ include "kubenab.labels" . | indent 6 }} 13 | endpoints: 14 | - path: '/metrics' 15 | port: https 16 | interval: {{ .Values.metrics.scrapeInterval }} 17 | scheme: https 18 | tlsConfig: 19 | insecureSkipVerify: {{ .Values.metrics.tlsSkipInsecure }} 20 | --- 21 | apiVersion: monitoring.coreos.com/v1 22 | kind: Prometheus 23 | metadata: 24 | name: prometheus-{{ include "kubenab.fullname" . }} 25 | labels: 26 | {{ include "kubenab.labels" . | indent 4 }} 27 | spec: 28 | version: v2.5.0 29 | serviceMonitors: 30 | - selector: 31 | matchLabels: 32 | {{ include "kubenab.labels" . | indent 8 }} 33 | --- 34 | apiVersion: v1 35 | kind: Service 36 | metadata: 37 | name: prometheus-{{ include "kubenab.fullname" . }} 38 | labels: 39 | {{ include "kubenab.labels" . | indent 4 }} 40 | spec: 41 | ports: 42 | - port: 9090 43 | name: http 44 | selector: 45 | prometheus: prometheus 46 | {{ end }} 47 | -------------------------------------------------------------------------------- /chart/kubenab/templates/mutating-webhook.yaml: -------------------------------------------------------------------------------- 1 | {{- if .Values.mutatingWebhook.enabled -}} 2 | apiVersion: admissionregistration.k8s.io/v1beta1 3 | kind: MutatingWebhookConfiguration 4 | metadata: 5 | name: {{ include "kubenab.fullname" . }}-mutate 6 | labels: 7 | {{ include "kubenab.labels" . | indent 4 }} 8 | annotations: 9 | cert-manager.io/inject-ca-from: "{{ .Release.Namespace }}/{{ include "kubenab.servingCertificate" . }}" 10 | webhooks: 11 | - name: kubenab-mutate.k8s.io 12 | rules: 13 | - operations: [ "CREATE", "UPDATE" ] 14 | apiGroups: [""] 15 | apiVersions: ["v1"] 16 | resources: ["pods"] 17 | failurePolicy: Ignore 18 | clientConfig: 19 | service: 20 | name: {{ include "kubenab.fullname" . }} 21 | namespace: {{ .Release.Namespace }} 22 | path: "/mutate" 23 | {{- end -}} 24 | -------------------------------------------------------------------------------- /chart/kubenab/templates/pki.yaml: -------------------------------------------------------------------------------- 1 | {{- if not .Values.tls.secretName -}} 2 | {{- if or .Values.mutatingWebhook.enabled .Values.validatingWebhook.enabled }} 3 | --- 4 | # Create a selfsigned Issuer, in order to create a root CA certificate for 5 | # signing kubenab serving certificates 6 | apiVersion: cert-manager.io/v1alpha2 7 | kind: Issuer 8 | metadata: 9 | name: {{ include "kubenab.selfSignedIssuer" . }} 10 | namespace: {{ .Release.Namespace | quote }} 11 | labels: 12 | {{ include "kubenab.labels" . | indent 4 }} 13 | spec: 14 | selfSigned: {} 15 | --- 16 | # Generate a CA Certificate used to sign certificates for the kubenab 17 | apiVersion: cert-manager.io/v1alpha2 18 | kind: Certificate 19 | metadata: 20 | name: {{ include "kubenab.rootCACertificate" . }} 21 | namespace: {{ .Release.Namespace | quote }} 22 | labels: 23 | {{ include "kubenab.labels" . | indent 4 }} 24 | spec: 25 | secretName: {{ include "kubenab.rootCACertificate" . }} 26 | duration: 43800h # 5y 27 | issuerRef: 28 | name: {{ include "kubenab.selfSignedIssuer" . }} 29 | commonName: "ca.kubenab.kubenab" 30 | isCA: true 31 | --- 32 | # Create an Issuer that uses the above generated CA certificate to issue certs 33 | apiVersion: cert-manager.io/v1alpha2 34 | kind: Issuer 35 | metadata: 36 | name: {{ include "kubenab.rootCAIssuer" . }} 37 | namespace: {{ .Release.Namespace | quote }} 38 | labels: 39 | {{ include "kubenab.labels" . | indent 4 }} 40 | spec: 41 | ca: 42 | secretName: {{ include "kubenab.rootCACertificate" . }} 43 | --- 44 | # Finally, generate a serving certificate for the kubenab to use 45 | apiVersion: cert-manager.io/v1alpha2 46 | kind: Certificate 47 | metadata: 48 | name: {{ include "kubenab.servingCertificate" . }} 49 | namespace: {{ .Release.Namespace | quote }} 50 | labels: 51 | {{ include "kubenab.labels" . | indent 4 }} 52 | spec: 53 | secretName: {{ include "kubenab.servingCertificate" . }} 54 | duration: 8760h # 1y 55 | issuerRef: 56 | name: {{ include "kubenab.rootCAIssuer" . }} 57 | dnsNames: 58 | - {{ include "kubenab.fullname" . }} 59 | - {{ include "kubenab.fullname" . }}.{{ .Release.Namespace }} 60 | - {{ include "kubenab.fullname" . }}.{{ .Release.Namespace }}.svc 61 | {{- end }} 62 | {{- end -}} 63 | -------------------------------------------------------------------------------- /chart/kubenab/templates/role.yaml: -------------------------------------------------------------------------------- 1 | {{- if .Values.rbac.create }} 2 | apiVersion: rbac.authorization.k8s.io/v1 3 | kind: Role 4 | metadata: 5 | name: {{ include "kubenab.fullname" . }} 6 | labels: 7 | {{ include "kubenab.labels" . | indent 4 }} 8 | rules: 9 | {{ toYaml .Values.rbac.role.rules }} 10 | {{- end }} 11 | -------------------------------------------------------------------------------- /chart/kubenab/templates/rolebinding.yaml: -------------------------------------------------------------------------------- 1 | {{- if .Values.rbac.create }} 2 | apiVersion: rbac.authorization.k8s.io/v1 3 | kind: RoleBinding 4 | metadata: 5 | name: {{ include "kubenab.fullname" . }} 6 | labels: 7 | {{ include "kubenab.labels" . | indent 4 }} 8 | subjects: 9 | - kind: ServiceAccount 10 | name: {{ include "kubenab.fullname" . }} 11 | roleRef: 12 | kind: Role 13 | apiGroup: rbac.authorization.k8s.io 14 | name: {{ include "kubenab.fullname" . }} 15 | {{- end }} 16 | -------------------------------------------------------------------------------- /chart/kubenab/templates/service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: {{ include "kubenab.fullname" . }} 5 | labels: 6 | {{ include "kubenab.labels" . | indent 4 }} 7 | spec: 8 | type: {{ .Values.service.type }} 9 | ports: 10 | - port: {{ .Values.service.port }} 11 | targetPort: https 12 | protocol: TCP 13 | name: https 14 | selector: 15 | {{ include "kubenab.labels" . | indent 4 }} 16 | -------------------------------------------------------------------------------- /chart/kubenab/templates/serviceaccount.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: ServiceAccount 3 | metadata: 4 | name: {{ include "kubenab.fullname" . }} 5 | labels: 6 | {{ include "kubenab.labels" . | indent 4 }} 7 | -------------------------------------------------------------------------------- /chart/kubenab/templates/validating-webhook.yaml: -------------------------------------------------------------------------------- 1 | {{- if .Values.validatingWebhook.enabled -}} 2 | apiVersion: admissionregistration.k8s.io/v1beta1 3 | kind: ValidatingWebhookConfiguration 4 | metadata: 5 | name: {{ include "kubenab.fullname" . }}-validate 6 | labels: 7 | {{ include "kubenab.labels" . | indent 4 }} 8 | annotations: 9 | cert-manager.io/inject-ca-from: "{{ .Release.Namespace }}/{{ include "kubenab.servingCertificate" . }}" 10 | webhooks: 11 | - name: kubenab-validate.jfrog.com 12 | rules: 13 | - apiGroups: 14 | - "" 15 | apiVersions: 16 | - v1 17 | operations: 18 | - CREATE 19 | - UPDATE 20 | resources: 21 | - pods 22 | failurePolicy: Ignore 23 | clientConfig: 24 | service: 25 | name: {{ include "kubenab.fullname" . }} 26 | namespace: {{ .Release.Namespace }} 27 | path: "/validate" 28 | {{- end -}} 29 | -------------------------------------------------------------------------------- /chart/kubenab/values.yaml: -------------------------------------------------------------------------------- 1 | # Default values for kubenab. 2 | # This is a YAML-formatted file. 3 | # Declare variables to be passed into your templates. 4 | 5 | replicaCount: 1 6 | 7 | imagePullSecrets: 8 | 9 | image: 10 | repository: docker.bintray.io/kubenab 11 | # Note that by default we use appVersion to get image tag 12 | # tag: 13 | pullPolicy: IfNotPresent 14 | port: 4443 15 | 16 | service: 17 | type: ClusterIP 18 | port: 443 19 | 20 | docker: 21 | registryUrl: 22 | registrySecret: regsecret 23 | 24 | # Set to 'true' if you want that the original Registry URL will be 25 | # replaced with your Docker Domain. 26 | # Or set to to 'false' if you want to pre-pend your Docker Domain to the 27 | # original Registry URL. 28 | # 29 | # Example: 30 | # Container Image: 'docker.io/library/nginx:latest' 31 | # Enabled replaceRegistryUrl: 'jfrog.local/library/nginx:latest' 32 | # Disabled replaceRegistryUrl: 'jfrog.local/docker.io/library/nginx:latest' 33 | replaceRegistryUrl: true 34 | 35 | ## Enabling this will add annotations and a Service-Discovery, so Prometheus 36 | ## – especially the Prometheus-Operator – detect this Service and collects 37 | ## metrics 38 | metrics: 39 | enable: true 40 | scrapeInterval: 10s 41 | 42 | ## you need to enable this if you are using self-signed TLS Certificates 43 | tlsSkipInsecure: false 44 | 45 | ## HPA (or HorizontalPodAutoScaling) is an Kubernetes Feature react dynamically 46 | ## to special situations. 47 | ## Kubernetes will scale 'kubenab' up if the current Number of Instances can't 48 | ## handle all the traffic and it will also scale down if there isn't a usage 49 | ## for the (new) Instances. 50 | hpa: 51 | enabled: false 52 | 53 | minReplicas: 1 54 | maxReplicas: 10 55 | 56 | ## To decide if the number of Replicas must be increased or decreased, 57 | ## Kubernetes needs Metrics. 58 | ## Kubernetes has some build-in Metrics (CPU-Utilization, Memory-Usage, ...) 59 | ## but to use advanced Metrics (like Number of Requests, Response Latency, ...) 60 | ## you need Prometheus and the Prometheus-Adapter (https://github.com/DirectXMan12/k8s-prometheus-adapter/) 61 | ## because Prometheus does not "export" those Metrics to Kubernetes. 62 | metrics: 63 | ## ===> build-in Metrics <=== 64 | cpuUtilization: 65 | enabled: false 66 | averageUtilization: 80 67 | 68 | ## ==> Prometheus Metrics <== 69 | ## !!The Metrics below requiring that you have deployed Prometheus(-Operator), 70 | ## prometheus-adapter and enabled `metrics`!! 71 | ## !!AND please also !!READ!! the Section 'Automatic Scaling' in the README.md!! 72 | 73 | ## This Metric contains the 'request/s' and the `targetAvg` is the avg across 74 | ## all deployed Pods, and if the Values is higher then `targetAvg`, Kubernetes 75 | ## will increase the Number of Replicas. 76 | httpRequests: 77 | enabled: false 78 | targetAvg: 300 79 | 80 | ## Latency describes the avg response Duration across all deployed Pods (99%). 81 | ## Don't set it below 76ms. 82 | latency: 83 | enabled: false 84 | targetAvg: 5000m # 5000m is equal to 5ms 85 | 86 | # Whitelist namespaces e.g "kubesystem,default,development" 87 | whitelistNamespaces: "kube-system,cert-manager" 88 | # Whitelist docker registries within non-whitelisted namespaces e.g "rimusz,10.110.50.0:5000,docker.artifactory.com" 89 | whitelistRegistries: 90 | 91 | # Set external secret for TLS certs, it disables SelfSigned certs from the cert-manager 92 | # Run script tls/gen-cert.sh to generate TLS certs and store them in kubenab-tls secret 93 | tls: 94 | secretName: # kubenab-tls 95 | 96 | # Use ValidatingAdmissionWebhook only if you want to check pulling 97 | # of docker image from a Private Docker Registry e.g JFrog Artifactory. 98 | # If your container image does not contain REGISTRY_URL then Kubetug will deny request to run that pod. 99 | validatingWebhook: 100 | enabled: true 101 | 102 | # Use MutatingAdmissionWebhook only if you want to enforce pulling 103 | # of docker image from a Private Docker Registry e.g JFrog Artifactory. 104 | # If your container image is nginx then Kubetug will append REGISTRY_URL to it. e.g nginx will become someregistry/nginx 105 | mutatingWebhook: 106 | enabled: false 107 | 108 | resources: 109 | limits: 110 | cpu: 200m 111 | memory: 256Mi 112 | requests: 113 | cpu: 50m 114 | memory: 64Mi 115 | 116 | # Defines securityContext for deployment to remove all permissions 117 | # that are not needed. 118 | securityContext: 119 | enabled: true 120 | privileged: false 121 | runAsNonRoot: true 122 | runAsUser: 1000 123 | allowPrivilegeEscalation: false 124 | readOnlyRootFilesystem: true 125 | capabilities: 126 | drop: 127 | - ALL 128 | 129 | # Defines livenessProbe to monitor deployment 130 | livenessProbe: 131 | enabled: true 132 | initialDelaySeconds: 1 133 | failureThreshold: 10 134 | periodSeconds: 10 135 | httpGet: 136 | path: "/ping" 137 | port: 4443 138 | scheme: HTTPS 139 | 140 | # Defines readinessProbe to monitor deployment 141 | readinessProbe: 142 | enabled: true 143 | initialDelaySeconds: 1 144 | failureThreshold: 10 145 | periodSeconds: 10 146 | httpGet: 147 | path: "/ping" 148 | port: 4443 149 | scheme: HTTPS 150 | 151 | # Defines priorityClass to run the deployment 152 | priorityClass: 153 | enabled: true 154 | name: system-cluster-critical 155 | 156 | ## Role Based Access Control 157 | rbac: 158 | create: true 159 | role: 160 | ## Rules to create. It follows the role specification 161 | rules: 162 | - apiGroups: 163 | - '' 164 | resources: 165 | - services 166 | - endpoints 167 | - pods 168 | verbs: 169 | - get 170 | - watch 171 | - list 172 | 173 | affinity: {} 174 | 175 | tolerations: [] 176 | 177 | nodeSelector: {} 178 | -------------------------------------------------------------------------------- /cmd/kubenab/admissions.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/jfrog/kubenab/log" 6 | "io/ioutil" 7 | "net/http" 8 | "os" 9 | "strconv" 10 | "strings" 11 | 12 | json "github.com/json-iterator/go" 13 | "k8s.io/api/admission/v1beta1" 14 | v1 "k8s.io/api/core/v1" 15 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 16 | 17 | "github.com/prometheus/client_golang/prometheus" 18 | ) 19 | 20 | var ( 21 | httpRequestsTotal = prometheus.NewCounterVec(prometheus.CounterOpts{ 22 | Name: "http_requests_total", 23 | Help: "Count of all HTTP requests", 24 | }, []string{"api_endpoint"}) 25 | 26 | httpRequestDuration = prometheus.NewHistogramVec(prometheus.HistogramOpts{ 27 | Name: "http_request_duration_milliseconds", 28 | Help: "The HTTP request Duration in Milliseconds", 29 | 30 | // Latency Distribution 31 | // 5ms, 10ms, 25ms, 50ms, 100ms, 250ms, 500ms, 1s, 2.5s 32 | Buckets: []float64{5, 10, 25, 50, 100, 250, 500, 1000, 2500}, 33 | }, []string{"api_method"}) 34 | ) 35 | 36 | var ( 37 | dockerRegistryUrl = os.Getenv("DOCKER_REGISTRY_URL") 38 | replaceRegistryUrl = os.Getenv("REPLACE_REGISTRY_URL") 39 | registrySecretName = os.Getenv("REGISTRY_SECRET_NAME") 40 | whitelistRegistries = os.Getenv("WHITELIST_REGISTRIES") 41 | whitelistNamespaces = os.Getenv("WHITELIST_NAMESPACES") 42 | whitelistedNamespaces = strings.Split(whitelistNamespaces, ",") 43 | whitelistedRegistries = strings.Split(whitelistRegistries, ",") 44 | ) 45 | 46 | type patch struct { 47 | Op string `json:"op"` 48 | Path string `json:"path"` 49 | Value interface{} `json:"value,omitempty"` 50 | } 51 | 52 | func mutateAdmissionReviewHandler(w http.ResponseWriter, r *http.Request) { 53 | httpRequestsTotal.With(prometheus.Labels{"api_endpoint": "mutate"}).Inc() 54 | 55 | // log Request Duration 56 | promTimer := prometheus.NewTimer(prometheus.ObserverFunc(func(v float64) { 57 | httpRequestDuration.WithLabelValues("mutate").Observe(v * 1000) // add Milliseconds 58 | })) 59 | defer promTimer.ObserveDuration() 60 | 61 | log.Printf("Serving request: %s", r.URL.Path) 62 | //set header 63 | w.Header().Set("Content-Type", "application/json") 64 | 65 | data, err := ioutil.ReadAll(r.Body) 66 | if err != nil { 67 | log.Println(err) 68 | w.WriteHeader(http.StatusBadRequest) 69 | return 70 | } 71 | 72 | log.Debugln(data) 73 | 74 | ar := v1beta1.AdmissionReview{} 75 | if err := json.Unmarshal(data, &ar); err != nil { 76 | log.Println(err) 77 | w.WriteHeader(http.StatusBadRequest) 78 | return 79 | } 80 | 81 | namespace := ar.Request.Namespace 82 | log.Printf("AdmissionReview Namespace is: %s", namespace) 83 | 84 | admissionResponse := v1beta1.AdmissionResponse{Allowed: false} 85 | patches := []patch{} 86 | if !contains(whitelistedNamespaces, namespace) { 87 | pod := v1.Pod{} 88 | if err := json.Unmarshal(ar.Request.Object.Raw, &pod); err != nil { 89 | log.Println(err) 90 | w.WriteHeader(http.StatusBadRequest) 91 | return 92 | } 93 | 94 | var patchPath strings.Builder 95 | 96 | // Handle Containers 97 | for i, container := range pod.Spec.Containers { 98 | createPatch := handleContainer(&container, dockerRegistryUrl) 99 | if createPatch { 100 | patchPath.Reset() 101 | // TODO: Check the returned Error 102 | _, _ = patchPath.WriteString("/spec/containers/") 103 | _, _ = patchPath.WriteString(strconv.Itoa(i)) 104 | _, _ = patchPath.WriteString("/image") 105 | 106 | patches = append(patches, patch{ 107 | Op: "replace", 108 | Path: patchPath.String(), 109 | Value: container.Image, 110 | }) 111 | } 112 | } 113 | 114 | // Handle init containers 115 | for i, container := range pod.Spec.InitContainers { 116 | createPatch := handleContainer(&container, dockerRegistryUrl) 117 | if createPatch { 118 | patchPath.Reset() 119 | 120 | // TODO: Check the returned Error 121 | _, _ = patchPath.WriteString("/spec/initContainers/") 122 | _, _ = patchPath.WriteString(strconv.Itoa(i)) 123 | _, _ = patchPath.WriteString("/image") 124 | 125 | patches = append(patches, patch{ 126 | Op: "replace", 127 | Path: patchPath.String(), 128 | Value: container.Image, 129 | }) 130 | } 131 | } 132 | } else { 133 | log.Printf("Namespace is %s Whitelisted", namespace) 134 | } 135 | 136 | admissionResponse.Allowed = true 137 | if len(patches) > 0 { 138 | // add image pull secret patch if User has added it 139 | if len(registrySecretName) > 0 { 140 | patches = append(patches, patch{ 141 | Op: "add", 142 | Path: "/spec/imagePullSecrets", 143 | Value: []v1.LocalObjectReference{ 144 | v1.LocalObjectReference{ 145 | Name: registrySecretName, 146 | }, 147 | }, 148 | }) 149 | } 150 | 151 | patchContent, err := json.Marshal(patches) 152 | if err != nil { 153 | log.Println(err) 154 | w.WriteHeader(http.StatusBadRequest) 155 | return 156 | } 157 | 158 | admissionResponse.Patch = patchContent 159 | pt := v1beta1.PatchTypeJSONPatch 160 | admissionResponse.PatchType = &pt 161 | } 162 | 163 | ar = v1beta1.AdmissionReview{ 164 | Response: &admissionResponse, 165 | } 166 | 167 | data, err = json.Marshal(ar) 168 | if err != nil { 169 | log.Println(err) 170 | w.WriteHeader(http.StatusInternalServerError) 171 | return 172 | } 173 | 174 | w.WriteHeader(http.StatusOK) 175 | w.Write(data) 176 | } 177 | 178 | func handleContainer(container *v1.Container, dockerRegistryUrl string) bool { 179 | log.Println("Container Image is", container.Image) 180 | 181 | if !containsRegisty(whitelistedRegistries, container.Image) { 182 | message := fmt.Sprintf("Image is not being pulled from Private Registry: %s", container.Image) 183 | log.Printf(message) 184 | 185 | imageParts := strings.Split(container.Image, "/") 186 | newImage := "" 187 | 188 | // pre-pend new Docker Registry Domain 189 | repRegUrl, _ := strconv.ParseBool(replaceRegistryUrl) // we do not need to check for errors here, since we have done this already in checkArguments() 190 | if (len(imageParts) < 3) || !repRegUrl { 191 | newImage = dockerRegistryUrl + "/" + container.Image 192 | } else { 193 | imageParts[0] = dockerRegistryUrl 194 | newImage = strings.Join(imageParts, "/") 195 | } 196 | log.Printf("Changing image registry to: %s", newImage) 197 | 198 | container.Image = newImage 199 | return true 200 | } else { 201 | log.Printf("Image is being pulled from Private Registry: %s", container.Image) 202 | } 203 | return false 204 | } 205 | 206 | func validateAdmissionReviewHandler(w http.ResponseWriter, r *http.Request) { 207 | httpRequestsTotal.With(prometheus.Labels{"api_endpoint": "validate"}).Inc() 208 | 209 | // log Request Duration 210 | promTimer := prometheus.NewTimer(prometheus.ObserverFunc(func(v float64) { 211 | httpRequestDuration.WithLabelValues("validate").Observe(v * 1000) // add Milliseconds 212 | })) 213 | defer promTimer.ObserveDuration() 214 | 215 | log.Printf("Serving request: %s", r.URL.Path) 216 | //set header 217 | w.Header().Set("Content-Type", "application/json") 218 | 219 | data, err := ioutil.ReadAll(r.Body) 220 | if err != nil { 221 | log.Println(err) 222 | w.WriteHeader(http.StatusBadRequest) 223 | return 224 | } 225 | 226 | log.Debug(data) 227 | 228 | ar := v1beta1.AdmissionReview{} 229 | if err := json.Unmarshal(data, &ar); err != nil { 230 | log.Println(err) 231 | w.WriteHeader(http.StatusBadRequest) 232 | return 233 | } 234 | 235 | namespace := ar.Request.Namespace 236 | log.Printf("AdmissionReview Namespace is: %s", namespace) 237 | 238 | admissionResponse := v1beta1.AdmissionResponse{Allowed: false} 239 | if !contains(whitelistedNamespaces, namespace) { 240 | pod := v1.Pod{} 241 | if err := json.Unmarshal(ar.Request.Object.Raw, &pod); err != nil { 242 | log.Println(err) 243 | w.WriteHeader(http.StatusBadRequest) 244 | return 245 | } 246 | 247 | // Handle containers 248 | for _, container := range pod.Spec.Containers { 249 | log.Println("Container Image is", container.Image) 250 | 251 | if !containsRegisty(whitelistedRegistries, container.Image) { 252 | message := fmt.Sprintf("Image is not being pulled from Private Registry: %s", container.Image) 253 | log.Printf(message) 254 | admissionResponse.Result = getInvalidContainerResponse(message) 255 | goto done 256 | } else { 257 | log.Printf("Image is being pulled from Private Registry: %s", container.Image) 258 | admissionResponse.Allowed = true 259 | } 260 | } 261 | 262 | // Handle init containers 263 | for _, container := range pod.Spec.InitContainers { 264 | log.Println("Init Container Image is", container.Image) 265 | 266 | if !containsRegisty(whitelistedRegistries, container.Image) { 267 | message := fmt.Sprintf("Image is not being pulled from Private Registry: %s", container.Image) 268 | log.Printf(message) 269 | admissionResponse.Result = getInvalidContainerResponse(message) 270 | goto done 271 | } else { 272 | log.Printf("Image is being pulled from Private Registry: %s", container.Image) 273 | admissionResponse.Allowed = true 274 | } 275 | } 276 | } else { 277 | log.Printf("Namespace is %s Whitelisted", namespace) 278 | admissionResponse.Allowed = true 279 | } 280 | 281 | done: 282 | ar = v1beta1.AdmissionReview{ 283 | Response: &admissionResponse, 284 | } 285 | 286 | data, err = json.Marshal(ar) 287 | if err != nil { 288 | log.Println(err) 289 | w.WriteHeader(http.StatusInternalServerError) 290 | return 291 | } 292 | 293 | w.WriteHeader(http.StatusOK) 294 | w.Write(data) 295 | } 296 | 297 | func getInvalidContainerResponse(message string) *metav1.Status { 298 | return &metav1.Status{ 299 | Reason: metav1.StatusReasonInvalid, 300 | Details: &metav1.StatusDetails{ 301 | Causes: []metav1.StatusCause{ 302 | {Message: message}, 303 | }, 304 | }, 305 | } 306 | } 307 | 308 | // if current namespace is part of whitelisted namespaces 309 | func contains(arr []string, str string) bool { 310 | for _, a := range arr { 311 | if a == str || strings.Contains(a, str) { 312 | return true 313 | } 314 | } 315 | return false 316 | } 317 | 318 | // if current registry is part of whitelisted registries 319 | func containsRegisty(arr []string, str string) bool { 320 | for _, a := range arr { 321 | if a == str || strings.Contains(str, a) { 322 | return true 323 | } 324 | } 325 | return false 326 | } 327 | 328 | // ping responds to the request with a plain-text "Ok" message. 329 | func healthCheck(w http.ResponseWriter, r *http.Request) { 330 | log.Printf("Serving request: %s", r.URL.Path) 331 | fmt.Fprintf(w, "Ok") 332 | } 333 | 334 | // check if all (required) Arguments are set and valid 335 | func checkArguments() { 336 | if len(dockerRegistryUrl) == 0 { 337 | log.Fatalln("Environment Variable 'DOCKER_REGISTRY_URL' not set") 338 | } 339 | 340 | if len(replaceRegistryUrl) == 0 { 341 | log.Fatalln("Environment Variable 'REPLACE_REGISTRY_URL' not set") 342 | } 343 | 344 | _, err := strconv.ParseBool(replaceRegistryUrl) 345 | if err != nil { 346 | log.Fatalln("Invalid Value in Environment Variable 'REPLACE_REGISTRY_URL'") 347 | } 348 | } 349 | -------------------------------------------------------------------------------- /cmd/kubenab/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/jfrog/kubenab 2 | 3 | require ( 4 | github.com/gogo/protobuf v1.3.0 // indirect 5 | github.com/json-iterator/go v1.1.7 6 | github.com/prometheus/client_golang v1.1.0 7 | github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4 // indirect 8 | github.com/prometheus/common v0.7.0 // indirect 9 | github.com/prometheus/procfs v0.0.5 // indirect 10 | golang.org/x/net v0.0.0-20190926025831-c00fd9afed17 // indirect 11 | golang.org/x/sys v0.0.0-20190927073244-c990c680b611 // indirect 12 | gopkg.in/inf.v0 v0.9.1 // indirect 13 | k8s.io/api v0.0.0-20190927115716-5d581ce610b0 14 | k8s.io/apimachinery v0.0.0-20190927035529-0104e33c351d 15 | ) 16 | 17 | go 1.13 18 | -------------------------------------------------------------------------------- /cmd/kubenab/go.sum: -------------------------------------------------------------------------------- 1 | github.com/NYTimes/gziphandler v0.0.0-20170623195520-56545f4a5d46/go.mod h1:3wb06e3pkSAbeQ52E9H9iFoQsEEwGN64994WTCIhntQ= 2 | github.com/PuerkitoBio/purell v1.0.0/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= 3 | github.com/PuerkitoBio/urlesc v0.0.0-20160726150825-5bd2802263f2/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= 4 | github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= 5 | github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= 6 | github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= 7 | github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= 8 | github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= 9 | github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= 10 | github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= 11 | github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= 12 | github.com/davecgh/go-spew v0.0.0-20151105211317-5215b55f46b2/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 13 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 14 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 15 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 16 | github.com/docker/spdystream v0.0.0-20160310174837-449fdfce4d96/go.mod h1:Qh8CwZgvJUkLughtfhJv5dyTYa91l1fOUCrgjqmcifM= 17 | github.com/elazarl/goproxy v0.0.0-20170405201442-c4fc26588b6e/go.mod h1:/Zj4wYkgs4iZTTu3o/KG3Itv/qCCa8VVMlb3i9OVuzc= 18 | github.com/emicklei/go-restful v0.0.0-20170410110728-ff4f55a20633/go.mod h1:otzb+WCGbkyDHkqmQmT5YD2WR4BBwUdeQoFo8l/7tVs= 19 | github.com/evanphx/json-patch v4.2.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= 20 | github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= 21 | github.com/ghodss/yaml v0.0.0-20150909031657-73d445a93680/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= 22 | github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= 23 | github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= 24 | github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= 25 | github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= 26 | github.com/go-logr/logr v0.1.0/go.mod h1:ixOQHD9gLJUVQQ2ZOR7zLEifBX6tGkNJF4QyIY7sIas= 27 | github.com/go-openapi/jsonpointer v0.0.0-20160704185906-46af16f9f7b1/go.mod h1:+35s3my2LFTysnkMfxsJBAMHj/DoqoB9knIWoYG/Vk0= 28 | github.com/go-openapi/jsonreference v0.0.0-20160704190145-13c6e3589ad9/go.mod h1:W3Z9FmVs9qj+KR4zFKmDPGiLdk1D9Rlm7cyMvf57TTg= 29 | github.com/go-openapi/spec v0.0.0-20160808142527-6aced65f8501/go.mod h1:J8+jY1nAiCcj+friV/PDoE1/3eeccG9LYBs0tYvLOWc= 30 | github.com/go-openapi/swag v0.0.0-20160704191624-1d0bd113de87/go.mod h1:DXUve3Dpr1UfpPtxFw+EFuQ41HhCWZfha5jSVRG7C7I= 31 | github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= 32 | github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= 33 | github.com/gogo/protobuf v1.2.2-0.20190723190241-65acae22fc9d/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= 34 | github.com/gogo/protobuf v1.3.0 h1:G8O7TerXerS4F6sx9OV7/nRfJdnXgHZu/S/7F2SN+UE= 35 | github.com/gogo/protobuf v1.3.0/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= 36 | github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= 37 | github.com/golang/protobuf v0.0.0-20161109072736-4bd1920723d7/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 38 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 39 | github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 40 | github.com/golang/protobuf v1.3.2 h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs= 41 | github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 42 | github.com/google/go-cmp v0.3.0 h1:crn/baboCvb5fXaQ0IJ1SGTsTVrWpDsCWC8EGETZijY= 43 | github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= 44 | github.com/google/gofuzz v0.0.0-20161122191042-44d81051d367/go.mod h1:HP5RmnzzSNb993RKQDq4+1A4ia9nllfqcQFTQJedwGI= 45 | github.com/google/gofuzz v1.0.0 h1:A8PeW59pxE9IoFRqBp37U+mSNaQoZ46F1f0f863XSXw= 46 | github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= 47 | github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= 48 | github.com/googleapis/gnostic v0.0.0-20170729233727-0c5108395e2d/go.mod h1:sJBsCZ4ayReDTBIg8b9dl28c5xFWyhBTVRp3pOg5EKY= 49 | github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= 50 | github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= 51 | github.com/json-iterator/go v0.0.0-20180612202835-f2b4162afba3/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= 52 | github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= 53 | github.com/json-iterator/go v1.1.7 h1:KfgG9LzI+pYjr4xvmz/5H4FXjokeP+rlHLhv3iH62Fo= 54 | github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= 55 | github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= 56 | github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= 57 | github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= 58 | github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= 59 | github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= 60 | github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= 61 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= 62 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 63 | github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= 64 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 65 | github.com/mailru/easyjson v0.0.0-20160728113105-d5b7844b561a/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= 66 | github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= 67 | github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= 68 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 69 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= 70 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 71 | github.com/modern-go/reflect2 v0.0.0-20180320133207-05fbef0ca5da/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= 72 | github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= 73 | github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI= 74 | github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= 75 | github.com/munnerz/goautoneg v0.0.0-20120707110453-a547fc61f48d/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= 76 | github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= 77 | github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f/go.mod h1:ZdcZmHo+o7JKHSa8/e818NopupXU1YMK5fe1lsApnBw= 78 | github.com/onsi/ginkgo v0.0.0-20170829012221-11459a886d9c/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= 79 | github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= 80 | github.com/onsi/ginkgo v1.8.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= 81 | github.com/onsi/gomega v0.0.0-20170829124025-dcabb60a477c/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= 82 | github.com/onsi/gomega v1.5.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= 83 | github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 84 | github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 85 | github.com/pmezard/go-difflib v0.0.0-20151028094244-d8ed2627bdf0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 86 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 87 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 88 | github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= 89 | github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= 90 | github.com/prometheus/client_golang v1.1.0 h1:BQ53HtBmfOitExawJ6LokA4x8ov/z0SYYb0+HxJfRI8= 91 | github.com/prometheus/client_golang v1.1.0/go.mod h1:I1FGZT9+L76gKKOs5djB6ezCbFQP1xR9D75/vuwEF3g= 92 | github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= 93 | github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= 94 | github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4 h1:gQz4mCbXsO+nc9n1hCxHcGA3Zx3Eo+UHZoInFGUIXNM= 95 | github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= 96 | github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= 97 | github.com/prometheus/common v0.6.0/go.mod h1:eBmuwkDJBwy6iBfxCBob6t6dR6ENT/y+J+Zk0j9GMYc= 98 | github.com/prometheus/common v0.7.0 h1:L+1lyG48J1zAQXA3RBX/nG/B3gjlHq0zTt2tlbJLyCY= 99 | github.com/prometheus/common v0.7.0/go.mod h1:DjGbpBbp5NYNiECxcL/VnbXCCaQpKd3tt26CguLLsqA= 100 | github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= 101 | github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= 102 | github.com/prometheus/procfs v0.0.3/go.mod h1:4A/X28fw3Fc593LaREMrKMqOKvUAntwMDaekg4FpcdQ= 103 | github.com/prometheus/procfs v0.0.5 h1:3+auTFlqw+ZaQYJARz6ArODtkaIwtvBTx3N2NehQlL8= 104 | github.com/prometheus/procfs v0.0.5/go.mod h1:4A/X28fw3Fc593LaREMrKMqOKvUAntwMDaekg4FpcdQ= 105 | github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= 106 | github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= 107 | github.com/spf13/pflag v0.0.0-20170130214245-9ff6c6923cff/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= 108 | github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg= 109 | github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= 110 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 111 | github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 112 | github.com/stretchr/testify v0.0.0-20151208002404-e3a8ff8ce365/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 113 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 114 | github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= 115 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 116 | golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= 117 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 118 | golang.org/x/net v0.0.0-20170114055629-f2499483f923/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 119 | golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 120 | golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 121 | golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 122 | golang.org/x/net v0.0.0-20190812203447-cdfb69ac37fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 123 | golang.org/x/net v0.0.0-20190926025831-c00fd9afed17 h1:qPnAdmjNA41t3QBTx2mFGf/SD1IoslhYu7AmdsVzCcs= 124 | golang.org/x/net v0.0.0-20190926025831-c00fd9afed17/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 125 | golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 126 | golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 127 | golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 128 | golang.org/x/sys v0.0.0-20170830134202-bb24a47a89ea/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 129 | golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 130 | golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 131 | golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 132 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 133 | golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 134 | golang.org/x/sys v0.0.0-20190616124812-15dcb6c0061f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 135 | golang.org/x/sys v0.0.0-20190801041406-cbf593c0f2f3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 136 | golang.org/x/sys v0.0.0-20190927073244-c990c680b611 h1:q9u40nxWT5zRClI/uU9dHCiYGottAg6Nzz4YUQyHxdA= 137 | golang.org/x/sys v0.0.0-20190927073244-c990c680b611/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 138 | golang.org/x/text v0.0.0-20160726164857-2910a502d2bf/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 139 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 140 | golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= 141 | golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= 142 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 143 | golang.org/x/tools v0.0.0-20181011042414-1f849cf54d09/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 144 | golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 145 | gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= 146 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 147 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= 148 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 149 | gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= 150 | gopkg.in/inf.v0 v0.9.0/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= 151 | gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= 152 | gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= 153 | gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= 154 | gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 155 | gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= 156 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 157 | k8s.io/api v0.0.0-20190927115716-5d581ce610b0 h1:fwx2jAKNlXBQ8uiB3RNN5hVU/nEJTEBg/CfxoXEYri4= 158 | k8s.io/api v0.0.0-20190927115716-5d581ce610b0/go.mod h1:l2ZHS8QbgqodGx7yrYsOSwIxOR76BpGiW1OywXo9PFI= 159 | k8s.io/apimachinery v0.0.0-20190927035529-0104e33c351d h1:oYLB5Nk2IOm17BHdatnaWAgzNGzq/5dlWy7Bzo5Htdc= 160 | k8s.io/apimachinery v0.0.0-20190927035529-0104e33c351d/go.mod h1:grJJH0hgilA2pYoUiJcPu2EDUal95NTq1vpxxvMLSu8= 161 | k8s.io/gengo v0.0.0-20190128074634-0689ccc1d7d6/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8IAqLxYwwyPxAX1Pzy0ii0= 162 | k8s.io/klog v0.0.0-20181102134211-b9b56d5dfc92/go.mod h1:Gq+BEi5rUBO/HRz0bTSXDUcqjScdoY3a9IHpCEIOOfk= 163 | k8s.io/klog v1.0.0 h1:Pt+yjF5aB1xDSVbau4VsWe+dQNzA0qv1LlXdC2dF6Q8= 164 | k8s.io/klog v1.0.0/go.mod h1:4Bi6QPql/J/LkTDqv7R/cd3hPo4k2DG6Ptcz060Ez5I= 165 | k8s.io/kube-openapi v0.0.0-20190816220812-743ec37842bf/go.mod h1:1TqjTSzOxsLGIKfj0lK8EeCP7K1iUG65v09OM0/WG5E= 166 | sigs.k8s.io/structured-merge-diff v0.0.0-20190525122527-15d366b2352e/go.mod h1:wWxsB5ozmmv/SG7nM11ayaAW51xMvak/t1r0CSlcokI= 167 | sigs.k8s.io/yaml v1.1.0 h1:4A07+ZFc2wgJwo8YNlQpr1rVlgUDlxXHhPJciaPY5gs= 168 | sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o= 169 | -------------------------------------------------------------------------------- /cmd/kubenab/log/log.go: -------------------------------------------------------------------------------- 1 | // Why a special log Package? Because if we compile a Release we do not need 2 | // the debug Output. 3 | package log 4 | 5 | import "log" 6 | 7 | func Fatal(v ...interface{}) { 8 | log.Fatal(v...) 9 | } 10 | 11 | func Fatalln(v ...interface{}) { 12 | log.Fatalln(v...) 13 | } 14 | 15 | func Println(v ...interface{}) { 16 | log.Println(v...) 17 | } 18 | 19 | func Printf(fmt string, args ...interface{}) { 20 | log.Printf(fmt, args...) 21 | } 22 | -------------------------------------------------------------------------------- /cmd/kubenab/log/log_debug.go: -------------------------------------------------------------------------------- 1 | // +build !strip_debug 2 | 3 | package log 4 | 5 | import "log" 6 | 7 | func Debug(v ...interface{}) { 8 | log.Print(v...) 9 | } 10 | 11 | func Debugln(v ...interface{}) { 12 | log.Println(v...) 13 | } 14 | 15 | func Debugf(fmt string, args ...interface{}) { 16 | log.Printf(fmt, args...) 17 | } 18 | -------------------------------------------------------------------------------- /cmd/kubenab/log/log_release.go: -------------------------------------------------------------------------------- 1 | // +build strip_debug,!debug 2 | 3 | package log 4 | 5 | func Debug(v ...interface{}) {} 6 | 7 | func Debugln(v ...interface{}) {} 8 | 9 | func Debugf(fmt string, args ...interface{}) {} 10 | -------------------------------------------------------------------------------- /cmd/kubenab/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto/tls" 5 | "flag" 6 | "log" 7 | "net/http" 8 | "os" 9 | 10 | "github.com/prometheus/client_golang/prometheus" 11 | "github.com/prometheus/client_golang/prometheus/promhttp" 12 | ) 13 | 14 | var ( 15 | tlsCertFile string 16 | tlsKeyFile string 17 | ) 18 | 19 | func main() { 20 | // print Version Informations 21 | log.Printf("Starting kubenab version %s - %s - %s", version, date, commit) 22 | 23 | // check if all required Flags are set and in a correct Format 24 | checkArguments() 25 | 26 | flag.StringVar(&tlsCertFile, "tls-cert", "/etc/admission-controller/tls/tls.crt", "TLS certificate file.") 27 | flag.StringVar(&tlsKeyFile, "tls-key", "/etc/admission-controller/tls/tls.key", "TLS key file.") 28 | flag.Parse() 29 | 30 | os.LookupEnv("PORT") 31 | port := "4443" 32 | if envPort, exists := os.LookupEnv("PORT"); exists { 33 | port = envPort 34 | } 35 | 36 | promRegistry := prometheus.NewRegistry() 37 | promRegistry.MustRegister(httpRequestsTotal) 38 | promRegistry.MustRegister(httpRequestDuration) 39 | 40 | http.Handle("/metrics", promhttp.HandlerFor(promRegistry, promhttp.HandlerOpts{})) 41 | http.HandleFunc("/ping", healthCheck) 42 | http.HandleFunc("/mutate", mutateAdmissionReviewHandler) 43 | http.HandleFunc("/validate", validateAdmissionReviewHandler) 44 | s := http.Server{ 45 | Addr: ":" + port, 46 | TLSConfig: &tls.Config{ 47 | ClientAuth: tls.NoClientCert, 48 | }, 49 | } 50 | 51 | log.Fatal(s.ListenAndServeTLS(tlsCertFile, tlsKeyFile)) 52 | } 53 | -------------------------------------------------------------------------------- /cmd/kubenab/version.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // This File contains only the Version Informations about `kubenab` 4 | 5 | var ( 6 | version = "** NOT SET **" // Contains a SemVer Version 7 | date = "** NOT SET **" // Contains the UTC Build Time 8 | commit = "** NOT SET **" // Contains the SHA1 Hash of the last Commit 9 | ) 10 | -------------------------------------------------------------------------------- /deployment/kubenab-deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | name: kubenab-deployment 5 | labels: 6 | app: kubenab 7 | spec: 8 | selector: 9 | matchLabels: 10 | app: "kubenab" 11 | replicas: 1 12 | template: 13 | metadata: 14 | labels: 15 | app: "kubenab" 16 | spec: 17 | priorityClassName: system-cluster-critical 18 | containers: 19 | - name: kubenab 20 | image: docker.bintray.io/kubexray:0.3.3 21 | imagePullPolicy: Always 22 | env: 23 | - name: DOCKER_REGISTRY_URL 24 | value: "kubenab" 25 | - name: REGISTRY_SECRET_NAME 26 | value: 'regsecret' 27 | - name: WHITELIST_NAMESPACES 28 | value: "kube-system,default" 29 | - name: WHITELIST_REGISTRIES 30 | value: "kubenab" 31 | - name: REPLACE_REGISTRY_URL 32 | value: "true" 33 | ports: 34 | - containerPort: 443 35 | name: https 36 | volumeMounts: 37 | - name: tls 38 | mountPath: /etc/admission-controller/tls 39 | resources: {} 40 | volumes: 41 | - name: tls 42 | secret: 43 | secretName: kubenab-certs 44 | -------------------------------------------------------------------------------- /deployment/kubenab-svc.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: kubenab 5 | labels: 6 | app: kubenab 7 | spec: 8 | type: ClusterIP 9 | ports: 10 | - port: 443 11 | protocol: "TCP" 12 | name: https 13 | selector: 14 | app: kubenab -------------------------------------------------------------------------------- /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: kubenab 14 | spec: 15 | selector: 16 | matchLabels: 17 | test: kubenab 18 | replicas: 1 19 | template: 20 | metadata: 21 | labels: 22 | test: kubenab 23 | spec: 24 | containers: 25 | - name: nginx 26 | image: nginx 27 | imagePullPolicy: IfNotPresent 28 | 29 | -------------------------------------------------------------------------------- /tls/gen-cert.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | #title="default" 3 | 4 | #[ -z ${title} ] && service="kubenab" 5 | #[ -z ${title} ] && secret="kubenab-certs" 6 | #[ -z ${title} ] && namespace="default" 7 | 8 | service="kubenab" 9 | secret="kubenab-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/kubenab-mutating-webhook-configuration.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: admissionregistration.k8s.io/v1beta1 2 | kind: MutatingWebhookConfiguration 3 | metadata: 4 | name: kubenab-mutate 5 | webhooks: 6 | - name: kubenab-mutate.kubenab.com 7 | rules: 8 | - operations: [ "CREATE", "UPDATE" ] 9 | apiGroups: [""] 10 | apiVersions: ["v1"] 11 | resources: ["pods"] 12 | failurePolicy: Ignore 13 | clientConfig: 14 | service: 15 | name: kubenab 16 | namespace: default 17 | path: "/mutate" 18 | caBundle: ${CA_BUNDLE} 19 | -------------------------------------------------------------------------------- /webhook/kubenab-validating-webhook-configuration.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: admissionregistration.k8s.io/v1beta1 2 | kind: ValidatingWebhookConfiguration 3 | metadata: 4 | name: kubenab-validate 5 | webhooks: 6 | - name: kubenab-validate.kubenab.com 7 | rules: 8 | - apiGroups: 9 | - "" 10 | apiVersions: 11 | - v1 12 | operations: 13 | - CREATE 14 | - UPDATE 15 | resources: 16 | - pods 17 | failurePolicy: Ignore 18 | clientConfig: 19 | service: 20 | name: kubenab 21 | namespace: default 22 | path: "/validate" 23 | caBundle: ${CA_BUNDLE} 24 | -------------------------------------------------------------------------------- /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}" --------------------------------------------------------------------------------