├── .gitignore ├── .github ├── test │ ├── resources │ │ └── test.yaml │ └── policy │ │ └── always_warn.rego └── workflows │ └── pull_request.yaml ├── Dockerfile ├── action.yml ├── main_test.go ├── README.md ├── LICENSE └── main.go /.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | gcs.json 3 | *.env 4 | -------------------------------------------------------------------------------- /.github/test/resources/test.yaml: -------------------------------------------------------------------------------- 1 | name: test 2 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM instrumenta/conftest:v0.20.0 as conftest 2 | 3 | FROM golang:1.15-alpine as builder 4 | COPY --from=conftest /conftest /usr/local/bin/conftest 5 | COPY main.go . 6 | RUN go build -o /entrypoint main.go 7 | CMD [ "/entrypoint" ] 8 | -------------------------------------------------------------------------------- /.github/test/policy/always_warn.rego: -------------------------------------------------------------------------------- 1 | package always_warn 2 | 3 | warn[msg] { 4 | msg := { 5 | "msg": "a warning! you should probably fix this", 6 | "details": {"policyID": "P0000"} 7 | } 8 | 9 | true 10 | } 11 | -------------------------------------------------------------------------------- /.github/workflows/pull_request.yaml: -------------------------------------------------------------------------------- 1 | name: Pull Request 2 | on: ["pull_request"] 3 | 4 | jobs: 5 | go-tests: 6 | name: Go Tests 7 | runs-on: ubuntu-latest 8 | steps: 9 | - name: setup go 10 | uses: actions/setup-go@v2 11 | with: 12 | go-version: 1.15.x 13 | 14 | - name: checkout 15 | uses: actions/checkout@v2 16 | 17 | - name: unit test 18 | run: go test -v ./... 19 | 20 | - name: test build 21 | run: go build -o build/action-conftest 22 | 23 | test-run-action: 24 | name: Test the Action 25 | needs: go-tests 26 | runs-on: ubuntu-latest 27 | steps: 28 | - name: checkout 29 | uses: actions/checkout@v2 30 | 31 | - name: run action 32 | uses: './' 33 | with: 34 | files: '.github/test/resources' 35 | policy: '.github/test/policy/always_warn.rego' 36 | gh-token: ${{ secrets.GITHUB_TOKEN }} 37 | gh-comment-url: ${{ github.event.pull_request.comments_url }} 38 | -------------------------------------------------------------------------------- /action.yml: -------------------------------------------------------------------------------- 1 | name: "Conftest Action" 2 | description: "Easily run Conftest, pull remote policies, surface the results, and obtain test metrics" 3 | branding: 4 | icon: "check-square" 5 | color: "purple" 6 | inputs: 7 | files: 8 | description: "Files and/or folders for Conftest to test (space delimited)" 9 | required: true 10 | policy: 11 | description: "Where to find the policy folder or file" 12 | default: "policy" 13 | required: false 14 | data: 15 | description: "Files or folder with supplemental test data" 16 | required: false 17 | all-namespaces: 18 | description: "Whether to use all namespaces in testing" 19 | default: "true" 20 | required: false 21 | combine: 22 | description: "Whether to combine input files" 23 | required: false 24 | pull-url: 25 | description: "URL to pull policies from" 26 | required: false 27 | pull-secret: 28 | description: "Secret that allows the policies to be pulled" 29 | required: false 30 | add-comment: 31 | description: "Whether or not to add a comment to the PR" 32 | default: "true" 33 | required: false 34 | docs-url: 35 | description: "URL where users can find out more about the policies" 36 | required: false 37 | no-fail: 38 | description: "Always returns an exit code of 0 (no error)" 39 | required: false 40 | gh-token: 41 | description: "Token that allows us to post a comment in the PR" 42 | required: false 43 | gh-comment-url: 44 | description: "URL of the comments for the PR" 45 | required: false 46 | metrics-url: 47 | description: "URL to POST the results to for metrics" 48 | required: false 49 | metrics-source: 50 | description: "Unique identifier for the source of the submission" 51 | required: false 52 | metrics-details: 53 | description: "Whether to include the full test results in the metrics" 54 | required: false 55 | metrics-token: 56 | description: "Bearer token for submitting metrics" 57 | required: false 58 | policy-id-key: 59 | description: "Name of the key in the details object that stores the policy ID" 60 | default: "policyID" 61 | required: false 62 | runs: 63 | using: 'docker' 64 | image: 'Dockerfile' 65 | env: 66 | FILES: ${{ inputs.files }} 67 | POLICY: ${{ inputs.policy }} 68 | DATA: ${{ inputs.data }} 69 | ALL_NAMESPACES: ${{ inputs.all-namespaces }} 70 | COMBINE: ${{ inputs.combine }} 71 | PULL_URL: ${{ inputs.pull-url }} 72 | PULL_SECRET: ${{ inputs.pull-secret }} 73 | ADD_COMMENT: ${{ inputs.add-comment }} 74 | DOCS_URL: ${{ inputs.docs-url }} 75 | NO_FAIL: ${{ inputs.no-fail }} 76 | GITHUB_TOKEN: ${{ inputs.gh-token }} 77 | GITHUB_COMMENT_URL: ${{ inputs.gh-comment-url }} 78 | METRICS_URL: ${{ inputs.metrics-url }} 79 | METRICS_SOURCE: ${{ inputs.metrics-source }} 80 | METRICS_DETAILS: ${{ inputs.metrics-details }} 81 | METRICS_TOKEN: ${{ inputs.metrics-token }} 82 | POLICY_ID_KEY: ${{ inputs.policy-id-key }} 83 | -------------------------------------------------------------------------------- /main_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 Yubico AB 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package main 18 | 19 | import ( 20 | "os" 21 | "reflect" 22 | "testing" 23 | ) 24 | 25 | func TestGetFullPullURL(t *testing.T) { 26 | tests := []struct { 27 | pullURL string 28 | pullSecret string 29 | expected string 30 | }{ 31 | {"", "", ""}, 32 | {"https://www.some.com/policy", "", "https://www.some.com/policy"}, 33 | {"gcs::https://www.some.com/policy", `{"test": "test"}`, "gcs::https://www.some.com/policy"}, 34 | {"s3::https://www.some.com/policy", "aws_access_key_id=KEYID&aws_access_key_secret=SECRETKEY", "s3::https://www.some.com/policy?aws_access_key_id=KEYID&aws_access_key_secret=SECRETKEY"}, 35 | {"https://www.some.com/policy", "user:pass", "https://user:pass@www.some.com/policy"}, 36 | } 37 | 38 | for _, test := range tests { 39 | os.Setenv("PULL_URL", test.pullURL) 40 | os.Setenv("PULL_SECRET", test.pullSecret) 41 | 42 | out, err := getFullPullURL() 43 | if err != nil { 44 | t.Fatal(err) 45 | } 46 | 47 | if out != test.expected { 48 | t.Errorf("output %v did not match expected %v", out, test.expected) 49 | } 50 | } 51 | } 52 | 53 | func TestGetFlagFromEnv(t *testing.T) { 54 | tests := []struct { 55 | env string 56 | expected string 57 | }{ 58 | {"ALL_NAMESPACES", "--all-namespaces"}, 59 | {"COMBINE", "--combine"}, 60 | {"data", "--data"}, 61 | } 62 | 63 | for _, test := range tests { 64 | out := getFlagFromEnv(test.env) 65 | if out != test.expected { 66 | t.Errorf("output %v did not match expected %v", out, test.expected) 67 | } 68 | } 69 | } 70 | 71 | func TestGetFlagsFromEnv(t *testing.T) { 72 | tests := []struct { 73 | envs map[string]string 74 | expected []string 75 | }{ 76 | { 77 | envs: map[string]string{ 78 | "COMBINE": "true", 79 | }, 80 | expected: []string{"--combine"}, 81 | }, 82 | { 83 | envs: map[string]string{ 84 | "COMBINE": "true", 85 | "ALL_NAMESPACES": "false", 86 | }, 87 | expected: []string{"--combine"}, 88 | }, 89 | { 90 | envs: map[string]string{ 91 | "COMBINE": "true", 92 | "POLICY": "some/path", 93 | }, 94 | expected: []string{"--combine", "--policy", "some/path"}, 95 | }, 96 | { 97 | envs: map[string]string{ 98 | "COMBINE": "true", 99 | "IRRELEVANT": "true", 100 | "DATA": "path2", 101 | }, 102 | expected: []string{"--combine", "--data", "path2"}, 103 | }, 104 | { 105 | envs: map[string]string{ 106 | "IRRELEVANT": "true", 107 | }, 108 | expected: nil, 109 | }, 110 | { 111 | envs: nil, 112 | expected: nil, 113 | }, 114 | } 115 | 116 | for _, test := range tests { 117 | for _, v := range conftestFlags { 118 | os.Unsetenv(v) 119 | } 120 | 121 | for k, v := range test.envs { 122 | os.Setenv(k, v) 123 | } 124 | 125 | out := getFlagsFromEnv() 126 | if !reflect.DeepEqual(out, test.expected) { 127 | t.Errorf("output %v did not match expected %v", out, test.expected) 128 | } 129 | } 130 | } 131 | 132 | func TestGetPolicyIDFromMetadata(t *testing.T) { 133 | metadata := map[string]interface{}{ 134 | "details": map[string]interface{}{ 135 | "policyID": "TEST", 136 | }, 137 | } 138 | 139 | const expected = "TEST" 140 | actual, err := getPolicyIDFromMetadata(metadata, "policyID") 141 | if err != nil { 142 | t.Fatal(err) 143 | } 144 | 145 | if actual != expected { 146 | t.Errorf("output %v did not match expected %v", actual, expected) 147 | } 148 | } 149 | 150 | func TestGetPolicyIDFromMetadata_Empty(t *testing.T) { 151 | metadata := map[string]interface{}{ 152 | "details": map[string]interface{}{ 153 | "test": "TEST", 154 | }, 155 | } 156 | 157 | _, err := getPolicyIDFromMetadata(metadata, "policyID") 158 | if err == nil { 159 | t.Errorf("should error when policyIDKey does not exist") 160 | } 161 | } 162 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # action-conftest 2 | 3 | A GitHub Action for easily using [conftest](https://github.com/open-policy-agent/conftest) in your CI. It allows for pulling policies from another source and can surface the violations and warnings into the comments of the pull request. Additionally, the action can submit metrics for the results of the tests to a remote server for analysis of the rate of failures and warnings, which is useful when deploying new policies. 4 | 5 | **NOTE:** This action only supports pull secrets for S3, GCS, and HTTP remotes. If you are pulling from an OCI registry, it is assumed that you have already authenticated using `docker login` in a previous step in the GitHub Actions `job` and you should not supply a `pull-secret` argument. 6 | 7 | ## Options 8 | 9 | | Option | Description | Default | Required | 10 | |-----------------|-----------------------------------------------------------------|----------|------------------------| 11 | | files | Files and/or folders for Conftest to test (space delimited) | | yes | 12 | | policy | Where to find the policy folder or file | policy | no | 13 | | data | Files or folder with supplemental test data | | no | 14 | | all-namespaces | Whether to use all namespaces in testing | true | no | 15 | | combine | Whether to combine input files | false | no | 16 | | pull-url | URL to pull policies from | | no | 17 | | pull-secret | Secret that allows the policies to be pulled | | no | 18 | | add-comment | Whether or not to add a comment to the PR | true | no | 19 | | docs-url | Documentation URL to link to in the PR comment | | no | 20 | | no-fail | Always returns an exit code of 0 (no error) | false | no | 21 | | gh-token | Token to authorize adding the PR comment | | if add-comment is true | 22 | | gh-comment-url | URL of the comments for the PR | | if add-comment is true | 23 | | metrics-url | URL to POST the results to for metrics | | no | 24 | | metrics-source | Unique ID for the source of the metrics (usually the repo name) | | if metrics-url is set | 25 | | metrics-details | Whether to include the full test results in the metrics | false | no 26 | | metrics-token | Bearer token for submitting the metrics | | no | 27 | | policy-id-key | Name of the key in the details object that stores the policy ID | policyID | if metrics-url is set | 28 | 29 | ## Example Usage 30 | 31 | ### Using policies already in the repo 32 | 33 | This is a basic example. It assumes the policies already exist in the repository in the default `policy/` directory. 34 | 35 | ```yaml 36 | name: conftest 37 | on: [pull_request] 38 | jobs: 39 | conftest: 40 | runs-on: ubuntu-latest 41 | steps: 42 | - name: checkout 43 | uses: actions/checkout@v2 44 | - name: conftest 45 | uses: YubicoLabs/action-conftest@v2 46 | with: 47 | files: some_deployment.yaml another_resource.yaml 48 | gh-token: ${{ secrets.GITHUB_TOKEN }} 49 | gh-comment-url: ${{ github.event.pull_request.comments_url }} 50 | ``` 51 | 52 | ### Pulling policies from a Google Cloud Storage bucket 53 | 54 | This example shows pulling the policy directory from a GCS bucket. In this case, the `pull-secret` variable is the JSON key for a service account with read acccess to the bucket. 55 | 56 | ```yaml 57 | name: conftest-with-pull 58 | on: [pull_request] 59 | jobs: 60 | conftest: 61 | runs-on: ubuntu-latest 62 | steps: 63 | - name: checkout 64 | uses: actions/checkout@v2 65 | - name: conftest 66 | uses: YubicoLabs/action-conftest@v2 67 | with: 68 | files: some_deployment.yaml another_resource.yaml 69 | pull-url: gcs::https://www.googleapis.com/storage/v1/bucket_name/policy 70 | pull-secret: ${{ secrets.POLICY_PULL_SECRET }} 71 | gh-token: ${{ secrets.GITHUB_TOKEN }} 72 | gh-comment-url: ${{ github.event.pull_request.comments_url }} 73 | ``` 74 | 75 | ### Submitting metrics to a remote server 76 | 77 | ```yaml 78 | name: conftest-push-metrics 79 | on: [pull_request] 80 | jobs: 81 | conftest: 82 | runs-on: ubuntu-latest 83 | steps: 84 | - name: checkout 85 | uses: actions/checkout@v2 86 | - name: conftest 87 | uses: YubicoLabs/action-conftest@v2 88 | with: 89 | files: some_deployment.yaml another_resource.yaml 90 | gh-token: ${{ secrets.GITHUB_TOKEN }} 91 | gh-comment-url: ${{ github.event.pull_request.comments_url }} 92 | metrics-url: https://your.com/metrics/endpoints/conftest 93 | metrics-source: your-repo-name 94 | ``` 95 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 Yubico AB 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package main 18 | 19 | import ( 20 | "bytes" 21 | "encoding/json" 22 | "fmt" 23 | "io/ioutil" 24 | "net/http" 25 | "net/url" 26 | "os" 27 | "os/exec" 28 | "strings" 29 | "text/template" 30 | ) 31 | 32 | type commentData struct { 33 | Fails []string 34 | Warns []string 35 | DocsURL string 36 | } 37 | 38 | type jsonResult struct { 39 | Message string `json:"msg"` 40 | Metadata map[string]interface{} `json:"metadata,omitempty"` 41 | } 42 | 43 | type jsonCheckResult struct { 44 | Filename string `json:"filename"` 45 | Successes []jsonResult `json:"successes"` 46 | Warnings []jsonResult `json:"warnings,omitempty"` 47 | Failures []jsonResult `json:"failures,omitempty"` 48 | } 49 | 50 | type metricsSubmission struct { 51 | SourceID string `json:"sourceID"` 52 | Successes int `json:"successes,omitempty"` 53 | Warnings metricsSeverity `json:"warns,omitempty"` 54 | Failures metricsSeverity `json:"fails,omitempty"` 55 | Details []jsonCheckResult `json:"details,omitempty"` 56 | } 57 | 58 | type metricsSeverity struct { 59 | Count int `json:"count,omitempty"` 60 | PolicyIDs []string `json:"policyIDs,omitempty"` 61 | } 62 | 63 | const commentTemplate = `**Conftest has identified issues with your resources** 64 | {{ if .Fails }} 65 | The following policy violations were identified. These are blocking and must be remediated before proceeding. 66 | 67 | {{ range .Fails }}* {{ . }} 68 | {{ end }}{{ end }}{{ if .Warns }} 69 | The following warnings were identified. These are issues that indicate the resources are not following best practices. 70 | 71 | {{ range .Warns }}* {{ . }} 72 | {{ end }}{{ end }} 73 | {{ if .DocsURL }}For more information, see the [policy documentation]({{ .DocsURL }}). 74 | {{end}}` 75 | 76 | var conftestFlags = []string{"COMBINE", "POLICY", "ALL_NAMESPACES", "DATA"} 77 | 78 | func main() { 79 | err := run() 80 | if err != nil { 81 | fmt.Println(err) 82 | os.Exit(1) 83 | } 84 | } 85 | 86 | func run() error { 87 | if os.Getenv("FILES") == "" { 88 | return fmt.Errorf("at least one file to test must be supplied") 89 | } 90 | 91 | pullURL, err := getFullPullURL() 92 | if err != nil { 93 | return fmt.Errorf("get full pull url: %w", err) 94 | } 95 | 96 | if pullURL != "" { 97 | if err := runConftestPull(pullURL); err != nil { 98 | return fmt.Errorf("runnning conftest pull: %w", err) 99 | } 100 | } 101 | 102 | results, err := runConftestTest() 103 | if err != nil { 104 | return fmt.Errorf("running conftest: %w", err) 105 | } 106 | 107 | metricsURL := os.Getenv("METRICS_URL") 108 | policyIDKey := os.Getenv("POLICY_ID_KEY") 109 | 110 | var policiesWithFails, policiesWithWarns []string 111 | var fails, warns []string 112 | var successes int 113 | for _, result := range results { 114 | successes += len(result.Successes) 115 | 116 | for _, fail := range result.Failures { 117 | // attempt to parse the policy ID section, skip if there are errors 118 | policyID, err := getPolicyIDFromMetadata(fail.Metadata, policyIDKey) 119 | if err != nil { 120 | fails = append(fails, fmt.Sprintf("%s - %s", result.Filename, fail.Message)) 121 | continue 122 | } 123 | 124 | fails = append(fails, fmt.Sprintf("%s - %s: %s", result.Filename, policyID, fail.Message)) 125 | 126 | if !contains(policiesWithFails, policyID) { 127 | policiesWithFails = append(policiesWithFails, policyID) 128 | } 129 | } 130 | 131 | for _, warn := range result.Warnings { 132 | // attempt to parse the policy ID section, skip if there are errors 133 | policyID, err := getPolicyIDFromMetadata(warn.Metadata, policyIDKey) 134 | if err != nil { 135 | warns = append(warns, fmt.Sprintf("%s - %s", result.Filename, warn.Message)) 136 | continue 137 | } 138 | 139 | warns = append(warns, fmt.Sprintf("%s - %s: %s", result.Filename, policyID, warn.Message)) 140 | 141 | if !contains(policiesWithWarns, policyID) { 142 | policiesWithWarns = append(policiesWithWarns, policyID) 143 | } 144 | } 145 | } 146 | 147 | // attempt to submit metrics, but do not fail the CI job if there are errors 148 | if metricsURL != "" { 149 | sourceID := os.Getenv("METRICS_SOURCE") 150 | if sourceID == "" { 151 | return fmt.Errorf("metrics-source must be specified if metrics-url is set") 152 | } 153 | 154 | metrics := metricsSubmission{ 155 | SourceID: sourceID, 156 | Successes: successes, 157 | Failures: metricsSeverity{ 158 | Count: len(fails), 159 | PolicyIDs: policiesWithFails, 160 | }, 161 | Warnings: metricsSeverity{ 162 | Count: len(warns), 163 | PolicyIDs: policiesWithWarns, 164 | }, 165 | } 166 | if strings.ToLower(os.Getenv("METRICS_DETAILS")) == "true" { 167 | metrics.Details = results 168 | } 169 | metricsJSON, err := json.Marshal(metrics) 170 | if err != nil { 171 | return fmt.Errorf("marshal metrics json: %w", err) 172 | } 173 | 174 | var metricsToken string 175 | if os.Getenv("METRICS_TOKEN") != "" { 176 | metricsToken = fmt.Sprintf("Bearer %s", os.Getenv("METRICS_TOKEN")) 177 | } 178 | 179 | submitPost(metricsURL, metricsJSON, metricsToken) 180 | } 181 | 182 | if len(fails) == 0 && len(warns) == 0 { 183 | fmt.Println("No policy violations or warnings were identified.") 184 | return nil 185 | } 186 | 187 | d := commentData{Fails: fails, Warns: warns} 188 | if os.Getenv("DOCS_URL") != "" { 189 | d.DocsURL = os.Getenv("DOCS_URL") 190 | } 191 | 192 | t, err := renderTemplate(d) 193 | if err != nil { 194 | return fmt.Errorf("rendering template: %w", err) 195 | } 196 | 197 | // ensure the results are written to the CI logs 198 | fmt.Println(string(t)) 199 | 200 | if os.Getenv("ADD_COMMENT") != "true" { 201 | return nil 202 | } 203 | 204 | ghComment, err := getCommentJSON(t) 205 | if err != nil { 206 | return fmt.Errorf("get comment json: %w", err) 207 | } 208 | 209 | ghToken := fmt.Sprintf("token %s", os.Getenv("GITHUB_TOKEN")) 210 | if err := submitPost(os.Getenv("GITHUB_COMMENT_URL"), ghComment, ghToken); err != nil { 211 | return fmt.Errorf("submitting comment: %w", err) 212 | } 213 | 214 | if len(fails) > 0 { 215 | if strings.ToLower(os.Getenv("NO_FAIL")) != "true" { 216 | return fmt.Errorf("%d policy violations were found", len(fails)) 217 | } 218 | } 219 | 220 | return nil 221 | } 222 | 223 | func getFullPullURL() (string, error) { 224 | pullURL := os.Getenv("PULL_URL") 225 | if pullURL == "" { 226 | return "", nil 227 | } 228 | 229 | pullURLSplit := strings.Split(pullURL, "/") 230 | if len(pullURLSplit) == 1 { 231 | return "", fmt.Errorf("invalid url: %s", pullURL) 232 | } 233 | 234 | pullSecret := os.Getenv("PULL_SECRET") 235 | if pullSecret == "" { 236 | return pullURL, nil 237 | } 238 | 239 | pullURI := pullURLSplit[0] 240 | switch pullURI { 241 | case "gcs::https:": 242 | if err := ioutil.WriteFile("gcs.json", []byte(pullSecret), os.ModePerm); err != nil { 243 | return "", fmt.Errorf("writing gcs creds: %w", err) 244 | } 245 | os.Setenv("GOOGLE_APPLICATION_CREDENTIALS", "gcs.json") 246 | 247 | case "s3::https:": 248 | pullURL = pullURL + "?" + pullSecret 249 | 250 | case "https:": 251 | u, err := url.Parse(pullURL) 252 | if err != nil { 253 | return "", fmt.Errorf("parsing url: %w", err) 254 | } 255 | pullURL = "https://" + pullSecret + "@" + u.Host + u.Path 256 | 257 | default: 258 | return "", fmt.Errorf("PULL_SECRET not supported with uri: %s", pullURI) 259 | } 260 | 261 | return pullURL, nil 262 | } 263 | 264 | func runConftestPull(url string) error { 265 | cmd := exec.Command("conftest", "pull", url) 266 | var out bytes.Buffer 267 | cmd.Stderr = &out 268 | if err := cmd.Run(); err != nil { 269 | return fmt.Errorf("%s", out.String()) 270 | } 271 | 272 | return nil 273 | } 274 | 275 | func runConftestTest() ([]jsonCheckResult, error) { 276 | args := []string{"test", "--no-color", "--output", "json"} 277 | flags := getFlagsFromEnv() 278 | args = append(args, flags...) 279 | files := strings.Split(os.Getenv("FILES"), " ") 280 | args = append(args, files...) 281 | 282 | cmd := exec.Command("conftest", args...) 283 | out, _ := cmd.CombinedOutput() // intentionally ignore errors so we can parse the results 284 | 285 | var results []jsonCheckResult 286 | if err := json.Unmarshal(out, &results); err != nil { 287 | return nil, fmt.Errorf("%s", string(out)) 288 | } 289 | 290 | return results, nil 291 | } 292 | 293 | func getPolicyIDFromMetadata(metadata map[string]interface{}, policyIDKey string) (string, error) { 294 | details := metadata["details"].(map[string]interface{}) 295 | if details[policyIDKey] == nil { 296 | return "", fmt.Errorf("empty policyID key") 297 | } 298 | 299 | return fmt.Sprintf("%v", details[policyIDKey]), nil 300 | } 301 | 302 | func getFlagsFromEnv() []string { 303 | var args []string 304 | for _, v := range conftestFlags { 305 | env := os.Getenv(v) 306 | if env == "" || strings.ToLower(env) == "false" { 307 | continue 308 | } 309 | 310 | flag := getFlagFromEnv(v) 311 | if strings.ToLower(env) == "true" { 312 | args = append(args, flag) 313 | } else { 314 | args = append(args, flag, env) 315 | } 316 | } 317 | 318 | return args 319 | } 320 | 321 | func renderTemplate(d commentData) ([]byte, error) { 322 | t, err := template.New("conftest").Parse(commentTemplate) 323 | if err != nil { 324 | return nil, fmt.Errorf("parsing template: %w", err) 325 | } 326 | 327 | var o bytes.Buffer 328 | if err := t.Execute(&o, d); err != nil { 329 | return nil, fmt.Errorf("executing template: %w", err) 330 | } 331 | 332 | return o.Bytes(), nil 333 | } 334 | 335 | func getCommentJSON(comment []byte) ([]byte, error) { 336 | j, err := json.Marshal(map[string]string{"body": string(comment)}) 337 | if err != nil { 338 | return nil, fmt.Errorf("marshalling comment: %w", err) 339 | } 340 | 341 | return j, nil 342 | } 343 | 344 | func submitPost(url string, data []byte, authz string) error { 345 | req, err := http.NewRequest("POST", url, bytes.NewReader(data)) 346 | if err != nil { 347 | return fmt.Errorf("creating http request: %w", err) 348 | } 349 | 350 | req.Header.Add("Content-Type", "application/json") 351 | if authz != "" { 352 | req.Header.Add("Authorization", authz) 353 | } 354 | 355 | c := http.Client{} 356 | resp, err := c.Do(req) 357 | if err != nil { 358 | return fmt.Errorf("submitting http request: %w", err) 359 | } 360 | defer resp.Body.Close() 361 | 362 | if resp.StatusCode < 200 || resp.StatusCode > 299 { 363 | msg, err := ioutil.ReadAll(resp.Body) 364 | if err != nil { 365 | msg = []byte(fmt.Sprintf("unable to read response body: %s", err)) 366 | } 367 | 368 | return fmt.Errorf("remote server error: status %d: %s", resp.StatusCode, string(msg)) 369 | } 370 | 371 | return nil 372 | } 373 | 374 | func getFlagFromEnv(e string) string { 375 | return fmt.Sprintf("--%s", strings.ToLower(strings.ReplaceAll(e, "_", "-"))) 376 | } 377 | 378 | func contains(list []string, item string) bool { 379 | for _, l := range list { 380 | if l == item { 381 | return true 382 | } 383 | } 384 | 385 | return false 386 | } 387 | --------------------------------------------------------------------------------