├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── index.js ├── package-lock.json ├── package.json └── test ├── fixtures.json └── test.js /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.gitignore.io/api/osx,node,code 3 | 4 | ### Code ### 5 | # Visual Studio Code - https://code.visualstudio.com/ 6 | .settings/ 7 | .vscode/ 8 | tsconfig.json 9 | jsconfig.json 10 | 11 | ### Node ### 12 | # Logs 13 | logs 14 | *.log 15 | npm-debug.log* 16 | yarn-debug.log* 17 | yarn-error.log* 18 | 19 | # Runtime data 20 | pids 21 | *.pid 22 | *.seed 23 | *.pid.lock 24 | 25 | # Directory for instrumented libs generated by jscoverage/JSCover 26 | lib-cov 27 | 28 | # Coverage directory used by tools like istanbul 29 | coverage 30 | 31 | # nyc test coverage 32 | .nyc_output 33 | 34 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 35 | .grunt 36 | 37 | # Bower dependency directory (https://bower.io/) 38 | bower_components 39 | 40 | # node-waf configuration 41 | .lock-wscript 42 | 43 | # Compiled binary addons (http://nodejs.org/api/addons.html) 44 | build/Release 45 | 46 | # Dependency directories 47 | node_modules/ 48 | jspm_packages/ 49 | 50 | # Typescript v1 declaration files 51 | typings/ 52 | 53 | # Optional npm cache directory 54 | .npm 55 | 56 | # Optional eslint cache 57 | .eslintcache 58 | 59 | # Optional REPL history 60 | .node_repl_history 61 | 62 | # Output of 'npm pack' 63 | *.tgz 64 | 65 | # Yarn Integrity file 66 | .yarn-integrity 67 | 68 | # dotenv environment variables file 69 | .env 70 | 71 | 72 | ### OSX ### 73 | *.DS_Store 74 | .AppleDouble 75 | .LSOverride 76 | 77 | # Icon must end with two \r 78 | Icon 79 | 80 | # Thumbnails 81 | ._* 82 | 83 | # Files that might appear in the root of a volume 84 | .DocumentRevisions-V100 85 | .fseventsd 86 | .Spotlight-V100 87 | .TemporaryItems 88 | .Trashes 89 | .VolumeIcon.icns 90 | .com.apple.timemachine.donotpresent 91 | 92 | # Directories potentially created on remote AFP share 93 | .AppleDB 94 | .AppleDesktop 95 | Network Trash Folder 96 | Temporary Items 97 | .apdisk 98 | 99 | 100 | # End of https://www.gitignore.io/api/osx,node,code -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:8.4.0-alpine 2 | 3 | # Create a directory where our app will be placed 4 | RUN mkdir -p /usr/src/app 5 | 6 | # Change directory so that our commands run inside this new directory 7 | WORKDIR /usr/src/app 8 | 9 | # Copy dependency definitions 10 | COPY package.json *.js /usr/src/app/ 11 | 12 | # Install dependecies 13 | RUN npm install --production 14 | 15 | # Expose the port the app runs in 16 | EXPOSE 9207 17 | 18 | # Serve the app 19 | CMD ["node", "index.js"] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # prometheus_inspec_exporter 2 | 3 | ## Hello Monitorama! 4 | 5 | [Join the "Security Through Observability" Google Group](https://groups.google.com/forum/#!forum/securitythroughobservability) to get updates about this project. 6 | 7 | For code/config snippets used in my demo, see this repo: https://github.com/geekdave/monitorama 8 | 9 | ## What is this? 10 | 11 | A Prometheus integration with the [InSpec](https://www.inspec.io/) "Compliance as Code" tool. 12 | 13 | ## What does it do? 14 | 15 | Converts InSpec json reports into Prometheus metrics, so you can monitor your compliance checks using Prometheus and fire alerts if anything falls out of compliance. 16 | 17 | ## How does it do that? 18 | 19 | 1. Assumes you have InSpec checks running periodicially as a cron job and outputting to a well-known directory such as `/usr/local/etc/inspec-results` 20 | 1. Exposes a `/metrics` endpoint 21 | 1. When the metrics endpoint is scraped, checks the pre-configured directory for `*.json` files 22 | 1. Parses the json file to determine the name of the inspec profile, the number of passes, failures, and skips, and exposes this data as Prometheus metrics like so: 23 | 24 | ``` 25 | # HELP inspec_checks_total Number of inspec checks 26 | # TYPE inspec_checks_total gauge 27 | inspec_checks_total{profile="ssl-baseline",status="passed"} 6 28 | inspec_checks_total{profile="ssl-baseline",status="failed"} 0 29 | inspec_checks_total{profile="ssl-baseline",status="skipped"} 0 30 | ``` 31 | 32 | ## Project status 33 | 34 | This project is currently in the early stages and may be rough around the edges. It may contain bugs. Please try it out and let us know how we can improve it! PRs are welcome! 35 | 36 | ## Usage 37 | 38 | ### Install InSpec 39 | 40 | See: https://www.inspec.io/downloads/ 41 | 42 | ### Set up Cron Job 43 | 44 | Run `sudo crontab -e` to set up a recurring job like this: 45 | 46 | ``` 47 | 0 * * * * /usr/local/bin/run_inspec.sh 48 | ``` 49 | 50 | Probably hourly is a good place to start, but your needs may vary. Some InSpec suites may take a couple minutes to run, so it's not recommended to run it more frequently than the duration of the suites. Otherwise you might run into errors with overlapping checks overwriting each other. 51 | 52 | ### Create InSpec runner 53 | 54 | Create a `run_inspec.sh` script like this: 55 | 56 | ``` 57 | #!/usr/bin/env bash 58 | 59 | # Run InSpec results and output to temp file 60 | inspec exec https://github.com/geekdave/monitorama --reporter json | jq '.' > /tmp/monitorama.json 61 | 62 | # Atomically move the temp file to the expected location to avoid reading partially-written results 63 | mv /tmp/monitorama.json /usr/local/etc/inspec-results/monitorama.json 64 | ``` 65 | 66 | ### Launch Container 67 | 68 | ``` 69 | sudo docker run \ 70 | -d \ 71 | --rm \ 72 | --name prometheus_inspec_exporter \ 73 | -v /usr/local/etc/inspec-results:/usr/local/etc/inspec-results \ 74 | -v /usr/local/etc/inspec-reports:/usr/local/etc/inspec-reports \ 75 | -p 9207:9207 \ 76 | geekdave/prometheus_inspec_exporter 77 | ``` 78 | 79 | * Change `/usr/local/etc/inspec-results:/usr/local/etc/inspec-results` to reflect `/path/to/your/inspec-results:/usr/local/etc/inspec-results` from your InSpec runner script (above) 80 | * Change `/usr/local/etc/inspec-reports:/usr/local/etc/inspec-reports` to reflect `/path/to/your/inspec-reports:/usr/local/etc/inspec-reports` - Any directory you want this exporter to save your HTML reports into. 81 | * Change `-p 9207:9207` to reflect `-p $PORT_YOU_WANT_TO_EXPOSE:9207` 82 | 83 | ### Prometheus Scraping 84 | 85 | Sample Prometheus config snippet 86 | 87 | ``` 88 | - job_name: 'inspec' 89 | scrape_interval: 1m 90 | scrape_timeout: 1m 91 | static_configs: 92 | - targets: 93 | - 'myhost1.example.com:9207' 94 | - 'myhost2.example.com:9207' 95 | - 'myhost3.example.com:9207' 96 | ``` 97 | 98 | See the Prometheus docs for setting up automatic service discovery instead of maintaining a list of static hosts. 99 | 100 | ## Alerting 101 | 102 | You can then write Prometheus alerts like this: 103 | 104 | ``` 105 | - alert: ComplianceFailure 106 | expr: inspec_checks_total{status="failed"} > 0 107 | labels: 108 | severity: slack 109 | annotations: 110 | identifier: "{{ $labels.profile }} : {{ $labels.instance }}" 111 | description: "{{ $labels.instance }} has {{ $value }} compliance failures on the {{ $labels.profile }} profile. 112 | ``` 113 | 114 | ## Alerting with Report Integration 115 | 116 | This exporter saves HTML versions of the full InSpec reports to `/usr/local/etc/inspec-reports` using a custom markdown/HTML format that preserves much more metadata than the out-of-the-box InSpec reports. 117 | 118 | HTML reports will be saved to `/usr/local/etc/inspec-reports` (map it using docker path mapping as defined above). 119 | 120 | You can write a script to periodically upload these files to S3 to make them available as click-throughs from your Prometheus alerts as shown below. 121 | 122 | TODO: Create automatic support for uploading to S3. 123 | 124 | ``` 125 | - alert: ComplianceFailure 126 | expr: inspec_checks_total{status="failed"} > 0 127 | labels: 128 | severity: slack 129 | annotations: 130 | identifier: "{{ $labels.profile }} : {{ $labels.instance }}" 131 | description: "{{ $labels.instance }} has {{ $value }} compliance failures on the {{ $labels.profile }} profile. Report and remediation steps: http://glueops-inspec-bucket-results.s3-website-us-east-1.amazonaws.com/{{ $labels.profile }}/{{ $labels.instance }}" 132 | ``` 133 | 134 | ## Checking Cron 135 | 136 | To make sure that your cron job is running as expected, and correctly refreshing the reports, this exporter also exposes a metric for the last modified time of the json file: 137 | 138 | ``` 139 | # HELP inspec_checks_mtime Last modified time of inspec checks 140 | # TYPE inspec_checks_mtime gauge 141 | inspec_checks_mtime{profile="ssl-baseline"} 1528206609632.9578 142 | ``` 143 | 144 | You can consume it like this: 145 | 146 | ``` 147 | time() - inspec_checks_mtime{instance=~"$instance"} / 1000 148 | ``` 149 | 150 | This will compare the current time with the last modified time, and you could write an alert like: 151 | 152 | ``` 153 | alert: StaleInSpecResults 154 | expr: time() - inspec_checks_mtime{instance=~"$instance"} / 1000 > 7200 155 | labels: 156 | severity: slack 157 | annotations: 158 | description: '{{ $labels.instance }} has stale InSpec metrics.' 159 | summary: Instance {{ $labels.instance }} expected to have InSpec results refreshed every hour, but it has been over 2 hours. Please check that the cron job is running as expected. 160 | ``` 161 | 162 | ## Building a docker container 163 | 164 | ``` 165 | docker build . -t org/containername:tag 166 | ``` 167 | 168 | i.e. 169 | 170 | ``` 171 | docker build . -t geekdave/prometheus_inspec_exporter:latest 172 | ``` 173 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | const _ = require('lodash'); 2 | const express = require('express'); 3 | const prometheusClient = require('prom-client'); 4 | const { spawn } = require('child_process'); 5 | const fs = require('fs'); 6 | const marked = require('marked'); 7 | 8 | var AsyncLock = require('async-lock'); 9 | var lock = new AsyncLock(); 10 | 11 | // const nock = require('nock'); 12 | // nock.recorder.rec(); 13 | 14 | const metricsServer = express(); 15 | 16 | const DEBUG = process.env['INSPEC_EXPORTER_DEBUG'] || false; 17 | 18 | // const collectDefaultMetrics = prometheusClient.collectDefaultMetrics; 19 | // collectDefaultMetrics(); 20 | 21 | const up = new prometheusClient.Gauge({name: 'up', help: 'UP Status'}); 22 | 23 | const controls = new prometheusClient.Gauge({ 24 | name: 'inspec_checks_total', 25 | help: 'Number of inspec checks', 26 | labelNames: ['profile', 'status'] 27 | }); 28 | 29 | const lastModified = new prometheusClient.Gauge({ 30 | name: 'inspec_checks_mtime', 31 | help: 'Last modified time of inspec checks', 32 | labelNames: ['profile'] 33 | }); 34 | 35 | if (require.main === module) { 36 | const options = {}; 37 | 38 | options.INSPEC_API_TOKEN = process.env.INSPEC_API_TOKEN; 39 | options.ORG_NAME = process.env.INSPEC_ORG_NAME; 40 | options.BASE_URL = process.env.INSPEC_API_BASE_URL; 41 | 42 | init(options); 43 | startServer(); 44 | } 45 | 46 | function init (options) { 47 | 48 | } 49 | 50 | function startServer () { 51 | metricsServer.get('/metrics', async (req, res) => { 52 | res.contentType(prometheusClient.register.contentType); 53 | 54 | try { 55 | resetStats(); 56 | var id = Math.random().toString(36).substring(7); 57 | console.log("starting with id " + id); 58 | var startTime = new Date(); 59 | const response = runInSpec(); 60 | 61 | var endTime = new Date(); 62 | var timeDiff = endTime - startTime; //in ms 63 | // strip the ms 64 | timeDiff /= 1000; 65 | 66 | // get seconds 67 | var seconds = Math.round(timeDiff); 68 | console.log("finished with id " + id + " in " + seconds + " seconds"); 69 | 70 | res.send(prometheusClient.register.metrics()); 71 | } catch (error) { 72 | // error connecting 73 | up.set(0); 74 | res.header('X-Error', error.message || error); 75 | res.send(prometheusClient.register.getSingleMetricAsString(up.name)); 76 | } 77 | }); 78 | 79 | console.log('Server listening to 9207, metrics exposed on /metrics endpoint'); 80 | metricsServer.listen(9207); 81 | } 82 | 83 | function shutdown () { 84 | metricsServer.close(); 85 | } 86 | 87 | function resetStats () { 88 | up.set(1); 89 | controls.reset(); 90 | lastModified.reset(); 91 | } 92 | 93 | function runInSpec () { 94 | //inspec supermarket exec dev-sec/cis-docker-benchmark --reporter json | jq 95 | 96 | var dirName = '/usr/local/etc/inspec-results'; 97 | var reportDirName = '/usr/local/etc/inspec-reports'; 98 | 99 | var files = fs.readdirSync(dirName); 100 | 101 | _.each(files, (file) => { 102 | var fullFilePath = dirName + "/" + file; 103 | var contents = fs.readFileSync(fullFilePath, 'utf8'); 104 | var mtime = fs.statSync(fullFilePath).mtimeMs; 105 | 106 | var currentTime = new Date(); 107 | var age = currentTime - mtime; 108 | 109 | var response = JSON.parse(contents); 110 | 111 | if (!response) { 112 | throw new Error('error retrieving response from inspec process'); 113 | } 114 | 115 | if (!response.profiles) { 116 | throw new Error('profiles not found in inspec result'); 117 | } 118 | 119 | _.each(response.profiles, (profile) => { 120 | 121 | var rendered = ""; 122 | 123 | var tocPassed = ""; 124 | var tocFailed = ""; 125 | var tocSkipped = ""; 126 | 127 | var summary = "# Summary\n\n"; 128 | 129 | var intro = ""; 130 | 131 | const profileName = profile.name; 132 | 133 | intro += `# ${profileName}\n\n`; 134 | 135 | var numPassed = 0; 136 | var numFailed = 0; 137 | var numSkipped = 0; 138 | 139 | _.each(profile.controls, (control) => { 140 | var controlId = control.id; 141 | var controlTitle = control.title; 142 | 143 | var passed = true; 144 | var skipped = false; 145 | 146 | if (!control.results || control.results.length === 0) { 147 | return; 148 | } 149 | 150 | var anchorTitle = `${controlId}: ${controlTitle}`; 151 | var anchorId = anchorTitle.replace(/[^a-zA-Z0-9_]+/g, "-"); 152 | anchorId = anchorId.toLowerCase(); 153 | const toc = `* [${anchorTitle}](#${anchorId})\n`; 154 | rendered += `\n## ${anchorTitle}\n\n`; 155 | var results = "### Results\n"; 156 | 157 | _.each(control.results, (result) => { 158 | 159 | results += `1. ${result.status}\n\n`; 160 | if (result.code_desc) { 161 | results += " * Description:\n\n" 162 | results += " ```\n"; 163 | const desc = ' ' + result.code_desc.replace(/\n/g, "\n "); 164 | results += `${desc}\n`; 165 | results += " ```\n"; 166 | } 167 | 168 | if (result.message) { 169 | results += " * Message:\n\n" 170 | results += " ```\n"; 171 | const msg = ' ' + result.message.replace(/\n/g, "\n ") 172 | results += `${msg}\n`; 173 | results += " ```\n"; 174 | } 175 | 176 | var status = result.status; 177 | if (status === "failed") { 178 | passed = false; 179 | } else if (status === "skipped") { 180 | skipped = true; 181 | } 182 | }); 183 | 184 | rendered += "### Status: "; 185 | if (!passed) { 186 | tocFailed += toc; 187 | rendered += "**Failed**"; 188 | numFailed++; 189 | } else { 190 | if (skipped) { 191 | tocSkipped += toc; 192 | rendered += "Skipped"; 193 | numSkipped++; 194 | } else { 195 | tocPassed += toc; 196 | rendered += "Passed"; 197 | numPassed++; 198 | } 199 | } 200 | 201 | rendered += `\n\n${results}\n\n`; 202 | 203 | if (control.desc) { 204 | rendered += `### Description:\n\n${control.desc}\n\n`; 205 | } 206 | 207 | if (control.refs && control.refs.length > 0) { 208 | rendered += `### References:\n\n`; 209 | 210 | _.each(control.refs, (ref) => { 211 | rendered += `1. [${ref.ref}](${ref.url})\n`; 212 | }); 213 | } 214 | 215 | rendered += "\n---\n[\[Back to Top\]](#summary)n\n" 216 | }); 217 | 218 | summary += `## Failed: ${numFailed}\n`; 219 | 220 | if (numFailed) { 221 | summary += tocFailed + "\n"; 222 | } 223 | 224 | summary += `## Passed: ${numPassed}\n`; 225 | 226 | if (numPassed) { 227 | summary += tocPassed + "\n"; 228 | } 229 | 230 | summary += `## Skipped: ${numSkipped}\n`; 231 | 232 | if (numSkipped) { 233 | summary += tocSkipped + "\n"; 234 | } 235 | 236 | intro += `Failed: ${numFailed} • Passed: ${numPassed} • Skipped: ${numSkipped}\n\n`; 237 | 238 | controls.set({ 239 | profile: profileName, 240 | status: "passed" 241 | }, numPassed); 242 | 243 | controls.set({ 244 | profile: profileName, 245 | status: "failed" 246 | }, numFailed); 247 | 248 | controls.set({ 249 | profile: profileName, 250 | status: "skipped" 251 | }, numSkipped); 252 | 253 | lastModified.set({ 254 | profile: profileName 255 | }, mtime); 256 | 257 | var markedUp = marked(rendered); 258 | var summaryMarkedUp = marked(summary); 259 | var introMarkedUp = marked(intro); 260 | 261 | var header = '' 262 | + '
\n' 263 | + ' \n' 264 | + ' \n' 279 | + '
\n' 280 | + '\n' 281 | + '
\n'; 282 | 283 | var footer = '
\n\n';; 284 | 285 | var final = header + introMarkedUp + summaryMarkedUp + markedUp + footer; 286 | 287 | fs.writeFile(reportDirName + '/inspec-' + file + '.html', final, (err) => { 288 | // throws an error, you could also catch it here 289 | if (err) throw err; 290 | 291 | // success case, the file was saved 292 | console.log('HTML saved!'); 293 | }); 294 | }); 295 | 296 | 297 | 298 | 299 | }); 300 | 301 | } 302 | 303 | 304 | module.exports = { 305 | init: init, 306 | shutdown: shutdown 307 | }; 308 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "prometheus_inspec_exporter", 3 | "engines": { 4 | "node": ">=7.6" 5 | }, 6 | "version": "0.0.2", 7 | "description": "Prometheus exporter for inspec data", 8 | "main": "index.js", 9 | "scripts": { 10 | "test": "nyc mocha", 11 | "coverage": "nyc report --reporter=text-lcov | coveralls", 12 | "format": "standard --fix", 13 | "build": "docker build . -t geekdave/prometheus_inspec_exporter" 14 | }, 15 | "author": "", 16 | "license": "Apache-2.0", 17 | "dependencies": { 18 | "async-lock": "^1.1.2", 19 | "axios": "^0.17.1", 20 | "express": "^4.16.2", 21 | "hyperdom": "^0.11.0", 22 | "jsdom": "^11.11.0", 23 | "lodash": "^4.17.4", 24 | "luxon": "^0.2.11", 25 | "marked": "^0.4.0", 26 | "prom-client": "^10.2.2", 27 | "renderjson": "^1.3.1" 28 | }, 29 | "devDependencies": { 30 | "chai": "^4.1.2", 31 | "coveralls": "^3.0.0", 32 | "mocha": "^5.0.0", 33 | "nock": "^9.1.6", 34 | "nyc": "^11.4.1", 35 | "semistandard": "^12.0.0" 36 | }, 37 | "semistandard": { 38 | "globals": [ 39 | "describe", 40 | "expect", 41 | "it", 42 | "beforeAll", 43 | "afterAll", 44 | "beforeEach", 45 | "afterEach" 46 | ] 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /test/fixtures.json: -------------------------------------------------------------------------------- 1 | { 2 | "org": { 3 | "name": "springfield", 4 | "id": "1234567a-123b-456c-def7-890abcdefg01" 5 | }, 6 | "projects": [{ 7 | "name": "burns", 8 | "id": "2234567a-123b-456c-def7-890abcdefg01" 9 | }, { 10 | "name": "smithers", 11 | "id": "3234567a-123b-456c-def7-890abcdefg01" 12 | }, { 13 | "name": "frink", 14 | "id": "4234567a-123b-456c-def7-890abcdefg01" 15 | }] 16 | } -------------------------------------------------------------------------------- /test/test.js: -------------------------------------------------------------------------------- 1 | const nock = require('nock'); 2 | const fixture = require('./fixtures.json'); 3 | var chai = require('chai'); 4 | var expect = chai.expect; 5 | 6 | var app = require('../index'); 7 | 8 | describe('getProjects', () => { 9 | beforeEach(() => { 10 | app.init({ 11 | SNYK_API_TOKEN: 'abc-123', 12 | ORG_NAME: 'springfield' 13 | }); 14 | }); 15 | 16 | beforeEach(() => { 17 | nock( 18 | 'https://snyk.io:443') 19 | .get('/api/v1/org/springfield/projects') 20 | .reply(200, fixture); 21 | }); 22 | 23 | it('should get the org information', async () => { 24 | const response = await app.getProjects('springfield'); 25 | expect(response.data.org.name).to.equal('springfield'); 26 | expect(response.data.org.id).to.equal('1234567a-123b-456c-def7-890abcdefg01'); 27 | }); 28 | 29 | it('should get the project information', async () => { 30 | const response = await app.getProjects('springfield'); 31 | expect(response.data.projects.length).to.equal(3); 32 | 33 | expect(response.data.projects[0].name).to.equal('burns'); 34 | expect(response.data.projects[0].id).to.equal('2234567a-123b-456c-def7-890abcdefg01'); 35 | 36 | expect(response.data.projects[1].name).to.equal('smithers'); 37 | expect(response.data.projects[1].id).to.equal('3234567a-123b-456c-def7-890abcdefg01'); 38 | 39 | expect(response.data.projects[2].name).to.equal('frink'); 40 | expect(response.data.projects[2].id).to.equal('4234567a-123b-456c-def7-890abcdefg01'); 41 | }); 42 | }); 43 | --------------------------------------------------------------------------------