├── .gitignore
├── Gopkg.lock
├── Gopkg.toml
├── LICENSE.txt
├── Makefile
├── README.md
├── circle.yml
├── install-binary.sh
├── main.go
├── plugin.yaml
└── testdata
├── .helmignore
├── Chart.yaml
├── policies
└── base.rego
├── templates
├── NOTES.txt
├── _helpers.tpl
├── deployment.yaml
├── ingress.yaml
└── service.yaml
└── values.yaml
/.gitignore:
--------------------------------------------------------------------------------
1 | debug*
2 | helm-opa*
3 | opa*
4 | _dist
5 | .vscode
6 | vendor
--------------------------------------------------------------------------------
/Gopkg.lock:
--------------------------------------------------------------------------------
1 | # This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
2 |
3 |
4 | [[projects]]
5 | name = "github.com/BurntSushi/toml"
6 | packages = ["."]
7 | revision = "b26d9c308763d68093482582cea63d69be07a0f0"
8 | version = "v0.3.0"
9 |
10 | [[projects]]
11 | name = "github.com/Masterminds/semver"
12 | packages = ["."]
13 | revision = "c7af12943936e8c39859482e61f0574c2fd7fc75"
14 | version = "v1.4.2"
15 |
16 | [[projects]]
17 | name = "github.com/Masterminds/sprig"
18 | packages = ["."]
19 | revision = "6b2a58267f6a8b1dc8e2eb5519b984008fa85e8c"
20 | version = "v2.15.0"
21 |
22 | [[projects]]
23 | name = "github.com/aokoli/goutils"
24 | packages = ["."]
25 | revision = "3391d3790d23d03408670993e957e8f408993c34"
26 | version = "v1.0.1"
27 |
28 | [[projects]]
29 | name = "github.com/dchest/siphash"
30 | packages = ["."]
31 | revision = "4ebf1de738443ea7f45f02dc394c4df1942a126d"
32 | version = "v1.1.0"
33 |
34 | [[projects]]
35 | name = "github.com/ghodss/yaml"
36 | packages = ["."]
37 | revision = "0ca9ea5df5451ffdf184b4428c902747c2c11cd7"
38 | version = "v1.0.0"
39 |
40 | [[projects]]
41 | name = "github.com/gobwas/glob"
42 | packages = [
43 | ".",
44 | "compiler",
45 | "match",
46 | "syntax",
47 | "syntax/ast",
48 | "syntax/lexer",
49 | "util/runes",
50 | "util/strings"
51 | ]
52 | revision = "5ccd90ef52e1e632236f7326478d4faa74f99438"
53 | version = "v0.2.3"
54 |
55 | [[projects]]
56 | name = "github.com/golang/protobuf"
57 | packages = [
58 | "proto",
59 | "ptypes/any",
60 | "ptypes/timestamp"
61 | ]
62 | revision = "b4deda0973fb4c70b50d226b1af49f3da59f5265"
63 | version = "v1.1.0"
64 |
65 | [[projects]]
66 | name = "github.com/google/uuid"
67 | packages = ["."]
68 | revision = "064e2069ce9c359c118179501254f67d7d37ba24"
69 | version = "0.2"
70 |
71 | [[projects]]
72 | name = "github.com/huandu/xstrings"
73 | packages = ["."]
74 | revision = "2bf18b218c51864a87384c06996e40ff9dcff8e1"
75 | version = "v1.0.0"
76 |
77 | [[projects]]
78 | name = "github.com/imdario/mergo"
79 | packages = ["."]
80 | revision = "9d5f1277e9a8ed20c3684bda8fde67c05628518c"
81 | version = "v0.3.4"
82 |
83 | [[projects]]
84 | name = "github.com/inconshreveable/mousetrap"
85 | packages = ["."]
86 | revision = "76626ae9c91c4f2a10f34cad8ce83ea42c93bb75"
87 | version = "v1.0"
88 |
89 | [[projects]]
90 | name = "github.com/open-policy-agent/opa"
91 | packages = [
92 | "ast",
93 | "metrics",
94 | "rego",
95 | "storage",
96 | "storage/inmem",
97 | "topdown",
98 | "topdown/builtins",
99 | "types",
100 | "util"
101 | ]
102 | revision = "91ad1a786f8e3f930bcb3ba44aacdabec7a3a45d"
103 | version = "v0.8.1"
104 |
105 | [[projects]]
106 | name = "github.com/pkg/errors"
107 | packages = ["."]
108 | revision = "645ef00459ed84a119197bfb8d8205042c6df63d"
109 | version = "v0.8.0"
110 |
111 | [[projects]]
112 | branch = "master"
113 | name = "github.com/rcrowley/go-metrics"
114 | packages = ["."]
115 | revision = "e2704e165165ec55d062f5919b4b29494e9fa790"
116 |
117 | [[projects]]
118 | name = "github.com/spf13/cobra"
119 | packages = ["."]
120 | revision = "a1f051bc3eba734da4772d60e2d677f47cf93ef4"
121 | version = "v0.0.2"
122 |
123 | [[projects]]
124 | name = "github.com/spf13/pflag"
125 | packages = ["."]
126 | revision = "583c0c0531f06d5278b7d917446061adc344b5cd"
127 | version = "v1.0.1"
128 |
129 | [[projects]]
130 | branch = "master"
131 | name = "github.com/yashtewari/glob-intersection"
132 | packages = ["."]
133 | revision = "7af743e8ec8480fee1932a737a406f7ec817f910"
134 |
135 | [[projects]]
136 | branch = "master"
137 | name = "golang.org/x/crypto"
138 | packages = [
139 | "pbkdf2",
140 | "scrypt"
141 | ]
142 | revision = "4ec37c66abab2c7e02ae775328b2ff001c3f025a"
143 |
144 | [[projects]]
145 | name = "gopkg.in/yaml.v2"
146 | packages = ["."]
147 | revision = "5420a8b6744d3b0345ab293f6fcba19c978f1183"
148 | version = "v2.2.1"
149 |
150 | [[projects]]
151 | branch = "master"
152 | name = "k8s.io/apimachinery"
153 | packages = ["pkg/version"]
154 | revision = "bd236513a4e35622d9007dff11eab07631645cd5"
155 |
156 | [[projects]]
157 | name = "k8s.io/helm"
158 | packages = [
159 | "pkg/chartutil",
160 | "pkg/engine",
161 | "pkg/ignore",
162 | "pkg/proto/hapi/chart",
163 | "pkg/proto/hapi/version",
164 | "pkg/sympath",
165 | "pkg/timeconv",
166 | "pkg/version"
167 | ]
168 | revision = "f6025bb9ee7daf9fee0026541c90a6f557a3e0bc"
169 | version = "v2.9.0"
170 |
171 | [solve-meta]
172 | analyzer-name = "dep"
173 | analyzer-version = 1
174 | inputs-digest = "40368d4b86870a889d81bad369131318b553cff4a0007612c42ef2b1c765bcd5"
175 | solver-name = "gps-cdcl"
176 | solver-version = 1
177 |
--------------------------------------------------------------------------------
/Gopkg.toml:
--------------------------------------------------------------------------------
1 | # Gopkg.toml example
2 | #
3 | # Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md
4 | # for detailed Gopkg.toml documentation.
5 | #
6 | # required = ["github.com/user/thing/cmd/thing"]
7 | # ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"]
8 | #
9 | # [[constraint]]
10 | # name = "github.com/user/project"
11 | # version = "1.0.0"
12 | #
13 | # [[constraint]]
14 | # name = "github.com/user/project2"
15 | # branch = "dev"
16 | # source = "github.com/myfork/project2"
17 | #
18 | # [[override]]
19 | # name = "github.com/x/y"
20 | # version = "2.4.0"
21 | #
22 | # [prune]
23 | # non-go = false
24 | # go-tests = true
25 | # unused-packages = true
26 |
27 |
28 | [prune]
29 | go-tests = true
30 | unused-packages = true
31 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
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 2018 Lukas Eichler
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.
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | HELM_HOME ?= $(shell helm home)
2 | HELM_PLUGIN_DIR ?= $(HELM_HOME)/plugins/helm-opa
3 | HAS_DEP := $(shell command -v DEP;)
4 | VERSION := $(shell sed -n -e 's/version:[ "]*\([^"]*\).*/\1/p' plugin.yaml)
5 | DIST := $(CURDIR)/_dist
6 | LDFLAGS := "-X main.version=${VERSION}"
7 |
8 | .PHONY: install
9 | install: bootstrap build
10 | cp opa $(HELM_PLUGIN_DIR)
11 | cp plugin.yaml $(HELM_PLUGIN_DIR)
12 |
13 | .PHONY: hookInstall
14 | hookInstall: bootstrap build
15 |
16 | .PHONY: build
17 | build:
18 | go build -o opa -ldflags $(LDFLAGS) ./main.go
19 |
20 | .PHONY: dist
21 | dist:
22 | mkdir -p $(DIST)
23 | GOOS=linux GOARCH=amd64 go build -o opa -ldflags $(LDFLAGS) ./main.go
24 | tar -zcvf $(DIST)/helm-opa-linux-$(VERSION).tgz opa README.md LICENSE.txt plugin.yaml
25 | GOOS=darwin GOARCH=amd64 go build -o opa -ldflags $(LDFLAGS) ./main.go
26 | tar -zcvf $(DIST)/helm-opa-macos-$(VERSION).tgz opa README.md LICENSE.txt plugin.yaml
27 | GOOS=windows GOARCH=amd64 go build -o opa.exe -ldflags $(LDFLAGS) ./main.go
28 | tar -zcvf $(DIST)/helm-opa-windows-$(VERSION).tgz opa.exe README.md LICENSE.txt plugin.yaml
29 |
30 | .PHONY: bootstrap
31 | bootstrap:
32 | ifndef HAS_DEP
33 | go get -u github.com/golang/dep/cmd/dep
34 | endif
35 | dep ensure
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Helm [OPA](https://www.openpolicyagent.org/) Plugin
2 | [](https://circleci.com/gh/eicnix/helm-opa)
3 |
4 | This plugin enables you to check your rendered templates files again [Open Policy Agent](https://www.openpolicyagent.org/) policies to ensure that they match your policies.
5 |
6 |
7 |
8 | ## Usage
9 |
10 | Define policies inside the `policies` folder in your Chart. e.g. Pods must run as nonRoot:
11 | ```
12 | deny[msg] {
13 | input.kind = "Deployment"
14 | not input.spec.template.spec.securityContext.runAsNonRoot = true
15 | msg = "Containers must not run as root"
16 | }
17 | ```
18 |
19 | Run the policy check:
20 | ```sh
21 | # helm opa CHART
22 | Processing file deployment.yaml
23 | Violations:
24 | - Containers must not run as root
25 | Processing file ingress.yaml
26 | Processing file service.yaml
27 | ===
28 | Result: Chart is not compliant
29 | ```
30 |
31 | ## Install
32 |
33 | ```sh
34 | $ helm plugin install https://github.com/eicnix/helm-opa
35 | ```
36 |
37 | ## License
38 |
39 | Copyright 2018 Lukas Eichler
40 |
41 | Licensed under the Apache License, Version 2.0 (the "License");
42 | you may not use this file except in compliance with the License.
43 | You may obtain a copy of the License at
44 |
45 | http://www.apache.org/licenses/LICENSE-2.0
46 |
47 | Unless required by applicable law or agreed to in writing, software
48 | distributed under the License is distributed on an "AS IS" BASIS,
49 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
50 | See the License for the specific language governing permissions and
51 | limitations under the License.
52 |
--------------------------------------------------------------------------------
/circle.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | jobs:
3 | build:
4 | docker:
5 | - image: circleci/golang:1.9
6 | working_directory: /go/src/github.com/eicnix/helm/opa
7 | steps:
8 | - checkout
9 | - run: go get -u github.com/golang/dep/cmd/dep
10 | - run: dep ensure
11 | - run: go build -v
--------------------------------------------------------------------------------
/install-binary.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Script from https://github.com/technosophos/helm-template
4 |
5 | PROJECT_NAME="helm-opa"
6 | PROJECT_GH="eicnix/$PROJECT_NAME"
7 |
8 | : ${HELM_PLUGIN_PATH:="$(helm home)/plugins/helm-template"}
9 |
10 | # Convert the HELM_PLUGIN_PATH to unix if cygpath is
11 | # available. This is the case when using MSYS2 or Cygwin
12 | # on Windows where helm returns a Windows path but we
13 | # need a Unix path
14 | if type cygpath > /dev/null; then
15 | HELM_PLUGIN_PATH=$(cygpath -u $HELM_PLUGIN_PATH)
16 | fi
17 |
18 | if [[ $SKIP_BIN_INSTALL == "1" ]]; then
19 | echo "Skipping binary install"
20 | exit
21 | fi
22 |
23 | # initArch discovers the architecture for this system.
24 | initArch() {
25 | ARCH=$(uname -m)
26 | case $ARCH in
27 | armv5*) ARCH="armv5";;
28 | armv6*) ARCH="armv6";;
29 | armv7*) ARCH="armv7";;
30 | aarch64) ARCH="arm64";;
31 | x86) ARCH="386";;
32 | x86_64) ARCH="amd64";;
33 | i686) ARCH="386";;
34 | i386) ARCH="386";;
35 | esac
36 | }
37 |
38 | # initOS discovers the operating system for this system.
39 | initOS() {
40 | OS=$(echo `uname`|tr '[:upper:]' '[:lower:]')
41 |
42 | case "$OS" in
43 | # Msys support
44 | msys*) OS='windows';;
45 | # Minimalist GNU for Windows
46 | mingw*) OS='windows';;
47 | darwin) OS='macos';;
48 | esac
49 | }
50 |
51 | # verifySupported checks that the os/arch combination is supported for
52 | # binary builds.
53 | verifySupported() {
54 | local supported="linux-amd64\nmacos-amd64\nwindows-amd64"
55 | if ! echo "${supported}" | grep -q "${OS}-${ARCH}"; then
56 | echo "No prebuild binary for ${OS}-${ARCH}."
57 | exit 1
58 | fi
59 |
60 | if ! type "curl" > /dev/null && ! type "wget" > /dev/null; then
61 | echo "Either curl or wget is required"
62 | exit 1
63 | fi
64 | }
65 |
66 | # getDownloadURL checks the latest available version.
67 | getDownloadURL() {
68 | # Use the GitHub API to find the latest version for this project.
69 | local latest_url="https://api.github.com/repos/$PROJECT_GH/releases/latest"
70 | if type "curl" > /dev/null; then
71 | DOWNLOAD_URL=$(curl -s $latest_url | grep $OS | awk '/\"browser_download_url\":/{gsub( /[,\"]/,"", $2); print $2}')
72 | elif type "wget" > /dev/null; then
73 | DOWNLOAD_URL=$(wget -q -O - $latest_url | awk '/\"browser_download_url\":/{gsub( /[,\"]/,"", $2); print $2}')
74 | fi
75 | }
76 |
77 | # downloadFile downloads the latest binary package and also the checksum
78 | # for that binary.
79 | downloadFile() {
80 | PLUGIN_TMP_FILE="/tmp/${PROJECT_NAME}.tgz"
81 | echo "Downloading $DOWNLOAD_URL"
82 | if type "curl" > /dev/null; then
83 | curl -L "$DOWNLOAD_URL" -o "$PLUGIN_TMP_FILE"
84 | elif type "wget" > /dev/null; then
85 | wget -q -O "$PLUGIN_TMP_FILE" "$DOWNLOAD_URL"
86 | fi
87 | }
88 |
89 | # installFile verifies the SHA256 for the file, then unpacks and
90 | # installs it.
91 | installFile() {
92 | HELM_TMP="/tmp/$PROJECT_NAME"
93 | mkdir -p "$HELM_TMP"
94 | tar xf "$PLUGIN_TMP_FILE" -C "$HELM_TMP"
95 | HELM_TMP_BIN="$HELM_TMP/tpl"
96 | echo "Preparing to install into ${HELM_PLUGIN_PATH}"
97 | # Use * to also copy the file withe the exe suffix on Windows
98 | cp "$HELM_TMP_BIN"* "$HELM_PLUGIN_PATH"
99 | }
100 |
101 | # fail_trap is executed if an error occurs.
102 | fail_trap() {
103 | result=$?
104 | if [ "$result" != "0" ]; then
105 | echo "Failed to install $PROJECT_NAME"
106 | echo "\tFor support, go to https://github.com/kubernetes/helm."
107 | fi
108 | exit $result
109 | }
110 |
111 | # testVersion tests the installed client to make sure it is working.
112 | testVersion() {
113 | set +e
114 | echo "$PROJECT_NAME installed into $HELM_PLUGIN_PATH/$PROJECT_NAME"
115 | # To avoid to keep track of the Windows suffix,
116 | # call the plugin assuming it is in the PATH
117 | PATH=$PATH:$HELM_PLUGIN_PATH
118 | tpl -h
119 | set -e
120 | }
121 |
122 | # Execution
123 |
124 | #Stop execution on any error
125 | trap "fail_trap" EXIT
126 | set -e
127 | initArch
128 | initOS
129 | verifySupported
130 | getDownloadURL
131 | downloadFile
132 | installFile
133 | testVersion
--------------------------------------------------------------------------------
/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "context"
5 | "errors"
6 | "fmt"
7 | "io/ioutil"
8 | "os"
9 | "path/filepath"
10 | "sort"
11 | "strings"
12 |
13 | "github.com/ghodss/yaml"
14 | "github.com/open-policy-agent/opa/ast"
15 | "github.com/open-policy-agent/opa/rego"
16 | "github.com/spf13/cobra"
17 | "k8s.io/helm/pkg/chartutil"
18 | "k8s.io/helm/pkg/engine"
19 | "k8s.io/helm/pkg/proto/hapi/chart"
20 | "k8s.io/helm/pkg/timeconv"
21 | )
22 |
23 | const globalUsage = `
24 | Checks the rendered chart templates against Open Policy Agent policies.
25 | All policies under policies/ will be evaluated.
26 | `
27 |
28 | var (
29 | flagVerbose bool
30 | showNotes bool
31 | )
32 |
33 | var version = "DEV"
34 |
35 | func main() {
36 | cmd := &cobra.Command{
37 | Use: "template [flags] CHART",
38 | Short: fmt.Sprintf("locally render templates (helm-template %s)", version),
39 | RunE: run,
40 | }
41 |
42 | f := cmd.Flags()
43 | f.BoolVarP(&flagVerbose, "verbose", "v", false, "show the computed YAML values as well.")
44 | f.BoolVar(&showNotes, "notes", false, "show the computed NOTES.txt file as well.")
45 |
46 | if err := cmd.Execute(); err != nil {
47 | os.Exit(1)
48 | }
49 | }
50 |
51 | func run(cmd *cobra.Command, args []string) error {
52 | if len(args) < 1 {
53 | return errors.New("chart is required")
54 | }
55 | c, err := chartutil.Load(args[0])
56 | if err != nil {
57 | return err
58 | }
59 |
60 | vv, err := yaml.Marshal(map[string]interface{}{})
61 | config := &chart.Config{Raw: string(vv), Values: map[string]*chart.Value{}}
62 |
63 | options := chartutil.ReleaseOptions{
64 | Name: "RELEASE",
65 | Time: timeconv.Now(),
66 | Namespace: "NAMESPACE",
67 | }
68 |
69 | renderer := engine.New()
70 |
71 | vals, err := chartutil.ToRenderValues(c, config, options)
72 | if err != nil {
73 | return err
74 | }
75 |
76 | out, err := renderer.Render(c, vals)
77 | if err != nil {
78 | return err
79 | }
80 |
81 | sortedKeys := make([]string, 0, len(out))
82 | for key := range out {
83 | sortedKeys = append(sortedKeys, key)
84 | }
85 | sort.Strings(sortedKeys)
86 |
87 | foundViolations := false
88 |
89 | compiler, err := buildCopmiler(args[0] + "/" + "policies")
90 |
91 | for _, name := range sortedKeys {
92 | data := out[name]
93 | fileName := filepath.Base(name)
94 |
95 | if strings.HasSuffix(fileName, ".yaml") {
96 | r, _ := processFile(fileName, data, compiler)
97 | if !foundViolations && r {
98 | foundViolations = r
99 | }
100 | }
101 |
102 | }
103 |
104 | fmt.Println("===")
105 | if foundViolations {
106 | fmt.Println("Result: Chart is not compliant")
107 | } else {
108 | fmt.Println("Result: Chart is compliant")
109 | }
110 |
111 | return nil
112 | }
113 |
114 | func processFile(fileName string, data string, compiler *ast.Compiler) (bool, error) {
115 | fmt.Printf("Processing file %v\n", fileName)
116 |
117 | ctx := context.Background()
118 | var input interface{}
119 | err := yaml.Unmarshal([]byte(data), &input)
120 |
121 | rego := rego.New(
122 | rego.Query("data.main.deny"),
123 | rego.Compiler(compiler),
124 | rego.Input(input))
125 |
126 | rs, err := rego.Eval(ctx)
127 |
128 | hasResults := func(expression interface{}) bool {
129 | if v, ok := expression.([]interface{}); ok {
130 | return len(v) > 0
131 | }
132 | return false
133 | }
134 |
135 | foundViolations := false
136 | for _, r := range rs {
137 | for _, e := range r.Expressions {
138 | value := e.Value
139 | if hasResults(value) {
140 | foundViolations = true
141 | fmt.Println("Violations:")
142 | for _, v := range value.([]interface{}) {
143 | fmt.Printf("- %v\n", v)
144 | }
145 | }
146 | }
147 | }
148 |
149 | return foundViolations, err
150 | }
151 |
152 | func buildCopmiler(path string) (*ast.Compiler, error) {
153 | files, err := ioutil.ReadDir(path)
154 | if err != nil {
155 | return nil, err
156 | }
157 |
158 | modules := map[string]*ast.Module{}
159 |
160 | for _, file := range files {
161 | if !strings.HasSuffix(file.Name(), ".rego") {
162 | continue
163 | }
164 |
165 | out, err := ioutil.ReadFile(path + "/" + file.Name())
166 | if err != nil {
167 | return nil, err
168 | }
169 |
170 | parsed, err := ast.ParseModule(file.Name(), string(out[:]))
171 | if err != nil {
172 | return nil, err
173 | }
174 | modules[file.Name()] = parsed
175 |
176 | }
177 |
178 | compiler := ast.NewCompiler()
179 | compiler.Compile(modules)
180 |
181 | if compiler.Failed() {
182 | panic(compiler.Errors)
183 | }
184 |
185 | return compiler, nil
186 | }
187 |
--------------------------------------------------------------------------------
/plugin.yaml:
--------------------------------------------------------------------------------
1 | name: "opa"
2 | # Version is the version of Helm plus the number of official builds for this
3 | # plugin
4 | version: "2.5.1+2"
5 | usage: "opa "
6 | description: "Checks rendered charts against OPA policies"
7 | command: "$HELM_PLUGIN_DIR/opa"
8 | hooks:
9 | install: "$HELM_PLUGIN_DIR/install-binary.sh"
--------------------------------------------------------------------------------
/testdata/.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 |
--------------------------------------------------------------------------------
/testdata/Chart.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: v1
2 | appVersion: "1.0"
3 | description: A Helm chart for Kubernetes
4 | name: .
5 | version: 0.1.0
6 |
--------------------------------------------------------------------------------
/testdata/policies/base.rego:
--------------------------------------------------------------------------------
1 | package main
2 |
3 |
4 | deny[msg] {
5 | input.kind = "Deployment"
6 | not input.spec.template.spec.securityContext.runAsNonRoot = true
7 | msg = "Containers must not run as root"
8 | }
9 |
10 | deny[msg] {
11 | input.kind = "Deployment"
12 | not input.spec.selector.matchLabels.app
13 | not input.spec.selector.matchLabels.release
14 | msg = "Containers must provide app/release labls for pod selectors"
15 | }
--------------------------------------------------------------------------------
/testdata/templates/NOTES.txt:
--------------------------------------------------------------------------------
1 | 1. Get the application URL by running these commands:
2 | {{- if .Values.ingress.enabled }}
3 | {{- range .Values.ingress.hosts }}
4 | http{{ if $.Values.ingress.tls }}s{{ end }}://{{ . }}{{ $.Values.ingress.path }}
5 | {{- end }}
6 | {{- else if contains "NodePort" .Values.service.type }}
7 | export NODE_PORT=$(kubectl get --namespace {{ .Release.Namespace }} -o jsonpath="{.spec.ports[0].nodePort}" services {{ template "..fullname" . }})
8 | export NODE_IP=$(kubectl get nodes --namespace {{ .Release.Namespace }} -o jsonpath="{.items[0].status.addresses[0].address}")
9 | echo http://$NODE_IP:$NODE_PORT
10 | {{- else if contains "LoadBalancer" .Values.service.type }}
11 | NOTE: It may take a few minutes for the LoadBalancer IP to be available.
12 | You can watch the status of by running 'kubectl get svc -w {{ template "..fullname" . }}'
13 | export SERVICE_IP=$(kubectl get svc --namespace {{ .Release.Namespace }} {{ template "..fullname" . }} -o jsonpath='{.status.loadBalancer.ingress[0].ip}')
14 | echo http://$SERVICE_IP:{{ .Values.service.port }}
15 | {{- else if contains "ClusterIP" .Values.service.type }}
16 | export POD_NAME=$(kubectl get pods --namespace {{ .Release.Namespace }} -l "app={{ template "..name" . }},release={{ .Release.Name }}" -o jsonpath="{.items[0].metadata.name}")
17 | echo "Visit http://127.0.0.1:8080 to use your application"
18 | kubectl port-forward $POD_NAME 8080:80
19 | {{- end }}
20 |
--------------------------------------------------------------------------------
/testdata/templates/_helpers.tpl:
--------------------------------------------------------------------------------
1 | {{/* vim: set filetype=mustache: */}}
2 | {{/*
3 | Expand the name of the chart.
4 | */}}
5 | {{- define "..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 "..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 "..chart" -}}
31 | {{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" -}}
32 | {{- end -}}
33 |
--------------------------------------------------------------------------------
/testdata/templates/deployment.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: apps/v1beta2
2 | kind: Deployment
3 | metadata:
4 | name: {{ template "..fullname" . }}
5 | labels:
6 | app: {{ template "..name" . }}
7 | chart: {{ template "..chart" . }}
8 | release: {{ .Release.Name }}
9 | heritage: {{ .Release.Service }}
10 | spec:
11 | replicas: {{ .Values.replicaCount }}
12 | selector:
13 | matchLabels:
14 | app: {{ template "..name" . }}
15 | release: {{ .Release.Name }}
16 | template:
17 | metadata:
18 | labels:
19 | app: {{ template "..name" . }}
20 | release: {{ .Release.Name }}
21 | spec:
22 | securityContext:
23 | runAsNonRoot: true
24 | containers:
25 | - name: {{ .Chart.Name }}
26 | image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
27 | imagePullPolicy: {{ .Values.image.pullPolicy }}
28 | ports:
29 | - name: http
30 | containerPort: 80
31 | protocol: TCP
32 | livenessProbe:
33 | httpGet:
34 | path: /
35 | port: http
36 | readinessProbe:
37 | httpGet:
38 | path: /
39 | port: http
40 | resources:
41 | {{ toYaml .Values.resources | indent 12 }}
42 | {{- with .Values.nodeSelector }}
43 | nodeSelector:
44 | {{ toYaml . | indent 8 }}
45 | {{- end }}
46 | {{- with .Values.affinity }}
47 | affinity:
48 | {{ toYaml . | indent 8 }}
49 | {{- end }}
50 | {{- with .Values.tolerations }}
51 | tolerations:
52 | {{ toYaml . | indent 8 }}
53 | {{- end }}
54 |
--------------------------------------------------------------------------------
/testdata/templates/ingress.yaml:
--------------------------------------------------------------------------------
1 | {{- if .Values.ingress.enabled -}}
2 | {{- $fullName := include "..fullname" . -}}
3 | {{- $servicePort := .Values.service.port -}}
4 | {{- $ingressPath := .Values.ingress.path -}}
5 | apiVersion: extensions/v1beta1
6 | kind: Ingress
7 | metadata:
8 | name: {{ $fullName }}
9 | labels:
10 | app: {{ template "..name" . }}
11 | chart: {{ template "..chart" . }}
12 | release: {{ .Release.Name }}
13 | heritage: {{ .Release.Service }}
14 | {{- with .Values.ingress.annotations }}
15 | annotations:
16 | {{ toYaml . | indent 4 }}
17 | {{- end }}
18 | spec:
19 | {{- if .Values.ingress.tls }}
20 | tls:
21 | {{- range .Values.ingress.tls }}
22 | - hosts:
23 | {{- range .hosts }}
24 | - {{ . }}
25 | {{- end }}
26 | secretName: {{ .secretName }}
27 | {{- end }}
28 | {{- end }}
29 | rules:
30 | {{- range .Values.ingress.hosts }}
31 | - host: {{ . }}
32 | http:
33 | paths:
34 | - path: {{ $ingressPath }}
35 | backend:
36 | serviceName: {{ $fullName }}
37 | servicePort: http
38 | {{- end }}
39 | {{- end }}
40 |
--------------------------------------------------------------------------------
/testdata/templates/service.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: v1
2 | kind: Service
3 | metadata:
4 | name: {{ template "..fullname" . }}
5 | labels:
6 | app: {{ template "..name" . }}
7 | chart: {{ template "..chart" . }}
8 | release: {{ .Release.Name }}
9 | heritage: {{ .Release.Service }}
10 | spec:
11 | type: {{ .Values.service.type }}
12 | ports:
13 | - port: {{ .Values.service.port }}
14 | targetPort: http
15 | protocol: TCP
16 | name: http
17 | selector:
18 | app: {{ template "..name" . }}
19 | release: {{ .Release.Name }}
20 |
--------------------------------------------------------------------------------
/testdata/values.yaml:
--------------------------------------------------------------------------------
1 | # Default values for ..
2 | # This is a YAML-formatted file.
3 | # Declare variables to be passed into your templates.
4 |
5 | replicaCount: 1
6 |
7 | image:
8 | repository: nginx
9 | tag: stable
10 | pullPolicy: IfNotPresent
11 |
12 | service:
13 | type: ClusterIP
14 | port: 80
15 |
16 | ingress:
17 | enabled: false
18 | annotations: {}
19 | # kubernetes.io/ingress.class: nginx
20 | # kubernetes.io/tls-acme: "true"
21 | path: /
22 | hosts:
23 | - chart-example.local
24 | tls: []
25 | # - secretName: chart-example-tls
26 | # hosts:
27 | # - chart-example.local
28 |
29 | resources: {}
30 | # We usually recommend not to specify default resources and to leave this as a conscious
31 | # choice for the user. This also increases chances charts run on environments with little
32 | # resources, such as Minikube. If you do want to specify resources, uncomment the following
33 | # lines, adjust them as necessary, and remove the curly braces after 'resources:'.
34 | # limits:
35 | # cpu: 100m
36 | # memory: 128Mi
37 | # requests:
38 | # cpu: 100m
39 | # memory: 128Mi
40 |
41 | nodeSelector: {}
42 |
43 | tolerations: []
44 |
45 | affinity: {}
46 |
--------------------------------------------------------------------------------