Compare commits

...
20 Commits
Author SHA1 Message Date
Nick Huanca f03f97ab07 bump version (#184) 2019-08-01 09:55:40 -06:00
Nick Huanca 75f70352ba Additional Pod Controller Scans (#166)
**Changes**

- Refactored the way controllers work to be an interface
- Added configurable controllers to include in scans
- Added daemonsets, jobs and cronjobs in scans
- Added `ReplicationController` type controllers to the supported list
- Adjusted logic for failed YAML parsing to bubble up errors
- Added better logic for calculating summaries on cluster wide results
- Relocated responsibilities for counting types into validators vs spreading it around more packages
- Fixed bug where cronjob parsing was using wrong KIND
- Added fixtures for mocking new controller types
- Added example yamls to test scanning files
- Added functions to NamespacedResult(s) to reduce code complexity deep set iterations
- Refactored how results get added to namespacedresults so adding more later is easier
- Minor signature changes for interface implementing structs for controllers
2019-07-31 15:56:27 -06:00
Bobby Brennan 4aa360a933 Remove swapfile 2019-07-31 14:26:18 -04:00
Will Ledingham dce24a0a34 Merge pull request #181 from FairwindsOps/wl/config-URL
Wl/config url
2019-07-31 10:45:21 -04:00
Will Ledingham fae7a9fc17 Merge branch 'master' into wl/config-URL 2019-07-30 17:02:02 -04:00
Will Ledingham 79b0a00d5c more edits 2019-07-30 16:59:11 -04:00
Will Ledingham e4fe5ab085 more edits 2019-07-30 16:45:49 -04:00
Will Ledingham 2049698c8e small edit 2019-07-30 16:37:24 -04:00
Bobby Brennan 20bd32afb6 Rename ReactiveOps to Fairwinds (#180)
* Rename ReactiveOps to Fairwinds

* Rename ReactiveOps to Fairwinds
2019-07-30 15:29:09 -04:00
Will Ledingham c132f7ee51 more edits 2019-07-29 13:29:53 -04:00
Will Ledingham 10025764cd altered to fix tests on CircleCl. 2019-07-29 11:10:59 -04:00
Will Ledingham c8c0e07a22 altered to fix tests on CircleCl. 2019-07-29 11:09:33 -04:00
Will Ledingham b55f4717b1 typo 2019-07-29 10:44:01 -04:00
Will Ledingham f493c380fc Merge branch 'wl/config-URL' of https://github.com/FairwindsOps/polaris into wl/config-URL 2019-07-29 10:34:56 -04:00
Will Ledingham baa652197a Fixed error handling in ParseFile, added a test for parseFile where no Http server is configured 2019-07-29 10:33:27 -04:00
Will Ledingham a6525fc807 Merge branch 'master' into wl/config-URL 2019-07-25 16:37:30 -04:00
Will Ledingham e01c39230a cleaned up unnecessary comments 2019-07-25 16:34:59 -04:00
Will Ledingham 7b8b5fee4d expanded ParseFile function to include URL's and added a test for it. 2019-07-25 16:31:17 -04:00
Will Ledingham 819b77ae1a Pod tests (#177)
* add pod test

* add pod test 2

* update tests

* Added pod tests for configured Host IPC, Host PID, and Host Newtowrk.

* Fixed expected vs. actual mixup
2019-07-25 09:31:37 -04:00
Bobby Brennan edccf88ccd update fairwinds logo (#179) 2019-07-25 08:52:57 -04:00
54 changed files with 1540 additions and 402 deletions
+7 -8
View File
@@ -70,6 +70,7 @@ references:
run:
name: Test Dashboard
command: |
sed -ri "s|'(quay.io/reactiveops/polaris:).+'|'\1${CIRCLE_SHA1}'|" ./deploy/dashboard.yaml
kubectl apply -f ./deploy/dashboard.yaml
sleep 10
kubectl get pods --namespace polaris
@@ -132,7 +133,7 @@ jobs:
- *test_kube_dashboard
test:
working_directory: /go/src/github.com/reactiveops/polaris/
working_directory: /go/src/github.com/fairwindsops/polaris/
docker:
- image: circleci/golang:1.12
steps:
@@ -144,7 +145,7 @@ jobs:
- *test_binary_dashboard
release_binary:
working_directory: /go/src/github.com/reactiveops/polaris/
working_directory: /go/src/github.com/fairwindsops/polaris/
docker:
- image: circleci/golang:1.12
steps:
@@ -158,7 +159,7 @@ jobs:
- *release_deploy_configs
release_images:
working_directory: /go/src/github.com/reactiveops/polaris/
working_directory: /go/src/github.com/fairwindsops/polaris/
docker:
- image: quay.io/reactiveops/ci-images:v8.0-stretch
steps:
@@ -172,11 +173,6 @@ workflows:
build:
jobs:
- test
- test_k8s:
# Ignore update-version branch, which changes deploy/ image references before the images are built
filters:
branches:
ignore: /.*\/update-version/
- build:
requires:
- test
@@ -185,6 +181,9 @@ workflows:
filters:
tags:
only: /^testing-.*/
- test_k8s:
requires:
- build
release:
jobs:
- release_binary:
+1 -1
View File
@@ -21,7 +21,7 @@ changelog:
- '^test:'
brew:
github:
owner: reactiveops
owner: FairwindsOps
name: homebrew-tap
folder: Formula
description: Open Source Best Practices for Kubernetes
+11 -8
View File
@@ -1,5 +1,8 @@
# x.x.x (next release)
# 0.4.0
* Added additional Pod Controllers to scan PodSpec (`jobs`, `cronjobs`, `daemonsets`, `replicationcontrollers`)
# 0.3.1
* Changed dashboard branding to refer to new org name Fairwinds
@@ -7,7 +10,7 @@
* Added `--set-exit-code-on-error` and `--set-exit-code-below-score` flags to better support CI/CD
# 0.2.1
* [Fix](https://github.com/reactiveops/polaris/issues/146): Fixed logic on RunAsNonRoot check to incorporate settings in podSpec
* [Fix](https://github.com/FairwindsOps/polaris/issues/146): Fixed logic on RunAsNonRoot check to incorporate settings in podSpec
# 0.2.0
* Added `--output-format` flag for better CI/CD support
@@ -16,23 +19,23 @@
* Show error message if no kubeconfig is set
# 0.1.5
* [Fix](https://github.com/reactiveops/polaris/issues/125): ignore limits/requests for initContainers
* [Fix](https://github.com/reactiveops/polaris/issues/132): support custom base path
* [Fix](https://github.com/FairwindsOps/polaris/issues/125): ignore limits/requests for initContainers
* [Fix](https://github.com/FairwindsOps/polaris/issues/132): support custom base path
# 0.1.4
* [Fix](https://github.com/reactiveops/polaris/issues/116): details pages getting template errors
* [Fix](https://github.com/reactiveops/polaris/issues/114): support all auth providers
* [Fix](https://github.com/reactiveops/polaris/issues/112): Ignore readiness probe for initContainers
* [Fix](https://github.com/FairwindsOps/polaris/issues/116): details pages getting template errors
* [Fix](https://github.com/FairwindsOps/polaris/issues/114): support all auth providers
* [Fix](https://github.com/FairwindsOps/polaris/issues/112): Ignore readiness probe for initContainers
# 0.1.3
* [Fix](https://github.com/reactiveops/polaris/issues/109): dashboard not updating when running persistently
* [Fix](https://github.com/FairwindsOps/polaris/issues/109): dashboard not updating when running persistently
# 0.1.2
* Stored all third-party assets (e.g. Charts.js) to local files to support offline dashboard viewing
* Fix: custom configs in `ConfigMap` not respected
# 0.1.1
* [Fix](https://github.com/reactiveops/polaris/issues/93): missing `config.yaml` and dashboard assets in binary releases
* [Fix](https://github.com/FairwindsOps/polaris/issues/93): missing `config.yaml` and dashboard assets in binary releases
* Added some tests and better error handling
# 0.1.0
+7 -7
View File
@@ -7,7 +7,7 @@ Issues, whether bugs, tasks, or feature requests are essential for keeping Polar
This project adheres to a [code of conduct](CODE_OF_CONDUCT.md). Please review this document before contributing to this project.
## Sign the CLA
Before you can contribute, you will need to sign the [Contributor License Agreement](https://cla-assistant.io/reactiveops/polaris).
Before you can contribute, you will need to sign the [Contributor License Agreement](https://cla-assistant.io/fairwinds/polaris).
## Project Structure
@@ -15,7 +15,7 @@ Polaris is built on top of [controller-runtime](https://github.com/kubernetes-si
## Getting Started
We label issues with the ["good first issue" tag](https://github.com/reactiveops/polaris/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) if we believe they'll be a good starting point for new contributors. If you're interested in working on an issue, please start a conversation on that issue, and we can help answer any questions as they come up.
We label issues with the ["good first issue" tag](https://github.com/FairwindsOps/polaris/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) if we believe they'll be a good starting point for new contributors. If you're interested in working on an issue, please start a conversation on that issue, and we can help answer any questions as they come up.
## Setting Up Your Development Environment
### Prerequisites
@@ -23,8 +23,8 @@ We label issues with the ["good first issue" tag](https://github.com/reactiveops
* If you want to see the local changes you make on a Polaris dashboard, you will need access to a Kubernetes cluster defined in `~/.kube/config`
### Installation
* Install the project with `go get github.com/reactiveops/polaris`
* Change into the polaris directory which is installed at `$GOPATH/src/github.com/reactiveops/polaris`
* Install the project with `go get github.com/fairwindsops/polaris`
* Change into the polaris directory which is installed at `$GOPATH/src/github.com/fairwindsops/polaris`
* See the dashboard with `go run main.go --dashboard`, then open http://localhost:8080/
* See the audit data `go run main.go --audit`. This command shows the audit information on the command line.
@@ -76,12 +76,12 @@ it needs to be a minor or major release in order to prevent breaking the Helm ch
### Minor/Major releases
Minor and major releases need to change both this repository and the
[Helm chart repo](https://github.com/reactiveops/charts/).
[Helm chart repo](https://github.com/FairwindsOps/charts/).
The steps are:
1. Modify the [Helm chart](https://github.com/reactiveops/charts/stable/polaris)
1. Modify the [Helm chart](https://github.com/FairwindsOps/charts/stable/polaris)
1. Clone the helm charts repo
1. `git clone https://github.com/reactiveops/charts`
1. `git clone https://github.com/FairwindsOps/charts`
2. `git checkout -b yourname/update-polaris`
1. Bump the version number in:
1. stable/polaris/README.md
+2 -2
View File
@@ -1,5 +1,5 @@
FROM golang:1.12.4 AS build-env
WORKDIR /go/src/github.com/reactiveops/polaris/
WORKDIR /go/src/github.com/fairwindsops/polaris/
COPY . .
RUN go get -u github.com/gobuffalo/packr/v2/packr2
@@ -11,7 +11,7 @@ RUN apk --no-cache add ca-certificates
RUN addgroup -S polaris && adduser -u 1200 -S polaris -G polaris
USER 1200
COPY --from=build-env /go/src/github.com/reactiveops/polaris/polaris .
COPY --from=build-env /go/src/github.com/fairwindsops/polaris/polaris .
WORKDIR /opt/app
+1 -1
View File
@@ -186,7 +186,7 @@
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2019 ReactiveOps
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.
+13 -147
View File
@@ -5,7 +5,7 @@
[![Version][version-image]][version-link] [![CircleCI][circleci-image]][circleci-link] [![Go Report Card][goreport-image]][goreport-link]
</div>
[version-image]: https://img.shields.io/static/v1.svg?label=Version&message=0.3.1&color=239922
[version-image]: https://img.shields.io/static/v1.svg?label=Version&message=0.4.0&color=239922
[version-link]: https://github.com/FairwindsOps/polaris
[goreport-image]: https://goreportcard.com/badge/github.com/FairwindsOps/polaris
@@ -22,16 +22,19 @@ problems in the future. Polaris can be run in a few different modes:
- An experimental validating webhook that can prevent any future deployments that do not live up to a configured standard.
- A command-line audit that can be incorporated into your CI/CD pipeline
**Want to learn more?** ReactiveOps holds [office hours on Zoom](https://zoom.us/j/242508205) the first Friday of every month, at 12pm Eastern. You can also reach out via email at `opensource@fairwinds.com`
**Want to learn more?** Fairwinds holds [office hours on Zoom](https://zoom.us/j/242508205) the first Friday of every month, at 12pm Eastern. You can also reach out via email at `opensource@fairwinds.com`
## Quickstart
# Dashboard Quickstart
```
kubectl apply -f https://github.com/reactiveops/polaris/releases/latest/download/dashboard.yaml
kubectl apply -f https://github.com/FairwindsOps/polaris/releases/latest/download/dashboard.yaml
kubectl port-forward --namespace polaris svc/polaris-dashboard 8080:80
```
With the port forwarding in place, you can open http://localhost:8080 in your browser to view the dashboard.
* * *
# Components
## Dashboard
The Polaris dashboard is a way to get a simple visual overview of the current state of your Kubernetes deployments as well as a roadmap for what can be improved. The dashboard provides a cluster wide overview as well as breaking out results by category, namespace, and deployment.
@@ -42,162 +45,25 @@ The Polaris dashboard is a way to get a simple visual overview of the current st
Our default standards in Polaris are rather high, so dont be surprised if your score is lower than you might expect. A key goal for Polaris was to set a high standard and aim for great configuration by default. If the defaults weve included are too strict, its easy to adjust the configuration as part of the deployment configuration to better suit your workloads.
## Webhook
Polaris includes experimental support for an optional validating webhook. This accepts the same configuration as the dashboard, and can run the same validations. This webhook will reject any deployments that trigger a validation error. This is indicative of the greater goal of Polaris, not just to encourage better configuration through dashboard visibility, but to actually enforce it with this webhook. *Although we are working towards greater stability and better test coverage, we do not currently consider this webhook component production ready.*
Unfortunately we have not found a way to display warnings as part of `kubectl` output unless we are rejecting a deployment altogether. That means that any checks with a severity of `warning` will still pass webhook validation, and the only evidence of that warning will either be in the Polaris dashboard or the Polaris webhook logs.
## Installation and Usage
Polaris can be installed on your cluster using kubectl or Helm. It can also
be run as a local binary, which will use your kubeconfig to connect to the cluster
or run against local YAML files.
# Usage Documentation
See the [Usage Guide](/docs/usage.md) in the docs folder.
### kubectl
#### Dashboard
```
kubectl apply -f https://github.com/reactiveops/polaris/releases/latest/download/dashboard.yaml
kubectl port-forward --namespace polaris svc/polaris-dashboard 8080:80
```
#### Webhook
```
kubectl apply -f https://github.com/reactiveops/polaris/releases/latest/download/webhook.yaml
```
### Helm
Start by adding the ReactiveOps Helm repo:
```
helm repo add reactiveops-stable https://charts.reactiveops.com/stable
```
#### Dashboard
```
helm upgrade --install polaris reactiveops-stable/polaris --namespace polaris
kubectl port-forward --namespace polaris svc/polaris-dashboard 8080:80
```
#### Webhook
```
helm upgrade --install polaris reactiveops-stable/polaris --namespace polaris \
--set webhook.enable=true --set dashboard.enable=false
```
### Local Binary
#### Installation
Binary releases are available on the [releases page](https://github.com/reactiveops/polaris/releases) or can be installed with [Homebrew](https://brew.sh/):
```
brew tap reactiveops/tap
brew install reactiveops/tap/polaris
polaris --version
```
You can run `polaris --help` to see a full list of options.
#### Dashboard
The dashboard can be run on your local machine, without installing anything on the cluster.
Polaris will use your local kubeconfig to connect to the cluster.
```
polaris --dashboard --dashboard-port 8080
```
#### Audits
You can also run audits on the command line and see the output as JSON, YAML, or a raw score:
```
polaris --audit --output-format yaml > report.yaml
polaris --audit --output-format score
# 92
```
Both the dashboard and audits can run against a local directory or YAML file
rather than a cluster:
```
polaris --audit --audit-path ./deploy/
```
##### Running with CI/CD
You can integrate Polaris into CI/CD for repositories containing infrastructure-as-code.
For example, to fail if polaris detects *any* error-level issues, or if the score drops below 90%:
```bash
polaris --audit --audit-path ./deploy/ \
--set-exit-code-on-error \
--set-exit-code-below-score 90
```
## Configuration
Polaris supports a wide range of validations covering a number of Kubernetes best practices. Here's a sample configuration file that includes all currently supported checks. The [default configuration](https://github.com/reactiveops/polaris/blob/master/examples/config.yaml) contains a number of those checks. This repository also includes a sample [full configuration file](https://github.com/reactiveops/polaris/blob/master/examples/config-full.yaml) that enables all available checks.
Each check can be assigned a `severity`. Only checks with a severity of `error` 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 `error` will result in a change being rejected.
Polaris validation checks fall into several different categories:
- [Health Checks](docs/health-checks.md)
- [Images](docs/images.md)
- [Networking](docs/networking.md)
- [Resources](docs/resources.md)
- [Security](docs/security.md)
## CLI Options
```
# high-level flags
-version
Prints the version of Polaris
-config string
Location of Polaris configuration file
-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
-dashboard
Runs the webserver for Polaris dashboard.
-dashboard-base-path string
Path on which the dashboard is served (default "/")
-dashboard-port int
Port for the dashboard webserver (default 8080)
-display-name string
An optional identifier for the audit
# audit flags
-audit
Runs a one-time audit.
-audit-path string
If specified, audits one or more YAML files instead of a cluster
-output-file string
Destination file for audit results
-output-format string
Output format for results - json, yaml, or score (default "json")
-output-url string
Destination URL to send audit results
-set-exit-code-below-score int
When running with --audit, set an exit code of 4 when the score is below this threshold (1-100)
-set-exit-code-on-error
When running with --audit, set an exit code of 3 when the audit contains error-level issues.
# webhook flags
-webhook
Runs the webhook webserver.
-webhook-port int
Port for the webhook webserver (default 9876)
-disable-webhook-config-installer
disable the installer in the webhook server, so it won't install webhook configuration resources during bootstrapping
```
## Contributing
# Contributing
PRs welcome! Check out the [Contributing Guidelines](CONTRIBUTING.md),
[Code of Conduct](CODE_OF_CONDUCT.md), and [Roadmap](ROADMAP.md) for more information.
## Further Information
# Further Information
A history of changes to this project can be viewed in the [Changelog](CHANGELOG.md)
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)
## License
# License
Apache License 2.0
+21 -2
View File
@@ -57,6 +57,13 @@ data:
- SYS_CHROOT
- KILL
- AUDIT_WRITE
controllers_to_scan:
- Deployments
- StatefulSets
- DaemonSets
- Jobs
- CronJobs
- ReplicationControllers
---
# Source: polaris/templates/dashboard.rbac.yaml
@@ -81,6 +88,15 @@ rules:
resources:
- 'deployments'
- 'statefulsets'
- 'daemonsets'
verbs:
- 'get'
- 'list'
- apiGroups:
- 'batch'
resources:
- 'jobs'
- 'cronjobs'
verbs:
- 'get'
- 'list'
@@ -90,6 +106,7 @@ rules:
- 'nodes'
- 'namespaces'
- 'pods'
- 'replicationcontrollers'
verbs:
- 'get'
- 'list'
@@ -133,7 +150,7 @@ apiVersion: apps/v1
kind: Deployment
metadata:
annotations:
checksum/config: '6ec4a4dc87403cae67c01438398a5f1d4ef836ffeaf26a33b685c066b940495a'
checksum/config: '8aa5a565fba7a2db98d46752087de8c1dcc83b70cd762c5829d5ba01270d54a2'
name: polaris-dashboard
namespace: polaris
labels:
@@ -161,7 +178,7 @@ spec:
- --dashboard
- --config
- /opt/app/config.yaml
image: 'quay.io/reactiveops/polaris:0.3'
image: 'quay.io/reactiveops/polaris:0.4'
imagePullPolicy: 'Always'
name: dashboard
ports:
@@ -199,6 +216,8 @@ spec:
subPath: config.yaml
readOnly: true
serviceAccountName: polaris-dashboard
nodeSelector: {}
tolerations: []
---
# Source: polaris/templates/audit.job.yaml
+31 -2
View File
@@ -69,6 +69,13 @@ data:
- SYS_CHROOT
- KILL
- AUDIT_WRITE
controllers_to_scan:
- Deployments
- StatefulSets
- DaemonSets
- Jobs
- CronJobs
- ReplicationControllers
---
# Source: polaris/templates/webhook.rbac.yaml
@@ -87,12 +94,32 @@ metadata:
labels:
app: polaris
rules:
# auditor rules rbac
- apiGroups:
- 'apps'
- 'extensions'
resources:
- 'deployments'
- 'statefulsets'
- 'daemonsets'
verbs:
- 'get'
- 'list'
- apiGroups:
- 'batch'
resources:
- 'jobs'
- 'cronjobs'
verbs:
- 'get'
- 'list'
- apiGroups:
- ''
resources:
- 'nodes'
- 'namespaces'
- 'pods'
- 'replicationcontrollers'
verbs:
- 'get'
- 'list'
@@ -186,7 +213,7 @@ apiVersion: apps/v1
kind: Deployment
metadata:
annotations:
checksum/config: '6ec4a4dc87403cae67c01438398a5f1d4ef836ffeaf26a33b685c066b940495a'
checksum/config: '8aa5a565fba7a2db98d46752087de8c1dcc83b70cd762c5829d5ba01270d54a2'
name: polaris-webhook
namespace: polaris
labels:
@@ -211,7 +238,7 @@ spec:
- --webhook
- --config
- /opt/app/config.yaml
image: 'quay.io/reactiveops/polaris:0.3'
image: 'quay.io/reactiveops/polaris:0.4'
imagePullPolicy: 'Always'
ports:
- containerPort: 9876
@@ -261,6 +288,8 @@ spec:
mountPath: /tmp/
readOnly: false
serviceAccountName: polaris-webhook
nodeSelector: {}
tolerations: []
volumes:
- name: config
configMap:
+13
View File
@@ -0,0 +1,13 @@
# Polaris Exit Codes for Audit Runs
<dl>
<dt>Exit 0</dt>
<dd>Successful exit code</dd>
<dt>Exit 1</dt>
<dd>Could not run audit, or application had a failure while running.</dd>
<dt>Exit 2</dt>
<dd>Unused</dd>
<dt>Exit 3</dt>
<dd>Exiting due to `--set-exit-code-on-error` being set and at least one error was found after an audit.</dd>
<dt>Edit 4</dd>
<dd>Exiting due to `--set-exit-code-below-score` being set and the audit resulted in a score less than the minimum score value.</dd>
</dl>
+145
View File
@@ -0,0 +1,145 @@
# Installation and Usage
Polaris can be installed on your cluster using kubectl or Helm. It can also
be run as a local binary, which will use your kubeconfig to connect to the cluster
or run against local YAML files.
## Configuration
Polaris supports a wide range of validations covering a number of Kubernetes best practices. Here's a sample configuration file that includes all currently supported checks. The [default configuration](https://github.com/fairwindsops/polaris/blob/master/examples/config.yaml) contains a number of those checks. This repository also includes a sample [full configuration file](https://github.com/fairwindsops/polaris/blob/master/examples/config-full.yaml) that enables all available checks.
Each check can be assigned a `severity`. Only checks with a severity of `error` 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 `error` will result in a change being rejected.
Polaris validation checks fall into several different categories:
- [Health Checks](check-documentation/health-checks.md)
- [Images](check-documentation/images.md)
- [Networking](check-documentation/networking.md)
- [Resources](check-documentation/resources.md)
- [Security](check-documentation/security.md)
## CLI Options
```
# high-level flags
-version
Prints the version of Polaris
-config string
Location of Polaris configuration file
-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
-dashboard
Runs the webserver for Polaris dashboard.
-dashboard-base-path string
Path on which the dashboard is served (default "/")
-dashboard-port int
Port for the dashboard webserver (default 8080)
-display-name string
An optional identifier for the audit
# audit flags
-audit
Runs a one-time audit.
-audit-path string
If specified, audits one or more YAML files instead of a cluster
-output-file string
Destination file for audit results
-output-format string
Output format for results - json, yaml, or score (default "json")
-output-url string
Destination URL to send audit results
-set-exit-code-below-score int
When running with --audit, set an exit code of 4 when the score is below this threshold (1-100)
-set-exit-code-on-error
When running with --audit, set an exit code of 3 when the audit contains error-level issues.
# webhook flags
-webhook
Runs the webhook webserver.
-webhook-port int
Port for the webhook webserver (default 9876)
-disable-webhook-config-installer
disable the installer in the webhook server, so it won't install webhook configuration resources during bootstrapping
```
# Installing
There are several ways to install and use Polaris. Below outline ways to install using `kubectl`, `helm` and `local binary`.
## kubectl
### Dashboard
```
kubectl apply -f https://github.com/fairwindsops/polaris/releases/latest/download/dashboard.yaml
kubectl port-forward --namespace polaris svc/polaris-dashboard 8080:80
```
### Webhook
```
kubectl apply -f https://github.com/fairwindsops/polaris/releases/latest/download/webhook.yaml
```
## Helm
Start by adding the ReactiveOps Helm repo:
```
helm repo add reactiveops-stable https://charts.reactiveops.com/stable
```
### Dashboard
```
helm upgrade --install polaris reactiveops-stable/polaris --namespace polaris
kubectl port-forward --namespace polaris svc/polaris-dashboard 8080:80
```
### Webhook
```
helm upgrade --install polaris reactiveops-stable/polaris --namespace polaris \
--set webhook.enable=true --set dashboard.enable=false
```
## Local Binary
### Installation
Binary releases are available on the [releases page](https://github.com/fairwindsops/polaris/releases) or can be installed with [Homebrew](https://brew.sh/):
```
brew tap reactiveops/tap
brew install reactiveops/tap/polaris
polaris --version
```
You can run `polaris --help` to see a full list of options.
### Dashboard
The dashboard can be run on your local machine, without installing anything on the cluster.
Polaris will use your local kubeconfig to connect to the cluster.
```
polaris --dashboard --dashboard-port 8080
```
### Audits
You can also run audits on the command line and see the output as JSON, YAML, or a raw score:
```
polaris --audit --output-format yaml > report.yaml
polaris --audit --output-format score
# 92
```
Both the dashboard and audits can run against a local directory or YAML file
rather than a cluster:
```
polaris --audit --audit-path ./deploy/
```
### Running with CI/CD
You can integrate Polaris into CI/CD for repositories containing infrastructure-as-code.
For example, to fail if polaris detects *any* error-level issues, or if the score drops below 90%:
```bash
polaris --audit --audit-path ./deploy/ \
--set-exit-code-on-error \
--set-exit-code-below-score 90
```
For more on exit code meanings, see [exit-code docs](exit-codes.md).
+7
View File
@@ -41,3 +41,10 @@ security:
- SYS_CHROOT
- KILL
- AUDIT_WRITE
controllers_to_scan:
- Deployments
- StatefulSets
- DaemonSets
- CronJobs
- Jobs
- ReplicationControllers
+37 -16
View File
@@ -1,4 +1,4 @@
// Copyright 2019 ReactiveOps
// 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.
@@ -22,15 +22,14 @@ import (
"io/ioutil"
"net/http"
"os"
"strings"
conf "github.com/reactiveops/polaris/pkg/config"
"github.com/reactiveops/polaris/pkg/dashboard"
"github.com/reactiveops/polaris/pkg/kube"
"github.com/reactiveops/polaris/pkg/validator"
fwebhook "github.com/reactiveops/polaris/pkg/webhook"
conf "github.com/fairwindsops/polaris/pkg/config"
"github.com/fairwindsops/polaris/pkg/dashboard"
"github.com/fairwindsops/polaris/pkg/kube"
"github.com/fairwindsops/polaris/pkg/validator"
fwebhook "github.com/fairwindsops/polaris/pkg/webhook"
"github.com/sirupsen/logrus"
appsv1 "k8s.io/api/apps/v1"
extensionsv1beta1 "k8s.io/api/extensions/v1beta1"
apitypes "k8s.io/apimachinery/pkg/types"
_ "k8s.io/client-go/plugin/pkg/client/auth" // Required for other auth providers like GKE.
"sigs.k8s.io/controller-runtime/pkg/client/config"
@@ -42,10 +41,12 @@ import (
const (
// Version represents the current release version of Polaris
Version = "0.3.1"
Version = "0.4.0"
)
func main() {
// Load CLI Flags
// TODO: Split up global flags vs dashboard/webhook/audit specific flags
dashboard := flag.Bool("dashboard", false, "Runs the webserver for Polaris dashboard.")
webhook := flag.Bool("webhook", false, "Runs the webhook webserver.")
audit := flag.Bool("audit", false, "Runs a one-time audit.")
@@ -67,11 +68,13 @@ func main() {
flag.Parse()
// if version is specified anywhere, print and exit
if *version {
fmt.Printf("Polaris version %s\n", Version)
os.Exit(0)
}
// Set logging level
parsedLevel, err := logrus.ParseLevel(*logLevel)
if err != nil {
logrus.Errorf("log-level flag has invalid value %s", *logLevel)
@@ -79,25 +82,32 @@ func main() {
logrus.SetLevel(parsedLevel)
}
// Parse the config file
c, err := conf.ParseFile(*configPath)
if *displayName != "" {
c.DisplayName = *displayName
}
if err != nil {
logrus.Errorf("Error parsing config at %s: %v", *configPath, err)
os.Exit(1)
}
// Override display name on reports if defined in CLI flags
if *displayName != "" {
c.DisplayName = *displayName
}
// default to run as audit if no "run-mode" is defined
if !*dashboard && !*webhook && !*audit {
*audit = true
}
// perform the action for the desired "run-mode"
if *webhook {
startWebhookServer(c, *disableWebhookConfigInstaller, *webhookPort)
} else if *dashboard {
startDashboardServer(c, *auditPath, *dashboardPort, *dashboardBasePath)
} else if *audit {
auditData := runAndReportAudit(c, *auditPath, *auditOutputFile, *auditOutputURL, *auditOutputFormat)
// exit code 3 if any errors in the audit else if score is under desired minimum, exit 4
if *setExitCode && auditData.ClusterSummary.Results.Totals.Errors > 0 {
logrus.Infof("%d errors found in audit", auditData.ClusterSummary.Results.Totals.Errors)
os.Exit(3)
@@ -174,10 +184,19 @@ func startWebhookServer(c conf.Configuration, disableWebhookConfigInstaller bool
logrus.Infof("Polaris webhook server listening on port %d", port)
d1 := fwebhook.NewWebhook("deployments", mgr, fwebhook.Validator{Config: c}, &appsv1.Deployment{})
d2 := fwebhook.NewWebhook("deployments-ext", mgr, fwebhook.Validator{Config: c}, &extensionsv1beta1.Deployment{})
// Iterate all the configurations supported controllers to scan and register them for webhooks
// Should only register controllers that are configured to be scanned
logrus.Debug("Registering webhooks to the webhook server")
if err = as.Register(d1, d2); err != nil {
var webhooks []webhook.Webhook
for index, controllerToScan := range c.ControllersToScan {
for innerIndex, supportedAPIType := range controllerToScan.ListSupportedAPIVersions() {
webhookName := strings.ToLower(fmt.Sprintf("%s-%d-%d", controllerToScan, index, innerIndex))
hook := fwebhook.NewWebhook(webhookName, mgr, fwebhook.Validator{Config: c}, supportedAPIType)
webhooks = append(webhooks, hook)
}
}
if err = as.Register(webhooks...); err != nil {
logrus.Debugf("Unable to register webhooks in the admission server: %v", err)
os.Exit(1)
}
@@ -190,6 +209,7 @@ func startWebhookServer(c conf.Configuration, disableWebhookConfigInstaller bool
}
func runAndReportAudit(c conf.Configuration, auditPath string, outputFile string, outputURL string, outputFormat string) validator.AuditData {
// Create a kubernetes client resource provider
k, err := kube.CreateResourceProvider(auditPath)
if err != nil {
logrus.Errorf("Error fetching Kubernetes resources %v", err)
@@ -198,7 +218,8 @@ func runAndReportAudit(c conf.Configuration, auditPath string, outputFile string
auditData, err := validator.RunAudit(c, k)
if err != nil {
panic(err)
logrus.Errorf("Error while running audit on resources: %v", err)
os.Exit(1)
}
var outputBytes []byte
+19 -8
View File
@@ -1,4 +1,4 @@
// Copyright 2019 ReactiveOps
// 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.
@@ -19,6 +19,8 @@ import (
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
packr "github.com/gobuffalo/packr/v2"
corev1 "k8s.io/api/core/v1"
@@ -28,12 +30,13 @@ import (
// Configuration contains all of the config for the validation checks.
type Configuration struct {
DisplayName string `json:"displayName"`
Resources Resources `json:"resources"`
HealthChecks HealthChecks `json:"healthChecks"`
Images Images `json:"images"`
Networking Networking `json:"networking"`
Security Security `json:"security"`
DisplayName string `json:"displayName"`
Resources Resources `json:"resources"`
HealthChecks HealthChecks `json:"healthChecks"`
Images Images `json:"images"`
Networking Networking `json:"networking"`
Security Security `json:"security"`
ControllersToScan []SupportedController `json:"controllers_to_scan"`
}
// Resources contains config for resource requests and limits.
@@ -112,12 +115,20 @@ type SecurityCapabilityLists struct {
// ParseFile parses config from a file.
func ParseFile(path string) (Configuration, error) {
configBox := packr.New("Config", "../../examples")
var rawBytes []byte
var err error
configBox := packr.New("Config", "../../examples")
if path == "" {
rawBytes, err = configBox.Find("config.yaml")
} else if strings.HasPrefix(path, "https://") || strings.HasPrefix(path, "http://") {
//path is a url
response, err2 := http.Get(path)
if err2 != nil {
return Configuration{}, err2
}
rawBytes, err = ioutil.ReadAll(response.Body)
} else {
//path is local
rawBytes, err = ioutil.ReadFile(path)
}
if err != nil {
+48 -2
View File
@@ -1,4 +1,4 @@
// Copyright 2019 ReactiveOps
// 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.
@@ -15,6 +15,11 @@
package config
import (
"context"
"io"
"log"
"net/http"
"regexp"
"testing"
"github.com/stretchr/testify/assert"
@@ -53,6 +58,13 @@ resources:
warning:
below: 300M
above: 4G
controllers_to_scan:
- Deployments
- StatefulSets
- Jobs
- CronJobs
- DaemonSets
- ReplicationControllers
`
var resourceConfJSON1 = `{
@@ -97,7 +109,8 @@ var resourceConfJSON1 = `{
"above": "4G"
}
}
}
},
"controllers_to_scan": ["Deployments", "StatefulSets", "Jobs", "CronJobs", "DaemonSets", "ReplicationControllers"]
}`
func TestParseError(t *testing.T) {
@@ -120,6 +133,36 @@ func TestParseJson(t *testing.T) {
testParsedConfig(t, &parsedConf)
}
func TestConfigFromURL(t *testing.T) {
var err error
var parsedConf Configuration
srv := &http.Server{Addr: ":8081"}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, resourceConfYAML1)
})
go func() {
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
log.Fatalf("ListenAndServe(): %s", err)
}
}()
parsedConf, err = ParseFile("http://localhost:8081/exampleURL")
assert.NoError(t, err, "Expected no error when parsing YAML from URL")
if err := srv.Shutdown(context.TODO()); err != nil {
panic(err)
}
testParsedConfig(t, &parsedConf)
}
func TestConfigNoServerError(t *testing.T) {
var err error
_, err = ParseFile("http://localhost:8081/exampleURL")
assert.Error(t, err)
assert.Regexp(t, regexp.MustCompile("connection refused"), err.Error())
}
func testParsedConfig(t *testing.T, config *Configuration) {
cpuRequests := config.Resources.CPURequestRanges
assert.Equal(t, int64(100), cpuRequests.Error.Below.ScaledValue(resource.Milli))
@@ -144,4 +187,7 @@ func testParsedConfig(t *testing.T, config *Configuration) {
assert.Equal(t, int64(6000), memLimits.Error.Above.ScaledValue(resource.Mega))
assert.Equal(t, int64(300), memLimits.Warning.Below.ScaledValue(resource.Mega))
assert.Equal(t, int64(4000), memLimits.Warning.Above.ScaledValue(resource.Mega))
controllersToScan := config.ControllersToScan
assert.ElementsMatch(t, []SupportedController{Deployments, StatefulSets, Jobs, CronJobs, DaemonSets, ReplicationControllers}, controllersToScan)
}
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2019 ReactiveOps
// 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.
+151
View File
@@ -0,0 +1,151 @@
package config
import (
"bytes"
"encoding/json"
"fmt"
"strings"
appsv1 "k8s.io/api/apps/v1"
batchv1 "k8s.io/api/batch/v1"
batchv1beta1 "k8s.io/api/batch/v1beta1"
corev1 "k8s.io/api/core/v1"
extensionsv1beta1 "k8s.io/api/extensions/v1beta1"
"k8s.io/apimachinery/pkg/runtime"
)
const (
// Unsupported is the default enum for non-defined controller types
Unsupported SupportedController = iota
// Deployments are a supported controller for scanning pod specs
Deployments
// StatefulSets are a supported controller for scanning pod specs
StatefulSets
// DaemonSets are a supported controller for scanning pod specs
DaemonSets
// Jobs are a supported controller for scanning pod specs
Jobs
// CronJobs are a supported controller for scanning pod specs
CronJobs
// ReplicationControllers are supported controllers for scanning pod specs
ReplicationControllers
)
// ControllerStrings are strongly ordered to match the SupportedController enum
var ControllerStrings = []string{
"Unsupported",
"Deployments",
"StatefulSets",
"DaemonSets",
"Jobs",
"CronJobs",
"ReplicationController",
}
// stringLookupForSupportedControllers is the list of lowercase singular and plural strings for string to enum lookup
var stringLookupForSupportedControllers = map[string]SupportedController{
"deployment": Deployments,
"deployments": Deployments,
"statefulset": StatefulSets,
"statefulsets": StatefulSets,
"daemonset": DaemonSets,
"daemonsets": DaemonSets,
"job": Jobs,
"jobs": Jobs,
"cronjob": CronJobs,
"cronjobs": CronJobs,
"replicationcontroller": ReplicationControllers,
"replicationcontrollers": ReplicationControllers,
}
// SupportedController is a constant item of a controller that is supported for scanning pod specs
type SupportedController int
// String returns the string name for a given SupportedController enum
func (s SupportedController) String() string {
return ControllerStrings[s]
}
// MarshalJSON manages writing the enum into json data or error on unsupported value
func (s SupportedController) MarshalJSON() ([]byte, error) {
if s == Unsupported {
return []byte{}, fmt.Errorf("Unsupported is not a valid Supported Controller")
}
buffer := bytes.NewBufferString(`"`)
buffer.WriteString(s.String())
buffer.WriteString(`"`)
return buffer.Bytes(), nil
}
// UnmarshalJSON handles reading json data into enum
func (s *SupportedController) UnmarshalJSON(b []byte) error {
var j string
err := json.Unmarshal(b, &j)
if err != nil {
return err
}
*s, err = GetSupportedControllerFromString(j)
if err != nil {
return err
}
return nil
}
// ListSupportedAPIVersions for SupportedController returns all the apimachinery object type supported
func (s SupportedController) ListSupportedAPIVersions() []runtime.Object {
var supportedVersions []runtime.Object
switch s {
case Deployments:
supportedVersions = []runtime.Object{
&appsv1.Deployment{},
&extensionsv1beta1.Deployment{},
}
case StatefulSets:
supportedVersions = []runtime.Object{
&appsv1.StatefulSet{},
}
case DaemonSets:
supportedVersions = []runtime.Object{
&appsv1.DaemonSet{},
}
case Jobs:
supportedVersions = []runtime.Object{
&batchv1.Job{},
}
case CronJobs:
supportedVersions = []runtime.Object{
&batchv1beta1.CronJob{},
}
case ReplicationControllers:
supportedVersions = []runtime.Object{
&corev1.ReplicationController{},
}
}
return supportedVersions
}
// GetSupportedControllerFromString fuzzy matches a string with a SupportedController Enum
func GetSupportedControllerFromString(str string) (SupportedController, error) {
lowerStr := strings.ToLower(str)
controller, keyFound := stringLookupForSupportedControllers[lowerStr]
if !keyFound || controller == Unsupported {
return 0, fmt.Errorf("Value ('%v') in configuration was not found in Supported Controllers: (%v)", str, strings.Join(ControllerStrings, ","))
}
return controller, nil
}
// CheckIfKindIsConfiguredForValidation takes a kind (in string format) and checks if Polaris is configured to scan this type of controller
func (c Configuration) CheckIfKindIsConfiguredForValidation(kind string) bool {
controller, err := GetSupportedControllerFromString(kind)
// if no errors then we found the kind in supported controller types
if err == nil {
// see if the kind exists in the controllers to scan config
for _, controllerToScan := range c.ControllersToScan {
if controller == controllerToScan {
return true
}
}
}
return false
}
+125
View File
@@ -0,0 +1,125 @@
// 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 config
import (
"encoding/json"
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
type checkMarshal struct {
Controllers []SupportedController `json:"controllers"`
}
func TestUnmarshalSupportedControllers(t *testing.T) {
for idx, controllerString := range ControllerStrings {
// Check taking all strings and convert them into enums
object := checkMarshal{}
jsonBytes := []byte(fmt.Sprintf(`{"controllers":["%v"]}`, controllerString))
err := json.Unmarshal(jsonBytes, &object)
if idx == 0 {
if err == nil {
// Assure the first element always should NOT unmarshal
t.Errorf("Expected the first element (%s) to fail json unmarshal. First element in this array should always be 'Unsupported'", controllerString)
}
} else if err != nil {
t.Errorf("Could not unmarshal json (%s) to a Supported controller; Received (%v)", jsonBytes, err)
}
}
badJSON := []byte(`{"controllers":[{"not":"valid_structure"}]}`)
err := json.Unmarshal(badJSON, &checkMarshal{})
if err == nil {
t.Error("expected invalid schema json to fail unmarshal")
}
}
func TestMarshalSupportedControllers(t *testing.T) {
for idx, controllerString := range ControllerStrings {
controllerType, err := GetSupportedControllerFromString(controllerString)
if idx == 0 {
if err == nil {
t.Errorf("Expected first element (%s) to fail as a non-valid supported controller. Reserved for 'Unsupported'", controllerString)
}
} else if err != nil {
t.Errorf("Unable to take the configured string (%s) and convert into Enum; Error: (%s)", controllerString, err)
}
object := checkMarshal{
Controllers: []SupportedController{controllerType},
}
_, err = json.Marshal(object)
if idx == 0 {
if err == nil {
t.Errorf("Expected (%s) to throw an error. Reserving the first element in the enum to be an invalid config", controllerString)
}
} else if err != nil {
t.Errorf("Could not write json output for element (%s); Received Error: (%s)", controllerString, err)
}
}
}
func TestCheckIfControllerKindIsConfiguredForValidation(t *testing.T) {
config := Configuration{}
for _, controllerString := range ControllerStrings[1:] {
controllerEnum, err := GetSupportedControllerFromString(controllerString)
if err != nil {
t.Errorf("Expected controller string (%s) to be convertable into enum: (%s)", controllerString, err)
}
config.ControllersToScan = append(config.ControllersToScan, controllerEnum)
}
validControllerKinds := []string{
"deployment",
"statefulset",
}
invalidControllerKinds := []string{
"nonExistent",
}
for _, kind := range validControllerKinds {
if ok := config.CheckIfKindIsConfiguredForValidation(kind); !ok {
t.Errorf("Kind (%s) expected to be valid for configuration.", kind)
}
}
for _, kind := range invalidControllerKinds {
if ok := config.CheckIfKindIsConfiguredForValidation(kind); ok {
t.Errorf("Kind (%s) should not be a valid controller to check", kind)
}
}
}
func TestGetSupportedControllerFromString(t *testing.T) {
fixture := map[string]SupportedController{
"": Unsupported,
"asdfasdf": Unsupported,
"\000": Unsupported,
"deployMENTS": Deployments,
"JOB": Jobs,
}
for inputString, expectedType := range fixture {
resolvedType, err := GetSupportedControllerFromString(inputString)
if expectedType == Unsupported && err == nil {
t.Errorf("Expected (%s) to resolve to an unsupported type and throw an error.", inputString)
}
assert.Equal(t, expectedType, resolvedType, fmt.Sprintf("Expected (%s) to return (%s) controller type.", inputString, expectedType))
}
}
+2 -11
View File
@@ -22,20 +22,11 @@ body {
}
.navbar .logo {
width: 250px;
}
.navbar span.oss-text {
color: #23103A;
display: block;
font-size: 11px;
margin-bottom: 3px;
padding-left: 66px;
margin-bottom: -8px;
height: 80px;
}
.navbar .fw-logo {
height: 50px;
height: 64px;
}
.navbar a {
Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

+5 -5
View File
@@ -1,4 +1,4 @@
// Copyright 2019 ReactiveOps
// 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.
@@ -23,9 +23,9 @@ import (
packr "github.com/gobuffalo/packr/v2"
"github.com/gorilla/mux"
conf "github.com/reactiveops/polaris/pkg/config"
"github.com/reactiveops/polaris/pkg/kube"
"github.com/reactiveops/polaris/pkg/validator"
conf "github.com/fairwindsops/polaris/pkg/config"
"github.com/fairwindsops/polaris/pkg/kube"
"github.com/fairwindsops/polaris/pkg/validator"
"github.com/sirupsen/logrus"
"gitlab.com/golang-commonmark/markdown"
)
@@ -72,7 +72,7 @@ func GetTemplateBox() *packr.Box {
// GetMarkdownBox returns a binary-friendly set of markdown files with error details
func GetMarkdownBox() *packr.Box {
if markdownBox == (*packr.Box)(nil) {
markdownBox = packr.New("Markdown", "../../docs")
markdownBox = packr.New("Markdown", "../../docs/check-documentation")
}
return markdownBox
}
+4 -6
View File
@@ -1,4 +1,4 @@
// Copyright 2019 ReactiveOps
// 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.
@@ -16,15 +16,13 @@ package dashboard
import (
"fmt"
"github.com/reactiveops/polaris/pkg/validator"
"strings"
"github.com/fairwindsops/polaris/pkg/validator"
)
func getAllControllerResults(nr validator.NamespaceResult) []validator.ControllerResult {
results := []validator.ControllerResult{}
results = append(results, nr.DeploymentResults...)
results = append(results, nr.StatefulSetResults...)
return results
return nr.GetAllControllerResults()
}
func getWarningWidth(counts validator.CountSummary, fullWidth int) uint {
+1 -2
View File
@@ -6,8 +6,7 @@
</a>
<div class="navbar-right">
<a href="https://fairwinds.com?source=polaris" target="_blank">
<span class="oss-text">An Open Source Project By</span>
<img class="fw-logo" src="static/images/fw-logo.svg" alt="Fairwinds" />
<img class="fw-logo" src="static/images/oss-logo.png" alt="Fairwinds" />
</a>
</div>
</div>
+84 -35
View File
@@ -11,6 +11,8 @@ import (
"github.com/sirupsen/logrus"
appsv1 "k8s.io/api/apps/v1"
batchv1 "k8s.io/api/batch/v1"
batchv1beta1 "k8s.io/api/batch/v1beta1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
k8sYaml "k8s.io/apimachinery/pkg/util/yaml"
@@ -21,15 +23,19 @@ import (
// ResourceProvider contains k8s resources to be audited
type ResourceProvider struct {
ServerVersion string
CreationTime time.Time
SourceName string
SourceType string
Nodes []corev1.Node
Deployments []appsv1.Deployment
StatefulSets []appsv1.StatefulSet
Namespaces []corev1.Namespace
Pods []corev1.Pod
ServerVersion string
CreationTime time.Time
SourceName string
SourceType string
Nodes []corev1.Node
Deployments []appsv1.Deployment
StatefulSets []appsv1.StatefulSet
DaemonSets []appsv1.DaemonSet
Jobs []batchv1.Job
CronJobs []batchv1beta1.CronJob
ReplicationControllers []corev1.ReplicationController
Namespaces []corev1.Namespace
Pods []corev1.Pod
}
type k8sResource struct {
@@ -47,14 +53,18 @@ func CreateResourceProvider(directory string) (*ResourceProvider, error) {
// 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{},
Deployments: []appsv1.Deployment{},
StatefulSets: []appsv1.StatefulSet{},
Namespaces: []corev1.Namespace{},
Pods: []corev1.Pod{},
ServerVersion: "unknown",
SourceType: "Path",
SourceName: directory,
Nodes: []corev1.Node{},
Deployments: []appsv1.Deployment{},
StatefulSets: []appsv1.StatefulSet{},
DaemonSets: []appsv1.DaemonSet{},
Jobs: []batchv1.Job{},
CronJobs: []batchv1beta1.CronJob{},
ReplicationControllers: []corev1.ReplicationController{},
Namespaces: []corev1.Namespace{},
Pods: []corev1.Pod{},
}
addYaml := func(contents string) error {
@@ -77,7 +87,7 @@ func CreateResourceProviderFromPath(directory string) (*ResourceProvider, error)
}
err = addYaml(spec)
if err != nil {
logrus.Errorf("Error parsing YAML %v", err)
logrus.Errorf("Error parsing YAML: (%v)", err)
return err
}
}
@@ -124,6 +134,26 @@ func CreateResourceProviderFromAPI(kube kubernetes.Interface, clusterName string
logrus.Errorf("Error fetching StatefulSets%v", err)
return nil, err
}
daemonSets, err := kube.AppsV1().DaemonSets("").List(listOpts)
if err != nil {
logrus.Errorf("Error fetching DaemonSets %v", err)
return nil, err
}
jobs, err := kube.BatchV1().Jobs("").List(listOpts)
if err != nil {
logrus.Errorf("Error fetching Jobs %v", err)
return nil, err
}
cronJobs, err := kube.BatchV1beta1().CronJobs("").List(listOpts)
if err != nil {
logrus.Errorf("Error fetching CronJobs %v", err)
return nil, err
}
replicationControllers, err := kube.CoreV1().ReplicationControllers("").List(listOpts)
if err != nil {
logrus.Errorf("Error fetching ReplicationControllers %v", err)
return nil, err
}
nodes, err := kube.CoreV1().Nodes().List(listOpts)
if err != nil {
logrus.Errorf("Error fetching Nodes %v", err)
@@ -141,15 +171,19 @@ func CreateResourceProviderFromAPI(kube kubernetes.Interface, clusterName string
}
api := ResourceProvider{
ServerVersion: serverVersion.Major + "." + serverVersion.Minor,
SourceType: "Cluster",
SourceName: clusterName,
CreationTime: time.Now(),
Deployments: deploys.Items,
StatefulSets: statefulSets.Items,
Nodes: nodes.Items,
Namespaces: namespaces.Items,
Pods: pods.Items,
ServerVersion: serverVersion.Major + "." + serverVersion.Minor,
SourceType: "Cluster",
SourceName: clusterName,
CreationTime: time.Now(),
Deployments: deploys.Items,
StatefulSets: statefulSets.Items,
DaemonSets: daemonSets.Items,
Jobs: jobs.Items,
CronJobs: cronJobs.Items,
ReplicationControllers: replicationControllers.Items,
Nodes: nodes.Items,
Namespaces: namespaces.Items,
Pods: pods.Items,
}
return &api, nil
}
@@ -160,19 +194,34 @@ func addResourceFromString(contents string, resources *ResourceProvider) error {
resource := k8sResource{}
err := decoder.Decode(&resource)
if err != nil {
// TODO: should we panic if the YAML is bad?
logrus.Errorf("Invalid YAML: %s", string(contents))
return nil
return err
}
decoder = k8sYaml.NewYAMLOrJSONDecoder(bytes.NewReader(contentBytes), 1000)
if resource.Kind == "Deployment" {
dep := appsv1.Deployment{}
err = decoder.Decode(&dep)
resources.Deployments = append(resources.Deployments, dep)
controller := appsv1.Deployment{}
err = decoder.Decode(&controller)
resources.Deployments = append(resources.Deployments, controller)
} else if resource.Kind == "StatefulSet" {
dep := appsv1.StatefulSet{}
err = decoder.Decode(&dep)
resources.StatefulSets = append(resources.StatefulSets, dep)
controller := appsv1.StatefulSet{}
err = decoder.Decode(&controller)
resources.StatefulSets = append(resources.StatefulSets, controller)
} else if resource.Kind == "DaemonSet" {
controller := appsv1.DaemonSet{}
err = decoder.Decode(&controller)
resources.DaemonSets = append(resources.DaemonSets, controller)
} else if resource.Kind == "Job" {
controller := batchv1.Job{}
err = decoder.Decode(&controller)
resources.Jobs = append(resources.Jobs, controller)
} else if resource.Kind == "CronJob" {
controller := batchv1beta1.CronJob{}
err = decoder.Decode(&controller)
resources.CronJobs = append(resources.CronJobs, controller)
} else if resource.Kind == "ReplicationController" {
controller := corev1.ReplicationController{}
err = decoder.Decode(&controller)
resources.ReplicationControllers = append(resources.ReplicationControllers, controller)
} else if resource.Kind == "Namespace" {
ns := corev1.Namespace{}
err = decoder.Decode(&ns)
+8 -2
View File
@@ -1,10 +1,11 @@
package kube
import (
"github.com/reactiveops/polaris/test"
"github.com/stretchr/testify/assert"
"testing"
"time"
"github.com/fairwindsops/polaris/test"
"github.com/stretchr/testify/assert"
)
func TestGetResourcesFromPath(t *testing.T) {
@@ -53,6 +54,11 @@ func TestGetMultipleResourceFromSingleFile(t *testing.T) {
assert.Equal(t, "polaris-2", resources.Namespaces[1].ObjectMeta.Name)
}
func TestGetMultipleResourceFromBadFile(t *testing.T) {
_, err := CreateResourceProviderFromPath("./test_files/test_3")
assert.NotEqual(t, nil, err, "CreateResource From Path should fail with bad yaml")
}
func TestGetResourceFromAPI(t *testing.T) {
k8s := test.SetupTestAPI()
k8s = test.SetupAddControllers(k8s, "test")
+16
View File
@@ -0,0 +1,16 @@
apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: test
spec:
schedule: "*/1 * * * *"
jobTemplate:
spec:
template:
spec:
containers:
- name: test
image: busybox
args:
- whoami
restartPolicy: OnFailure
@@ -0,0 +1,20 @@
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: test
labels:
k8s-app: test
spec:
selector:
matchLabels:
name: test
template:
metadata:
labels:
name: test
spec:
containers:
- name: test
image: busybox
command: ["whoami"]
resources: {}
+12
View File
@@ -0,0 +1,12 @@
apiVersion: batch/v1
kind: Job
metadata:
name: test
spec:
template:
spec:
containers:
- name: test
image: alpine
command: ["whoami"]
restartPolicy: Never
@@ -0,0 +1,19 @@
apiVersion: v1
kind: ReplicationController
metadata:
name: test
spec:
replicas: 1
selector:
app: test
template:
metadata:
name: test
labels:
app: test
spec:
containers:
- name: test
image: busybox
command: ["tail"]
args: ["-f", "/dev/null"]
+5
View File
@@ -0,0 +1,5 @@
--
# Source: polaris/templates/dashboard.deployment.yaml
apiVersion: extensions/v1beta1
kind: Deployment
::::
+3 -3
View File
@@ -1,4 +1,4 @@
// Copyright 2019 ReactiveOps
// 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.
@@ -18,8 +18,8 @@ import (
"fmt"
"strings"
conf "github.com/reactiveops/polaris/pkg/config"
"github.com/reactiveops/polaris/pkg/validator/messages"
conf "github.com/fairwindsops/polaris/pkg/config"
"github.com/fairwindsops/polaris/pkg/validator/messages"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
)
+2 -2
View File
@@ -1,4 +1,4 @@
// Copyright 2019 ReactiveOps
// 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.
@@ -17,7 +17,7 @@ package validator
import (
"testing"
conf "github.com/reactiveops/polaris/pkg/config"
conf "github.com/fairwindsops/polaris/pkg/config"
"github.com/stretchr/testify/assert"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
+21 -64
View File
@@ -1,4 +1,4 @@
// Copyright 2019 ReactiveOps
// 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.
@@ -15,82 +15,39 @@
package validator
import (
conf "github.com/reactiveops/polaris/pkg/config"
"github.com/reactiveops/polaris/pkg/kube"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
conf "github.com/fairwindsops/polaris/pkg/config"
"github.com/fairwindsops/polaris/pkg/kube"
"github.com/fairwindsops/polaris/pkg/validator/controllers"
controller "github.com/fairwindsops/polaris/pkg/validator/controllers"
"github.com/sirupsen/logrus"
)
// ControllerSpec is a generic type for k8s controller specs
type ControllerSpec struct {
Template corev1.PodTemplateSpec
}
// Controller is a generic type for k8s controllers (e.g. Deployments and StatefulSets)
type Controller struct {
Type string
Name string
Namespace string
Spec ControllerSpec
}
// ValidateController validates a single controller, returns a ControllerResult.
func ValidateController(conf conf.Configuration, controller Controller) ControllerResult {
pod := controller.Spec.Template.Spec
podResult := ValidatePod(conf, &pod)
func ValidateController(conf conf.Configuration, controller controller.Interface) ControllerResult {
pod := controller.GetPodSpec()
podResult := ValidatePod(conf, pod)
return ControllerResult{
Type: controller.Type,
Name: controller.Name,
Type: controller.GetType().String(),
Name: controller.GetName(),
PodResult: podResult,
}
}
// ValidateControllers validates that each deployment conforms to the Polaris config,
// returns a list of ResourceResults organized by namespace.
// builds a list of ResourceResults organized by namespace.
func ValidateControllers(config conf.Configuration, kubeResources *kube.ResourceProvider, nsResults *NamespacedResults) {
controllers := []Controller{}
for _, deploy := range kubeResources.Deployments {
controllers = append(controllers, ControllerFromDeployment(deploy))
var controllersToAudit []controller.Interface
for _, supportedControllers := range config.ControllersToScan {
loadedControllers, _ := controllers.LoadControllersByType(supportedControllers, kubeResources)
controllersToAudit = append(controllersToAudit, loadedControllers...)
}
for _, deploy := range kubeResources.StatefulSets {
controllers = append(controllers, ControllerFromStatefulSet(deploy))
}
for _, controller := range controllers {
for _, controller := range controllersToAudit {
controllerResult := ValidateController(config, controller)
nsResult := nsResults.getNamespaceResult(controller.Namespace)
nsResult := nsResults.getNamespaceResult(controller.GetNamespace())
nsResult.Summary.appendResults(*controllerResult.PodResult.Summary)
if controller.Type == "Deployment" {
nsResult.DeploymentResults = append(nsResult.DeploymentResults, controllerResult)
} else if controller.Type == "StatefulSet" {
nsResult.StatefulSetResults = append(nsResult.StatefulSetResults, controllerResult)
if err := nsResult.AddResult(controller.GetType(), controllerResult); err != nil {
logrus.Errorf("Internal Error: Failed to add a grouped result: %s", err)
}
}
}
// ControllerFrom* functions are 100% boilerplate
// ControllerFromDeployment creates a controller
func ControllerFromDeployment(c appsv1.Deployment) Controller {
spec := ControllerSpec{
Template: c.Spec.Template,
}
return Controller{
Type: "Deployment",
Name: c.Name,
Namespace: c.Namespace,
Spec: spec,
}
}
// ControllerFromStatefulSet creates a controller
func ControllerFromStatefulSet(c appsv1.StatefulSet) Controller {
spec := ControllerSpec{
Template: c.Spec.Template,
}
return Controller{
Type: "StatefulSet",
Name: c.Name,
Namespace: c.Namespace,
Spec: spec,
}
}
+37
View File
@@ -0,0 +1,37 @@
package controllers
import (
"github.com/fairwindsops/polaris/pkg/config"
kubeAPIBatchV1beta1 "k8s.io/api/batch/v1beta1"
kubeAPICoreV1 "k8s.io/api/core/v1"
)
// CronJobController is an implementation of controller for deployments
type CronJobController struct {
GenericController
K8SResource kubeAPIBatchV1beta1.CronJob
}
// GetPodTemplate returns the original template spec
func (c CronJobController) GetPodTemplate() *kubeAPICoreV1.PodTemplateSpec {
return &c.K8SResource.Spec.JobTemplate.Spec.Template
}
// GetPodSpec returns the original kubernetes template pod spec
func (c CronJobController) GetPodSpec() *kubeAPICoreV1.PodSpec {
return &c.K8SResource.Spec.JobTemplate.Spec.Template.Spec
}
// GetType returns the supportedcontroller enum type
func (c CronJobController) GetType() config.SupportedController {
return config.CronJobs
}
// NewCronJobController builds a new controller interface for Deployments
func NewCronJobController(originalDeploymentResource kubeAPIBatchV1beta1.CronJob) Interface {
controller := CronJobController{}
controller.Name = originalDeploymentResource.Name
controller.Namespace = originalDeploymentResource.Namespace
controller.K8SResource = originalDeploymentResource
return controller
}
+37
View File
@@ -0,0 +1,37 @@
package controllers
import (
"github.com/fairwindsops/polaris/pkg/config"
kubeAPIAppsV1 "k8s.io/api/apps/v1"
kubeAPICoreV1 "k8s.io/api/core/v1"
)
// DaemonSetController is an implementation of controller for deployments
type DaemonSetController struct {
GenericController
K8SResource kubeAPIAppsV1.DaemonSet
}
// GetPodTemplate returns the original template spec
func (d DaemonSetController) GetPodTemplate() *kubeAPICoreV1.PodTemplateSpec {
return &d.K8SResource.Spec.Template
}
// GetPodSpec returns the original kubernetes template pod spec
func (d DaemonSetController) GetPodSpec() *kubeAPICoreV1.PodSpec {
return &d.K8SResource.Spec.Template.Spec
}
// GetType returns the supportedcontroller enum type
func (d DaemonSetController) GetType() config.SupportedController {
return config.DaemonSets
}
// NewDaemonSetController builds a new controller interface for Deployments
func NewDaemonSetController(originalResource kubeAPIAppsV1.DaemonSet) Interface {
controller := DaemonSetController{}
controller.Name = originalResource.Name
controller.Namespace = originalResource.Namespace
controller.K8SResource = originalResource
return controller
}
+37
View File
@@ -0,0 +1,37 @@
package controllers
import (
"github.com/fairwindsops/polaris/pkg/config"
kubeAPIAppsV1 "k8s.io/api/apps/v1"
kubeAPICoreV1 "k8s.io/api/core/v1"
)
// DeploymentController is an implementation of controller for deployments
type DeploymentController struct {
GenericController
K8SResource kubeAPIAppsV1.Deployment
}
// GetPodTemplate returns the original template spec
func (d DeploymentController) GetPodTemplate() *kubeAPICoreV1.PodTemplateSpec {
return &d.K8SResource.Spec.Template
}
// GetPodSpec returns the original kubernetes template pod spec
func (d DeploymentController) GetPodSpec() *kubeAPICoreV1.PodSpec {
return &d.K8SResource.Spec.Template.Spec
}
// GetType returns the supportedcontroller enum type
func (d DeploymentController) GetType() config.SupportedController {
return config.Deployments
}
// NewDeploymentController builds a new controller interface for Deployments
func NewDeploymentController(originalDeploymentResource kubeAPIAppsV1.Deployment) Interface {
controller := DeploymentController{}
controller.Name = originalDeploymentResource.Name
controller.Namespace = originalDeploymentResource.Namespace
controller.K8SResource = originalDeploymentResource
return controller
}
+69
View File
@@ -0,0 +1,69 @@
package controllers
import (
"fmt"
"github.com/fairwindsops/polaris/pkg/config"
"github.com/fairwindsops/polaris/pkg/kube"
kubeAPICoreV1 "k8s.io/api/core/v1"
)
// Interface is an interface for k8s controllers (e.g. Deployments and StatefulSets)
type Interface interface {
GetName() string
GetNamespace() string
GetPodTemplate() *kubeAPICoreV1.PodTemplateSpec
GetPodSpec() *kubeAPICoreV1.PodSpec
GetType() config.SupportedController
}
// GenericController is a base implementation with some free methods for inherited structs
type GenericController struct {
Name string
Namespace string
}
// GetName is inherited by all controllers using generic controller to get the name of the controller
func (g GenericController) GetName() string {
return g.Name
}
// GetNamespace is inherited by all controllers using generic controller to get the namespace of the controller
func (g GenericController) GetNamespace() string {
return g.Namespace
}
// LoadControllersByType loads a list of controllers from the kubeResources by detecting their type
func LoadControllersByType(controllerType config.SupportedController, kubeResources *kube.ResourceProvider) ([]Interface, error) {
interfaces := []Interface{}
switch controllerType {
case config.Deployments:
for _, deploy := range kubeResources.Deployments {
interfaces = append(interfaces, NewDeploymentController(deploy))
}
case config.StatefulSets:
for _, statefulSet := range kubeResources.StatefulSets {
interfaces = append(interfaces, NewStatefulSetController(statefulSet))
}
case config.DaemonSets:
for _, daemonSet := range kubeResources.DaemonSets {
interfaces = append(interfaces, NewDaemonSetController(daemonSet))
}
case config.Jobs:
for _, job := range kubeResources.Jobs {
interfaces = append(interfaces, NewJobController(job))
}
case config.CronJobs:
for _, cronJob := range kubeResources.CronJobs {
interfaces = append(interfaces, NewCronJobController(cronJob))
}
case config.ReplicationControllers:
for _, replicationController := range kubeResources.ReplicationControllers {
interfaces = append(interfaces, NewReplicationControllerController(replicationController))
}
}
if len(interfaces) > 0 {
return interfaces, nil
}
return nil, fmt.Errorf("Controller type (%s) does not have a generator", controllerType)
}
+37
View File
@@ -0,0 +1,37 @@
package controllers
import (
"github.com/fairwindsops/polaris/pkg/config"
kubeAPIBatchV1 "k8s.io/api/batch/v1"
kubeAPICoreV1 "k8s.io/api/core/v1"
)
// JobController is an implementation of controller for deployments
type JobController struct {
GenericController
K8SResource kubeAPIBatchV1.Job
}
// GetPodTemplate returns the original template spec
func (j JobController) GetPodTemplate() *kubeAPICoreV1.PodTemplateSpec {
return &j.K8SResource.Spec.Template
}
// GetPodSpec returns the original kubernetes template pod spec
func (j JobController) GetPodSpec() *kubeAPICoreV1.PodSpec {
return &j.K8SResource.Spec.Template.Spec
}
// GetType returns the supportedcontroller enum type
func (j JobController) GetType() config.SupportedController {
return config.Jobs
}
// NewJobController builds a new controller interface for Deployments
func NewJobController(originalResource kubeAPIBatchV1.Job) Interface {
controller := JobController{}
controller.Name = originalResource.Name
controller.Namespace = originalResource.Namespace
controller.K8SResource = originalResource
return controller
}
@@ -0,0 +1,39 @@
package controllers
import (
"github.com/fairwindsops/polaris/pkg/config"
kubeAPICoreV1 "k8s.io/api/core/v1"
)
// NOTE: Maybe this name of ReplicationController is duplicative but it's more explicit since
// that's how kubernetes refers the the object.
// ReplicationControllerController is an implementation of controller for deployments
type ReplicationControllerController struct {
GenericController
K8SResource kubeAPICoreV1.ReplicationController
}
// GetPodTemplate returns the original template spec
func (r ReplicationControllerController) GetPodTemplate() *kubeAPICoreV1.PodTemplateSpec {
return r.K8SResource.Spec.Template
}
// GetPodSpec returns the original kubernetes template pod spec
func (r ReplicationControllerController) GetPodSpec() *kubeAPICoreV1.PodSpec {
return &r.K8SResource.Spec.Template.Spec
}
// GetType returns the supportedcontroller enum type
func (r ReplicationControllerController) GetType() config.SupportedController {
return config.ReplicationControllers
}
// NewReplicationControllerController builds a new controller interface for Deployments
func NewReplicationControllerController(originalResource kubeAPICoreV1.ReplicationController) Interface {
controller := ReplicationControllerController{}
controller.Name = originalResource.Name
controller.Namespace = originalResource.Namespace
controller.K8SResource = originalResource
return controller
}
+37
View File
@@ -0,0 +1,37 @@
package controllers
import (
"github.com/fairwindsops/polaris/pkg/config"
kubeAPIAppsV1 "k8s.io/api/apps/v1"
kubeAPICoreV1 "k8s.io/api/core/v1"
)
// StatefulSetController is an implementation of controller for deployments
type StatefulSetController struct {
GenericController
K8SResource kubeAPIAppsV1.StatefulSet
}
// GetPodTemplate returns the kubernetes template spec
func (s StatefulSetController) GetPodTemplate() *kubeAPICoreV1.PodTemplateSpec {
return &s.K8SResource.Spec.Template
}
// GetPodSpec returns the podspec from the original kubernetes resource
func (s StatefulSetController) GetPodSpec() *kubeAPICoreV1.PodSpec {
return &s.K8SResource.Spec.Template.Spec
}
// GetType returns the supportedcontroller enum type
func (s StatefulSetController) GetType() config.SupportedController {
return config.StatefulSets
}
// NewStatefulSetController builds a statefulset controller
func NewStatefulSetController(originalResource kubeAPIAppsV1.StatefulSet) Interface {
controller := StatefulSetController{}
controller.Name = originalResource.Name
controller.Namespace = originalResource.Namespace
controller.K8SResource = originalResource
return controller
}
+28 -25
View File
@@ -3,8 +3,8 @@ package validator
import (
"time"
conf "github.com/reactiveops/polaris/pkg/config"
"github.com/reactiveops/polaris/pkg/kube"
conf "github.com/fairwindsops/polaris/pkg/config"
"github.com/fairwindsops/polaris/pkg/kube"
)
const (
@@ -14,14 +14,18 @@ const (
// ClusterSummary contains Polaris results as well as some high-level stats
type ClusterSummary struct {
Results ResultSummary
Version string
Nodes int
Pods int
Namespaces int
Deployments int
StatefulSets int
Score uint
Results ResultSummary
Version string
Nodes int
Pods int
Namespaces int
Deployments int
StatefulSets int
DaemonSets int
Jobs int
CronJobs int
ReplicationControllers int
Score uint
}
// AuditData contains all the data from a full Polaris audit
@@ -43,13 +47,8 @@ func RunAudit(config conf.Configuration, kubeResources *kube.ResourceProvider) (
clusterResults := ResultSummary{}
// Aggregate all summary counts to get a clusterwide count.
for _, nsRes := range nsResults {
for _, dr := range nsRes.DeploymentResults {
clusterResults.appendResults(*dr.PodResult.Summary)
}
for _, dr := range nsRes.StatefulSetResults {
clusterResults.appendResults(*dr.PodResult.Summary)
}
for _, result := range nsResults.GetAllControllerResults() {
clusterResults.appendResults(*result.PodResult.Summary)
}
displayName := config.DisplayName
@@ -64,14 +63,18 @@ func RunAudit(config conf.Configuration, kubeResources *kube.ResourceProvider) (
SourceName: kubeResources.SourceName,
DisplayName: displayName,
ClusterSummary: ClusterSummary{
Version: kubeResources.ServerVersion,
Nodes: len(kubeResources.Nodes),
Pods: len(kubeResources.Pods),
Namespaces: len(kubeResources.Namespaces),
Deployments: len(kubeResources.Deployments),
StatefulSets: len(kubeResources.StatefulSets),
Results: clusterResults,
Score: clusterResults.Totals.GetScore(),
Version: kubeResources.ServerVersion,
Nodes: len(kubeResources.Nodes),
Pods: len(kubeResources.Pods),
Namespaces: len(kubeResources.Namespaces),
Deployments: len(kubeResources.Deployments),
StatefulSets: len(kubeResources.StatefulSets),
DaemonSets: len(kubeResources.DaemonSets),
Jobs: len(kubeResources.Jobs),
CronJobs: len(kubeResources.CronJobs),
ReplicationControllers: len(kubeResources.ReplicationControllers),
Results: clusterResults,
Score: clusterResults.Totals.GetScore(),
},
NamespacedResults: nsResults,
}
+18 -9
View File
@@ -3,9 +3,9 @@ package validator
import (
"testing"
conf "github.com/reactiveops/polaris/pkg/config"
"github.com/reactiveops/polaris/pkg/kube"
"github.com/reactiveops/polaris/test"
conf "github.com/fairwindsops/polaris/pkg/config"
"github.com/fairwindsops/polaris/pkg/kube"
"github.com/fairwindsops/polaris/test"
"github.com/stretchr/testify/assert"
)
@@ -20,23 +20,32 @@ func TestGetTemplateData(t *testing.T) {
ReadinessProbeMissing: conf.SeverityError,
LivenessProbeMissing: conf.SeverityWarning,
},
ControllersToScan: []conf.SupportedController{
conf.Deployments,
conf.StatefulSets,
conf.DaemonSets,
conf.Jobs,
conf.CronJobs,
conf.ReplicationControllers,
},
}
// TODO: split out the logic for calculating summaries into another set of tests
sum := ResultSummary{
Totals: CountSummary{
Successes: uint(8),
Warnings: uint(2),
Errors: uint(2),
Successes: uint(24),
Warnings: uint(6),
Errors: uint(6),
},
ByCategory: CategorySummary{},
}
sum.ByCategory["Health Checks"] = &CountSummary{
Successes: uint(0),
Warnings: uint(2),
Errors: uint(2),
Warnings: uint(6),
Errors: uint(6),
}
sum.ByCategory["Resources"] = &CountSummary{
Successes: uint(8),
Successes: uint(24),
Warnings: uint(0),
Errors: uint(0),
}
+3 -3
View File
@@ -1,4 +1,4 @@
// Copyright 2019 ReactiveOps
// 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.
@@ -15,8 +15,8 @@
package validator
import (
conf "github.com/reactiveops/polaris/pkg/config"
"github.com/reactiveops/polaris/pkg/validator/messages"
conf "github.com/fairwindsops/polaris/pkg/config"
"github.com/fairwindsops/polaris/pkg/validator/messages"
corev1 "k8s.io/api/core/v1"
)
+169 -6
View File
@@ -1,4 +1,4 @@
// Copyright 2019 ReactiveOps
// 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.
@@ -17,8 +17,8 @@ package validator
import (
"testing"
conf "github.com/reactiveops/polaris/pkg/config"
"github.com/reactiveops/polaris/test"
conf "github.com/fairwindsops/polaris/pkg/config"
"github.com/fairwindsops/polaris/test"
"github.com/stretchr/testify/assert"
)
@@ -70,7 +70,170 @@ func TestValidatePod(t *testing.T) {
actualPodResult := ValidatePod(c, &pod.Spec)
assert.Equal(t, len(actualPodResult.ContainerResults), 1, "should be equal")
assert.EqualValues(t, actualPodResult.Summary, &expectedSum)
assert.EqualValues(t, actualPodResult.Messages, expectedMessages)
assert.Equal(t, 1, len(actualPodResult.ContainerResults), "should be equal")
assert.EqualValues(t, &expectedSum, actualPodResult.Summary)
assert.EqualValues(t, expectedMessages, actualPodResult.Messages)
}
func TestInvalidIPCPod(t *testing.T) {
c := conf.Configuration{
Security: conf.Security{
HostIPCSet: conf.SeverityError,
HostPIDSet: conf.SeverityError,
},
Networking: conf.Networking{
HostNetworkSet: conf.SeverityWarning,
HostPortSet: conf.SeverityError,
},
}
k8s := test.SetupTestAPI()
k8s = test.SetupAddControllers(k8s, "test")
pod := test.MockPod()
pod.Spec.HostIPC = true
expectedSum := ResultSummary{
Totals: CountSummary{
Successes: uint(7),
Warnings: uint(0),
Errors: uint(1),
},
ByCategory: make(map[string]*CountSummary),
}
expectedSum.ByCategory["Networking"] = &CountSummary{
Successes: uint(2),
Warnings: uint(0),
Errors: uint(0),
}
expectedSum.ByCategory["Resources"] = &CountSummary{
Successes: uint(4),
Warnings: uint(0),
Errors: uint(0),
}
expectedSum.ByCategory["Security"] = &CountSummary{
Successes: uint(1),
Warnings: uint(0),
Errors: uint(1),
}
expectedMessages := []*ResultMessage{
{Message: "Host IPC should not be configured", Type: "error", Category: "Security"},
{Message: "Host PID is not configured", Type: "success", Category: "Security"},
{Message: "Host network is not configured", Type: "success", Category: "Networking"},
}
actualPodResult := ValidatePod(c, &pod.Spec)
assert.Equal(t, 1, len(actualPodResult.ContainerResults), "should be equal")
assert.EqualValues(t, &expectedSum, actualPodResult.Summary)
assert.EqualValues(t, expectedMessages, actualPodResult.Messages)
}
func TestInvalidNeworkPod(t *testing.T) {
c := conf.Configuration{
Networking: conf.Networking{
HostNetworkSet: conf.SeverityWarning,
HostPortSet: conf.SeverityError,
},
Security: conf.Security{
HostIPCSet: conf.SeverityError,
HostPIDSet: conf.SeverityError,
},
}
k8s := test.SetupTestAPI()
k8s = test.SetupAddControllers(k8s, "test")
pod := test.MockPod()
pod.Spec.HostNetwork = true
expectedSum := ResultSummary{
Totals: CountSummary{
Successes: uint(7),
Warnings: uint(1),
Errors: uint(0),
},
ByCategory: make(map[string]*CountSummary),
}
expectedSum.ByCategory["Networking"] = &CountSummary{
Successes: uint(1),
Warnings: uint(1),
Errors: uint(0),
}
expectedSum.ByCategory["Resources"] = &CountSummary{
Successes: uint(4),
Warnings: uint(0),
Errors: uint(0),
}
expectedSum.ByCategory["Security"] = &CountSummary{
Successes: uint(2),
Warnings: uint(0),
Errors: uint(0),
}
expectedMessages := []*ResultMessage{
{Message: "Host network should not be configured", Type: "warning", Category: "Networking"},
{Message: "Host IPC is not configured", Type: "success", Category: "Security"},
{Message: "Host PID is not configured", Type: "success", Category: "Security"},
}
actualPodResult := ValidatePod(c, &pod.Spec)
assert.Equal(t, 1, len(actualPodResult.ContainerResults), "should be equal")
assert.EqualValues(t, &expectedSum, actualPodResult.Summary)
assert.EqualValues(t, expectedMessages, actualPodResult.Messages)
}
func TestInvalidPIDPod(t *testing.T) {
c := conf.Configuration{
Security: conf.Security{
HostIPCSet: conf.SeverityError,
HostPIDSet: conf.SeverityError,
},
Networking: conf.Networking{
HostNetworkSet: conf.SeverityWarning,
HostPortSet: conf.SeverityError,
},
}
k8s := test.SetupTestAPI()
k8s = test.SetupAddControllers(k8s, "test")
pod := test.MockPod()
pod.Spec.HostPID = true
expectedSum := ResultSummary{
Totals: CountSummary{
Successes: uint(7),
Warnings: uint(0),
Errors: uint(1),
},
ByCategory: make(map[string]*CountSummary),
}
expectedSum.ByCategory["Networking"] = &CountSummary{
Successes: uint(2),
Warnings: uint(0),
Errors: uint(0),
}
expectedSum.ByCategory["Resources"] = &CountSummary{
Successes: uint(4),
Warnings: uint(0),
Errors: uint(0),
}
expectedSum.ByCategory["Security"] = &CountSummary{
Successes: uint(1),
Warnings: uint(0),
Errors: uint(1),
}
expectedMessages := []*ResultMessage{
{Message: "Host PID should not be configured", Type: "error", Category: "Security"},
{Message: "Host IPC is not configured", Type: "success", Category: "Security"},
{Message: "Host network is not configured", Type: "success", Category: "Networking"},
}
actualPodResult := ValidatePod(c, &pod.Spec)
assert.Equal(t, 1, len(actualPodResult.ContainerResults), "should be equal")
assert.EqualValues(t, &expectedSum, actualPodResult.Summary)
assert.EqualValues(t, expectedMessages, actualPodResult.Messages)
}
+2 -2
View File
@@ -1,4 +1,4 @@
// Copyright 2019 ReactiveOps
// 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.
@@ -15,7 +15,7 @@
package validator
import (
conf "github.com/reactiveops/polaris/pkg/config"
conf "github.com/fairwindsops/polaris/pkg/config"
"github.com/sirupsen/logrus"
)
+79 -9
View File
@@ -1,4 +1,4 @@
// Copyright 2019 ReactiveOps
// 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.
@@ -14,7 +14,13 @@
package validator
import corev1 "k8s.io/api/core/v1"
import (
"fmt"
"github.com/fairwindsops/polaris/pkg/config"
conf "github.com/fairwindsops/polaris/pkg/config"
corev1 "k8s.io/api/core/v1"
)
// MessageType represents the type of Message
type MessageType string
@@ -32,23 +38,87 @@ const (
// NamespaceResult groups container results by parent resource.
type NamespaceResult struct {
Name string
Summary *ResultSummary
DeploymentResults []ControllerResult
StatefulSetResults []ControllerResult
Name string
Summary *ResultSummary
// TODO: This struct could use some love to reorganize it as just having "results"
// and then having methods to return filtered results by type
// (deploy, daemonset, etc)
// The way this is structured right now makes it difficult to add
// additional result types and potentially miss things in the metrics
// summary.
DeploymentResults []ControllerResult
StatefulSetResults []ControllerResult
DaemonSetResults []ControllerResult
JobResults []ControllerResult
CronJobResults []ControllerResult
ReplicationControllerResults []ControllerResult
}
// AddResult adds a result to the result sets by leveraging the types supported by NamespaceResult
func (n *NamespaceResult) AddResult(resourceType config.SupportedController, result ControllerResult) error {
// Iterate all the resource types supported in this struct
var results *[]ControllerResult
switch resourceType {
case conf.Deployments:
results = &n.DeploymentResults
case conf.StatefulSets:
results = &n.StatefulSetResults
case conf.DaemonSets:
results = &n.DaemonSetResults
case conf.Jobs:
results = &n.JobResults
case conf.CronJobs:
results = &n.CronJobResults
case conf.ReplicationControllers:
results = &n.ReplicationControllerResults
default:
return fmt.Errorf("Unknown Resource Type: (%s) Missing Implementation in NamespacedResult", resourceType)
}
// Append the new result to the results pointer loaded from the supported values
*results = append(*results, result)
return nil
}
// GetAllControllerResults grabs all the different types of controller results from the namespaced result as a single list for easier iteration
func (n NamespaceResult) GetAllControllerResults() []ControllerResult {
all := []ControllerResult{}
all = append(all, n.DeploymentResults...)
all = append(all, n.StatefulSetResults...)
all = append(all, n.DaemonSetResults...)
all = append(all, n.JobResults...)
all = append(all, n.CronJobResults...)
all = append(all, n.ReplicationControllerResults...)
return all
}
// NamespacedResults is a mapping of namespace name to the validation results.
type NamespacedResults map[string]*NamespaceResult
// GetAllControllerResults aggregates all the namespaced results in the set together
func (nsResults NamespacedResults) GetAllControllerResults() []ControllerResult {
all := []ControllerResult{}
for _, nsResult := range nsResults {
all = append(all, nsResult.GetAllControllerResults()...)
}
return all
}
func (nsResults NamespacedResults) getNamespaceResult(nsName string) *NamespaceResult {
nsResult := &NamespaceResult{}
switch nsResults[nsName] {
case nil:
nsResult = &NamespaceResult{
Summary: &ResultSummary{},
DeploymentResults: []ControllerResult{},
StatefulSetResults: []ControllerResult{},
Summary: &ResultSummary{},
DeploymentResults: []ControllerResult{},
StatefulSetResults: []ControllerResult{},
DaemonSetResults: []ControllerResult{},
JobResults: []ControllerResult{},
CronJobResults: []ControllerResult{},
ReplicationControllerResults: []ControllerResult{},
}
nsResults[nsName] = nsResult
default:
+43 -9
View File
@@ -1,4 +1,4 @@
// Copyright 2019 ReactiveOps
// 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.
@@ -20,11 +20,14 @@ import (
"net/http"
"os"
conf "github.com/reactiveops/polaris/pkg/config"
validator "github.com/reactiveops/polaris/pkg/validator"
conf "github.com/fairwindsops/polaris/pkg/config"
validator "github.com/fairwindsops/polaris/pkg/validator"
"github.com/fairwindsops/polaris/pkg/validator/controllers"
"github.com/sirupsen/logrus"
admissionregistrationv1beta1 "k8s.io/api/admissionregistration/v1beta1"
appsv1 "k8s.io/api/apps/v1"
batchv1 "k8s.io/api/batch/v1"
batchv1beta1 "k8s.io/api/batch/v1beta1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
@@ -92,16 +95,47 @@ func (v *Validator) Handle(ctx context.Context, req types.Request) types.Respons
err = v.decoder.Decode(req, &pod)
podResult = validator.ValidatePod(v.Config, &pod.Spec)
} else {
var controller validator.Controller
switch req.AdmissionRequest.Kind.Kind {
case "Deployment":
var controller controllers.Interface
if yes := v.Config.CheckIfKindIsConfiguredForValidation(req.AdmissionRequest.Kind.Kind); !yes {
logrus.Warnf("Skipping, kind (%s) isn't something we are configured to scan", req.AdmissionRequest.Kind.Kind)
return admission.ValidationResponse(true, fmt.Sprintf("Skipping: (%s) isn't something we're configured to scan.", req.AdmissionRequest.Kind.Kind))
}
// We should never hit this case unless something is misconfiured in CheckIfKindIsConfiguredForValidation
controllerType, err := conf.GetSupportedControllerFromString(req.AdmissionRequest.Kind.Kind)
if err != nil {
msg := fmt.Errorf("Unexpected error occurred. Expected Kind to be a supported type (%s)", req.AdmissionRequest.Kind.Kind)
logrus.Error(msg)
return admission.ErrorResponse(http.StatusInternalServerError, err)
}
// For each type, perform the scan
// TODO: This isn't really that elegant due to the decoder and NewXXXController setup :( could use love
switch controllerType {
case conf.Deployments:
deploy := appsv1.Deployment{}
err = v.decoder.Decode(req, &deploy)
controller = validator.ControllerFromDeployment(deploy)
case "StatefulSet":
controller = controllers.NewDeploymentController(deploy)
case conf.StatefulSets:
statefulSet := appsv1.StatefulSet{}
err = v.decoder.Decode(req, &statefulSet)
controller = validator.ControllerFromStatefulSet(statefulSet)
controller = controllers.NewStatefulSetController(statefulSet)
case conf.DaemonSets:
daemonSet := appsv1.DaemonSet{}
err = v.decoder.Decode(req, &daemonSet)
controller = controllers.NewDaemonSetController(daemonSet)
case conf.Jobs:
job := batchv1.Job{}
err = v.decoder.Decode(req, &job)
controller = controllers.NewJobController(job)
case conf.CronJobs:
cronJob := batchv1beta1.CronJob{}
err = v.decoder.Decode(req, &cronJob)
controller = controllers.NewCronJobController(cronJob)
case conf.ReplicationControllers:
replicationController := corev1.ReplicationController{}
err = v.decoder.Decode(req, &replicationController)
controller = controllers.NewReplicationControllerController(replicationController)
}
controllerResult := validator.ValidateController(v.Config, controller)
podResult = controllerResult.PodResult
+63 -4
View File
@@ -4,6 +4,8 @@ import (
"fmt"
appsv1 "k8s.io/api/apps/v1"
batchv1 "k8s.io/api/batch/v1"
batchv1beta1 "k8s.io/api/batch/v1beta1"
corev1 "k8s.io/api/core/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/fake"
@@ -49,6 +51,43 @@ func mockStatefulSet() appsv1.StatefulSet {
return s
}
func mockDaemonSet() appsv1.DaemonSet {
return appsv1.DaemonSet{
Spec: appsv1.DaemonSetSpec{
Template: MockPod(),
},
}
}
func mockJob() batchv1.Job {
return batchv1.Job{
Spec: batchv1.JobSpec{
Template: MockPod(),
},
}
}
func mockCronJob() batchv1beta1.CronJob {
return batchv1beta1.CronJob{
Spec: batchv1beta1.CronJobSpec{
JobTemplate: batchv1beta1.JobTemplateSpec{
Spec: batchv1.JobSpec{
Template: MockPod(),
},
},
},
}
}
func mockReplicationController() corev1.ReplicationController {
p := MockPod()
return corev1.ReplicationController{
Spec: corev1.ReplicationControllerSpec{
Template: &p,
},
}
}
// SetupTestAPI creates a test kube API struct.
func SetupTestAPI() kubernetes.Interface {
return fake.NewSimpleClientset()
@@ -57,14 +96,34 @@ func SetupTestAPI() kubernetes.Interface {
// SetupAddControllers creates mock controllers and adds them to the test clientset.
func SetupAddControllers(k kubernetes.Interface, namespace string) kubernetes.Interface {
d1 := mockDeploy()
_, err := k.AppsV1().Deployments(namespace).Create(&d1)
if err != nil {
if _, err := k.AppsV1().Deployments(namespace).Create(&d1); err != nil {
fmt.Println(err)
}
s1 := mockStatefulSet()
_, err = k.AppsV1().StatefulSets(namespace).Create(&s1)
if err != nil {
if _, err := k.AppsV1().StatefulSets(namespace).Create(&s1); err != nil {
fmt.Println(err)
}
ds1 := mockDaemonSet()
if _, err := k.AppsV1().DaemonSets(namespace).Create(&ds1); err != nil {
fmt.Println(err)
}
j1 := mockJob()
if _, err := k.BatchV1().Jobs(namespace).Create(&j1); err != nil {
fmt.Println(err)
}
cj1 := mockCronJob()
if _, err := k.BatchV1beta1().CronJobs(namespace).Create(&cj1); err != nil {
fmt.Println(err)
}
rc1 := mockReplicationController()
if _, err := k.CoreV1().ReplicationControllers(namespace).Create(&rc1); err != nil {
fmt.Println(err)
}
return k
}