Compare commits

..
114 Commits
Author SHA1 Message Date
Timur Girgin 6b72508e0b chore(deps): add @axe-core/react 2021-11-03 18:13:47 -04:00
Timur Girgin 5c5d3d4e5d refactor: navigation bars 2021-11-03 18:12:03 -04:00
Timur Girgin 52df126b93 chore(deps): add prettier 2021-11-03 16:42:50 -04:00
Taryn Martin 6ae13d8603 Fix layout for nav bars 2021-11-03 14:03:31 -06:00
Taryn Martin 6aff3c8ee0 Add top nav bar and basic navigation 2021-11-03 12:31:47 -06:00
Taryn Martin 714add15e2 Create left nav bar 2021-11-03 10:45:48 -06:00
Timur Girgin 05da87eadf chore: use sass instead of css 2021-11-03 11:30:01 -04:00
Timur Girgin 908a3a9c72 chore(deps): add sass 2021-11-03 11:29:41 -04:00
Timur Girgin 3e8a3c92e6 chore(style): import bootstrap styles 2021-11-03 10:52:27 -04:00
Timur Girgin bddfece857 chore: init react/typescript ui with bootstrap 2021-11-03 10:26:25 -04:00
Janki Chhatbar 268f0e6811 Correct URL to download polaris tar (#660) 2021-11-03 06:32:29 -06:00
Terraform User e31f3f1b41 Managed by Terraform 2021-10-26 12:21:30 -06:00
Timur Girgin 5acdc4a4b9 fix: add space before "in namespace" output (#650) 2021-10-15 15:48:58 -04:00
Luke Reed 0f1d4cd952 fix configuration syntax for goreleaser (#644) 2021-09-28 12:36:50 -07:00
Luke Reed c398f1043c prep for 4.2.0 release and helm chart update (#643) 2021-09-28 11:31:34 -07:00
Luke Reed 091fa77d11 update goreleaser and make sure to build darwin arm build for homebrew (#642) 2021-09-28 06:22:38 -07:00
dependabot[bot]andlnx01 1b97f31edb Bump sigs.k8s.io/controller-runtime from 0.10.0 to 0.10.1 (#640)
Bumps [sigs.k8s.io/controller-runtime](https://github.com/kubernetes-sigs/controller-runtime) from 0.10.0 to 0.10.1.
- [Release notes](https://github.com/kubernetes-sigs/controller-runtime/releases)
- [Commits](https://github.com/kubernetes-sigs/controller-runtime/compare/v0.10.0...v0.10.1)

---
updated-dependencies:
- dependency-name: sigs.k8s.io/controller-runtime
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-09-27 14:01:22 -04:00
dependabot[bot]andlnx01 8c454fa733 Bump k8s.io/api from 0.22.1 to 0.22.2 (#630)
Bumps [k8s.io/api](https://github.com/kubernetes/api) from 0.22.1 to 0.22.2.
- [Release notes](https://github.com/kubernetes/api/releases)
- [Commits](https://github.com/kubernetes/api/compare/v0.22.1...v0.22.2)

---
updated-dependencies:
- dependency-name: k8s.io/api
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-09-27 12:57:07 -04:00
Maxime VISONNEAUandRobert Brennan 32c1150b28 config: new flags '--disallow-(config|annotation)-exemptions' (#636)
This change follows up #635 and lets end-users decide to disallow exemption rules defined as part of the config file or the controller annotations (whether none, any or both). The main use case here is to be able to prevent users with edit privileges over a controller to add a new exemption rule through an annotation which may obfuscate the actual policies we want to enforce.

Signed-off-by: Maxime VISONNEAU <maxime.visonneau@gmail.com>

Co-authored-by: Robert Brennan <accounts@rbren.io>
2021-09-27 12:56:59 -04:00
dependabot[bot]andlnx01 19341205b7 Bump sigs.k8s.io/yaml from 1.2.0 to 1.3.0 (#639)
Bumps [sigs.k8s.io/yaml](https://github.com/kubernetes-sigs/yaml) from 1.2.0 to 1.3.0.
- [Release notes](https://github.com/kubernetes-sigs/yaml/releases)
- [Changelog](https://github.com/kubernetes-sigs/yaml/blob/master/RELEASE.md)
- [Commits](https://github.com/kubernetes-sigs/yaml/compare/v1.2.0...v1.3.0)

---
updated-dependencies:
- dependency-name: sigs.k8s.io/yaml
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-09-27 08:46:25 -04:00
dependabot[bot]andlnx01 89dfce5bbd Bump github.com/fatih/color from 1.12.0 to 1.13.0 (#641)
Bumps [github.com/fatih/color](https://github.com/fatih/color) from 1.12.0 to 1.13.0.
- [Release notes](https://github.com/fatih/color/releases)
- [Commits](https://github.com/fatih/color/compare/v1.12.0...v1.13.0)

---
updated-dependencies:
- dependency-name: github.com/fatih/color
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-09-27 08:46:12 -04:00
Luke Reed a62389b85f Update documentation from template (#634) 2021-09-21 07:50:08 -07:00
dependabot[bot]andlnx01 5aa397ca22 Bump github.com/thoas/go-funk from 0.9.0 to 0.9.1 (#624)
Bumps [github.com/thoas/go-funk](https://github.com/thoas/go-funk) from 0.9.0 to 0.9.1.
- [Release notes](https://github.com/thoas/go-funk/releases)
- [Changelog](https://github.com/thoas/go-funk/blob/master/CHANGELOG.md)
- [Commits](https://github.com/thoas/go-funk/compare/v0.9.0...v0.9.1)

---
updated-dependencies:
- dependency-name: github.com/thoas/go-funk
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-09-15 14:00:24 -04:00
Robert Brennan d41ce88f16 Update README.md (#627) 2021-09-14 16:13:41 -04:00
Robert Brennan 310015ff53 bump to 4.1.0 (#623)
* bump to 4.1.0

* fix deploy files
2021-09-07 09:53:12 -04:00
dependabot[bot]andlnx01 bb7ba83362 Bump sigs.k8s.io/controller-runtime from 0.9.6 to 0.10.0 (#621)
Bumps [sigs.k8s.io/controller-runtime](https://github.com/kubernetes-sigs/controller-runtime) from 0.9.6 to 0.10.0.
- [Release notes](https://github.com/kubernetes-sigs/controller-runtime/releases)
- [Commits](https://github.com/kubernetes-sigs/controller-runtime/compare/v0.9.6...v0.10.0)

---
updated-dependencies:
- dependency-name: sigs.k8s.io/controller-runtime
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-09-07 09:52:23 -04:00
Robert Brennan c0d8eb6318 handle case-insensitivity for capabilities (#619)
* handle lowercase letters in ALL for capabilities

* change all caps to regexp

* revert file
2021-08-31 11:40:47 -04:00
Robert Brennan 19bf91e13b change test for PDB disruptions (#620) 2021-08-31 11:40:36 -04:00
Robert Brennan 9ae4f774e9 bump version, add docs, fix up dashboard (#595)
* bump version\, add docs\, fix up dashboard

* fix pretty output

* Update config.yaml

* fix extra kinds appearing
2021-08-18 17:55:48 -04:00
Robert Brennan 6c14d968c9 bump alpine (#610) 2021-08-18 14:59:25 -04:00
dependabot[bot]andlnx01 3e655d846b Bump url-parse from 1.5.1 to 1.5.3 in /docs (#611)
Bumps [url-parse](https://github.com/unshiftio/url-parse) from 1.5.1 to 1.5.3.
- [Release notes](https://github.com/unshiftio/url-parse/releases)
- [Commits](https://github.com/unshiftio/url-parse/compare/1.5.1...1.5.3)

---
updated-dependencies:
- dependency-name: url-parse
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-08-18 14:59:17 -04:00
dependabot[bot]andlnx01 0232e31a50 Bump path-parse from 1.0.6 to 1.0.7 in /docs (#607)
Bumps [path-parse](https://github.com/jbgutierrez/path-parse) from 1.0.6 to 1.0.7.
- [Release notes](https://github.com/jbgutierrez/path-parse/releases)
- [Commits](https://github.com/jbgutierrez/path-parse/commits/v1.0.7)

---
updated-dependencies:
- dependency-name: path-parse
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-08-18 14:59:09 -04:00
dependabot[bot]andlnx01 a396f049d0 Bump k8s.io/client-go from 0.21.2 to 0.22.0 (#603)
Bumps [k8s.io/client-go](https://github.com/kubernetes/client-go) from 0.21.2 to 0.22.0.
- [Release notes](https://github.com/kubernetes/client-go/releases)
- [Changelog](https://github.com/kubernetes/client-go/blob/master/CHANGELOG.md)
- [Commits](https://github.com/kubernetes/client-go/compare/v0.21.2...v0.22.0)

---
updated-dependencies:
- dependency-name: k8s.io/client-go
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-08-18 14:59:00 -04:00
dependabot[bot]andlnx01 a55acdd372 Bump sigs.k8s.io/controller-runtime from 0.9.3 to 0.9.6 (#608)
Bumps [sigs.k8s.io/controller-runtime](https://github.com/kubernetes-sigs/controller-runtime) from 0.9.3 to 0.9.6.
- [Release notes](https://github.com/kubernetes-sigs/controller-runtime/releases)
- [Commits](https://github.com/kubernetes-sigs/controller-runtime/compare/v0.9.3...v0.9.6)

---
updated-dependencies:
- dependency-name: sigs.k8s.io/controller-runtime
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-08-17 11:28:45 -04:00
Robert Brennan ca3e46ebbd Update documentation from template (#609) 2021-08-17 11:26:25 -04:00
Terraform User e661e9542d Managed by Terraform 2021-07-29 10:53:58 -04:00
Robert Brennan b923caf79e better support for namespaces in additional schemas (#593)
* better support for namespaces in additional schemas

* add alertmanager check

* Revert " revert file"

This reverts commit f55839b87aeec5af20ac28ecff664d17ac1159b3.

* remove alertmanager check
2021-07-27 10:31:34 -04:00
dependabot[bot]andlnx01 3e79863aa7 Bump sigs.k8s.io/controller-runtime from 0.9.2 to 0.9.3 (#594)
Bumps [sigs.k8s.io/controller-runtime](https://github.com/kubernetes-sigs/controller-runtime) from 0.9.2 to 0.9.3.
- [Release notes](https://github.com/kubernetes-sigs/controller-runtime/releases)
- [Commits](https://github.com/kubernetes-sigs/controller-runtime/compare/v0.9.2...v0.9.3)

---
updated-dependencies:
- dependency-name: sigs.k8s.io/controller-runtime
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-07-26 08:26:06 -04:00
dependabot[bot]andlnx01 d172d8e18b Bump color-string from 1.5.4 to 1.5.5 in /docs (#588)
Bumps [color-string](https://github.com/Qix-/color-string) from 1.5.4 to 1.5.5.
- [Release notes](https://github.com/Qix-/color-string/releases)
- [Changelog](https://github.com/Qix-/color-string/blob/master/CHANGELOG.md)
- [Commits](https://github.com/Qix-/color-string/compare/1.5.4...1.5.5)

---
updated-dependencies:
- dependency-name: color-string
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-07-22 14:35:46 -04:00
dependabot[bot]andlnx01 38c410c5aa Bump k8s.io/api from 0.21.2 to 0.21.3 (#590)
Bumps [k8s.io/api](https://github.com/kubernetes/api) from 0.21.2 to 0.21.3.
- [Release notes](https://github.com/kubernetes/api/releases)
- [Commits](https://github.com/kubernetes/api/compare/v0.21.2...v0.21.3)

---
updated-dependencies:
- dependency-name: k8s.io/api
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-07-22 14:35:21 -04:00
dependabot[bot]andlnx01 653eac6002 Bump github.com/spf13/cobra from 1.1.3 to 1.2.1 (#582)
Bumps [github.com/spf13/cobra](https://github.com/spf13/cobra) from 1.1.3 to 1.2.1.
- [Release notes](https://github.com/spf13/cobra/releases)
- [Changelog](https://github.com/spf13/cobra/blob/master/CHANGELOG.md)
- [Commits](https://github.com/spf13/cobra/compare/v1.1.3...v1.2.1)

---
updated-dependencies:
- dependency-name: github.com/spf13/cobra
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-07-22 14:35:13 -04:00
Robert Brennan 6c995eb04c fix goreleaser format 2021-07-22 15:26:29 +00:00
Robert Brennan e52f1e76e9 bump version 2021-07-22 15:20:38 +00:00
Robert Brennan cf69099d3a Fix helm-values (#591)
* Update audit.go

* Update audit.go
2021-07-22 11:19:17 -04:00
Robert Brennan 20f1be3975 Update .goreleaser.yml (#592)
* Update audit.go

* Update audit.go

* Update .goreleaser.yml

* revert cmd
2021-07-22 10:33:21 -04:00
dependabot[bot]andlnx01 f602687c90 Bump prismjs from 1.23.0 to 1.24.0 in /docs (#580)
Bumps [prismjs](https://github.com/PrismJS/prism) from 1.23.0 to 1.24.0.
- [Release notes](https://github.com/PrismJS/prism/releases)
- [Changelog](https://github.com/PrismJS/prism/blob/master/CHANGELOG.md)
- [Commits](https://github.com/PrismJS/prism/compare/v1.23.0...v1.24.0)

---
updated-dependencies:
- dependency-name: prismjs
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-07-14 14:06:19 -04:00
dependabot[bot]andlnx01 a3404a132d Bump github.com/thoas/go-funk from 0.8.0 to 0.9.0 (#584)
Bumps [github.com/thoas/go-funk](https://github.com/thoas/go-funk) from 0.8.0 to 0.9.0.
- [Release notes](https://github.com/thoas/go-funk/releases)
- [Changelog](https://github.com/thoas/go-funk/blob/master/CHANGELOG.md)
- [Commits](https://github.com/thoas/go-funk/compare/v0.8.0...v0.9.0)

---
updated-dependencies:
- dependency-name: github.com/thoas/go-funk
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-07-14 14:05:51 -04:00
dependabot[bot]andlnx01 46836ccc4c Bump sigs.k8s.io/controller-runtime from 0.9.0 to 0.9.2 (#579)
Bumps [sigs.k8s.io/controller-runtime](https://github.com/kubernetes-sigs/controller-runtime) from 0.9.0 to 0.9.2.
- [Release notes](https://github.com/kubernetes-sigs/controller-runtime/releases)
- [Commits](https://github.com/kubernetes-sigs/controller-runtime/compare/v0.9.0...v0.9.2)

---
updated-dependencies:
- dependency-name: sigs.k8s.io/controller-runtime
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-07-14 14:05:42 -04:00
Robert Brennan ff8e66af07 bump version (#587) 2021-07-14 10:26:27 -03:00
jdesouza 01cc5fa642 Fixed repeated names on dashboard (#586)
* Fixed repeated names on dashboard

* Fixed unit test
2021-07-14 09:17:40 -04:00
Robert Brennan cd47487b0b bump version (#578) 2021-06-25 18:06:06 -04:00
Robert Brennan 7e7e553c0d fix dashboard banner (#577) 2021-06-25 17:54:02 -04:00
Robert Brennan 8385fd10e5 fix webhook for top-level resources (#576)
* fix webhook for top-level resources

* delete unused code

* unused imports
2021-06-25 14:42:51 -04:00
Robert Brennan ccc795d58e bump version, update changelog (#575)
* bump version\, update changelog

* add docs
2021-06-21 14:00:36 -04:00
dependabot[bot]andlnx01 0007b12080 Bump ini from 1.3.5 to 1.3.8 in /docs (#574)
Bumps [ini](https://github.com/isaacs/ini) from 1.3.5 to 1.3.8.
- [Release notes](https://github.com/isaacs/ini/releases)
- [Commits](https://github.com/isaacs/ini/compare/v1.3.5...v1.3.8)

---
updated-dependencies:
- dependency-name: ini
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-06-21 12:27:30 -04:00
dependabot[bot]andlnx01 2958b5cc07 Bump prismjs from 1.22.0 to 1.23.0 in /docs (#573)
Bumps [prismjs](https://github.com/PrismJS/prism) from 1.22.0 to 1.23.0.
- [Release notes](https://github.com/PrismJS/prism/releases)
- [Changelog](https://github.com/PrismJS/prism/blob/master/CHANGELOG.md)
- [Commits](https://github.com/PrismJS/prism/compare/v1.22.0...v1.23.0)

---
updated-dependencies:
- dependency-name: prismjs
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-06-21 12:27:19 -04:00
dependabot[bot]andlnx01 0c5014489e Bump elliptic from 6.5.3 to 6.5.4 in /docs (#572)
Bumps [elliptic](https://github.com/indutny/elliptic) from 6.5.3 to 6.5.4.
- [Release notes](https://github.com/indutny/elliptic/releases)
- [Commits](https://github.com/indutny/elliptic/compare/v6.5.3...v6.5.4)

---
updated-dependencies:
- dependency-name: elliptic
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-06-21 12:27:09 -04:00
dependabot[bot]andlnx01 ebf99869ff Bump lodash from 4.17.20 to 4.17.21 in /docs (#571)
Bumps [lodash](https://github.com/lodash/lodash) from 4.17.20 to 4.17.21.
- [Release notes](https://github.com/lodash/lodash/releases)
- [Commits](https://github.com/lodash/lodash/compare/4.17.20...4.17.21)

---
updated-dependencies:
- dependency-name: lodash
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-06-21 12:26:56 -04:00
Robert Brennan a43a0fe2f5 fix score when onlyOutputFailed is true (#563)
* fix score when onlyOutputFailed is true

* fix tests

* remove return
2021-06-21 12:26:44 -04:00
dependabot[bot]andlnx01 88b57f9f32 Bump y18n from 4.0.0 to 4.0.3 in /docs (#570)
Bumps [y18n](https://github.com/yargs/y18n) from 4.0.0 to 4.0.3.
- [Release notes](https://github.com/yargs/y18n/releases)
- [Changelog](https://github.com/yargs/y18n/blob/y18n-v4.0.3/CHANGELOG.md)
- [Commits](https://github.com/yargs/y18n/compare/v4.0.0...y18n-v4.0.3)

---
updated-dependencies:
- dependency-name: y18n
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-06-21 11:55:38 -04:00
dependabot[bot]andlnx01 e028c34448 Bump url-parse from 1.4.7 to 1.5.1 in /docs (#569)
Bumps [url-parse](https://github.com/unshiftio/url-parse) from 1.4.7 to 1.5.1.
- [Release notes](https://github.com/unshiftio/url-parse/releases)
- [Commits](https://github.com/unshiftio/url-parse/compare/1.4.7...1.5.1)

---
updated-dependencies:
- dependency-name: url-parse
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-06-21 11:55:28 -04:00
dependabot[bot]andlnx01 7c1ec6a762 Bump browserslist from 4.14.7 to 4.16.6 in /docs (#568)
Bumps [browserslist](https://github.com/browserslist/browserslist) from 4.14.7 to 4.16.6.
- [Release notes](https://github.com/browserslist/browserslist/releases)
- [Changelog](https://github.com/browserslist/browserslist/blob/main/CHANGELOG.md)
- [Commits](https://github.com/browserslist/browserslist/compare/4.14.7...4.16.6)

---
updated-dependencies:
- dependency-name: browserslist
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-06-21 11:55:19 -04:00
dependabot[bot]andlnx01 fa6843ae61 Bump dns-packet from 1.3.1 to 1.3.4 in /docs (#567)
Bumps [dns-packet](https://github.com/mafintosh/dns-packet) from 1.3.1 to 1.3.4.
- [Release notes](https://github.com/mafintosh/dns-packet/releases)
- [Changelog](https://github.com/mafintosh/dns-packet/blob/master/CHANGELOG.md)
- [Commits](https://github.com/mafintosh/dns-packet/compare/v1.3.1...v1.3.4)

---
updated-dependencies:
- dependency-name: dns-packet
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-06-21 11:55:08 -04:00
dependabot[bot]andlnx01 76cc9e3296 Bump postcss from 7.0.35 to 7.0.36 in /docs (#566)
Bumps [postcss](https://github.com/postcss/postcss) from 7.0.35 to 7.0.36.
- [Release notes](https://github.com/postcss/postcss/releases)
- [Changelog](https://github.com/postcss/postcss/blob/main/CHANGELOG.md)
- [Commits](https://github.com/postcss/postcss/compare/7.0.35...7.0.36)

---
updated-dependencies:
- dependency-name: postcss
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-06-21 11:54:57 -04:00
dependabot[bot]andlnx01 6bcdb834ed Bump ssri from 6.0.1 to 6.0.2 in /docs (#565)
Bumps [ssri](https://github.com/npm/ssri) from 6.0.1 to 6.0.2.
- [Release notes](https://github.com/npm/ssri/releases)
- [Changelog](https://github.com/npm/ssri/blob/v6.0.2/CHANGELOG.md)
- [Commits](https://github.com/npm/ssri/compare/v6.0.1...v6.0.2)

---
updated-dependencies:
- dependency-name: ssri
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-06-21 11:54:48 -04:00
dependabot[bot]andlnx01 2bac1c9ba9 Bump ws from 6.2.1 to 6.2.2 in /docs (#564)
Bumps [ws](https://github.com/websockets/ws) from 6.2.1 to 6.2.2.
- [Release notes](https://github.com/websockets/ws/releases)
- [Commits](https://github.com/websockets/ws/compare/6.2.1...6.2.2)

---
updated-dependencies:
- dependency-name: ws
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-06-21 11:54:39 -04:00
Robert Brennan 0e6ca81f57 add banner (#560)
* add banner

* add link
2021-06-21 11:54:17 -04:00
dependabot[bot]andlnx01 4bc2522e25 Bump k8s.io/client-go from 0.21.1 to 0.21.2 (#561)
Bumps [k8s.io/client-go](https://github.com/kubernetes/client-go) from 0.21.1 to 0.21.2.
- [Release notes](https://github.com/kubernetes/client-go/releases)
- [Changelog](https://github.com/kubernetes/client-go/blob/master/CHANGELOG.md)
- [Commits](https://github.com/kubernetes/client-go/compare/v0.21.1...v0.21.2)

---
updated-dependencies:
- dependency-name: k8s.io/client-go
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-06-21 11:53:56 -04:00
dependabot[bot]andlnx01 d4bb6239c7 Bump sigs.k8s.io/controller-runtime from 0.9.0-alpha.1 to 0.9.0 (#559)
Bumps [sigs.k8s.io/controller-runtime](https://github.com/kubernetes-sigs/controller-runtime) from 0.9.0-alpha.1 to 0.9.0.
- [Release notes](https://github.com/kubernetes-sigs/controller-runtime/releases)
- [Commits](https://github.com/kubernetes-sigs/controller-runtime/compare/v0.9.0-alpha.1...v0.9.0)

---
updated-dependencies:
- dependency-name: sigs.k8s.io/controller-runtime
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-06-21 10:52:27 -04:00
Cydnee OwensandRobert Brennan 082e9c0406 process helm templates method (#556)
* process helm templates method

* update helm chart error paths and add helmValues

Co-authored-by: Robert Brennan <accounts@rbren.io>
2021-06-04 12:47:45 -07:00
Robert Brennan 178742e0f3 Update README.md (#557) 2021-05-28 13:36:01 -04:00
Robert Brennan 1651aa7004 remove 386 arch (#555)
* remove 386 arch

* update version
2021-05-25 13:35:44 -04:00
Robert Brennan e6c9e4558e update go (#554)
* update go

* update version
2021-05-25 13:28:19 -04:00
Cydnee OwensandRobert Brennan b6f1bdf098 update version from 3.2.0 to 4.0.0 (#553)
* update version from 3.2.0 to 4.0.0

* update deployment files

Co-authored-by: Robert Brennan <contact@rbren.io>
2021-05-25 13:21:46 -04:00
Cydnee Owens cbc15ad069 Pod level testing (#546)
* update runAsPrivileged to test at pod level

* update runAsPrivileged to test at pod level

* add pod level success/failure tests

* add insuecure capabilities pod level testing

* update checks to include good/bad security

* update checks for good/bad security

* remove good security from runAsPrivileged
2021-05-25 12:59:28 -04:00
dependabot[bot]andlnx01 68d295ec6b Bump github.com/fatih/color from 1.11.0 to 1.12.0 (#549)
Bumps [github.com/fatih/color](https://github.com/fatih/color) from 1.11.0 to 1.12.0.
- [Release notes](https://github.com/fatih/color/releases)
- [Commits](https://github.com/fatih/color/compare/v1.11.0...v1.12.0)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-05-25 12:53:52 -04:00
dependabot[bot]andlnx01 90339357c2 Bump k8s.io/client-go from 0.21.0 to 0.21.1 (#550)
Bumps [k8s.io/client-go](https://github.com/kubernetes/client-go) from 0.21.0 to 0.21.1.
- [Release notes](https://github.com/kubernetes/client-go/releases)
- [Changelog](https://github.com/kubernetes/client-go/blob/master/CHANGELOG.md)
- [Commits](https://github.com/kubernetes/client-go/compare/v0.21.0...v0.21.1)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-05-25 12:53:44 -04:00
Robert Brennan 2e7368d011 change fairwinds links (#552) 2021-05-25 12:53:32 -04:00
Robert Brennan 6cd65fbed8 Update README.md (#551)
* Update README.md

* Update README.md
2021-05-25 12:33:35 -04:00
Cydnee OwensandRobert Brennan 1ede736971 update notReadOnlyRootFilesystem check (#543)
* update notReadOnlyRootFilesystem check

* remove run as user

* add pod level testing to notreadonlyrootFileSystem and update schema_test.go file

Co-authored-by: Robert Brennan <accounts@rbren.io>
2021-05-24 15:21:04 -07:00
Cydnee OwensandRobert Brennan 1935abd563 Test layout refactor (#545)
* refactor test structure

* update syntax to include template/spec layout

* update syntax to include template/spec layout

Co-authored-by: Robert Brennan <accounts@rbren.io>
2021-05-24 16:30:10 -04:00
842ccf4853 Multiple replicas (#534)
* add file structure and success/failure yaml files

* add success/fail check tests for liveness probe missing

* add success/fail check tests for readiness probe missing

* add cpu limit missing success/failure

* add cpu requests missing success/failure

* add hostPortMissing success/failure

* add readinessProbeMissing success/failure

* Add success/failure test for dangerousCapabilities

* add success test

* submit for review for potential bug

* remove outdated files

* fix test cases

Co-authored-by: Robert Brennan <contact@rbren.io>
Co-authored-by: Robert Brennan <accounts@rbren.io>
2021-05-18 13:16:08 -07:00
Cydnee OwensandRobert Brennan 2c56a313a1 add failure, failure.latest and success.yaml file (#541)
Co-authored-by: Robert Brennan <accounts@rbren.io>
2021-05-18 12:40:55 -07:00
dependabot[bot]andlnx01 7b00d73a6f Bump github.com/fatih/color from 1.10.0 to 1.11.0 (#544)
Bumps [github.com/fatih/color](https://github.com/fatih/color) from 1.10.0 to 1.11.0.
- [Release notes](https://github.com/fatih/color/releases)
- [Commits](https://github.com/fatih/color/compare/v1.10.0...v1.11.0)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-05-17 09:13:29 -04:00
Robert Brennan a995e7e724 Set goflags to fix deps (#542)
* update deps

* tidy up

* try setting goflags
2021-05-12 15:52:04 -04:00
Terraform User 3211d6d25d Managed by Terraform 2021-05-11 18:06:06 -04:00
Cydnee OwensandRobert Brennan d011bb454a add failure.all.yaml for dangerouscapabilities test (#538)
* add failure.all.yaml for dangerouscapabilities test

* change to [ALL] failing test

* add failure.all.yaml for dangerouscapabilities test

* change to [ALL] failing test

* fix dangerous caps test

Co-authored-by: Robert Brennan <contact@rbren.io>
2021-05-11 13:12:46 -07:00
Soto Sugita 8e62436697 Fix the installation command by helm (#539)
The installation by helm will fail because the namespace does not exist.
Added the `--create-namespace` flag to create a namespace if not exist.
2021-05-11 09:00:29 -04:00
Cydnee OwensandRobert Brennan c9811171ce Check testing (#535)
* add file structure and success/failure yaml files

* add success/fail check tests for liveness probe missing

* add success/fail check tests for readiness probe missing

* add cpu limit missing success/failure

* add cpu requests missing success/failure

* add hostPortMissing success/failure

* add readinessProbeMissing success/failure

* Add success/failure test for dangerousCapabilities

* add success test

* add success/failure tests

* name change pdbDisruptionsGreaterThanZero to pdbDisruptionsIsZero for test

Co-authored-by: Robert Brennan <accounts@rbren.io>
2021-05-07 09:46:26 -07:00
Cydnee Owens 30eebaf16a add memory limits and requests success/failure tests (#537) 2021-05-06 14:15:22 -07:00
dependabot[bot]andlnx01 dbf001fa53 Bump github.com/thoas/go-funk from 0.7.0 to 0.8.0 (#530)
Bumps [github.com/thoas/go-funk](https://github.com/thoas/go-funk) from 0.7.0 to 0.8.0.
- [Release notes](https://github.com/thoas/go-funk/releases)
- [Changelog](https://github.com/thoas/go-funk/blob/master/CHANGELOG.md)
- [Commits](https://github.com/thoas/go-funk/compare/v0.7.0...v0.8.0)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-05-06 14:19:39 -04:00
Robert Brennan f753fc91f2 Support multi-resource templates (#524)
* able to run multi-resource tests

* start passing resource provider through

* working end-to-end

* better support for go templating

* fix tests

* delint

* add test

* add json annotations

* remove panics

* fix annotation

* fix for groupkinds

* add comment

* add docs

* change jsonSchema field to schemaString

* rename check

* add pdb to tests

* add ingress to tests

* update deps

* fix up policy import

* update go

* fix check name

* funk it up

* better docs
2021-05-06 14:01:20 -04:00
Cydnee OwensandRobert Brennan 239a321588 Liveness probe (#529)
* add file structure and success/failure yaml files

* add success/fail check tests for liveness probe missing

* add success/fail check tests for readiness probe missing

* add cpu limit missing success/failure

* add cpu requests missing success/failure

* add hostPortMissing success/failure

* add readinessProbeMissing success/failure

* delete misspelled file folder readinessProb

Co-authored-by: Robert Brennan <accounts@rbren.io>
2021-05-06 09:11:10 -07:00
Robert Brennan 61eb1f95a4 run check tests in CI (#532) 2021-04-30 08:51:47 -04:00
dependabot-preview[bot]andlnx01 a66a6b89da Upgrade to GitHub-native Dependabot (#528)
Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
2021-04-30 08:02:05 -04:00
Cydnee Owens 46923d0a0a Helper tests2 (#527)
* Add test for getWeatherIcon and getGrade helper methods

* Add tests for all helper methods
2021-04-23 10:49:01 -07:00
Cydnee Owens ba1b4d5db9 Add test for getWeatherIcon and getGrade helper methods (#526) 2021-04-22 09:58:04 -07:00
Robert Brennan ba0a25acf9 Delete codecov.yml (#525)
* Delete codecov.yml

* Update config.yml
2021-04-16 14:27:00 -06:00
Robert BrennanandJordan Doig 371e30fe3d Add support for check templates (#520)
* Add basic flow

* Add arbitrary validator

* Pipe config through to resource provider

* Set arbitraries on resource provider

* Add arbitrary validation to fullaudit

* Add conf argument

* Fix resource setting from string

* PR updates

* Fix nil map error

* Delete lingering print, add pdb check, start implementing validator test

* move ingress to arbitrary

* fix compile

* refactor a bunch

* add tls tests

* tests passing

* resource provider helper

* refactor tests

* fix exemptions

* fix check test

* fix up resource creation from API

* fix init containers

* fix cronjob test

* fix pod tests

* combine controllers and-noncontrollers in resource provider

* delint

* add ingress backward compat

* fix tests

* reenable test

* rename a fn

* remove unused fn

* remove if

* first pass

* more progress

* debug

* update jsonschema

* Revert "update jsonschema"

This reverts commit 45e6c398ff.

* Revert "Revert "update jsonschema""

This reverts commit f8c5ec223824694c43a6af9dae9319f1f0e30b37.

* templating working

* rename check

* add failure details to results

* minor edits

* add runAsRoot test

* Revert "Revert "Revert "update jsonschema"""

This reverts commit fcdacdc3c22e32c580541901f99e154d00bedbc8.

* minor fixes

* most tests passing

* fix json annotations

* logspam

* delint

* add comment

Co-authored-by: Jordan Doig <jordan.steele.doig@gmail.com>
2021-04-09 09:08:31 -04:00
Terraform User 1013834e3c Managed by Terraform 2021-04-07 10:45:20 -06:00
Terraform User e802c28801 Managed by Terraform 2021-04-07 09:59:48 -06:00
Robert Brennan 14d503580b Update documentation from template (#521) 2021-04-05 11:47:39 -04:00
Terraform User 0fc109c199 Managed by Terraform 2021-03-30 12:20:28 -06:00
Jordan DoigandRobert Brennan 63fd576d3e Add support for arbitrary Kinds (#505)
* Add basic flow

* Add arbitrary validator

* Pipe config through to resource provider

* Set arbitraries on resource provider

* Add arbitrary validation to fullaudit

* Add conf argument

* Fix resource setting from string

* PR updates

* Fix nil map error

* Delete lingering print, add pdb check, start implementing validator test

* move ingress to arbitrary

* fix compile

* refactor a bunch

* add tls tests

* tests passing

* resource provider helper

* refactor tests

* fix exemptions

* fix check test

* fix up resource creation from API

* fix init containers

* fix cronjob test

* fix pod tests

* combine controllers and-noncontrollers in resource provider

* delint

* add ingress backward compat

* fix tests

* reenable test

* rename a fn

* remove unused fn

* remove if

Co-authored-by: Robert Brennan <contact@rbren.io>
2021-03-26 08:29:59 -04:00
Robert Brennan f0c8ee256e Update documentation from template (#518) 2021-03-17 13:55:36 -04:00
dependabot-preview[bot]andlnx01 d5cb68084e Bump github.com/fatih/color from 1.7.0 to 1.10.0 (#515)
Bumps [github.com/fatih/color](https://github.com/fatih/color) from 1.7.0 to 1.10.0.
- [Release notes](https://github.com/fatih/color/releases)
- [Commits](https://github.com/fatih/color/compare/v1.7.0...v1.10.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
2021-03-17 12:51:17 -04:00
dependabot-preview[bot]andlnx01 f7d2309608 Bump github.com/sirupsen/logrus from 1.8.0 to 1.8.1 (#514)
Bumps [github.com/sirupsen/logrus](https://github.com/sirupsen/logrus) from 1.8.0 to 1.8.1.
- [Release notes](https://github.com/sirupsen/logrus/releases)
- [Changelog](https://github.com/sirupsen/logrus/blob/master/CHANGELOG.md)
- [Commits](https://github.com/sirupsen/logrus/compare/v1.8.0...v1.8.1)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
2021-03-17 12:51:10 -04:00
Robert Brennan d800e8d629 empty commit 2021-03-16 13:30:47 +00:00
Robert Brennan eebc9537a2 update for 3.2.0 (#513) 2021-03-12 13:12:16 -05:00
Robert Brennan 1fed099b53 Pretty printer for audit (#512)
* pretty output

* add colors

* better nocolor

* fix up main title

* delint

* remove double negative

* update docs
2021-03-12 12:20:00 -05:00
Robert Brennan 25dfae1fea add to changelog 2021-03-08 14:03:51 +00:00
Robert Brennan c365fb08cf bump version 2021-03-08 14:03:15 +00:00
Robert Brennan 768b715fdf fix npe (#511) 2021-03-08 08:34:31 -05:00
dependabot-preview[bot]andlnx01 7d938ac405 Bump k8s.io/client-go from 0.20.2 to 0.20.4 (#502)
Bumps [k8s.io/client-go](https://github.com/kubernetes/client-go) from 0.20.2 to 0.20.4.
- [Release notes](https://github.com/kubernetes/client-go/releases)
- [Changelog](https://github.com/kubernetes/client-go/blob/master/CHANGELOG.md)
- [Commits](https://github.com/kubernetes/client-go/compare/v0.20.2...v0.20.4)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
2021-03-04 08:43:20 -05:00
185 changed files with 60877 additions and 3438 deletions
+6 -16
View File
@@ -17,6 +17,7 @@ references:
echo 'export PUSH_ALL_VERSION_TAGS=true' >> ${BASH_ENV}
echo 'export GOPROXY=https://proxy.golang.org' >> ${BASH_ENV}
echo 'export GO111MODULE=on' >> ${BASH_ENV}
echo 'export GOFLAGS=-mod=mod' >> ${BASH_ENV}
install_k8s: &install_k8s
run:
@@ -58,16 +59,6 @@ references:
helm install cert-manager jetstack/cert-manager --namespace cert-manager --version 0.16.1 --set "installCRDs=true" --wait
echo "Install cert-manager successful"
# Test scripts
update_coverage: &update_coverage
run:
name: Update Coverage
command: |
if [[ -z $CIRCLE_PR_NUMBER ]]; then
bash <(curl -s https://codecov.io/bash)
else
echo "Skipping coverage for forked PR"
fi
test_binary_dashboard: &test_binary_dashboard
run:
name: Test Dashboard
@@ -96,8 +87,8 @@ references:
run:
name: Install GoReleaser
command: |
curl -fsSLo goreleaser.deb https://github.com/goreleaser/goreleaser/releases/download/v0.131.1/goreleaser_amd64.deb
echo "640790dcbfa864f26de4c26c2d491f293a64525c8c6641c5bbdec7136b38977e goreleaser.deb" | sha256sum -c -
curl -fsSLo goreleaser.deb https://github.com/goreleaser/goreleaser/releases/download/v0.174.2/goreleaser_amd64.deb
echo "bad33997ea9977a84196bdca1d5993fada909cd81c3e88d52bd297666bea61a4 goreleaser.deb" | sha256sum -c -
sudo dpkg -i goreleaser.deb
rm goreleaser.deb
@@ -157,16 +148,15 @@ jobs:
test:
working_directory: /go/src/github.com/fairwindsops/polaris/
docker:
- image: circleci/golang:1.13
- image: circleci/golang:1.16
steps:
- checkout
- *set_environment_variables
- run: go get -u golang.org/x/lint/golint
- run: go list ./... | grep -v vendor | xargs golint -set_exit_status
- run: go list ./... | grep -v vendor | xargs go vet
- run: go test ./pkg/... -coverprofile=coverage.txt -covermode=count
- run: go test ./... -coverprofile=coverage.txt -covermode=count
- run: go run main.go audit --audit-path ./deploy --set-exit-code-below-score 100 --set-exit-code-on-danger
- *update_coverage
- *test_binary_dashboard
insights:
@@ -187,7 +177,7 @@ jobs:
release_binary:
working_directory: /go/src/github.com/fairwindsops/polaris/
docker:
- image: circleci/golang:1.13
- image: circleci/golang:1.16
steps:
- checkout
- setup_remote_docker
+3 -2
View File
@@ -3,15 +3,16 @@ if [[ -z "$INPUT_VERSION" ]]; then
echo "Missing polaris version information"
exit 1
fi
POLARIS_URL=https://github.com/FairwindsOps/polaris/releases/download/$INPUT_VERSION/polaris_linux_amd64.tar.gz
polaris version | grep "$INPUT_VERSION" &> /dev/null
if [ $? == 0 ]; then
echo "Polaris $INPUT_VERSION is already installed! Exiting gracefully."
exit 0
else
echo "Installing polaris to path."
echo "Installing polaris to path from " $POLARIS_URL
fi
TARGET_FILE="polaris.tar.gz"
curl -LJ -o $TARGET_FILE 'https://github.com/FairwindsOps/polaris/releases/download/'"$INPUT_VERSION"'/polaris_'"$INPUT_VERSION"'_linux_386.tar.gz'
curl -LJ -o $TARGET_FILE $POLARIS_URL
mkdir polaris
tar -xzf $TARGET_FILE -C polaris
rm $TARGET_FILE
+44
View File
@@ -0,0 +1,44 @@
version: 2
updates:
- package-ecosystem: gomod
directory: "/"
schedule:
interval: weekly
time: "11:00"
ignore:
- dependency-name: cloud.google.com/go
versions:
- ">= 0.57.a, < 0.58"
- dependency-name: github.com/go-logr/logr
versions:
- ">= 0.2.a, < 0.3"
- dependency-name: github.com/go-logr/zapr
versions:
- ">= 0.2.a, < 0.3"
- dependency-name: github.com/googleapis/gnostic
versions:
- ">= 0.4.a, < 0.5"
- dependency-name: github.com/googleapis/gnostic
versions:
- ">= 0.5.a, < 0.6"
- dependency-name: github.com/qri-io/jsonschema
versions:
- ">= 0.2.a, < 0.3"
- dependency-name: k8s.io/api
versions:
- ">= 0.19.a, < 0.20"
- dependency-name: k8s.io/apimachinery
versions:
- ">= 0.19.a, < 0.20"
- dependency-name: k8s.io/client-go
versions:
- ">= 0.19.a, < 0.20"
- dependency-name: sigs.k8s.io/controller-runtime
versions:
- ">= 0.5.a, < 0.6"
- dependency-name: sigs.k8s.io/controller-runtime
versions:
- ">= 0.8.a, < 0.9"
- dependency-name: k8s.io/apimachinery
versions:
- 0.20.4
+18
View File
@@ -0,0 +1,18 @@
daysUntilStale: 30
daysUntilClose: 7
onlyLabels: []
exemptLabels:
- pinned
- security
exemptProjects: false
exemptMilestones: true
exemptAssignees: false
staleLabel: stale
markComment: >
This issue has been automatically marked as stale because it has not had
recent activity. It will be closed if no further activity occurs. Thank you
for your contributions.
limitPerRun: 30
+2 -2
View File
@@ -11,7 +11,7 @@ jobs:
- name: Setup polaris
uses: ./.github/actions/setup-polaris
with:
version: 3.0.3
version: 4.2.0
- name: Use command
run: polaris version
@@ -22,6 +22,6 @@ jobs:
- name: Setup polaris
uses: fairwindsops/polaris/.github/actions/setup-polaris@master
with:
version: 3.0.3
version: 4.2.0
- name: Use command
run: polaris version
+10 -3
View File
@@ -7,21 +7,28 @@ changelog:
- '^docs:'
- '^test:'
builds:
- id: watcher
- id: polaris
env:
- CGO_ENABLED=0
- GO111MODULE=on
goos:
- linux
- darwin
- windows
goarch:
- amd64
- arm
- arm64
- 386
goarm:
- 6
- 7
archives:
- id: polaris
builds: ["polaris"]
name_template: "{{ .ProjectName }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}{{ if .Mips }}_{{ .Mips }}{{ end }}"
brews:
- name: polaris
github:
tap:
owner: FairwindsOps
name: homebrew-tap
folder: Formula
+1 -1
View File
@@ -1 +1 @@
* @rbren @makoscafee @jordandoig @baderbuddy @shaswa
* @rbren @makoscafee
+74
View File
@@ -0,0 +1,74 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at opensource@fairwinds.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
+2 -2
View File
@@ -1,4 +1,4 @@
FROM golang:1.13 AS build-env
FROM golang:1.16 AS build-env
WORKDIR /go/src/github.com/fairwindsops/polaris/
ENV GO111MODULE=on
@@ -15,7 +15,7 @@ RUN go get -u github.com/gobuffalo/packr/v2/packr2
COPY . .
RUN packr2 build -a -o polaris *.go
FROM alpine:3.13
FROM alpine:3.14
WORKDIR /usr/local/bin
RUN apk --no-cache add ca-certificates
+28 -31
View File
@@ -3,12 +3,12 @@
<br>
<h3>Best Practices for Kubernetes Workload Configuration</h3>
<a href="https://github.com/FairwindsOps/polaris">
<img src="https://img.shields.io/static/v1.svg?label=Version&message=3.1.5&color=239922">
<img src="https://img.shields.io/static/v1.svg?label=Version&message=4.2.0&color=239922">
</a>
<a href="https://goreportcard.com/report/github.com/FairwindsOps/polaris">
<img src="https://goreportcard.com/badge/github.com/FairwindsOps/polaris">
</a>
<a href="https://circleci.com/gh/FairwindsOps/polaris.svg">
<a href="https://circleci.com/gh/FairwindsOps/polaris">
<img src="https://circleci.com/gh/FairwindsOps/polaris.svg?style=svg">
</a>
<a href="https://insights.fairwinds.com/gh/FairwindsOps/polaris">
@@ -29,41 +29,38 @@ Polaris can be run in three different modes:
<img src="https://polaris.docs.fairwinds.com/img/architecture.svg" alt="Polaris Architecture" width="550"/>
</p>
**Want to learn more?** Reach out on [the Slack channel](https://fairwindscommunity.slack.com/messages/polaris) ([request invite](https://join.slack.com/t/fairwindscommunity/shared_invite/zt-e3c6vj4l-3lIH6dvKqzWII5fSSFDi1g)), send an email to `opensource@fairwinds.com`, or join us for [office hours on Zoom](https://fairwindscommunity.slack.com/messages/office-hours)
## Documentation
Check out the [documentation at docs.fairwinds.com](https://polaris.docs.fairwinds.com)
## Integration with Fairwinds Insights
<p align="center">
<img src="https://polaris.docs.fairwinds.com/img/FW_Insights_Polaris.svg" alt="Fairwinds Insights" width="550"/>
</p>
<!-- Begin boilerplate -->
## Join the Fairwinds Open Source Community
[Fairwinds Insights](https://www.fairwinds.com/fairwinds-polaris-upgrade)
is a platform for auditing Kubernetes clusters and enforcing policy. If you'd like to:
* manage Polaris across a fleet of clusters
* track findings over time
* send results to services like Slack and Datadog
* add additional checks from tools like
[Trivy](https://github.com/aquasecurity/trivy),
[Goldilocks](https://github.com/FairwindsOps/goldilocks/), and
[OPA](https://www.openpolicyagent.org)
The goal of the Fairwinds Community is to exchange ideas, influence the open source roadmap,
and network with fellow Kubernetes users.
[Chat with us on Slack](https://join.slack.com/t/fairwindscommunity/shared_invite/zt-e3c6vj4l-3lIH6dvKqzWII5fSSFDi1g)
or
[join the user group](https://www.fairwinds.com/open-source-software-user-group) to get involved!
you can sign up for a [free account here](https://insights.fairwinds.com?source=polaris).
<a href="https://www.fairwinds.com/t-shirt-offer?utm_source=polaris&utm_medium=polaris&utm_campaign=polaris-tshirt">
<img src="https://www.fairwinds.com/hubfs/Doc_Banners/Fairwinds_OSS_User_Group_740x125_v6.png" alt="Love Fairwinds Open Source? Share your business email and job title and we'll send you a free Fairwinds t-shirt!" />
</a>
## Contributing
PRs welcome! Check out the [Contributing Guidelines](https://polaris.docs.fairwinds.com/contributing) and [Code of Conduct](https://polaris.docs.fairwinds.com/code-of-conduct) for more information.
## Other Projects from Fairwinds
## Further Information
A history of changes to this project can be viewed in the [Changelog](https://polaris.docs.fairwinds.com/changelog)
Enjoying Polaris? Check out some of our other projects:
* [Goldilocks](https://github.com/FairwindsOps/Goldilocks) - Right-size your Kubernetes Deployments by compare your memory and CPU settings against actual usage
* [Pluto](https://github.com/FairwindsOps/Pluto) - Detect Kubernetes resources that have been deprecated or removed in future versions
* [Nova](https://github.com/FairwindsOps/Nova) - Check to see if any of your Helm charts have updates available
* [rbac-manager](https://github.com/FairwindsOps/rbac-manager) - Simplify the management of RBAC in your Kubernetes clusters
If you'd like to learn more about Polaris, or if you'd like to speak with
a Kubernetes expert, you can contact `info@fairwinds.com` or [visit our website](https://fairwinds.com)
---
<p align="center">
<img src="https://polaris.docs.fairwinds.com/img/dashboard-screenshot.png" alt="Polaris Dashboard" width="550"/>
</p>
Or [check out the full list](https://www.fairwinds.com/open-source-software?utm_source=polaris&utm_medium=polaris&utm_campaign=polaris)
## Fairwinds Insights
If you're interested in running Polaris in multiple clusters,
tracking the results over time, integrating with Slack, Datadog, and Jira,
or unlocking other functionality, check out
[Fairwinds Insights](https://www.fairwinds.com/polaris-user-insights-demo?utm_source=polaris&utm_medium=polaris&utm_campaign=polaris),
a platform for auditing and enforcing policy in Kubernetes clusters.
<a href="https://www.fairwinds.com/polaris-user-insights-demo?utm_source=polaris&utm_medium=ad&utm_campaign=polarisad">
<img src="https://www.fairwinds.com/hubfs/Doc_Banners/Fairwinds_Polaris_Ad.png" alt="Fairwinds Insights" />
</a>
+10 -9
View File
@@ -14,12 +14,13 @@ schema:
properties:
add:
type: array
not:
contains:
const: ALL
not:
contains:
const: SYS_ADMIN
not:
contains:
const: NET_ADMIN
allOf:
- not:
contains:
pattern: '^(?i)ALL$'
- not:
contains:
pattern: '^(?i)SYS_ADMIN$'
- not:
contains:
pattern: '^(?i)NET_ADMIN$'
+16 -17
View File
@@ -22,36 +22,35 @@ schema:
type: array
oneOf:
- contains:
const: ALL
pattern: '^(?i)ALL$'
- allOf:
- contains:
const: NET_ADMIN
pattern: '^(?i)NET_ADMIN$'
- contains:
const: CHOWN
pattern: '^(?i)CHOWN$'
- contains:
const: DAC_OVERRIDE
pattern: '^(?i)DAC_OVERRIDE$'
- contains:
const: FSETID
pattern: '^(?i)FSETID$'
- contains:
const: FOWNER
pattern: '^(?i)FOWNER$'
- contains:
const: MKNOD
pattern: '^(?i)MKNOD$'
- contains:
const: NET_RAW
pattern: '^(?i)NET_RAW$'
- contains:
const: SETGID
pattern: '^(?i)SETGID$'
- contains:
const: SETUID
pattern: '^(?i)SETUID$'
- contains:
const: SETFCAP
pattern: '^(?i)SETFCAP$'
- contains:
const: SETPCAP
pattern: '^(?i)SETPCAP$'
- contains:
const: NET_BIND_SERVICE
pattern: '^(?i)NET_BIND_SERVICE$'
- contains:
const: SYS_CHROOT
pattern: '^(?i)SYS_CHROOT$'
- contains:
const: KILL
pattern: '^(?i)KILL$'
- contains:
const: AUDIT_WRITE
pattern: '^(?i)AUDIT_WRITE$'
+17
View File
@@ -0,0 +1,17 @@
successMessage: Label app.kubernetes.io/name matches metadata.name
failureMessage: Label app.kubernetes.io/name must match metadata.name
target: Controller
schema:
'$schema': http://json-schema.org/draft-07/schema
type: object
properties:
metadata:
type: object
required: ["labels"]
properties:
labels:
type: object
required: ["app.kubernetes.io/name"]
properties:
app.kubernetes.io/name:
const: "{{ .metadata.name }}"
+39
View File
@@ -0,0 +1,39 @@
successMessage: A PodDisruptionBudget is attached
failureMessage: Should have a PodDisruptionBudget
category: Reliability
target: Controller
controllers:
include:
- Deployment
schema:
'$schema': http://json-schema.org/draft-07/schema
type: object
properties:
metadata:
type: object
properties:
labels:
type: object
minProperties: 1
additionalSchemaStrings:
policy/PodDisruptionBudget: |
type: object
properties:
spec:
type: object
required: ["selector"]
properties:
selector:
type: object
required: ["matchLabels"]
properties:
matchLabels:
type: object
anyOf:
{{ range $key, $value := .metadata.labels }}
- properties:
"{{ $key }}":
type: string
const: {{ $value }}
required: ["{{ $key }}"]
{{ end }}
+34 -7
View File
@@ -2,15 +2,42 @@ successMessage: Filesystem is read only
failureMessage: Filesystem should be read only
category: Security
target: Container
schemaTarget: Pod
schema:
'$schema': http://json-schema.org/draft-07/schema
type: object
required:
- securityContext
properties:
securityContext:
required:
- readOnlyRootFilesystem
definitions:
goodSecurityContext:
type: object
anyOf:
- required:
- readOnlyRootFilesystem
properties:
readOnlyRootFilesystem:
const: true
notBadSecurityContext:
type: object
properties:
readOnlyRootFilesystem:
const: true
type: object
anyOf:
- required:
- securityContext
properties:
securityContext:
$ref: "#/definitions/goodSecurityContext"
containers:
type: array
items:
properties:
securityContext:
$ref: "#/definitions/notBadSecurityContext"
- properties:
containers:
type: array
items:
required:
- securityContext
properties:
securityContext:
$ref: "#/definitions/goodSecurityContext"
+22
View File
@@ -0,0 +1,22 @@
successMessage: Voluntary evictions are possible
failureMessage: Voluntary evictions are not possible
category: Reliability
target: policy/PodDisruptionBudget
schema:
'$schema': http://json-schema.org/draft-07/schema
type: object
required:
- spec
properties:
spec:
type: object
properties:
minAvailable:
not:
const: '100%'
maxUnavailable:
allOf:
- not:
const: 0
- not:
const: '0%'
+34 -7
View File
@@ -2,15 +2,42 @@ successMessage: Privilege escalation not allowed
failureMessage: Privilege escalation should not be allowed
category: Security
target: Container
schemaTarget: Pod
schema:
'$schema': http://json-schema.org/draft-07/schema
type: object
required:
- securityContext
properties:
securityContext:
required:
- allowPrivilegeEscalation
definitions:
goodSecurityContext:
type: object
anyOf:
- required:
- allowPrivilegeEscalation
properties:
allowPrivilegeEscalation:
const: false
notBadSecurityContext:
type: object
properties:
allowPrivilegeEscalation:
const: false
type: object
anyOf:
- required:
- securityContext
properties:
securityContext:
$ref: "#/definitions/goodSecurityContext"
containers:
type: array
items:
properties:
securityContext:
$ref: "#/definitions/notBadSecurityContext"
- properties:
containers:
type: array
items:
required:
- securityContext
properties:
securityContext:
$ref: "#/definitions/goodSecurityContext"
+14 -3
View File
@@ -2,12 +2,23 @@ successMessage: Not running as privileged
failureMessage: Should not be running as privileged
category: Security
target: Container
schemaTarget: Pod
schema:
'$schema': http://json-schema.org/draft-07/schema
type: object
properties:
securityContext:
definitions:
notBadSecurityContext:
type: object
properties:
privileged:
not:
const: true
type: object
properties:
securityContext:
$ref: "#/definitions/notBadSecurityContext"
containers:
type: array
items:
properties:
securityContext:
$ref: "#/definitions/notBadSecurityContext"
+1 -1
View File
@@ -1,7 +1,7 @@
successMessage: Ingress has TLS configured
failureMessage: Ingress does not have TLS configured
category: Security
target: Ingress
target: networking.k8s.io/Ingress
schema:
'$schema': http://json-schema.org/draft-07/schema
type: object
+68 -17
View File
@@ -22,8 +22,8 @@ import (
"io/ioutil"
"net/http"
"os"
"os/exec"
conf "github.com/fairwindsops/polaris/pkg/config"
"github.com/fairwindsops/polaris/pkg/kube"
"github.com/fairwindsops/polaris/pkg/validator"
"github.com/sirupsen/logrus"
@@ -38,6 +38,9 @@ var auditOutputURL string
var auditOutputFile string
var auditOutputFormat string
var resourceToAudit string
var useColor bool
var helmChart string
var helmValues string
func init() {
rootCmd.AddCommand(auditCmd)
@@ -47,9 +50,12 @@ func init() {
auditCmd.PersistentFlags().IntVar(&minScore, "set-exit-code-below-score", 0, "Set an exit code of 4 when the score is below this threshold (1-100).")
auditCmd.PersistentFlags().StringVar(&auditOutputURL, "output-url", "", "Destination URL to send audit results.")
auditCmd.PersistentFlags().StringVar(&auditOutputFile, "output-file", "", "Destination file for audit results.")
auditCmd.PersistentFlags().StringVarP(&auditOutputFormat, "format", "f", "json", "Output format for results - json, yaml, or score.")
auditCmd.PersistentFlags().StringVarP(&auditOutputFormat, "format", "f", "json", "Output format for results - json, yaml, pretty, or score.")
auditCmd.PersistentFlags().BoolVar(&useColor, "color", true, "Whether to use color in pretty format.")
auditCmd.PersistentFlags().StringVar(&displayName, "display-name", "", "An optional identifier for the audit.")
auditCmd.PersistentFlags().StringVar(&resourceToAudit, "resource", "", "Audit a specific resource, in the format namespace/kind/version/name, e.g. nginx-ingress/Deployment.apps/v1/default-backend.")
auditCmd.PersistentFlags().StringVar(&helmChart, "helm-chart", "", "Will fill out Helm template")
auditCmd.PersistentFlags().StringVar(&helmValues, "helm-values", "", "Optional flag to add helm values")
}
var auditCmd = &cobra.Command{
@@ -60,8 +66,28 @@ var auditCmd = &cobra.Command{
if displayName != "" {
config.DisplayName = displayName
}
if helmChart != "" {
var err error
auditPath, err = ProcessHelmTemplates(helmChart, helmValues)
if err != nil {
logrus.Infof("Couldn't process helm chart: %v", err)
os.Exit(1)
}
}
auditData := runAndReportAudit(cmd.Context(), config, auditPath, resourceToAudit, auditOutputFile, auditOutputURL, auditOutputFormat)
k, err := kube.CreateResourceProvider(context.TODO(), auditPath, resourceToAudit, config)
if err != nil {
logrus.Errorf("Error fetching Kubernetes resources %v", err)
os.Exit(1)
}
auditData, err := validator.RunAudit(config, k)
if err != nil {
logrus.Errorf("Error while running audit on resources: %v", err)
os.Exit(1)
}
outputAudit(auditData, auditOutputFile, auditOutputURL, auditOutputFormat, useColor, onlyShowFailedTests)
summary := auditData.GetSummary()
score := summary.GetScore()
@@ -75,29 +101,55 @@ var auditCmd = &cobra.Command{
},
}
func runAndReportAudit(ctx context.Context, c conf.Configuration, auditPath, workload, outputFile, outputURL, outputFormat string) validator.AuditData {
// Create a kubernetes client resource provider
k, err := kube.CreateResourceProvider(ctx, auditPath, workload)
// ProcessHelmTemplates turns helm into yaml to be processed by Polaris or the other tools.
func ProcessHelmTemplates(helmChart, helmValues string) (string, error) {
cmd := exec.Command("helm", "dependency", "update", helmChart)
output, err := cmd.CombinedOutput()
if err != nil {
logrus.Errorf("Error fetching Kubernetes resources %v", err)
os.Exit(1)
}
var auditData validator.AuditData
auditData, err = validator.RunAudit(c, k, onlyShowFailedTests)
if err != nil {
logrus.Errorf("Error while running audit on resources: %v", err)
os.Exit(1)
logrus.Error(string(output))
return "", err
}
dir, err := ioutil.TempDir("", "*")
if err != nil {
return "", err
}
params := []string{
"template", helmChart,
helmChart,
"--output-dir",
dir,
}
if helmValues != "" {
params = append(params, "--values", helmValues)
}
cmd = exec.Command("helm", params...)
output, err = cmd.CombinedOutput()
if err != nil {
logrus.Error(string(output))
return "", err
}
return dir, nil
}
func outputAudit(auditData validator.AuditData, outputFile, outputURL, outputFormat string, useColor bool, onlyShowFailedTests bool) {
if onlyShowFailedTests {
auditData = auditData.RemoveSuccessfulResults()
}
var outputBytes []byte
var err error
if outputFormat == "score" {
outputBytes = []byte(fmt.Sprintf("%d\n", auditData.GetSummary().GetScore()))
} else if outputFormat == "yaml" {
jsonBytes, err := json.Marshal(auditData)
var jsonBytes []byte
jsonBytes, err = json.Marshal(auditData)
if err == nil {
outputBytes, err = yaml.JSONToYAML(jsonBytes)
}
} else if outputFormat == "pretty" {
outputBytes = []byte(auditData.GetPrettyOutput(useColor))
} else {
outputBytes, err = json.MarshalIndent(auditData, "", " ")
}
@@ -151,5 +203,4 @@ func runAndReportAudit(ctx context.Context, c conf.Configuration, auditPath, wor
}
}
}
return auditData
}
+7 -6
View File
@@ -25,7 +25,7 @@ import (
)
var configPath string
var disallowExemptions bool
var disallowExemptions, disallowConfigExemptions, disallowAnnotationExemptions bool
var logLevel string
var auditPath string
var displayName string
@@ -37,7 +37,9 @@ var (
func init() {
// Flags
rootCmd.PersistentFlags().StringVarP(&configPath, "config", "c", "", "Location of Polaris configuration file.")
rootCmd.PersistentFlags().BoolVarP(&disallowExemptions, "disallow-exemptions", "", false, "Disallow any exemptions from configuration file.")
rootCmd.PersistentFlags().BoolVarP(&disallowExemptions, "disallow-exemptions", "", false, "Disallow any configured exemption.")
rootCmd.PersistentFlags().BoolVarP(&disallowConfigExemptions, "disallow-config-exemptions", "", false, "Disallow exemptions set within the configuration file.")
rootCmd.PersistentFlags().BoolVarP(&disallowAnnotationExemptions, "disallow-annotation-exemptions", "", false, "Disallow any exemption defined as a controller annotation.")
rootCmd.PersistentFlags().StringVarP(&logLevel, "log-level", "", logrus.InfoLevel.String(), "Logrus log level.")
flag.Parse()
pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
@@ -63,10 +65,9 @@ var rootCmd = &cobra.Command{
os.Exit(1)
}
if disallowExemptions {
config.DisallowExemptions = true
}
config.DisallowExemptions = disallowExemptions
config.DisallowConfigExemptions = disallowConfigExemptions
config.DisallowAnnotationExemptions = disallowAnnotationExemptions
},
Run: func(cmd *cobra.Command, args []string) {
logrus.Error("You must specify a sub-command.")
-2
View File
@@ -1,2 +0,0 @@
coverage:
range: 50...80
+23
View File
@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
+6
View File
@@ -0,0 +1,6 @@
trailingComma: "es5"
tabWidth: 2
semi: true
singleQuote: true
jsxSingleQuote: false
parser: typescript
+46
View File
@@ -0,0 +1,46 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
+40056
View File
File diff suppressed because it is too large Load Diff
+51
View File
@@ -0,0 +1,51 @@
{
"name": "dashboard",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.15.0",
"@testing-library/react": "^11.2.7",
"@testing-library/user-event": "^12.8.3",
"@types/jest": "^26.0.24",
"@types/node": "^12.20.36",
"@types/react": "^17.0.34",
"@types/react-bootstrap": "^0.32.28",
"@types/react-dom": "^17.0.11",
"bootstrap": "^5.1.3",
"node-sass": "^6.0.1",
"react": "^17.0.2",
"react-bootstrap": "^2.0.1",
"react-dom": "^17.0.2",
"react-scripts": "4.0.3",
"typescript": "^4.4.4",
"web-vitals": "^1.1.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@axe-core/react": "^4.3.1",
"prettier": "^2.4.1"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 342 B

+37
View File
@@ -0,0 +1,37 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Validation of best practices in your Kubernetes clusters"
/>
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>Fairwinds Polaris</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
+3
View File
@@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:
+18
View File
@@ -0,0 +1,18 @@
@import "~bootstrap/scss/bootstrap.scss";
.App {
width: 100%;
height: 100%;
display: flex;
.app-content {
padding: 1rem;
width: 100%;
height: 100%;
}
#mainContainer {
width: 100%;
height: 100%;
}
}
+9
View File
@@ -0,0 +1,9 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});
+43
View File
@@ -0,0 +1,43 @@
import React, { useState, useEffect } from 'react';
import LeftNavBar from './components/Navigation/LeftBar/LeftNavBar';
import TopNavBar from './components/Navigation/TopBar/TopNavBar';
import './App.scss';
import data from './data.json';
function App() {
const [pageDisplay, setPageDisplay] = useState<string>('dashboard');
const [namespaces, setNamespaces] = useState<string[]>([]);
const [selectedNamespace, setSelectedNamespace] = useState<string>('');
useEffect(() => {
const allNamespaces: Set<string> = new Set();
data.Results.forEach((result) => {
allNamespaces.add(result.Namespace);
});
setNamespaces(Array.from(allNamespaces));
setSelectedNamespace('');
}, []);
return (
<div className="App">
<LeftNavBar />
<div id="mainContainer">
<TopNavBar
pageDisplay={pageDisplay}
setPageDisplay={setPageDisplay}
namespaces={namespaces}
setSelected={setSelectedNamespace}
/>
<main className="app-content">
{pageDisplay === 'dashboard' && <h1>Polaris Dashboard</h1>}
{pageDisplay === 'namespaces' && (
<h1>{selectedNamespace} Namespace</h1>
)}
</main>
</div>
</div>
);
}
export default App;
+5
View File
@@ -0,0 +1,5 @@
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M4.83333 4C4.61232 4 4.40036 4.08231 4.24408 4.22882C4.0878 4.37534 4 4.57405 4 4.78125C4 4.98845 4.0878 5.18716 4.24408 5.33368C4.40036 5.48019 4.61232 5.5625 4.83333 5.5625H14.8333C15.0543 5.5625 15.2663 5.48019 15.4226 5.33368C15.5789 5.18716 15.6667 4.98845 15.6667 4.78125C15.6667 4.57405 15.5789 4.37534 15.4226 4.22882C15.2663 4.08231 15.0543 4 14.8333 4H4.83333ZM4 7.90625C4 7.69905 4.0878 7.50034 4.24408 7.35382C4.40036 7.20731 4.61232 7.125 4.83333 7.125H14.8333C15.0543 7.125 15.2663 7.20731 15.4226 7.35382C15.5789 7.50034 15.6667 7.69905 15.6667 7.90625C15.6667 8.11345 15.5789 8.31216 15.4226 8.45868C15.2663 8.60519 15.0543 8.6875 14.8333 8.6875H4.83333C4.61232 8.6875 4.40036 8.60519 4.24408 8.45868C4.0878 8.31216 4 8.11345 4 7.90625ZM4.83333 10.25C4.61232 10.25 4.40036 10.3323 4.24408 10.4788C4.0878 10.6253 4 10.824 4 11.0312C4 11.2385 4.0878 11.4372 4.24408 11.5837C4.40036 11.7302 4.61232 11.8125 4.83333 11.8125H14.8333C15.0543 11.8125 15.2663 11.7302 15.4226 11.5837C15.5789 11.4372 15.6667 11.2385 15.6667 11.0312C15.6667 10.824 15.5789 10.6253 15.4226 10.4788C15.2663 10.3323 15.0543 10.25 14.8333 10.25H4.83333ZM4.83333 13.375C4.61232 13.375 4.40036 13.4573 4.24408 13.6038C4.0878 13.7503 4 13.949 4 14.1562C4 14.3635 4.0878 14.5622 4.24408 14.7087C4.40036 14.8552 4.61232 14.9375 4.83333 14.9375H9.83333C10.0543 14.9375 10.2663 14.8552 10.4226 14.7087C10.5789 14.5622 10.6667 14.3635 10.6667 14.1562C10.6667 13.949 10.5789 13.7503 10.4226 13.6038C10.2663 13.4573 10.0543 13.375 9.83333 13.375H4.83333Z" fill="white"/>
<path d="M0 2.5C0 1.83696 0.351189 1.20107 0.976311 0.732233C1.60143 0.263392 2.44928 0 3.33333 0L16.6667 0C17.5507 0 18.3986 0.263392 19.0237 0.732233C19.6488 1.20107 20 1.83696 20 2.5V17.5C20 18.163 19.6488 18.7989 19.0237 19.2678C18.3986 19.7366 17.5507 20 16.6667 20H3.33333C2.44928 20 1.60143 19.7366 0.976311 19.2678C0.351189 18.7989 0 18.163 0 17.5V2.5ZM16.6667 1.25H3.33333C2.89131 1.25 2.46738 1.3817 2.15482 1.61612C1.84226 1.85054 1.66667 2.16848 1.66667 2.5V17.5C1.66667 17.8315 1.84226 18.1495 2.15482 18.3839C2.46738 18.6183 2.89131 18.75 3.33333 18.75H16.6667C17.1087 18.75 17.5326 18.6183 17.8452 18.3839C18.1577 18.1495 18.3333 17.8315 18.3333 17.5V2.5C18.3333 2.16848 18.1577 1.85054 17.8452 1.61612C17.5326 1.3817 17.1087 1.25 16.6667 1.25Z" fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 2.4 KiB

+3
View File
@@ -0,0 +1,3 @@
<svg width="25" height="19" viewBox="0 0 25 19" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M25 3.125C25 2.2962 24.6708 1.50134 24.0847 0.915291C23.4987 0.32924 22.7038 0 21.875 0H3.125C2.2962 0 1.50134 0.32924 0.915293 0.915291C0.329241 1.50134 0 2.2962 0 3.125V15.625C0 16.4538 0.329241 17.2487 0.915293 17.8347C1.50134 18.4208 2.2962 18.75 3.125 18.75H21.875C22.7038 18.75 23.4987 18.4208 24.0847 17.8347C24.6708 17.2487 25 16.4538 25 15.625V3.125ZM21.875 1.5625C22.2894 1.5625 22.6868 1.72712 22.9799 2.02015C23.2729 2.31317 23.4375 2.7106 23.4375 3.125V3.46406L12.5 10.0266L1.5625 3.46406V3.125C1.5625 2.7106 1.72712 2.31317 2.02015 2.02015C2.31317 1.72712 2.7106 1.5625 3.125 1.5625H21.875ZM1.5625 5.28594L8.99688 9.74687L1.5625 14.2406V5.2875V5.28594ZM1.61563 16.0328L10.5141 10.6562L12.5 11.8484L14.4875 10.6562L23.3844 16.0312C23.295 16.3632 23.0987 16.6563 22.8258 16.8654C22.5529 17.0744 22.2187 17.1876 21.875 17.1875H3.125C2.78147 17.1877 2.44744 17.0747 2.17459 16.866C1.90174 16.6573 1.70529 16.3644 1.61563 16.0328ZM23.4375 14.2406L16.0031 9.74687L23.4375 5.28594V14.2391V14.2406Z" fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

+3
View File
@@ -0,0 +1,3 @@
<svg width="25" height="24" viewBox="0 0 25 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M12.5 0C5.59375 0 0 5.50583 0 12.3035C0 17.7478 3.57812 22.3463 8.54688 23.9765C9.17188 24.0842 9.40625 23.715 9.40625 23.3921C9.40625 23.0999 9.39062 22.131 9.39062 21.1005C6.25 21.6696 5.4375 20.347 5.1875 19.6549C5.04688 19.3012 4.4375 18.2092 3.90625 17.917C3.46875 17.6863 2.84375 17.1173 3.89062 17.1019C4.875 17.0865 5.57812 17.9939 5.8125 18.363C6.9375 20.2239 8.73438 19.701 9.45312 19.3781C9.5625 18.5783 9.89062 18.04 10.25 17.7325C7.46875 17.4249 4.5625 16.3637 4.5625 11.6576C4.5625 10.3196 5.04688 9.21227 5.84375 8.35102C5.71875 8.04343 5.28125 6.78232 5.96875 5.09058C5.96875 5.09058 7.01562 4.76762 9.40625 6.3517C10.4062 6.07487 11.4688 5.93645 12.5313 5.93645C13.5938 5.93645 14.6563 6.07487 15.6563 6.3517C18.0469 4.75224 19.0938 5.09058 19.0938 5.09058C19.7812 6.78232 19.3438 8.04343 19.2188 8.35102C20.0156 9.21227 20.5 10.3042 20.5 11.6576C20.5 16.3791 17.5781 17.4249 14.7969 17.7325C15.25 18.1169 15.6406 18.8552 15.6406 20.0086C15.6406 21.6542 15.625 22.9768 15.625 23.3921C15.625 23.715 15.8594 24.0995 16.4844 23.9765C18.966 23.1521 21.1224 21.5824 22.65 19.4884C24.1777 17.3944 24.9996 14.8815 25 12.3035C25 5.50583 19.4062 0 12.5 0Z" fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

@@ -0,0 +1,3 @@
<svg width="9" height="14" viewBox="0 0 9 14" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M0.755859 1.59702L7.77688 7.00555L0.755859 12.4141V1.59702ZM0.353294 12.7242C0.353419 12.7241 0.353541 12.724 0.353666 12.7239L0.353294 12.7242ZM8.03353 7.20326L8.03397 7.2036L8.18654 7.00555L8.03397 7.2036C8.03382 7.20349 8.03367 7.20337 8.03353 7.20326Z" stroke="white" stroke-width="1.5"/>
</svg>

After

Width:  |  Height:  |  Size: 403 B

+3
View File
@@ -0,0 +1,3 @@
<svg width="20" height="21" viewBox="0 0 20 21" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M7.66849 0L7.39526 2.46812C6.35771 2.81801 5.41199 3.37161 4.60838 4.08015L2.33151 3.07832L0 7.12204L1.99452 8.58833C1.89056 9.10843 1.83971 9.64966 1.83971 10.2004C1.83971 10.751 1.89059 11.2923 1.99452 11.8124L0 13.2787L2.33151 17.3224L4.60838 16.3206C5.41199 17.0291 6.35771 17.5827 7.39526 17.9326L7.66849 20.4007H12.3315L12.6047 17.9326C13.6423 17.5827 14.588 17.0291 15.3916 16.3206L17.6685 17.3224L20 13.2787L18.0055 11.8124C18.1094 11.2923 18.1603 10.751 18.1603 10.2004C18.1603 9.64966 18.1094 9.10843 18.0055 8.58833L20 7.12204L17.6685 3.07832L15.3916 4.08015C14.588 3.37161 13.6423 2.81801 12.6047 2.46812L12.3315 0H7.66849ZM10 5.2459C12.7363 5.2459 14.9545 7.46404 14.9545 10.2004C14.9545 12.9366 12.7363 15.1548 10 15.1548C7.26374 15.1548 5.04554 12.9366 5.04554 10.2004C5.04554 7.46404 7.26374 5.2459 10 5.2459Z" fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 954 B

+3
View File
@@ -0,0 +1,3 @@
<svg width="25" height="25" viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M5.25313 15.7969C5.25313 17.2437 4.07188 18.4234 2.62656 18.4234C1.18125 18.4234 0 17.2437 0 15.7984C0 14.3531 1.18125 13.1719 2.625 13.1719H5.25313V15.7969ZM6.575 15.7969C6.575 14.3531 7.75625 13.1719 9.20156 13.1719C10.6469 13.1719 11.8281 14.3531 11.8281 15.7969V22.375C11.8281 23.8188 10.6469 25 9.20312 25C8.50702 24.9988 7.83974 24.7219 7.34723 24.23C6.85472 23.7381 6.57706 23.0711 6.575 22.375V15.7969ZM9.20312 5.25313C7.75625 5.25313 6.575 4.07188 6.575 2.62656C6.575 1.18125 7.75625 0 9.20312 0C10.65 0 11.8281 1.18125 11.8281 2.625V5.25313H9.20312ZM9.20312 6.575C10.6469 6.575 11.8281 7.75625 11.8281 9.20156C11.8281 10.6469 10.6469 11.8281 9.20312 11.8281H2.625C1.18281 11.8281 0 10.6469 0 9.20312C0 7.75625 1.18125 6.575 2.625 6.575H9.20312ZM19.7484 9.20312C19.7484 7.75625 20.9281 6.575 22.3734 6.575C23.8188 6.575 25 7.75625 25 9.20156C25 10.6469 23.8188 11.8281 22.375 11.8281H19.7484V9.20312ZM18.4234 9.20312C18.4234 10.6469 17.2437 11.8281 15.7984 11.8281C15.1026 11.8265 14.4357 11.5494 13.9436 11.0576C13.4514 10.5657 13.1739 9.89895 13.1719 9.20312V2.625C13.1719 1.18281 14.3531 0 15.7969 0C17.2437 0 18.4234 1.18125 18.4234 2.625V9.20312ZM15.7969 19.7469C17.2437 19.7469 18.425 20.9281 18.425 22.3734C18.425 23.8188 17.2437 25 15.7969 25C14.35 25 13.1703 23.8188 13.1703 22.375V19.7469H15.7953H15.7969ZM15.7969 18.4234C14.3531 18.4234 13.1719 17.2437 13.1719 15.7984C13.1719 14.3531 14.3531 13.1719 15.7969 13.1719H22.375C23.8188 13.1719 25 14.3531 25 15.7969C25 17.2437 23.8188 18.4234 22.375 18.4234H15.7969Z" fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 1.6 KiB

+3
View File
@@ -0,0 +1,3 @@
<svg width="25" height="21" viewBox="0 0 25 21" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M7.85313 21C17.2875 21 22.4484 12.9187 22.4484 5.9228C22.4484 5.69666 22.4484 5.46729 22.4391 5.24115C23.4438 4.4892 24.311 3.55825 25 2.49191C24.0614 2.91972 23.0668 3.20168 22.0484 3.32863C23.1211 2.66578 23.9246 1.62283 24.3094 0.393637C23.3015 1.01088 22.1985 1.44418 21.0484 1.67457C20.2753 0.823345 19.2522 0.259434 18.1376 0.0701857C17.0231 -0.119063 15.8793 0.0769118 14.8833 0.627754C13.8874 1.1786 13.095 2.05356 12.6288 3.11713C12.1626 4.18069 12.0487 5.37349 12.3047 6.51077C10.2652 6.40505 8.27003 5.85733 6.4485 4.90314C4.62698 3.94894 3.01982 2.60957 1.73125 0.971914C1.07709 2.13991 0.877459 3.5215 1.17288 4.83614C1.46831 6.15077 2.23665 7.29989 3.32187 8.05015C2.50866 8.02159 1.71331 7.79584 1 7.39111V7.4638C1.0014 8.68736 1.41142 9.87289 2.16074 10.82C2.91006 11.7671 3.95273 12.4177 5.1125 12.6618C4.67229 12.7872 4.21755 12.8497 3.76094 12.8476C3.43904 12.8486 3.11778 12.8178 2.80156 12.7555C3.12935 13.8088 3.76761 14.7297 4.62695 15.3892C5.48628 16.0488 6.52365 16.4139 7.59375 16.4336C5.77587 17.9096 3.53031 18.7102 1.21875 18.7063C0.811439 18.7081 0.404411 18.6838 0 18.6336C2.34612 20.1799 5.07078 21.0009 7.85313 21Z" fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

@@ -0,0 +1,63 @@
.left-nav-bar {
display: flex;
flex-direction: column;
justify-content: space-between;
background-color: #23103a;
color: white;
height: 100vh;
padding: 1rem;
width: 250px;
min-width: 250px;
.top-div {
img {
width: 220px;
}
}
.bottom-div {
display: flex;
flex-direction: column;
flex-wrap: wrap;
gap: 1rem;
.links-title {
color: #eceeef;
font-size: 1rem;
font-weight: 300;
margin-bottom: 0;
}
.nav-link-section {
display: flex;
flex-direction: row;
flex-wrap: wrap;
align-items: center;
gap: 1rem;
text-decoration: none;
.link-name {
font-size: 1.2rem;
font-weight: 300;
margin-bottom: 0;
}
.docs {
color: white;
}
}
.external-links {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: space-between;
}
.feedback {
text-decoration: none;
color: white;
font-size: 1rem;
font-weight: 300;
}
}
}
@@ -0,0 +1,79 @@
import React from 'react';
// import Settings from '../../assets/icons/settings.svg';
import Docs from '../../../assets/icons/docs.svg';
import RightArrow from '../../../assets/icons/rightArrow.svg';
import Github from '../../../assets/icons/github.svg';
import Twitter from '../../../assets/icons/twitter.svg';
import Slack from '../../../assets/icons/slack.svg';
import Email from '../../../assets/icons/email.svg';
import PolarisLogo from '../../../assets/images/polaris-logo.png';
import './LeftNavBar.scss';
const LeftNavBar = (): JSX.Element => {
return (
<section className="left-nav-bar">
<div className="top-div">
<img src={PolarisLogo} alt="Polaris icon" />
</div>
<div className="bottom-div">
<h2 className="links-title">Application</h2>
{/* TODO: no settings in Polaris? */}
{/* <div className="nav-link-section">
<img src={Settings} alt='gear icon' />
<h3 className="link-name">Settings</h3>
</div> */}
<a
className="nav-link-section"
href="https://polaris.docs.fairwinds.com/"
target="_blank"
rel="noreferrer"
>
<img src={Docs} alt="doc icon" />
<h3 className="link-name docs">Docs</h3>
<img src={RightArrow} alt="arrow pointing right" />
</a>
<div className="external-links">
<a
href="https://github.com/FairwindsOps/polaris"
target="_blank"
rel="noreferrer"
>
<img src={Github} alt="github logo" />
</a>
<a
href="https://twitter.com/fairwindsops"
target="_blank"
rel="noreferrer"
>
<img src={Twitter} alt="twitter logo" />
</a>
<a
href="https://join.slack.com/t/fairwindscommunity/shared_invite/zt-e3c6vj4l-3lIH6dvKqzWII5fSSFDi1g"
target="_blank"
rel="noreferrer"
>
<img src={Slack} alt="slack logo" />
</a>
<a
href="https://www.fairwinds.com/fairwinds-newsletter"
target="_blank"
rel="noreferrer"
>
<img src={Email} alt="envelope for newsletter" />
</a>
</div>
<a
href="https://github.com/fairwindsops/polaris/issues"
target="_blank"
rel="noreferrer"
className="feedback"
>
Feedback
</a>
</div>
</section>
);
};
export default LeftNavBar;
@@ -0,0 +1,40 @@
.top-nav-bar {
z-index: 3;
background-color: white;
height: 3rem;
position: sticky;
top: 0;
padding-bottom: 0 !important;
.top-nav {
padding: 0 24px;
height: inherit;
align-content: end;
width: 100%;
.nav-item > .dropdown-menu {
max-height: 15rem;
overflow: auto;
}
.nav-item > .nav-link {
color: #495057;
&:hover,
&:focus {
border-color: transparent;
}
&.active {
border-color: #fff #fff;
margin-bottom: -2px;
border-bottom: 2px solid #445688;
color: #445688;
padding-bottom: 14px;
}
}
#nav-dropdown {
padding-left: 0;
}
}
}
@@ -0,0 +1,72 @@
import React, { SyntheticEvent, useState } from 'react';
import { Nav, Navbar, NavDropdown } from 'react-bootstrap';
import './TopNavBar.scss';
type NavProps = {
pageDisplay: string;
setPageDisplay: React.Dispatch<React.SetStateAction<string>>;
namespaces: string[];
setSelected: React.Dispatch<React.SetStateAction<string>>;
};
const TopNavBar = ({
pageDisplay,
setPageDisplay,
namespaces,
setSelected,
}: NavProps): JSX.Element => {
const [selectedNamespace, setSelectedNamespace] =
useState<string>('All Namespaces');
const handleNamespaceSelection = (
namespace: SyntheticEvent<HTMLDivElement, Event>
): void => {
if (namespace.toString() === 'All Namespaces') {
setSelectedNamespace('All Namespace');
} else if (namespace) {
setSelectedNamespace(namespace.toString());
}
setPageDisplay('namespaces');
setSelected(namespace.toString());
};
const NavItems = (): JSX.Element => (
<>
{namespaces.map((item) => {
return (
<NavDropdown.Item key={item} eventKey={item}>
{item}
</NavDropdown.Item>
);
})}
</>
);
return (
<header>
<Navbar className="top-nav-bar" expand={true}>
<Nav variant="tabs" className="top-nav">
<NavDropdown
title={selectedNamespace}
id="nav-dropdown"
active={pageDisplay === 'namespaces'}
onSelect={handleNamespaceSelection}
>
<NavDropdown.Item
key={'all-namespaces'}
eventKey={'all-namespaces'}
>
All Namespaces
</NavDropdown.Item>
<NavItems />
</NavDropdown>
<Nav.Item onClick={() => setPageDisplay('dashboard')}>
<Nav.Link active={pageDisplay === 'dashboard'}>Dashboard</Nav.Link>
</Nav.Item>
</Nav>
</Navbar>
</header>
);
};
export default TopNavBar;
File diff suppressed because one or more lines are too long
+13
View File
@@ -0,0 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
+22
View File
@@ -0,0 +1,22 @@
import React from 'react';
import ReactDOM from 'react-dom';
import './index.scss';
import App from './App';
import reportWebVitals from './reportWebVitals';
if (process.env.NODE_ENV !== 'production') {
const axe = require('@axe-core/react');
axe(React, ReactDOM, 1000);
}
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
+1
View File
@@ -0,0 +1 @@
/// <reference types="react-scripts" />
+15
View File
@@ -0,0 +1,15 @@
import { ReportHandler } from 'web-vitals';
const reportWebVitals = (onPerfEntry?: ReportHandler) => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;
+5
View File
@@ -0,0 +1,5 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';
+26
View File
@@ -0,0 +1,26 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
]
}
+11 -1
View File
@@ -31,6 +31,14 @@ rules:
verbs:
- 'get'
- 'list'
- apiGroups:
- 'monitoring.coreos.com'
resources:
- 'prometheuses'
- 'alertmanagers'
verbs:
- 'get'
- 'list'
---
# Source: polaris/templates/rbac.yaml
apiVersion: rbac.authorization.k8s.io/v1
@@ -109,7 +117,9 @@ spec:
- command:
- polaris
- dashboard
image: 'quay.io/fairwinds/polaris:3.1'
- --port
- "8080"
image: 'quay.io/fairwinds/polaris:4.2'
imagePullPolicy: 'Always'
name: dashboard
ports:
+9 -1
View File
@@ -31,6 +31,14 @@ rules:
verbs:
- 'get'
- 'list'
- apiGroups:
- 'monitoring.coreos.com'
resources:
- 'prometheuses'
- 'alertmanagers'
verbs:
- 'get'
- 'list'
---
# Source: polaris/templates/rbac.yaml
apiVersion: rbac.authorization.k8s.io/v1
@@ -109,7 +117,7 @@ spec:
command:
- polaris
- webhook
image: 'quay.io/fairwinds/polaris:3.1'
image: 'quay.io/fairwinds/polaris:4.2'
imagePullPolicy: 'Always'
ports:
- containerPort: 9876
+7
View File
@@ -33,6 +33,13 @@ module.exports = {
"/infrastructure-as-code",
],
},
{
title: "Usage",
collapsable: false,
children: [
"/cli",
],
},
{
title: "Customization",
collapsable: false,
+1 -1
View File
@@ -42,7 +42,7 @@ const baseConfig = {
],
themeConfig: {
docsRepo: "",
docsDir: 'docs-md',
docsDir: 'docs',
editLinks: true,
editLinkText: "Help us improve this page",
logo: '/img/fairwinds-logo.svg',
Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

+1 -1
View File
@@ -26,4 +26,4 @@ fbq('track', 'PageView');
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-K5KK5H3');
})(window,document,'script','dataLayer','GTM-TM95WXQ');
+7
View File
@@ -23,6 +23,13 @@
color: $successColor;
}
blockquote {
border-left: 0.2rem solid $warningColor;
}
blockquote p {
color: $warningColor;
}
.theme-default-content:not(.custom),
.page-nav,
.page-edit,
+5 -2
View File
@@ -3,7 +3,7 @@
<br>
<h3>Best Practices for Kubernetes Workload Configuration</h3>
<a href="https://github.com/FairwindsOps/polaris">
<img src="https://img.shields.io/static/v1.svg?label=Version&message=3.0.0&color=239922">
<img src="https://img.shields.io/static/v1.svg?label=Version&message=3.1.6&color=239922">
</a>
<a href="https://goreportcard.com/report/github.com/FairwindsOps/polaris">
<img src="https://goreportcard.com/badge/github.com/FairwindsOps/polaris">
@@ -11,11 +11,14 @@
<a href="https://circleci.com/gh/FairwindsOps/polaris.svg">
<img src="https://circleci.com/gh/FairwindsOps/polaris.svg?style=svg">
</a>
<a href="https://insights.fairwinds.com/gh/FairwindsOps/polaris">
<img src="https://insights.fairwinds.com/v0/gh/FairwindsOps/polaris/badge.svg">
</a>
</div>
Fairwinds' Polaris keeps your clusters sailing smoothly. It runs a variety of checks to ensure that
Kubernetes pods and controllers are configured using best practices, helping you avoid
problems in the future. Polaris can be run in a few different modes:
problems in the future.
Polaris can be run in three different modes:
* As a [dashboard](/dashboard), so you can audit what's running inside your cluster.
+6 -1
View File
@@ -1,3 +1,8 @@
---
meta:
- name: description
content: "Fairwinds Polaris | Documentation: Polaris can be run as an admission controller that acts as a validating webhook."
---
# Admission Controller
> Want to manage the Admission Controller across multiple clusters? Check out
> [Fairwinds Insights](https://www.fairwinds.com/fairwinds-polaris-upgrade)
@@ -28,7 +33,7 @@ kubectl apply -f https://github.com/fairwindsops/polaris/releases/latest/downloa
### Helm
```bash
helm repo add fairwinds-stable https://charts.fairwinds.com/stable
helm upgrade --install polaris fairwinds-stable/polaris --namespace polaris \
helm upgrade --install polaris fairwinds-stable/polaris --namespace polaris --create-namespace \
--set webhook.enable=true --set dashboard.enable=false
```
+57
View File
@@ -1,7 +1,64 @@
---
sidebarDepth: 0
meta:
- name: description
content: "Fairwinds Polaris | Changelog"
---
## 4.2.0
* New flags `--disallow-(config|annotation)-exemptions`
* Kubernetes dependency updates
* Documentation updates
## 4.1.0
* Handle case-insentitivity in capabilities checks
* Change test for PDB disruptions to better handle IaC
## 4.0.9
* Update Alpine base image
## 4.0.8
* Fix support for namespace checks
## 4.0.7
* Fix goreleaser format
## 4.0.6
* Change goreleaser format
* Fix `--helm-values` flag
## 4.0.5
* Bugfix for repeated objects on the dashboard
## 4.0.4
* Bugfix for validating webhook and non-pod checks
## 4.0.3
* Fixed bad interaction between `--set-exit-score-below` and `--only-show-failed-tests`
* Dependency updates
* Support for Helm chart scanning
## 4.0.2
* Goreleaser fix
## 4.0.1
* Goreleaser fix
## 4.0.0
* Add support for arbitrary resources, like Ingress or PodDisruptionBudget
* Add support check templating (see docs)
* Add support for multi-resource checks (see docs)
### Breaking Changes
* In custom checks, `jsonSchema` is now `schemaString`
* Check `pdbDisruptionsAllowedGreaterThanZero` is now called `pdbDisruptionsIsZero`
## 3.2.0
* Add `--format=pretty` option for CLI output
## 3.1.6
* Fix nil pointer issue with --only-output-failed-tests
## 3.1.5
* Fix UI display of Ingress checks
+5
View File
@@ -1,3 +1,8 @@
---
meta:
- name: description
content: "Fairwinds Polaris | Ensure that CPU and memory settings are configured, so that Kubernetes can schedule your workload effectively"
---
# Efficiency
These checks ensure that CPU and memory settings are configured, so that
+6
View File
@@ -1,3 +1,8 @@
---
meta:
- name: description
content: "Fairwinds Polaris | Make sure your Kubernetes workloads are always available, and are running the correct image."
---
# Reliability
These checks help to make sure your workloads are always available,
@@ -11,6 +16,7 @@ key | default | description
`pullPolicyNotAlways` | `warning` | Fails when an image pull policy is not `always`.
`priorityClassNotSet` | `ignore` | Fails when a priorityClassName is not set for a pod.
`multipleReplicasForDeployment` | `ignore` | Fails when there is only one replica for a deployment.
`missingPodDisruptionBudget` | `ignore`
## Background
+5
View File
@@ -1,3 +1,8 @@
---
meta:
- name: description
content: "Fairwinds Polaris | Security Checks Documentation"
---
# Security
These checks are related to security concerns. Workloads that fail these
+58
View File
@@ -0,0 +1,58 @@
---
meta:
- name: description
content: "Fairwinds Polaris | Learn your CLI options"
---
#### CLI Options
```
# top-level commands
audit
Runs a one-time audit.
dashboard
Runs the webserver for Polaris dashboard.
help
Prints help, if you give it a command then it will print help for that command. Same as -h
version
Prints the version of Polaris
webhook
Runs the webhook webserver
# global flags
-c, --config string Location of Polaris configuration file.
--disallow-exemptions Disallow any exemptions from configuration file.
--disallow-config-exemptions Disallow exemptions set within the configuration file.
--disallow-annotation-exemptions Disallow any exemption defined as a controller annotation.
--kubeconfig string Paths to a kubeconfig. Only required if out-of-cluster.
--log-level string Logrus log level. (default "info")
# dashboard flags
--audit-path string If specified, audits one or more YAML files instead of a cluster.
--base-path string Path on which the dashboard is served. (default "/")
--display-name string An optional identifier for the audit.
-h, --help help for dashboard
--listening-address string Listening Address for the dashboard webserver.
--load-audit-file string Runs the dashboard with data saved from a past audit.
-p, --port int Port for the dashboard webserver. (default 8080)
# audit flags
--audit-path string If specified, audits one or more YAML files instead of a cluster.
--color Whether to use color in pretty format. (default true)
--display-name string An optional identifier for the audit.
-f, --format string Output format for results - json, yaml, pretty, or score. (default "json")
--helm-chart string Will fill out Helm template
--helm-values string Optional flag to add helm values
-h, --help help for audit
--only-show-failed-tests If specified, audit output will only show failed tests.
--output-file string Destination file for audit results.
--output-url string Destination URL to send audit results.
--resource string Audit a specific resource, in the format namespace/kind/version/name, e.g. nginx-ingress/Deployment.apps/v1/default-backend.
--set-exit-code-below-score int Set an exit code of 4 when the score is below this threshold (1-100).
--set-exit-code-on-danger Set an exit code of 3 when the audit contains danger-level issues.
# webhook flags
--disable-webhook-config-installer disable the installer in the webhook server, so it won't install webhook configuration resources during bootstrapping.
-h, --help help for webhook
-p, --port int Port for the dashboard webserver. (default 9876)
```
-66
View File
@@ -1,66 +0,0 @@
#### CLI Options
```
# top-level commands
audit
Runs a one-time audit.
dashboard
Runs the webserver for Polaris dashboard.
help
Prints help, if you give it a command then it will print help for that command. Same as -h
version
Prints the version of Polaris
webhook
Runs the webhook webserver
# high-level flags
-c, --config string
Location of Polaris configuration file
--disallow-exemptions
Disallow any exemptions from configuration file.
-h, --help
Help for Polaris (same as help command)
--kubeconfig string
Path to a kubeconfig. Only required if out-of-cluster.
--log-level string
Logrus log level (default "info")
--master string
The address of the Kubernetes API server. Overrides any value in kubeconfig. Only required if out-of-cluster.
# dashboard flags
--audit-path string
If specified, audits one or more YAML files instead of a cluster
--base-path string
Path on which the dashboard is served (default "/")
--display-name string
An optional identifier for the audit
--load-audit-file string
Runs the dashboard with data saved from a past audit.
-p, --port int
Port for the dashboard webserver (default 8080)
# audit flags
--audit-path string
If specified, audits one or more YAML files instead of a cluster
--resource string
If specified, audit a specific resource, in the format namespace/kind/version/name, e.g. nginx-ingress/Deployment.apps/v1/default-backend
--display-name string
An optional identifier for the audit
--format string
Output format for results - json, yaml, or score (default "json")
--output-file string
Destination file for audit results
--output-url string
Destination URL to send audit results
--set-exit-code-below-score int
Set an exit code of 4 when the score is below this threshold (1-100)
--set-exit-code-on-danger
Set an exit code of 3 when the audit contains danger-level issues.
# webhook flags
--disable-webhook-config-installer
disable the installer in the webhook server, so it won't install webhook configuration resources during bootstrapping
-p, --port int
Port for the webhook webserver (default 9876)
```
+5
View File
@@ -1,3 +1,8 @@
---
meta:
- name: description
content: "Fairwinds Polaris | Contribution Code of Conduct"
---
# Code of Conduct
## Our Pledge
+5
View File
@@ -1,3 +1,8 @@
---
meta:
- name: description
content: "Fairwinds Polaris | Contribution Guidelines"
---
# Contributing
Issues, whether bugs, tasks, or feature requests are essential for keeping Polaris great. We believe it should be as easy as possible to contribute changes that get things working in your environment. There are a few guidelines that we need contributors to follow so that we can keep on top of things.
+5
View File
@@ -1,3 +1,8 @@
---
meta:
- name: description
content: "Fairwinds Polaris | Documentation on setting checks by severity "
---
# Check Settings
Each check can be assigned a `severity`. Only checks with a severity of `danger` or `warning` will be validated. The results of these validations are visible on the dashboard. In the case of the validating webhook, only failures with a severity of `danger` will result in a change being rejected.
+5
View File
@@ -1,3 +1,8 @@
---
meta:
- name: description
content: "Fairwinds Polaris | Learn about Polaris defaults and how to customize configurations. "
---
# Configuration
The default Polaris configuration can be [seen here](https://github.com/FairwindsOps/polaris/blob/master/examples/config.yaml).
+192 -9
View File
@@ -1,16 +1,29 @@
---
meta:
- name: description
content: "Fairwinds Polaris | Documentation: Create your own checks, you can use JSON Schema"
---
# Custom Checks
If you'd like to create your own checks, you can use [JSON Schema](https://json-schema.org/). For example,
to disallow images from quay.io:
If you'd like to create your own checks, you can use [JSON Schema](https://json-schema.org/).
This is how built-in Polaris checks are defined as well - you can see all the built-in checks
in the [checks folder](https://github.com/FairwindsOps/polaris/tree/master/checks) for examples.
If you write a check that could be useful for others, feel free to open a PR to add it in!
## Basic Example
For example, to disallow images from quay.io:
```yaml
checks:
imageRegistry: warning
customChecks:
imageRegistry:
successMessage: Image comes from allowed registries
failureMessage: Image should not be from disallowed registry
category: Images
target: Container # target can be "Container" or "Pod"
category: Security
target: Container
schema:
'$schema': http://json-schema.org/draft-07/schema
type: object
@@ -21,6 +34,181 @@ customChecks:
pattern: ^quay.io
```
## Available Options
All custom checks should go under the `customChecks` field in your Polaris config, keyed by the
check ID. Note that you'll also have to set its severity in the `checks` section of your Polaris config.
* `successMessage` - the message to show when the check succeeds
* `failureMessage` - the message to show when the check fails
* `category` - one of `Security`, `Efficiency`, or `Reliability`
* `target` - specifies the type of resource to check. This can be:
* a group and kind, e.g. `apps/Deployment` or `networking.k8s.io/Ingress`
* `Controller`, to check _any_ resource that contains a pod spec (e.g. Deployments, CronJobs, StatefulSets), as well as naked Pods
* `Pod`, same as `Controller`, but the schema applies to the Pod spec rather than the top-level controller
* `Container` same as `Controller`, but the schema applies to all Container specs rather than the top-level controller
* `controllers` - if `target` is `Controller`, `Pod` or `Container`, you can use this to change which types of controllers are checked
* `controllers.include` - _only_ check these controllers
* `controllers.exclude` - check all controllers except these
* `containers` - if `target` is `Container`, you can use this to decide if `initContainers`, `containers`, or both should be checked
* `containers.exclude` - can be set to a list including `initContainer` or `container`
* `schema` - the JSON Schema to check against, as a YAML object
* `schemaString` - this JSON Schema to check against, as a YAML or JSON string. See [Templating](#templating) below
* Note: only _one_ of `schema` and `schemaString` can be specified.
* `additionalSchemas` - see [Multi-Resource Checks](#multi-resource-checks) below
* `additionalSchemaStrings` - see [Multi-Resource Checks](#multi-resource-checks) below
* Note: only _one_ of `additionalSchemas` and `additionalSchemaStrings` can be specified.
## Checking CPU and Memory
We extend JSON Schema with `resourceMinimum` and `resourceMaximum` fields to help compare memory and CPU resource
strings like `1000m` and `1G`. Here's an example check that memory and CPU falls within a certain range.
```yaml
customChecks:
resourceLimits:
containers:
exclude:
- initContainer
successMessage: Resource limits are within the required range
failureMessage: Resource limits should be within the required range
category: Resources
target: Container
schema:
'$schema': http://json-schema.org/draft-07/schema
type: object
required:
- resources
properties:
resources:
type: object
required:
- limits
properties:
limits:
type: object
required:
- memory
- cpu
properties:
memory:
type: string
resourceMinimum: 100M
resourceMaximum: 6G
cpu:
type: string
resourceMinimum: 100m
resourceMaximum: "2"
```
## Resource Presence
You can test for the presence of a resource in each Namespace. For example, to
ensure an AlertmanagerConfig is in every Namespace:
```yaml
successMessage: Namespace has monitoring configuration
failureMessage: Namespace should have monitoring configuration
category: Security
target: Namespace
schema: {}
additionalSchemas:
monitoring.coreos.com/AlertmanagerConfig: {}
```
## Templating
You can also utilize go templating in your JSON schema in order to match one field against another.
E.g. here is the built-in check to ensure that the `name` annotation matches the object's name:
```yaml
successMessage: Label app.kubernetes.io/name matches metadata.name
failureMessage: Label app.kubernetes.io/name must match metadata.name
target: Controller
schema:
'$schema': http://json-schema.org/draft-07/schema
type: object
properties:
metadata:
type: object
required: ["labels"]
properties:
labels:
type: object
required: ["app.kubernetes.io/name"]
properties:
app.kubernetes.io/name:
const: "{{ .metadata.name }}"
```
You can also use the full [Go template syntax](https://golang.org/pkg/text/template/), though
you may need to specify your schema as a string in order to use concepts like `range`. E.g.
this check ensures that at least one of the object's labels is present in `matchLabels`:
```yaml
schemaString: |
type: object
properties:
spec:
type: object
required: ["selector"]
properties:
selector:
type: object
required: ["matchLabels"]
properties:
matchLabels:
type: object
anyOf:
{{ range $key, $value := .metadata.labels }}
- properties:
"{{ $key }}":
type: string
const: {{ $value }}
required: ["{{ $key }}"]
{{ end }}
```
## Multi-Resource Checks
You can write checks that span multiple resources. This is helpful for ensuring e.g.
that every Deployment has a PDB or an HPA associated with it.
Here's the check to ensure that every Deployment has a PDB:
```yaml
successMessage: A PodDisruptionBudget is attached
failureMessage: Should have a PodDisruptionBudget
category: Reliability
target: Controller
controllers:
include:
- Deployment
schema:
'$schema': http://json-schema.org/draft-07/schema
type: object
properties:
metadata:
type: object
properties:
labels:
type: object
minProperties: 1
additionalSchemaStrings:
policy/PodDisruptionBudget: |
type: object
properties:
spec:
type: object
required: ["selector"]
properties:
selector:
type: object
required: ["matchLabels"]
properties:
matchLabels:
type: object
anyOf:
{{ range $key, $value := .metadata.labels }}
- properties:
"{{ $key }}":
type: string
const: {{ $value }}
required: ["{{ $key }}"]
{{ end }}
```
## JSON vs YAML
Schemas can also be specified as JSON strings instead of YAML, for easier copy/pasting:
```yaml
customChecks:
@@ -32,8 +220,3 @@ customChecks:
}
```
We extend JSON Schema with `resourceMinimum` and `resourceMaximum` fields to help compare memory and CPU resource
strings like `1000m` and `1G`. You can see an example in [the extended config](https://github.com/FairwindsOps/polaris/tree/master/examples/config-full.yaml)
There are additional examples in the [checks folder](https://github.com/FairwindsOps/polaris/tree/master/checks).
+5
View File
@@ -1,3 +1,8 @@
---
meta:
- name: description
content: "Fairwinds Polaris | Exemptions"
---
# Exemptions
Sometimes a workload really does need to do things that Polaris considers insecure. For instance,
many of the `kube-system` workloads need to run as root, or need access to the host network. In these
+6 -1
View File
@@ -1,3 +1,8 @@
---
meta:
- name: description
content: "Fairwinds Polaris | Ways to run Polaris | The Polaris dashboard can be installed on a cluster using kubectl or Helm"
---
# Dashboard
> Want to see Polaris results for all your clusters in a single dashboard? Check out
@@ -19,7 +24,7 @@ kubectl port-forward --namespace polaris svc/polaris-dashboard 8080:80
### Helm
```bash
helm repo add fairwinds-stable https://charts.fairwinds.com/stable
helm upgrade --install polaris fairwinds-stable/polaris --namespace polaris
helm upgrade --install polaris fairwinds-stable/polaris --namespace polaris --create-namespace
kubectl port-forward --namespace polaris svc/polaris-dashboard 8080:80
```
+34 -5
View File
@@ -1,3 +1,8 @@
---
meta:
- name: description
content: "Fairwinds Polaris | Documentation | Polaris can be used on the command line to audit local Kubernetes manifests stored in YAML files."
---
# Infrastructure as Code
> Want to see results for all your IaC repos in one place? Check out
> [Fairwinds Insights](https://www.fairwinds.com/fairwinds-polaris-upgrade)
@@ -22,7 +27,7 @@ polaris version
## Running in a CI pipeline
### Set minimum score for an exit code
### Set minimum score for an exit code
You can tell the CLI to set an exit code if it detects certain issues with your YAML files.
For example, to fail if polaris detects *any* danger-level issues, or if the score drops below 90%:
```bash
@@ -31,6 +36,22 @@ polaris audit --audit-path ./deploy/ \
--set-exit-code-below-score 90
```
### Pretty-print results
By default, results are output as JSON. You can get human-readable output with
the `--format=pretty` flag:
```bash
polaris audit --audit-path ./deploy/ \
--format=pretty
```
You can also disable colors and emoji:
```bash
polaris audit --audit-path ./deploy/ \
--format=pretty \
--color=false
```
### Output only showing failed tests
The CLI to gives you ability to display results containing only failed tests.
For example:
@@ -39,6 +60,14 @@ polaris audit --audit-path ./deploy/ \
--only-show-failed-tests true
```
### Audit Helm Charts
You can audit helm charts using the `--helm-chart` and `--helm-values` flags:
```
polaris audit \
--helm-chart ./deploy/chart \
--helm-values ./deploy/chart/values.yml
```
### As Github Action
#### Setup polaris action
@@ -59,9 +88,9 @@ The version number of the release tag.
##### Example usage
```yaml
uses: fairwindsops/polaris@master
uses: fairwindsops/polaris/.github/actions/setup-polaris@master
with:
version: "3.0.3"
version: 4.2.0
```
Example inside a job:
@@ -70,9 +99,9 @@ Example inside a job:
steps:
- uses: actions/checkout@v2
- name: Setup polaris
uses: fairwindsops/polaris@master
uses: fairwindsops/polaris/.github/actions/setup-polaris@master
with:
version: 3.0.3
version: 4.2.0
- name: Use command
run: polaris version
+5
View File
@@ -0,0 +1,5 @@
---
meta:
- name: description
content: "Fairwinds Polaris | Documentation"
---
+16613 -1853
View File
File diff suppressed because it is too large Load Diff
+4
View File
@@ -6,6 +6,10 @@ checks:
pullPolicyNotAlways: warning
readinessProbeMissing: warning
livenessProbeMissing: warning
metadataAndNameMismatched: ignore
pdbDisruptionsIsZero: warning
missingPodDisruptionBudget: ignore
# efficiency
cpuRequestsMissing: warning
cpuLimitsMissing: warning
+11 -23
View File
@@ -1,37 +1,25 @@
module github.com/fairwindsops/polaris
go 1.13
go 1.15
require (
cloud.google.com/go v0.74.0 // indirect
github.com/Azure/go-autorest/autorest v0.11.15 // indirect
github.com/Azure/go-autorest/autorest/adal v0.9.10 // indirect
github.com/fatih/color v1.13.0
github.com/gobuffalo/packr/v2 v2.8.1
github.com/google/gofuzz v1.2.0 // indirect
github.com/google/uuid v1.1.3 // indirect
github.com/googleapis/gnostic v0.5.3 // indirect
github.com/gorilla/mux v1.8.0
github.com/imdario/mergo v0.3.11 // indirect
github.com/karrick/godirwalk v1.16.1 // indirect
github.com/kr/pretty v0.2.1 // indirect
github.com/prometheus/client_golang v1.9.0 // indirect
github.com/qri-io/jsonschema v0.1.1
github.com/rogpeppe/go-internal v1.6.2 // indirect
github.com/sirupsen/logrus v1.8.0
github.com/spf13/cobra v1.1.3
github.com/sirupsen/logrus v1.8.1
github.com/spf13/cobra v1.2.1
github.com/spf13/pflag v1.0.5
github.com/stretchr/testify v1.7.0
go.uber.org/zap v1.16.0 // indirect
golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad // indirect
golang.org/x/net v0.0.0-20201224014010-6772e930b67b // indirect
golang.org/x/sys v0.0.0-20201231184435-2d18734c6014 // indirect
golang.org/x/term v0.0.0-20201210144234-2321bbc49cbf // indirect
golang.org/x/time v0.0.0-20201208040808-7e3f01d25324 // indirect
gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776
k8s.io/api v0.20.4
k8s.io/apimachinery v0.20.4
k8s.io/client-go v0.20.2
k8s.io/component-base v0.20.1 // indirect
sigs.k8s.io/controller-runtime v0.7.0
sigs.k8s.io/yaml v1.2.0
github.com/thoas/go-funk v0.9.1
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b
k8s.io/api v0.22.2
k8s.io/apimachinery v0.22.2
k8s.io/client-go v0.22.2
sigs.k8s.io/controller-runtime v0.10.1
sigs.k8s.io/yaml v1.3.0
)
+264 -389
View File
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -15,12 +15,12 @@
package main
import (
"github.com/fairwindsops/polaris/cmd/polaris"
cmd "github.com/fairwindsops/polaris/cmd/polaris"
)
const (
// Version represents the current release version of Polaris
Version = "3.1.5"
Version = "4.2.0"
)
func main() {
+60
View File
@@ -0,0 +1,60 @@
package config
import (
"github.com/gobuffalo/packr/v2"
"github.com/sirupsen/logrus"
)
var (
// BuiltInChecks contains the checks that come pre-installed w/ Polaris
BuiltInChecks = map[string]SchemaCheck{}
schemaBox = (*packr.Box)(nil)
// We explicitly set the order to avoid thrash in the
// tests as we migrate toward JSON schema
checkOrder = []string{
// Controller Checks
"multipleReplicasForDeployment",
// Pod checks
"hostIPCSet",
"hostPIDSet",
"hostNetworkSet",
// Container checks
"memoryLimitsMissing",
"memoryRequestsMissing",
"cpuLimitsMissing",
"cpuRequestsMissing",
"readinessProbeMissing",
"livenessProbeMissing",
"pullPolicyNotAlways",
"tagNotSpecified",
"hostPortSet",
"runAsRootAllowed",
"runAsPrivileged",
"notReadOnlyRootFilesystem",
"privilegeEscalationAllowed",
"dangerousCapabilities",
"insecureCapabilities",
"priorityClassNotSet",
// Other checks
"tlsSettingsMissing",
"pdbDisruptionsIsZero",
"metadataAndNameMismatched",
"missingPodDisruptionBudget",
}
)
func init() {
schemaBox = packr.New("Schemas", "../../checks")
for _, checkID := range checkOrder {
contents, err := schemaBox.Find(checkID + ".yaml")
if err != nil {
panic(err)
}
check, err := ParseCheck(checkID, contents)
if err != nil {
logrus.Errorf("Error while parsing check %s", checkID)
panic(err)
}
BuiltInChecks[checkID] = check
}
}
+7 -5
View File
@@ -29,11 +29,13 @@ import (
// Configuration contains all of the config for the validation checks.
type Configuration struct {
DisplayName string `json:"displayName"`
Checks map[string]Severity `json:"checks"`
CustomChecks map[string]SchemaCheck `json:"customChecks"`
Exemptions []Exemption `json:"exemptions"`
DisallowExemptions bool `json:"disallowExemptions"`
DisplayName string `json:"displayName"`
Checks map[string]Severity `json:"checks"`
CustomChecks map[string]SchemaCheck `json:"customChecks"`
Exemptions []Exemption `json:"exemptions"`
DisallowExemptions bool `json:"disallowExemptions"`
DisallowConfigExemptions bool `json:"disallowConfigExemptions"`
DisallowAnnotationExemptions bool `json:"disallowAnnotationExemptions"`
}
// Exemption represents an exemption to normal rules
+12 -6
View File
@@ -16,6 +16,7 @@ package config
import (
"context"
"fmt"
"io"
"log"
"net/http"
@@ -142,7 +143,9 @@ func TestConfigNoServerError(t *testing.T) {
func TestConfigWithCustomChecks(t *testing.T) {
valid := map[string]interface{}{
"securityContext": map[string]interface{}{},
"securityContext": map[string]interface{}{
"foo": "bar",
},
}
invalid := map[string]interface{}{
"notSecurityContext": map[string]interface{}{},
@@ -151,20 +154,23 @@ func TestConfigWithCustomChecks(t *testing.T) {
parsedConf, err := Parse([]byte(confCustomChecks))
assert.NoError(t, err, "Expected no error when parsing YAML config")
assert.Equal(t, 1, len(parsedConf.CustomChecks))
isValid, err := parsedConf.CustomChecks["foo"].CheckObject(valid)
check, err := parsedConf.CustomChecks["foo"].TemplateForResource(map[string]interface{}{})
isValid, _, err := check.CheckObject(valid)
assert.NoError(t, err)
assert.Equal(t, true, isValid)
isValid, err = parsedConf.CustomChecks["foo"].CheckObject(invalid)
isValid, _, err = check.CheckObject(invalid)
assert.NoError(t, err)
assert.Equal(t, false, isValid)
parsedConf, err = Parse([]byte(confCustomChecksWithJSONSchema))
assert.NoError(t, err, "Expected no error when parsing YAML config")
assert.Equal(t, 1, len(parsedConf.CustomChecks))
isValid, err = parsedConf.CustomChecks["foo"].CheckObject(valid)
isValid, problems, err := parsedConf.CustomChecks["foo"].CheckObject(valid)
assert.NoError(t, err)
assert.Equal(t, true, isValid)
isValid, err = parsedConf.CustomChecks["foo"].CheckObject(invalid)
if !assert.Equal(t, true, isValid) {
fmt.Println(problems[0].PropertyPath, problems[0].InvalidValue, problems[0].Message)
}
isValid, _, err = check.CheckObject(invalid)
assert.NoError(t, err)
assert.Equal(t, false, isValid)
}
+6 -4
View File
@@ -2,18 +2,20 @@ package config
import (
"strings"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// IsActionable determines whether a check is actionable given the current configuration
func (conf Configuration) IsActionable(ruleID, namespace, controllerName, containerName string) bool {
func (conf Configuration) IsActionable(ruleID string, objMeta metav1.Object, containerName string) bool {
if severity, ok := conf.Checks[ruleID]; !ok || !severity.IsActionable() {
return false
}
if conf.DisallowExemptions {
if conf.DisallowExemptions || conf.DisallowConfigExemptions {
return true
}
for _, exemption := range conf.Exemptions {
if exemption.Namespace != "" && exemption.Namespace != namespace {
if exemption.Namespace != "" && exemption.Namespace != objMeta.GetNamespace() {
continue
}
@@ -27,7 +29,7 @@ func (conf Configuration) IsActionable(ruleID, namespace, controllerName, contai
}
if len(exemption.Rules) == 0 || checkIfRuleMatches {
if !isExemptionCheckMatched(exemption.ControllerNames, controllerName) {
if !isExemptionCheckMatched(exemption.ControllerNames, objMeta.GetName()) {
continue
}
if isExemptionCheckMatched(exemption.ContainerNames, containerName) {
+63 -49
View File
@@ -18,6 +18,9 @@ import (
"testing"
"github.com/stretchr/testify/assert"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
)
var confContainerTest = `
@@ -68,26 +71,37 @@ exemptions:
- namespace: polaris
`
func createMeta(namespace, name string) metav1.Object {
unst := unstructured.Unstructured{}
obj, err := meta.Accessor(&unst)
if err != nil {
panic(err)
}
obj.SetName(name)
obj.SetNamespace(namespace)
return obj
}
func TestNamespaceExemptionForSpecifiedRules(t *testing.T) {
parsedConf, err := Parse([]byte(confContainerTest))
assert.NoError(t, err)
actionable := parsedConf.IsActionable("multipleReplicasForDeployment", "prometheus", "", "")
actionable := parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("prometheus", ""), "")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "prometheus", "controller1", "container11")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("prometheus", "controller1"), "container11")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "prometheus", "", "container11")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("prometheus", ""), "container11")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "prometheus", "controller1", "")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("prometheus", "controller1"), "")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("pullPolicyNotAlways", "prometheus", "controller1", "")
actionable = parsedConf.IsActionable("pullPolicyNotAlways", createMeta("prometheus", "controller1"), "")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "kube-system", "", "")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", ""), "")
assert.True(t, actionable)
}
@@ -95,19 +109,19 @@ func TestNamespaceExemptionForAllRules(t *testing.T) {
parsedConf, err := Parse([]byte(confContainerTest))
assert.NoError(t, err)
actionable := parsedConf.IsActionable("multipleReplicasForDeployment", "polaris", "", "")
actionable := parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("polaris", ""), "")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "polaris", "controller1", "container11")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("polaris", "controller1"), "container11")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "polaris", "", "container11")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("polaris", ""), "container11")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "polaris", "controller1", "")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("polaris", "controller1"), "")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("pullPolicyNotAlways", "polaris", "controller1", "")
actionable = parsedConf.IsActionable("pullPolicyNotAlways", createMeta("polaris", "controller1"), "")
assert.False(t, actionable)
}
@@ -115,28 +129,28 @@ func TestControllerExemption(t *testing.T) {
parsedConf, err := Parse([]byte(confContainerTest))
assert.NoError(t, err)
actionable := parsedConf.IsActionable("multipleReplicasForDeployment", "", "controller2", "")
actionable := parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("", "controller2"), "")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "", "controller2", "container21")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("", "controller2"), "container21")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "prometheus", "controller2", "container21")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("prometheus", "controller2"), "container21")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "prometheus", "controller2", "")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("prometheus", "controller2"), "")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "", "controller3", "")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("", "controller3"), "")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "kube-system", "controller3", "")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", "controller3"), "")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "kube-system", "controller3", "container31")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", "controller3"), "container31")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "kube-system", "controller4", "")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", "controller4"), "")
assert.True(t, actionable)
}
@@ -144,22 +158,22 @@ func TestOnlyContainerExemption(t *testing.T) {
parsedConf, err := Parse([]byte(confContainerTest))
assert.NoError(t, err)
actionable := parsedConf.IsActionable("multipleReplicasForDeployment", "", "", "container41")
actionable := parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("", ""), "container41")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "", "", "container42")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("", ""), "container42")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "", "controller4", "container41")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("", "controller4"), "container41")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "kube-system", "", "container41")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", ""), "container41")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "kube-system", "controller4", "container41")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", "controller4"), "container41")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "", "", "container51")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("", ""), "container51")
assert.True(t, actionable)
}
@@ -167,25 +181,25 @@ func TestNamespaceAndContainerExemption(t *testing.T) {
parsedConf, err := Parse([]byte(confContainerTest))
assert.NoError(t, err)
actionable := parsedConf.IsActionable("multipleReplicasForDeployment", "kube-system", "", "container51")
actionable := parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", ""), "container51")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("priorityClassNotSet", "kube-system", "", "container51")
actionable = parsedConf.IsActionable("priorityClassNotSet", createMeta("kube-system", ""), "container51")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "kube-system", "controller5", "container51")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", "controller5"), "container51")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "kube-system", "controller5", "")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", "controller5"), "")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "insights-agent", "", "container51")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("insights-agent", ""), "container51")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "", "", "container51")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("", ""), "container51")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "", "controller5", "container51")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("", "controller5"), "container51")
assert.True(t, actionable)
}
@@ -193,25 +207,25 @@ func TestControllerAndContainerExemption(t *testing.T) {
parsedConf, err := Parse([]byte(confContainerTest))
assert.NoError(t, err)
actionable := parsedConf.IsActionable("multipleReplicasForDeployment", "", "controller6", "container61")
actionable := parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("", "controller6"), "container61")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("priorityClassNotSet", "", "controller6", "container61")
actionable = parsedConf.IsActionable("priorityClassNotSet", createMeta("", "controller6"), "container61")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "kube-system", "controller6", "container61")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", "controller6"), "container61")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "kube-system", "controller6", "")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", "controller6"), "")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "", "controller7", "container61")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("", "controller7"), "container61")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "", "", "container61")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("", ""), "container61")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "kube-system", "", "container61")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", ""), "container61")
assert.True(t, actionable)
}
@@ -219,33 +233,33 @@ func TestContainerExemption(t *testing.T) {
parsedConf, err := Parse([]byte(confContainerTest))
assert.NoError(t, err)
actionable := parsedConf.IsActionable("multipleReplicasForDeployment", "", "", "container71")
actionable := parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("", ""), "container71")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "kube-system", "", "container71")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", ""), "container71")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "", "controller7", "container71")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("", "controller7"), "container71")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "kube-system", "controller7", "")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", "controller7"), "")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "kube-system", "controller7", "container71")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", "controller7"), "container71")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "insights-agent", "controller7", "container71")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("insights-agent", "controller7"), "container71")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "kube-system", "controller6", "container71")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", "controller6"), "container71")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", "kube-system", "controller7", "container61")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", "controller7"), "container61")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("priorityClassNotSet", "kube-system", "controller7", "container71")
actionable = parsedConf.IsActionable("priorityClassNotSet", createMeta("kube-system", "controller7"), "container71")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("pullPolicyNotAlways", "kube-system", "controller8", "container71")
actionable = parsedConf.IsActionable("pullPolicyNotAlways", createMeta("kube-system", "controller8"), "container71")
assert.True(t, actionable)
}
+158 -29
View File
@@ -1,45 +1,86 @@
package config
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"strings"
"text/template"
"github.com/qri-io/jsonschema"
"github.com/thoas/go-funk"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
k8sYaml "k8s.io/apimachinery/pkg/util/yaml"
)
// TargetKind represents the part of the config to be validated
type TargetKind string
const (
// TargetController points to the controller's spec
TargetController TargetKind = "Controller"
// TargetContainer points to the container spec
TargetContainer TargetKind = "Container"
// TargetPod points to the pod spec
TargetPod TargetKind = "Pod"
// TargetController points to the controller's spec
TargetController TargetKind = "Controller"
// TargetIngress points to the ingress spec
TargetIngress TargetKind = "Ingress"
)
// HandledTargets is a list of target names that are explicitly handled
var HandledTargets = []TargetKind{
TargetController,
TargetContainer,
TargetPod,
}
// SchemaCheck is a Polaris check that runs using JSON Schema
type SchemaCheck struct {
ID string `yaml:"id"`
Category string `yaml:"category"`
SuccessMessage string `yaml:"successMessage"`
FailureMessage string `yaml:"failureMessage"`
Controllers includeExcludeList `yaml:"controllers"`
Containers includeExcludeList `yaml:"containers"`
Target TargetKind `yaml:"target"`
SchemaTarget TargetKind `yaml:"schemaTarget"`
Schema jsonschema.RootSchema `yaml:"schema"`
JSONSchema string `yaml:"jsonSchema"`
ID string `yaml:"id" json:"id"`
Category string `yaml:"category" json:"category"`
SuccessMessage string `yaml:"successMessage" json:"successMessage"`
FailureMessage string `yaml:"failureMessage" json:"failureMessage"`
Controllers includeExcludeList `yaml:"controllers" json:"controllers"`
Containers includeExcludeList `yaml:"containers" json:"containers"`
Target TargetKind `yaml:"target" json:"target"`
SchemaTarget TargetKind `yaml:"schemaTarget" json:"schemaTarget"`
Schema map[string]interface{} `yaml:"schema" json:"schema"`
SchemaString string `yaml:"schemaString" json:"schemaString"`
Validator jsonschema.RootSchema `yaml:"-" json:"-"`
AdditionalSchemas map[string]map[string]interface{} `yaml:"additionalSchemas" json:"additionalSchemas"`
AdditionalSchemaStrings map[string]string `yaml:"additionalSchemaStrings" json:"additionalSchemaStrings"`
AdditionalValidators map[string]jsonschema.RootSchema `yaml:"-" json:"-"`
}
type resourceMinimum string
type resourceMaximum string
func unmarshalYAMLOrJSON(raw []byte, dest interface{}) error {
reader := bytes.NewReader(raw)
d := k8sYaml.NewYAMLOrJSONDecoder(reader, 4096)
for {
if err := d.Decode(dest); err != nil {
if err == io.EOF {
break
}
return fmt.Errorf("Decoding schema check failed: %v", err)
}
}
return nil
}
// ParseCheck parses a check from a byte array
func ParseCheck(id string, rawBytes []byte) (SchemaCheck, error) {
check := SchemaCheck{}
err := unmarshalYAMLOrJSON(rawBytes, &check)
if err != nil {
return check, err
}
check.Initialize(id)
return check, nil
}
func init() {
jsonschema.RegisterValidator("resourceMinimum", newResourceMinimum)
jsonschema.RegisterValidator("resourceMaximum", newResourceMaximum)
@@ -119,48 +160,136 @@ func validateRange(path string, limit interface{}, data interface{}, isMinimum b
// Initialize sets up the schema
func (check *SchemaCheck) Initialize(id string) error {
check.ID = id
if check.JSONSchema != "" {
if err := json.Unmarshal([]byte(check.JSONSchema), &check.Schema); err != nil {
if check.SchemaString == "" {
jsonBytes, err := json.Marshal(check.Schema)
if err != nil {
return err
}
check.SchemaString = string(jsonBytes)
}
if check.AdditionalSchemaStrings == nil {
check.AdditionalSchemaStrings = make(map[string]string)
}
for kind, schema := range check.AdditionalSchemas {
jsonBytes, err := json.Marshal(schema)
if err != nil {
return err
}
check.AdditionalSchemaStrings[kind] = string(jsonBytes)
}
check.Schema = map[string]interface{}{}
check.AdditionalSchemas = map[string]map[string]interface{}{}
return nil
}
// TemplateForResource fills out a check's templated fields given a particular resource
func (check SchemaCheck) TemplateForResource(res interface{}) (*SchemaCheck, error) {
newCheck := check // Make a copy of the check, since we're going to modify the schema
templateStrings := map[string]string{
"": newCheck.SchemaString,
}
for kind, schema := range newCheck.AdditionalSchemaStrings {
templateStrings[kind] = schema
}
newCheck.SchemaString = ""
newCheck.AdditionalSchemaStrings = map[string]string{}
for kind, tmplString := range templateStrings {
tmpl := template.New(newCheck.ID)
tmpl, err := tmpl.Parse(tmplString)
if err != nil {
return nil, err
}
w := bytes.Buffer{}
err = tmpl.Execute(&w, res)
if err != nil {
return nil, err
}
if kind == "" {
newCheck.SchemaString = w.String()
} else {
newCheck.AdditionalSchemaStrings[kind] = w.String()
}
}
newCheck.AdditionalValidators = map[string]jsonschema.RootSchema{}
for kind, schemaStr := range newCheck.AdditionalSchemaStrings {
val := jsonschema.RootSchema{}
err := unmarshalYAMLOrJSON([]byte(schemaStr), &val)
if err != nil {
return nil, err
}
newCheck.AdditionalValidators[kind] = val
}
err := unmarshalYAMLOrJSON([]byte(newCheck.SchemaString), &newCheck.Validator)
if err != nil {
return nil, err
}
return &newCheck, err
}
// CheckPod checks a pod spec against the schema
func (check SchemaCheck) CheckPod(pod *corev1.PodSpec) (bool, error) {
func (check SchemaCheck) CheckPod(pod *corev1.PodSpec) (bool, []jsonschema.ValError, error) {
return check.CheckObject(pod)
}
// CheckController checks a controler's spec against the schema
func (check SchemaCheck) CheckController(bytes []byte) (bool, error) {
errs, err := check.Schema.ValidateBytes(bytes)
return len(errs) == 0, err
func (check SchemaCheck) CheckController(bytes []byte) (bool, []jsonschema.ValError, error) {
errs, err := check.Validator.ValidateBytes(bytes)
return len(errs) == 0, errs, err
}
// CheckContainer checks a container spec against the schema
func (check SchemaCheck) CheckContainer(container *corev1.Container) (bool, error) {
func (check SchemaCheck) CheckContainer(container *corev1.Container) (bool, []jsonschema.ValError, error) {
return check.CheckObject(container)
}
// CheckObject checks arbitrary data against the schema
func (check SchemaCheck) CheckObject(obj interface{}) (bool, error) {
func (check SchemaCheck) CheckObject(obj interface{}) (bool, []jsonschema.ValError, error) {
bytes, err := json.Marshal(obj)
if err != nil {
return false, err
return false, nil, err
}
errs, err := check.Schema.ValidateBytes(bytes)
return len(errs) == 0, err
errs, err := check.Validator.ValidateBytes(bytes)
return len(errs) == 0, errs, err
}
// CheckAdditionalObjects looks for an object that passes the specified additional schema
func (check SchemaCheck) CheckAdditionalObjects(groupkind string, objects []interface{}) (bool, error) {
val, ok := check.AdditionalValidators[groupkind]
if !ok {
return false, errors.New("No validator found for " + groupkind)
}
for _, obj := range objects {
bytes, err := json.Marshal(obj)
if err != nil {
return false, err
}
errs, err := val.ValidateBytes(bytes)
if err != nil {
return false, err
}
if len(errs) == 0 {
return true, nil
}
}
return false, nil
}
// IsActionable decides if this check applies to a particular target
func (check SchemaCheck) IsActionable(target TargetKind, controllerType string, isInit bool) bool {
if check.Target != target {
func (check SchemaCheck) IsActionable(target TargetKind, kind string, isInit bool) bool {
if funk.Contains(HandledTargets, target) {
if check.Target != target {
return false
}
} else if string(check.Target) != kind && !strings.HasSuffix(string(check.Target), "/"+kind) {
return false
}
isIncluded := len(check.Controllers.Include) == 0
for _, inclusion := range check.Controllers.Include {
if inclusion == controllerType {
if inclusion == kind {
isIncluded = true
break
}
@@ -169,7 +298,7 @@ func (check SchemaCheck) IsActionable(target TargetKind, controllerType string,
return false
}
for _, exclusion := range check.Controllers.Exclude {
if exclusion == controllerType {
if exclusion == kind {
return false
}
}
+4 -2
View File
@@ -13,8 +13,10 @@
padding-right: 40px;
box-shadow: none;
}
.card.insights img {
max-width: 400px;
.card.transparent {
background-color: transparent;
border: none;
box-shadow: none;
}
.card.insights a {
background-color: #20162D;
Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

After

Width:  |  Height:  |  Size: 66 KiB

+13 -9
View File
@@ -130,13 +130,17 @@ func writeTemplate(tmpl *template.Template, data *templateData, w http.ResponseW
func getConfigForQuery(base config.Configuration, query url.Values) config.Configuration {
c := base
exemptions := query.Get("disallowExemptions")
if exemptions == "false" {
c.DisallowExemptions = false
}
if exemptions == "true" {
switch query.Get("disallowExemptions") {
case "true":
c.DisallowExemptions = true
c.DisallowConfigExemptions = true
c.DisallowAnnotationExemptions = true
default:
c.DisallowExemptions = false
c.DisallowConfigExemptions = false
c.DisallowAnnotationExemptions = false
}
return c
}
@@ -173,7 +177,7 @@ func GetRouter(c config.Configuration, auditPath string, port int, basePath stri
router.HandleFunc("/results.json", func(w http.ResponseWriter, r *http.Request) {
adjustedConf := getConfigForQuery(c, r.URL.Query())
if auditData == nil {
k, err := kube.CreateResourceProvider(r.Context(), auditPath, "")
k, err := kube.CreateResourceProvider(r.Context(), auditPath, "", c)
if err != nil {
logrus.Errorf("Error fetching Kubernetes resources %v", err)
http.Error(w, "Error fetching Kubernetes resources", http.StatusInternalServerError)
@@ -181,7 +185,7 @@ func GetRouter(c config.Configuration, auditPath string, port int, basePath stri
}
var auditDataObj validator.AuditData
auditDataObj, err = validator.RunAudit(adjustedConf, k, false)
auditDataObj, err = validator.RunAudit(adjustedConf, k)
if err != nil {
http.Error(w, "Error Fetching Deployments", http.StatusInternalServerError)
return
@@ -206,7 +210,7 @@ func GetRouter(c config.Configuration, auditPath string, port int, basePath stri
adjustedConf := getConfigForQuery(c, r.URL.Query())
if auditData == nil {
k, err := kube.CreateResourceProvider(r.Context(), auditPath, "")
k, err := kube.CreateResourceProvider(r.Context(), auditPath, "", c)
if err != nil {
logrus.Errorf("Error fetching Kubernetes resources %v", err)
http.Error(w, "Error fetching Kubernetes resources", http.StatusInternalServerError)
@@ -214,7 +218,7 @@ func GetRouter(c config.Configuration, auditPath string, port int, basePath stri
}
var auditData validator.AuditData
auditData, err = validator.RunAudit(adjustedConf, k, false)
auditData, err = validator.RunAudit(adjustedConf, k)
if err != nil {
logrus.Errorf("Error getting audit data: %v", err)
http.Error(w, "Error running audit", 500)
+241
View File
@@ -0,0 +1,241 @@
package dashboard
import (
"testing"
"github.com/fairwindsops/polaris/pkg/config"
"github.com/fairwindsops/polaris/pkg/validator"
"github.com/stretchr/testify/assert"
)
func TestWarningWidth(t *testing.T) {
input1 := validator.CountSummary{
Successes: 0,
Warnings: 0,
Dangers: 0,
}
input2 := 6
expectedOutput := uint(0x6)
actual := getWarningWidth(input1, input2)
assert.Equal(t, expectedOutput, actual)
input1 = validator.CountSummary{
Successes: 10,
Warnings: 3,
Dangers: 1,
}
input2 = 3
expectedOutput = uint(0x2)
actual = getWarningWidth(input1, input2)
assert.Equal(t, expectedOutput, actual)
}
func TestSuccessWidth(t *testing.T) {
input1 := validator.CountSummary{
Successes: 0,
Warnings: 0,
Dangers: 0,
}
input2 := 6
expectedOutput := uint(0x6)
actual := getSuccessWidth(input1, input2)
assert.Equal(t, expectedOutput, actual)
input1 = validator.CountSummary{
Successes: 8,
Warnings: 6,
Dangers: 4,
}
input2 = 7
expectedOutput = uint(0x3)
actual = getSuccessWidth(input1, input2)
assert.Equal(t, expectedOutput, actual)
}
func TestGetGrade(t *testing.T) {
input := validator.CountSummary{
Successes: 10,
Warnings: 3,
Dangers: 1,
}
expectedOutput := "B-"
actual := getGrade(input)
assert.Equal(t, expectedOutput, actual)
assert.NotEqual(t, "A+", actual)
}
func TestGetWeatherIcon(t *testing.T) {
input := validator.CountSummary{
Successes: 10,
Warnings: 3,
Dangers: 1,
}
expectedOutput := "fa-cloud-sun"
actual := getWeatherIcon(input)
assert.Equal(t, expectedOutput, actual)
assert.NotEqual(t, "fa-cloud-showers-heavy", actual)
}
func TestGetResultClass(t *testing.T) {
input := validator.ResultMessage{
ID: "",
Message: "",
Details: []string(nil),
Success: false,
Severity: "",
Category: "",
}
expectedOutput := " failure"
actual := getResultClass(input)
assert.Equal(t, expectedOutput, actual)
assert.NotEqual(t, " success", actual)
input = validator.ResultMessage{
ID: "",
Message: "",
Details: []string(nil),
Success: true,
Severity: "",
Category: "",
}
expectedOutput = " success"
actual = getResultClass(input)
assert.Equal(t, expectedOutput, actual)
assert.NotEqual(t, " failure", actual)
}
func TestGetWeatherText(t *testing.T) {
input := validator.CountSummary{
Successes: 10,
Warnings: 3,
Dangers: 1,
}
expectedOutput := "Mostly smooth sailing"
actual := getWeatherText(input)
assert.Equal(t, expectedOutput, actual)
assert.NotEqual(t, "Storms ahead, be careful", actual)
}
func TestGetIcon(t *testing.T) {
input := validator.ResultMessage{
ID: "",
Message: "",
Details: []string(nil),
Success: false,
Severity: "",
Category: "",
}
expectedOutput := "fas fa-times"
actual := getIcon(input)
assert.Equal(t, expectedOutput, actual)
assert.NotEqual(t, "fas fa-check", actual)
input = validator.ResultMessage{
ID: "",
Message: "",
Details: []string(nil),
Success: true,
Severity: "",
Category: "",
}
expectedOutput = "fas fa-check"
actual = getIcon(input)
assert.Equal(t, expectedOutput, actual)
assert.NotEqual(t, "fas fa-times", actual)
input = validator.ResultMessage{
ID: "",
Message: "",
Details: []string(nil),
Success: false,
Severity: config.SeverityWarning,
Category: "",
}
expectedOutput = "fas fa-exclamation"
actual = getIcon(input)
assert.Equal(t, expectedOutput, actual)
assert.NotEqual(t, "fas fa-times", actual)
}
func TestGetCategoryLink(t *testing.T) {
input := "Efficiency"
expectedOutput := "https://polaris.docs.fairwinds.com/checks/efficiency"
actual := getCategoryLink(input)
assert.Equal(t, expectedOutput, actual)
assert.NotEqual(t, "ttps://polaris.docs.fairwinds.com/checks/reliability", actual)
}
func TestGetCategoryInfo(t *testing.T) {
input := "Security"
expectedOutput :=
`
Kubernetes provides a great deal of configurability when it comes to the
security of your workloads. A key principle here involves limiting the level
of access any individual workload has. Polaris has validations for a number of
best practices, mostly focused on ensuring that unnecessary access has not
been granted to an application workload.
`
actual := getCategoryInfo(input)
assert.Equal(t, expectedOutput, actual)
assert.NotEqual(t, "fas fa-times", actual)
input = "Reliability"
expectedOutput =
`
Kubernetes is built to reliabily run highly available applications.
Polaris includes a number of checks to ensure that you are maximizing
the reliability potential of Kubernetes.
`
actual = getCategoryInfo(input)
assert.Equal(t, expectedOutput, actual)
assert.NotEqual(t, "fas fa-times", actual)
}
func TestStringInSlice(t *testing.T) {
input1 := "a"
input2 := []string{"a", "b", "cde"}
expectedOutput := true
actual := stringInSlice(input1, input2)
assert.Equal(t, expectedOutput, actual)
assert.NotEqual(t, false, actual)
input1 = "f"
input2 = []string{"a", "b", "cde"}
expectedOutput = false
actual = stringInSlice(input1, input2)
assert.Equal(t, expectedOutput, actual)
assert.NotEqual(t, true, actual)
}
+10 -4
View File
@@ -83,10 +83,12 @@
</div>
</div>
<div id="insights" class="card insights py-2">
<img class="align-self-center" src="static/images/FW_Insights_Polaris.svg" />
<span>Fairwinds, the company behind Polaris, now offers Fairwinds Insights, a multi-cluster, multi-user Kubernetes configuration validation and policy enforcement platform. Fairwinds Insights can help you avoid errors that lead to wasted time, compute costs, and increased risk.</span>
<a class="col-auto py-1 px-3 mt-2 align-self-center" href="https://fairwinds.com/insights?source=polaris" target="_blank">Try Insights</a>
<div class="card transparent">
<a class="align-self-center"
target="_blank"
href="https://www.fairwinds.com/polaris-user-insights-demo?utm_source=polaris&utm_medium=ad&utm_campaign=polarisad">
<img src="static/images/FW_Insights_Polaris.svg" />
</a>
</div>
<div id="categories" class="card category">
@@ -134,7 +136,11 @@
{{ range $namespace, $results := .FilteredAuditData.GetResultsByNamespace }}
<div id="{{ $namespace }}" class="card namespace">
{{ if eq $namespace "" }}
<h3>Cluster Resources</h3>
{{ else }}
<h3>Namespace: <strong>{{ $namespace }}</strong></h3>
{{ end }}
<div class="expandable-table">
{{ range $index, $result := $results }}
<div class="resource-info">
+1 -1
View File
@@ -23,7 +23,7 @@
<hr class="col-11">
<div class="align-self-center d-flex flex-column justify-content-center">
<img class="row mb-4 fw-logo" src="static/images/purple_logo_fairwinds.svg" alt="Fairwinds" />
<a class="row justify-content-center" href="https://fairwinds.com?source=polaris" target="_blank">&copy; 2020 Fairwinds Ops Inc.</a>
<a class="row justify-content-center" href="https://www.fairwinds.com/polaris-user-insights-demo?utm_source=polaris&utm_medium=polaris&utm_campaign=polaris" target="_blank">&copy; 2020 Fairwinds Ops Inc.</a>
</div>
</div>
{{end}}
+1 -1
View File
@@ -2,7 +2,7 @@
<div class="navbar">
<div class="fw-nav">
<div class="container p-2">
<a href="https://fairwinds.com?source=polaris" target="_blank">
<a href="https://www.fairwinds.com/polaris-user-insights-demo?utm_source=polaris&utm_medium=polaris&utm_campaign=polaris" target="_blank">
<img class="fw-logo" src="static/images/white_logo_fairwinds.svg" alt="Fairwinds" />
</a>
<div class="right-section p-0 d-flex justify-content-between">
+60 -89
View File
@@ -1,7 +1,6 @@
package kube
import (
"bytes"
"context"
"encoding/json"
"fmt"
@@ -13,61 +12,62 @@ import (
kubeAPIMetaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
k8sYaml "k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/client-go/dynamic"
)
// GenericWorkload is a base implementation with some free methods for inherited structs
type GenericWorkload struct {
// GenericResource is a base implementation with some free methods for inherited structs
type GenericResource struct {
Kind string
PodSpec kubeAPICoreV1.PodSpec
ObjectMeta kubeAPIMetaV1.Object
Resource unstructured.Unstructured
PodSpec *kubeAPICoreV1.PodSpec
OriginalObjectJSON []byte
}
// NewGenericWorkloadFromUnstructured creates a workload from an unstructured.Unstructured
func NewGenericWorkloadFromUnstructured(kind string, unst *unstructured.Unstructured) (GenericWorkload, error) {
workload := GenericWorkload{
Kind: kind,
// NewGenericResourceFromUnstructured creates a workload from an unstructured.Unstructured
func NewGenericResourceFromUnstructured(unst unstructured.Unstructured) (GenericResource, error) {
workload := GenericResource{
Kind: unst.GetKind(),
Resource: unst,
}
objMeta, err := meta.Accessor(unst)
objMeta, err := meta.Accessor(&unst)
if err != nil {
return workload, err
}
workload.ObjectMeta = objMeta
b, err := json.Marshal(unst)
b, err := json.Marshal(&unst)
if err != nil {
return workload, err
}
workload.OriginalObjectJSON = b
m := make(map[string]interface{})
err = json.Unmarshal(b, &m)
if err != nil {
return workload, err
}
podSpecMap := GetPodSpec(m)
b, err = json.Marshal(podSpecMap)
if err != nil {
return workload, err
if podSpecMap != nil {
b, err = json.Marshal(podSpecMap)
if err != nil {
return workload, err
}
podSpec := kubeAPICoreV1.PodSpec{}
err = json.Unmarshal(b, &podSpec)
if err != nil {
return workload, err
}
workload.PodSpec = &podSpec
}
podSpec := kubeAPICoreV1.PodSpec{}
err = json.Unmarshal(b, &podSpec)
if err != nil {
return workload, err
}
workload.PodSpec = podSpec
return workload, nil
}
// NewGenericWorkloadFromPod builds a new workload for a given Pod without looking at parents
func NewGenericWorkloadFromPod(podResource kubeAPICoreV1.Pod, originalObject interface{}) (GenericWorkload, error) {
workload := GenericWorkload{
// NewGenericResourceFromPod builds a new workload for a given Pod without looking at parents
func NewGenericResourceFromPod(podResource kubeAPICoreV1.Pod, originalObject interface{}) (GenericResource, error) {
workload := GenericResource{
Kind: "Pod",
PodSpec: podResource.Spec,
PodSpec: &podResource.Spec,
ObjectMeta: podResource.ObjectMeta.GetObjectMeta(),
}
if originalObject != nil {
@@ -77,13 +77,12 @@ func NewGenericWorkloadFromPod(podResource kubeAPICoreV1.Pod, originalObject int
}
workload.OriginalObjectJSON = bytes
var unst unstructured.Unstructured
err = json.Unmarshal(bytes, &unst.Object)
err = json.Unmarshal(bytes, &workload.Resource.Object)
if err != nil {
logrus.Error("Couldn't marshal JSON for pod ", err)
return workload, err
}
objMeta, err := meta.Accessor(&unst)
objMeta, err := meta.Accessor(&workload.Resource)
if err != nil {
logrus.Error("Couldn't create meta accessor for unstructred ", err)
return workload, err
@@ -93,26 +92,36 @@ func NewGenericWorkloadFromPod(podResource kubeAPICoreV1.Pod, originalObject int
return workload, nil
}
// NewGenericWorkload builds a new workload for a given Pod
func NewGenericWorkload(ctx context.Context, podResource kubeAPICoreV1.Pod, dynamicClient *dynamic.Interface, restMapper *meta.RESTMapper, objectCache map[string]unstructured.Unstructured) (GenericWorkload, error) {
workload, err := newGenericWorkload(ctx, podResource, dynamicClient, restMapper, objectCache)
// NewGenericResourceFromBytes parses a generic kubernetes resource
func NewGenericResourceFromBytes(contentBytes []byte) (GenericResource, error) {
unst := unstructured.Unstructured{}
err := yaml.Unmarshal(contentBytes, &unst.Object)
if err != nil {
return GenericResource{}, err
}
return NewGenericResourceFromUnstructured(unst)
}
// ResolveControllerFromPod builds a new workload for a given Pod
func ResolveControllerFromPod(ctx context.Context, podResource kubeAPICoreV1.Pod, dynamicClient *dynamic.Interface, restMapper *meta.RESTMapper, objectCache map[string]unstructured.Unstructured) (GenericResource, error) {
workload, err := resolveControllerFromPod(ctx, podResource, dynamicClient, restMapper, objectCache)
if err != nil {
return workload, err
}
if len(workload.OriginalObjectJSON) == 0 {
return NewGenericWorkloadFromPod(podResource, podResource)
return NewGenericResourceFromPod(podResource, podResource)
}
return workload, err
}
func newGenericWorkload(ctx context.Context, podResource kubeAPICoreV1.Pod, dynamicClient *dynamic.Interface, restMapper *meta.RESTMapper, objectCache map[string]unstructured.Unstructured) (GenericWorkload, error) {
workload, err := NewGenericWorkloadFromPod(podResource, nil)
func resolveControllerFromPod(ctx context.Context, podResource kubeAPICoreV1.Pod, dynamicClient *dynamic.Interface, restMapper *meta.RESTMapper, objectCache map[string]unstructured.Unstructured) (GenericResource, error) {
podWorkload, err := NewGenericResourceFromPod(podResource, nil)
if err != nil {
return workload, err
return podWorkload, err
}
// If an owner exists then set the name to the workload.
// This allows us to handle CRDs creating Workloads or DeploymentConfigs in OpenShift.
owners := workload.ObjectMeta.GetOwnerReferences()
topKind := "Pod"
topMeta := podWorkload.ObjectMeta
owners := podResource.ObjectMeta.GetOwnerReferences()
lastKey := ""
for len(owners) > 0 {
if len(owners) > 1 {
@@ -122,12 +131,12 @@ func newGenericWorkload(ctx context.Context, podResource kubeAPICoreV1.Pod, dyna
if firstOwner.Kind == "Node" {
break
}
workload.Kind = firstOwner.Kind
key := fmt.Sprintf("%s/%s/%s", firstOwner.Kind, workload.ObjectMeta.GetNamespace(), firstOwner.Name)
topKind = firstOwner.Kind
key := fmt.Sprintf("%s/%s/%s", firstOwner.Kind, topMeta.GetNamespace(), firstOwner.Name)
lastKey = key
abstractObject, ok := objectCache[key]
if !ok {
err = cacheAllObjectsOfKind(ctx, firstOwner.APIVersion, firstOwner.Kind, dynamicClient, restMapper, objectCache)
err := cacheAllObjectsOfKind(ctx, firstOwner.APIVersion, firstOwner.Kind, dynamicClient, restMapper, objectCache)
if err != nil {
logrus.Warnf("Error caching objects of Kind %s %v", firstOwner.Kind, err)
break
@@ -142,26 +151,22 @@ func newGenericWorkload(ctx context.Context, podResource kubeAPICoreV1.Pod, dyna
objMeta, err := meta.Accessor(&abstractObject)
if err != nil {
logrus.Warnf("Error retrieving parent metadata %s of API %s and Kind %s because of error: %v ", firstOwner.Name, firstOwner.APIVersion, firstOwner.Kind, err)
return workload, err
return GenericResource{}, err
}
workload.ObjectMeta = objMeta
topMeta = objMeta
owners = abstractObject.GetOwnerReferences()
}
if lastKey != "" {
unst := objectCache[lastKey]
bytes, err := json.Marshal(&unst)
if err != nil {
return workload, err
}
workload.OriginalObjectJSON = bytes
} else {
bytes, err := json.Marshal(podResource)
if err != nil {
return workload, err
}
workload.OriginalObjectJSON = bytes
return NewGenericResourceFromUnstructured(unst)
}
workload, err := NewGenericResourceFromPod(podResource, podResource)
if err != nil {
return workload, err
}
workload.Kind = topKind
workload.ObjectMeta = topMeta
return workload, nil
}
@@ -207,37 +212,3 @@ func GetPodSpec(yaml map[string]interface{}) interface{} {
}
return nil
}
// GetWorkloadFromBytes parses a GenericWorkload
func GetWorkloadFromBytes(contentBytes []byte) (*GenericWorkload, error) {
yamlNode := make(map[string]interface{})
err := yaml.Unmarshal(contentBytes, &yamlNode)
if err != nil {
logrus.Errorf("Invalid YAML: %s", string(contentBytes))
return nil, err
}
finalDoc := make(map[string]interface{})
finalDoc["metadata"] = yamlNode["metadata"]
finalDoc["apiVersion"] = "v1"
finalDoc["kind"] = "Pod"
podSpec := GetPodSpec(yamlNode)
if podSpec == nil {
return nil, nil
}
finalDoc["spec"] = podSpec
marshaledYaml, err := yaml.Marshal(finalDoc)
if err != nil {
logrus.Errorf("Could not marshal yaml: %v", err)
return nil, err
}
decoder := k8sYaml.NewYAMLOrJSONDecoder(bytes.NewReader(marshaledYaml), 1000)
pod := kubeAPICoreV1.Pod{}
err = decoder.Decode(&pod)
newController, err := NewGenericWorkloadFromPod(pod, yamlNode)
if err != nil {
return nil, err
}
newController.Kind = yamlNode["kind"].(string)
return &newController, nil
}
+158 -70
View File
@@ -12,12 +12,15 @@ import (
"strings"
"time"
conf "github.com/fairwindsops/polaris/pkg/config"
"github.com/sirupsen/logrus"
"github.com/thoas/go-funk"
corev1 "k8s.io/api/core/v1"
v1beta1 "k8s.io/api/extensions/v1beta1"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
k8sYaml "k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
@@ -34,8 +37,74 @@ type ResourceProvider struct {
SourceType string
Nodes []corev1.Node
Namespaces []corev1.Namespace
Controllers []GenericWorkload
Ingresses []v1beta1.Ingress
Resources resourceKindMap
}
type resourceKindMap map[string][]GenericResource
func (rkm resourceKindMap) addResource(r GenericResource) {
gvk := r.Resource.GroupVersionKind()
key := gvk.Group + "/" + gvk.Kind
rkm[key] = append(rkm[key], r)
}
func (rkm resourceKindMap) addResources(rs []GenericResource) {
for _, r := range rs {
rkm.addResource(r)
}
}
func (rkm resourceKindMap) GetLength() int {
total := 0
for _, rs := range rkm {
total += len(rs)
}
return total
}
func (rkm resourceKindMap) GetNumberOfControllers() int {
total := 0
for _, rs := range rkm {
for _, r := range rs {
if r.PodSpec != nil {
total++
}
}
}
return total
}
// This is here for backward compatibility reasons
func maybeTransformKindIntoGroupKind(k string) string {
if k == "Ingress" {
return "networking.k8s.io/Ingress"
} else if k == "PodDisruptionBudget" {
return "policy/PodDisruptionBudget"
}
return k
}
func parseGroupKind(gk string) schema.GroupKind {
i := strings.Index(gk, "/")
if i == -1 {
return schema.GroupKind{Kind: gk}
}
group := gk[:i]
kind := gk[i+1:]
return schema.GroupKind{Group: group, Kind: kind}
}
func newResourceProvider(version, sourceType, sourceName string) ResourceProvider {
return ResourceProvider{
ServerVersion: version,
SourceType: sourceType,
SourceName: sourceName,
CreationTime: time.Now(),
Nodes: make([]corev1.Node, 0),
Namespaces: make([]corev1.Namespace, 0),
Resources: make(map[string][]GenericResource),
}
}
type k8sResource struct {
@@ -45,18 +114,18 @@ type k8sResource struct {
var podSpecFields = []string{"jobTemplate", "spec", "template"}
// CreateResourceProvider returns a new ResourceProvider object to interact with k8s resources
func CreateResourceProvider(ctx context.Context, directory, workload string) (*ResourceProvider, error) {
func CreateResourceProvider(ctx context.Context, directory, workload string, c conf.Configuration) (*ResourceProvider, error) {
if workload != "" {
return CreateResourceProviderFromWorkload(ctx, workload)
return CreateResourceProviderFromResource(ctx, workload)
}
if directory != "" {
return CreateResourceProviderFromPath(directory)
}
return CreateResourceProviderFromCluster(ctx)
return CreateResourceProviderFromCluster(ctx, c)
}
// CreateResourceProviderFromWorkload creates a new ResourceProvider that just contains one workload
func CreateResourceProviderFromWorkload(ctx context.Context, workload string) (*ResourceProvider, error) {
// CreateResourceProviderFromResource creates a new ResourceProvider that just contains one workload
func CreateResourceProviderFromResource(ctx context.Context, workload string) (*ResourceProvider, error) {
kubeConf, configError := config.GetConfig()
if configError != nil {
logrus.Errorf("Error fetching KubeConfig: %v", configError)
@@ -72,14 +141,7 @@ func CreateResourceProviderFromWorkload(ctx context.Context, workload string) (*
logrus.Errorf("Error fetching Cluster API version: %v", err)
return nil, err
}
resources := ResourceProvider{
ServerVersion: serverVersion.Major + "." + serverVersion.Minor,
SourceType: "Workload",
SourceName: workload,
CreationTime: time.Now(),
Nodes: []corev1.Node{},
Namespaces: []corev1.Namespace{},
}
resources := newResourceProvider(serverVersion.Major+"."+serverVersion.Minor, "Resource", workload)
parts := strings.Split(workload, "/")
if len(parts) != 4 {
@@ -106,31 +168,24 @@ func CreateResourceProviderFromWorkload(ctx context.Context, workload string) (*
logrus.Errorf("Could not find workload %s: %v", workload, err)
return nil, err
}
workloadObj, err := NewGenericWorkloadFromUnstructured(kind, obj)
workloadObj, err := NewGenericResourceFromUnstructured(*obj)
if err != nil {
logrus.Errorf("Could not parse workload %s: %v", workload, err)
return nil, err
}
resources.Controllers = []GenericWorkload{workloadObj}
resources.Resources.addResource(workloadObj)
return &resources, nil
}
// CreateResourceProviderFromPath returns a new ResourceProvider using the YAML files in a directory
func CreateResourceProviderFromPath(directory string) (*ResourceProvider, error) {
resources := ResourceProvider{
ServerVersion: "unknown",
SourceType: "Path",
SourceName: directory,
Nodes: []corev1.Node{},
Namespaces: []corev1.Namespace{},
Controllers: []GenericWorkload{},
}
resources := newResourceProvider("unknown", "Path", directory)
if directory == "-" {
fi, err := os.Stdin.Stat()
if err == nil && fi.Mode()&os.ModeNamedPipe == os.ModeNamedPipe {
if err := addResourcesFromReader(os.Stdin, &resources); err != nil {
if err := resources.addResourcesFromReader(os.Stdin); err != nil {
return nil, err
}
return &resources, nil
@@ -146,7 +201,7 @@ func CreateResourceProviderFromPath(directory string) (*ResourceProvider, error)
logrus.Errorf("Error reading file: %v", path)
return err
}
return addResourcesFromYaml(string(contents), &resources)
return resources.addResourcesFromYaml(string(contents))
}
err := filepath.Walk(directory, visitFile)
@@ -157,7 +212,7 @@ func CreateResourceProviderFromPath(directory string) (*ResourceProvider, error)
}
// CreateResourceProviderFromCluster creates a new ResourceProvider using live data from a cluster
func CreateResourceProviderFromCluster(ctx context.Context) (*ResourceProvider, error) {
func CreateResourceProviderFromCluster(ctx context.Context, c conf.Configuration) (*ResourceProvider, error) {
kubeConf, configError := config.GetConfig()
if configError != nil {
logrus.Errorf("Error fetching KubeConfig: %v", configError)
@@ -173,17 +228,18 @@ func CreateResourceProviderFromCluster(ctx context.Context) (*ResourceProvider,
logrus.Errorf("Error connecting to dynamic interface: %v", err)
return nil, err
}
return CreateResourceProviderFromAPI(ctx, api, kubeConf.Host, &dynamicInterface)
return CreateResourceProviderFromAPI(ctx, api, kubeConf.Host, &dynamicInterface, c)
}
// CreateResourceProviderFromAPI creates a new ResourceProvider from an existing k8s interface
func CreateResourceProviderFromAPI(ctx context.Context, kube kubernetes.Interface, clusterName string, dynamic *dynamic.Interface) (*ResourceProvider, error) {
func CreateResourceProviderFromAPI(ctx context.Context, kube kubernetes.Interface, clusterName string, dynamic *dynamic.Interface, c conf.Configuration) (*ResourceProvider, error) {
listOpts := metav1.ListOptions{}
serverVersion, err := kube.Discovery().ServerVersion()
if err != nil {
logrus.Errorf("Error fetching Cluster API version: %v", err)
return nil, err
}
provider := newResourceProvider(serverVersion.Major+"."+serverVersion.Minor, "Cluster", clusterName)
nodes, err := kube.CoreV1().Nodes().List(ctx, listOpts)
if err != nil {
@@ -200,11 +256,6 @@ func CreateResourceProviderFromAPI(ctx context.Context, kube kubernetes.Interfac
logrus.Errorf("Error fetching Pods: %v", err)
return nil, err
}
ingressList, err := kube.ExtensionsV1beta1().Ingresses("").List(ctx, listOpts)
if err != nil {
logrus.Errorf("Error fetching Ingresses: %v", err)
return nil, err
}
resources, err := restmapper.GetAPIGroupResources(kube.Discovery())
if err != nil {
@@ -212,6 +263,51 @@ func CreateResourceProviderFromAPI(ctx context.Context, kube kubernetes.Interfac
return nil, err
}
restMapper := restmapper.NewDiscoveryRESTMapper(resources)
allChecks := []conf.SchemaCheck{}
for _, check := range c.CustomChecks {
allChecks = append(allChecks, check)
}
for _, check := range conf.BuiltInChecks {
allChecks = append(allChecks, check)
}
var additionalKinds []conf.TargetKind
for _, check := range allChecks {
neededKinds := []conf.TargetKind{check.Target}
for key := range check.AdditionalSchemas {
neededKinds = append(neededKinds, conf.TargetKind(key))
}
for key := range check.AdditionalSchemaStrings {
neededKinds = append(neededKinds, conf.TargetKind(key))
}
for _, kind := range neededKinds {
if !funk.Contains(conf.HandledTargets, kind) && !funk.Contains(additionalKinds, kind) {
additionalKinds = append(additionalKinds, kind)
}
}
}
for _, kind := range additionalKinds {
groupKind := parseGroupKind(maybeTransformKindIntoGroupKind(string(kind)))
mapping, err := (restMapper).RESTMapping(groupKind)
if err != nil {
logrus.Warnf("Error retrieving mapping of Kind %s because of error: %v", kind, err)
return nil, err
}
objects, err := (*dynamic).Resource(mapping.Resource).Namespace("").List(ctx, metav1.ListOptions{})
if err != nil {
logrus.Warnf("Error retrieving parent object API %s and Kind %s because of error: %v", mapping.Resource.Version, mapping.Resource.Resource, err)
return nil, err
}
for _, obj := range objects.Items {
res, err := NewGenericResourceFromUnstructured(obj)
if err != nil {
return nil, err
}
provider.Resources.addResource(res)
}
}
objectCache := map[string]unstructured.Unstructured{}
@@ -220,23 +316,15 @@ func CreateResourceProviderFromAPI(ctx context.Context, kube kubernetes.Interfac
logrus.Errorf("Error loading controllers from pods: %v", err)
return nil, err
}
api := ResourceProvider{
ServerVersion: serverVersion.Major + "." + serverVersion.Minor,
SourceType: "Cluster",
SourceName: clusterName,
CreationTime: time.Now(),
Nodes: nodes.Items,
Namespaces: namespaces.Items,
Controllers: controllers,
Ingresses: ingressList.Items,
}
return &api, nil
provider.Nodes = nodes.Items
provider.Namespaces = namespaces.Items
provider.Resources.addResources(controllers)
return &provider, nil
}
// LoadControllers loads a list of controllers from the kubeResources Pods
func LoadControllers(ctx context.Context, pods []corev1.Pod, dynamicClientPointer *dynamic.Interface, restMapperPointer *meta.RESTMapper, objectCache map[string]unstructured.Unstructured) ([]GenericWorkload, error) {
interfaces := []GenericWorkload{}
func LoadControllers(ctx context.Context, pods []corev1.Pod, dynamicClientPointer *dynamic.Interface, restMapperPointer *meta.RESTMapper, objectCache map[string]unstructured.Unstructured) ([]GenericResource, error) {
interfaces := []GenericResource{}
deduped := map[string]corev1.Pod{}
for _, pod := range pods {
owners := pod.ObjectMeta.OwnerReferences
@@ -247,7 +335,7 @@ func LoadControllers(ctx context.Context, pods []corev1.Pod, dynamicClientPointe
deduped[pod.ObjectMeta.Namespace+"/"+owners[0].Kind+"/"+owners[0].Name] = pod
}
for _, pod := range deduped {
workload, err := NewGenericWorkload(ctx, pod, dynamicClientPointer, restMapperPointer, objectCache)
workload, err := ResolveControllerFromPod(ctx, pod, dynamicClientPointer, restMapperPointer, objectCache)
if err != nil {
return nil, err
}
@@ -258,8 +346,8 @@ func LoadControllers(ctx context.Context, pods []corev1.Pod, dynamicClientPointe
// Because the controllers with an Owner take on the name of the Owner, this eliminates any duplicates.
// In cases like CronJobs older children can hang around, so this takes the most recent.
func deduplicateControllers(inputControllers []GenericWorkload) []GenericWorkload {
controllerMap := make(map[string]GenericWorkload)
func deduplicateControllers(inputControllers []GenericResource) []GenericResource {
controllerMap := make(map[string]GenericResource)
for _, controller := range inputControllers {
key := controller.ObjectMeta.GetNamespace() + "/" + controller.Kind + "/" + controller.ObjectMeta.GetName()
oldController, ok := controllerMap[key]
@@ -267,32 +355,34 @@ func deduplicateControllers(inputControllers []GenericWorkload) []GenericWorkloa
controllerMap[key] = controller
}
}
results := make([]GenericWorkload, 0)
results := make([]GenericResource, len(controllerMap))
idx := 0
for _, controller := range controllerMap {
results = append(results, controller)
results[idx] = controller
idx++
}
return results
}
func addResourcesFromReader(reader io.Reader, resources *ResourceProvider) error {
func (resources *ResourceProvider) addResourcesFromReader(reader io.Reader) error {
contents, err := ioutil.ReadAll(reader)
if err != nil {
logrus.Errorf("Error reading from %v: %v", reader, err)
return err
}
if err := addResourcesFromYaml(string(contents), resources); err != nil {
if err := resources.addResourcesFromYaml(string(contents)); err != nil {
return err
}
return nil
}
func addResourcesFromYaml(contents string, resources *ResourceProvider) error {
func (resources *ResourceProvider) addResourcesFromYaml(contents string) error {
specs := regexp.MustCompile("[\r\n]-+[\r\n]").Split(string(contents), -1)
for _, spec := range specs {
if strings.TrimSpace(spec) == "" {
continue
}
err := addResourceFromString(spec, resources)
err := resources.addResourceFromString(spec)
if err != nil {
logrus.Errorf("Error parsing YAML: (%v)", err)
return err
@@ -301,7 +391,7 @@ func addResourcesFromYaml(contents string, resources *ResourceProvider) error {
return nil
}
func addResourceFromString(contents string, resources *ResourceProvider) error {
func (resources *ResourceProvider) addResourceFromString(contents string) error {
contentBytes := []byte(contents)
decoder := k8sYaml.NewYAMLOrJSONDecoder(bytes.NewReader(contentBytes), 1000)
resource := k8sResource{}
@@ -316,27 +406,25 @@ func addResourceFromString(contents string, resources *ResourceProvider) error {
ns := corev1.Namespace{}
err = decoder.Decode(&ns)
resources.Namespaces = append(resources.Namespaces, ns)
} else if resource.Kind == "Pod" {
}
if resource.Kind == "Pod" {
pod := corev1.Pod{}
err = decoder.Decode(&pod)
if err != nil {
return err
}
workload, err := NewGenericWorkloadFromPod(pod, pod)
workload, err := NewGenericResourceFromPod(pod, pod)
if err != nil {
return err
}
resources.Controllers = append(resources.Controllers, workload)
} else if resource.Kind == "Ingress" {
ingress := v1beta1.Ingress{}
err = decoder.Decode(&ingress)
resources.Ingresses = append(resources.Ingresses, ingress)
resources.Resources.addResource(workload)
} else {
newController, err := GetWorkloadFromBytes(contentBytes)
if err != nil || newController == nil {
newResource, err := NewGenericResourceFromBytes(contentBytes)
if err != nil {
return err
}
resources.Controllers = append(resources.Controllers, *newController)
resources.Resources.addResource(newResource)
}
return err
}
+27 -31
View File
@@ -7,32 +7,34 @@ import (
"testing"
"time"
conf "github.com/fairwindsops/polaris/pkg/config"
"github.com/fairwindsops/polaris/test"
"github.com/stretchr/testify/assert"
corev1 "k8s.io/api/core/v1"
)
func TestGetResourcesFromPath(t *testing.T) {
resources, err := CreateResourceProviderFromPath("./test_files/test_1")
provider, err := CreateResourceProviderFromPath("./test_files/test_1")
assert.Equal(t, nil, err, "Error should be nil")
assert.Equal(t, "Path", resources.SourceType, "Should have type Path")
assert.Equal(t, "./test_files/test_1", resources.SourceName, "Should have filename as name")
assert.Equal(t, "unknown", resources.ServerVersion, "Server version should be unknown")
assert.IsType(t, time.Now(), resources.CreationTime, "Creation time should be set")
assert.Equal(t, "Path", provider.SourceType, "Should have type Path")
assert.Equal(t, "./test_files/test_1", provider.SourceName, "Should have filename as name")
assert.Equal(t, "unknown", provider.ServerVersion, "Server version should be unknown")
assert.IsType(t, time.Now(), provider.CreationTime, "Creation time should be set")
assert.Equal(t, 0, len(resources.Nodes), "Should not have any nodes")
assert.Equal(t, 0, len(provider.Nodes), "Should not have any nodes")
assert.Equal(t, 1, len(resources.Namespaces), "Should have a namespace")
assert.Equal(t, "two", resources.Namespaces[0].ObjectMeta.Name)
assert.Equal(t, 1, len(provider.Namespaces), "Should have a namespace")
assert.Equal(t, "two", provider.Namespaces[0].ObjectMeta.Name)
assert.Equal(t, 9, len(resources.Controllers), "Should have eight controllers")
namespaceCount := map[string]int{}
for _, controller := range resources.Controllers {
namespaceCount[controller.ObjectMeta.GetNamespace()]++
for _, resources := range provider.Resources {
for _, controller := range resources {
namespaceCount[controller.ObjectMeta.GetNamespace()]++
}
}
assert.Equal(t, 8, namespaceCount[""])
assert.Equal(t, 11, provider.Resources.GetLength())
assert.Equal(t, 10, namespaceCount[""])
assert.Equal(t, 1, namespaceCount["two"])
}
@@ -48,8 +50,8 @@ func TestGetMultipleResourceFromSingleFile(t *testing.T) {
assert.Equal(t, 0, len(resources.Nodes), "Should not have any nodes")
assert.Equal(t, 1, len(resources.Controllers), "Should have one controller")
assert.Equal(t, "dashboard", resources.Controllers[0].PodSpec.Containers[0].Name)
assert.Equal(t, 1, len(resources.Resources["extensions/Deployment"]), "Should have one controller")
assert.Equal(t, "dashboard", resources.Resources["extensions/Deployment"][0].PodSpec.Containers[0].Name)
assert.Equal(t, 2, len(resources.Namespaces), "Should have a namespace")
assert.Equal(t, "polaris", resources.Namespaces[0].ObjectMeta.Name)
@@ -65,21 +67,14 @@ func TestAddResourcesFromReader(t *testing.T) {
contents, err := ioutil.ReadFile("./test_files/test_2/multi.yaml")
assert.NoError(t, err)
reader := bytes.NewBuffer(contents)
resources := &ResourceProvider{
ServerVersion: "unknown",
SourceType: "Path",
SourceName: "-",
Nodes: []corev1.Node{},
Namespaces: []corev1.Namespace{},
Controllers: []GenericWorkload{},
}
err = addResourcesFromReader(reader, resources)
resources := newResourceProvider("unknown", "Path", "-")
err = resources.addResourcesFromReader(reader)
assert.NoError(t, err)
assert.Equal(t, 0, len(resources.Nodes), "Should not have any nodes")
assert.Equal(t, 1, len(resources.Controllers), "Should have one controller")
assert.Equal(t, "dashboard", resources.Controllers[0].PodSpec.Containers[0].Name)
assert.Equal(t, 1, len(resources.Resources["extensions/Deployment"]), "Should have one controller")
assert.Equal(t, "dashboard", resources.Resources["extensions/Deployment"][0].PodSpec.Containers[0].Name)
assert.Equal(t, 2, len(resources.Namespaces), "Should have a namespace")
assert.Equal(t, "polaris", resources.Namespaces[0].ObjectMeta.Name)
@@ -88,7 +83,7 @@ func TestAddResourcesFromReader(t *testing.T) {
func TestGetResourceFromAPI(t *testing.T) {
k8s, dynamicInterface := test.SetupTestAPI(test.GetMockControllers("test")...)
resources, err := CreateResourceProviderFromAPI(context.Background(), k8s, "test", &dynamicInterface)
resources, err := CreateResourceProviderFromAPI(context.Background(), k8s, "test", &dynamicInterface, conf.Configuration{})
assert.Equal(t, nil, err, "Error should be nil")
assert.Equal(t, "Cluster", resources.SourceType, "Should have type Path")
@@ -96,8 +91,7 @@ func TestGetResourceFromAPI(t *testing.T) {
assert.IsType(t, time.Now(), resources.CreationTime, "Creation time should be set")
assert.Equal(t, 0, len(resources.Nodes), "Should not have any nodes")
assert.Equal(t, 0, len(resources.Ingresses), "Should not have any ingresses")
assert.Equal(t, 5, len(resources.Controllers), "Should have 5 controllers")
assert.Equal(t, 5, len(resources.Resources), "Should have 5 controllers")
expectedNames := map[string]bool{
"deploy": false,
@@ -106,8 +100,10 @@ func TestGetResourceFromAPI(t *testing.T) {
"statefulset": false,
"daemonset": false,
}
for _, ctrl := range resources.Controllers {
expectedNames[ctrl.ObjectMeta.GetName()] = true
for _, controllers := range resources.Resources {
for _, ctrl := range controllers {
expectedNames[ctrl.ObjectMeta.GetName()] = true
}
}
for name, val := range expectedNames {
assert.Equal(t, true, val, name)
@@ -15,50 +15,75 @@
package validator
import (
"encoding/json"
"testing"
conf "github.com/fairwindsops/polaris/pkg/config"
"github.com/fairwindsops/polaris/test"
"github.com/fairwindsops/polaris/pkg/kube"
"github.com/stretchr/testify/assert"
extv1beta1 "k8s.io/api/extensions/v1beta1"
network "k8s.io/api/networking/v1beta1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
)
func TestValidatePDB(t *testing.T) {
c := conf.Configuration{
Checks: map[string]conf.Severity{
"pdbDisruptionsIsZero": conf.SeverityWarning,
},
}
pdb := unstructured.Unstructured{}
res, err := kube.NewGenericResourceFromUnstructured(pdb)
res.Kind = "PodDisruptionBudget"
actualResult, err := applyNonControllerSchemaChecks(&c, nil, res)
if err != nil {
panic(err)
}
results := actualResult.Results["pdbDisruptionsIsZero"]
assert.False(t, results.Success)
assert.Equal(t, conf.SeverityWarning, results.Severity)
assert.Equal(t, "Reliability", results.Category)
assert.EqualValues(t, "Voluntary evictions are not possible", results.Message)
}
func TestValidateIngress(t *testing.T) {
c := conf.Configuration{
Checks: map[string]conf.Severity{
"tlsSettingsMissing": conf.SeverityWarning,
},
}
ingress := test.MockIngress()
tls := network.IngressTLS{
Hosts: []string{"test"},
SecretName: "secret",
}
var actualResult Result
actualResult, err := ValidateIngress(&c, ingress)
ingress := network.Ingress{}
ingress.Spec.TLS = []network.IngressTLS{tls}
b, err := json.Marshal(ingress)
if err != nil {
panic(err)
}
unst := unstructured.Unstructured{}
err = json.Unmarshal(b, &unst.Object)
if err != nil {
panic(err)
}
res, err := kube.NewGenericResourceFromUnstructured(unst)
if err != nil {
panic(err)
}
res.Kind = "Ingress"
actualResult, err := applyNonControllerSchemaChecks(&c, nil, res)
if err != nil {
panic(err)
}
results := actualResult.Results["tlsSettingsMissing"]
assert.False(t, results.Success)
assert.Equal(t, conf.Severity("warning"), results.Severity)
assert.Equal(t, "Security", results.Category)
assert.EqualValues(t, "Ingress does not have TLS configured", results.Message)
tls := extv1beta1.IngressTLS{
Hosts: []string{"test"},
SecretName: "secret",
}
ingress.Spec.TLS = []extv1beta1.IngressTLS{tls}
actualResult, err = ValidateIngress(&c, ingress)
if err != nil {
panic(err)
}
results = actualResult.Results["tlsSettingsMissing"]
assert.True(t, results.Success)
assert.Equal(t, conf.Severity("warning"), results.Severity)
assert.Equal(t, conf.SeverityWarning, results.Severity)
assert.Equal(t, "Security", results.Category)
assert.EqualValues(t, "Ingress has TLS configured", results.Message)
}
-58
View File
@@ -1,58 +0,0 @@
// Copyright 2019 FairwindsOps Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package validator
import (
"github.com/fairwindsops/polaris/pkg/config"
"github.com/fairwindsops/polaris/pkg/kube"
corev1 "k8s.io/api/core/v1"
)
// ValidateContainer validates a single container from a given controller
func ValidateContainer(conf *config.Configuration, controller kube.GenericWorkload, container *corev1.Container, isInit bool) (ContainerResult, error) {
results, err := applyContainerSchemaChecks(conf, controller, container, isInit)
if err != nil {
return ContainerResult{}, err
}
cRes := ContainerResult{
Name: container.Name,
Results: results,
}
return cRes, nil
}
// ValidateAllContainers validates both init and regular containers
func ValidateAllContainers(conf *config.Configuration, controller kube.GenericWorkload) ([]ContainerResult, error) {
results := []ContainerResult{}
pod := controller.PodSpec
for _, container := range pod.InitContainers {
result, err := ValidateContainer(conf, controller, &container, true)
if err != nil {
return nil, err
}
results = append(results, result)
}
for _, container := range pod.Containers {
result, err := ValidateContainer(conf, controller, &container, false)
if err != nil {
return nil, err
}
results = append(results, result)
}
return results, nil
}
+22 -19
View File
@@ -50,8 +50,8 @@ exemptions:
- foo
`
func getEmptyWorkload(t *testing.T, name string) kube.GenericWorkload {
workload, err := kube.NewGenericWorkloadFromPod(corev1.Pod{
func getEmptyWorkload(t *testing.T, name string) kube.GenericResource {
workload, err := kube.NewGenericResourceFromPod(corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
@@ -64,25 +64,28 @@ func testValidate(t *testing.T, container *corev1.Container, resourceConf *strin
testValidateWithWorkload(t, container, resourceConf, getEmptyWorkload(t, controllerName), expectedDangers, expectedWarnings, expectedSuccesses)
}
func testValidateWithWorkload(t *testing.T, container *corev1.Container, resourceConf *string, workload kube.GenericWorkload, expectedDangers []ResultMessage, expectedWarnings []ResultMessage, expectedSuccesses []ResultMessage) {
func testValidateWithWorkload(t *testing.T, container *corev1.Container, resourceConf *string, workload kube.GenericResource, expectedDangers []ResultMessage, expectedWarnings []ResultMessage, expectedSuccesses []ResultMessage) {
parsedConf, err := conf.Parse([]byte(*resourceConf))
assert.NoError(t, err, "Expected no error when parsing config")
var results ResultSet
results, err = applyContainerSchemaChecks(&parsedConf, workload, container, false)
results, err = applyContainerSchemaChecks(&parsedConf, nil, workload, container, false)
if err != nil {
panic(err)
}
summary := results.GetSummary()
assert.Equal(t, uint(len(expectedWarnings)), summary.Warnings)
assert.ElementsMatch(t, expectedWarnings, results.GetWarnings())
if assert.Equal(t, uint(len(expectedWarnings)), summary.Warnings) {
assert.ElementsMatch(t, expectedWarnings, results.GetWarnings())
}
assert.Equal(t, uint(len(expectedDangers)), summary.Dangers)
assert.ElementsMatch(t, expectedDangers, results.GetDangers())
if assert.Equal(t, uint(len(expectedDangers)), summary.Dangers) {
assert.ElementsMatch(t, expectedDangers, results.GetDangers())
}
assert.Equal(t, uint(len(expectedSuccesses)), summary.Successes)
assert.ElementsMatch(t, expectedSuccesses, results.GetSuccesses())
if assert.Equal(t, uint(len(expectedSuccesses)), summary.Successes) {
assert.ElementsMatch(t, expectedSuccesses, results.GetSuccesses())
}
}
func TestValidateResourcesEmptyConfig(t *testing.T) {
@@ -90,7 +93,7 @@ func TestValidateResourcesEmptyConfig(t *testing.T) {
Name: "Empty",
}
results, err := applyContainerSchemaChecks(&conf.Configuration{}, getEmptyWorkload(t, ""), container, false)
results, err := applyContainerSchemaChecks(&conf.Configuration{}, nil, getEmptyWorkload(t, ""), container, false)
if err != nil {
panic(err)
}
@@ -187,7 +190,7 @@ func TestValidateHealthChecks(t *testing.T) {
for idx, tt := range testCases {
t.Run(tt.name, func(t *testing.T) {
controller := getEmptyWorkload(t, "")
results, err := applyContainerSchemaChecks(&conf.Configuration{Checks: tt.probes}, controller, tt.container, tt.isInit)
results, err := applyContainerSchemaChecks(&conf.Configuration{Checks: tt.probes}, nil, controller, tt.container, tt.isInit)
if err != nil {
panic(err)
}
@@ -301,7 +304,7 @@ func TestValidateImage(t *testing.T) {
for _, tt := range testCases {
t.Run(tt.name, func(t *testing.T) {
controller := getEmptyWorkload(t, "")
results, err := applyContainerSchemaChecks(&conf.Configuration{Checks: tt.image}, controller, tt.container, false)
results, err := applyContainerSchemaChecks(&conf.Configuration{Checks: tt.image}, nil, controller, tt.container, false)
if err != nil {
panic(err)
}
@@ -418,7 +421,7 @@ func TestValidateNetworking(t *testing.T) {
for _, tt := range testCases {
t.Run(tt.name, func(t *testing.T) {
controller := getEmptyWorkload(t, "")
results, err := applyContainerSchemaChecks(&conf.Configuration{Checks: tt.networkConf}, controller, tt.container, false)
results, err := applyContainerSchemaChecks(&conf.Configuration{Checks: tt.networkConf}, nil, controller, tt.container, false)
if err != nil {
panic(err)
}
@@ -921,9 +924,9 @@ func TestValidateSecurity(t *testing.T) {
for _, tt := range testCases {
t.Run(tt.name, func(t *testing.T) {
workload, err := kube.NewGenericWorkloadFromPod(corev1.Pod{Spec: *tt.pod}, nil)
workload, err := kube.NewGenericResourceFromPod(corev1.Pod{Spec: *tt.pod}, nil)
assert.NoError(t, err)
results, err := applyContainerSchemaChecks(&conf.Configuration{Checks: tt.securityConf}, workload, tt.container, false)
results, err := applyContainerSchemaChecks(&conf.Configuration{Checks: tt.securityConf}, nil, workload, tt.container, false)
if err != nil {
panic(err)
}
@@ -1066,9 +1069,9 @@ func TestValidateRunAsRoot(t *testing.T) {
}
for idx, tt := range testCases {
t.Run(tt.name, func(t *testing.T) {
workload, err := kube.NewGenericWorkloadFromPod(corev1.Pod{Spec: *tt.pod}, nil)
workload, err := kube.NewGenericResourceFromPod(corev1.Pod{Spec: *tt.pod}, nil)
assert.NoError(t, err)
results, err := applyContainerSchemaChecks(&config, workload, tt.container, false)
results, err := applyContainerSchemaChecks(&config, nil, workload, tt.container, false)
if err != nil {
panic(err)
}
@@ -1168,7 +1171,7 @@ func TestValidateResourcesEmptyContainerCPURequestsExempt(t *testing.T) {
expectedSuccesses := []ResultMessage{}
workload, err := kube.NewGenericWorkloadFromPod(corev1.Pod{
workload, err := kube.NewGenericResourceFromPod(corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
Annotations: map[string]string{

Some files were not shown because too many files have changed in this diff Show More