Compare commits

..
1 Commits
Author SHA1 Message Date
Robert Brennan 195619fcab empty commit 2021-09-07 13:33:01 +00:00
197 changed files with 2949 additions and 20506 deletions
+57 -40
View File
@@ -1,9 +1,5 @@
version: 2.1
orbs:
rok8s: fairwinds/rok8s-scripts@11
oss-docs: fairwinds/oss-docs@0
executors:
vm:
machine:
@@ -22,7 +18,6 @@ references:
echo 'export GOPROXY=https://proxy.golang.org' >> ${BASH_ENV}
echo 'export GO111MODULE=on' >> ${BASH_ENV}
echo 'export GOFLAGS=-mod=mod' >> ${BASH_ENV}
echo 'export GORELEASER_CURRENT_TAG="${CIRCLE_TAG}"' >> $BASH_ENV
install_k8s: &install_k8s
run:
@@ -33,20 +28,20 @@ references:
sudo apt-get install -yqq jq git
echo "Installing KIND"
curl -sLO https://github.com/kubernetes-sigs/kind/releases/download/v0.14.0/kind-linux-amd64
curl -sLO https://github.com/kubernetes-sigs/kind/releases/download/v0.8.1/kind-linux-amd64
chmod 0755 kind-linux-amd64
sudo mv kind-linux-amd64 /usr/local/bin/kind
kind version
echo "Installing Kubectl"
curl -sLO https://storage.googleapis.com/kubernetes-release/release/v1.21.12/bin/linux/amd64/kubectl
curl -sLO https://storage.googleapis.com/kubernetes-release/release/v1.18.6/bin/linux/amd64/kubectl
chmod 0755 kubectl
sudo mv kubectl /usr/local/bin/
kubectl version --client
echo "Creating Kubernetes Cluster with Kind"
kind create cluster --wait=90s --image kindest/node:v1.21.12
kind create cluster --wait=90s --image kindest/node:v1.15.11
docker ps -a
kubectl version
@@ -87,6 +82,16 @@ references:
echo "Skipping Kubernetes tests for forked PR"
fi
# Release scripts
install_goreleaser: &install_goreleaser
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 -
sudo dpkg -i goreleaser.deb
rm goreleaser.deb
docker_build: &docker_build
run:
name: Docker login and build
@@ -103,25 +108,14 @@ references:
docker login quay.io -u="${fairwinds_quay_user}" -p="${fairwinds_quay_token}"
docker-push -f .circleci/build.config
enable_experimental_features: &enable_experimental_docker_features
release_deploy_configs: &release_deploy_configs
run:
name: enable experimental features
name: Release deploy configs
command: |
set -ex
apk --update add openssh
ssh remote-docker \<<EOF
sudo bash -c 'echo "{\"experimental\": true}" > /etc/docker/daemon.json'
sudo systemctl restart docker
EOF
install_vault_alpine: &install_vault_alpine
run:
name: install hashicorp vault
command: |
apk --update add curl yq
cd /tmp
curl -LO https://releases.hashicorp.com/vault/1.9.3/vault_1.9.3_linux_amd64.zip
unzip vault_1.9.3_linux_amd64.zip
mv vault /usr/bin/vault
upload_url=$(curl --silent https://api.github.com/repos/FairwindsOps/polaris/releases/latest | grep upload_url)
upload_url=$(echo $upload_url | sed -e 's/.*\(https.*\){.*$/\1/')
curl -X POST "$upload_url?name=dashboard.yaml" --data-binary "@./deploy/dashboard.yaml" -H "Authorization: Bearer $GITHUB_TOKEN" -H "Content-Type: application/x-yaml"
curl -X POST "$upload_url?name=webhook.yaml" --data-binary "@./deploy/webhook.yaml" -H "Authorization: Bearer $GITHUB_TOKEN" -H "Content-Type: application/x-yaml"
jobs:
build:
@@ -154,7 +148,7 @@ jobs:
test:
working_directory: /go/src/github.com/fairwindsops/polaris/
docker:
- image: circleci/golang:1.17
- image: circleci/golang:1.16
steps:
- checkout
- *set_environment_variables
@@ -162,6 +156,7 @@ jobs:
- run: go list ./... | grep -v vendor | xargs golint -set_exit_status
- run: go list ./... | grep -v vendor | xargs go vet
- 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
- *test_binary_dashboard
insights:
@@ -170,32 +165,29 @@ jobs:
steps:
- checkout
- setup_remote_docker
- run:
name: Adjust configs for latest image
command: |
sed -r "s|'(quay.io/fairwinds/polaris:).+'|'\1${CIRCLE_SHA1}'|" ./deploy/webhook.yaml > ./deploy/dashboard.yaml
sed -r "s|'(quay.io/fairwinds/polaris:).+'|'\1${CIRCLE_SHA1}'|" ./deploy/dashboard.yaml > ./deploy/webhook.yaml
- run:
name: Insights CI
command: curl -L https://insights.fairwinds.com/v0/insights-ci.sh | bash
release_binary:
working_directory: /go/src/github.com/fairwindsops/polaris/
resource_class: large
shell: /bin/bash
docker:
- image: goreleaser/goreleaser:v1.3.0
- image: circleci/golang:1.16
steps:
- checkout
- setup_remote_docker:
version: 20.10.6
- *enable_experimental_docker_features
- *install_vault_alpine
- rok8s/get_vault_env:
vault_path: repo/global/env
- rok8s/get_vault_env:
vault_path: repo/polaris/env
- setup_remote_docker
- *set_environment_variables
- *install_goreleaser
- run: go get -u github.com/gobuffalo/packr/v2/packr2
- run: git checkout -- . # FIXME: the go get makes the directory dirty
- run: packr2
- run: echo 'export GORELEASER_CURRENT_TAG="${CIRCLE_TAG}"' >> $BASH_ENV
- run: goreleaser
- *release_deploy_configs
release_images:
working_directory: /go/src/github.com/fairwindsops/polaris/
@@ -206,6 +198,32 @@ jobs:
- setup_remote_docker
- *set_environment_variables
- *docker_build_and_push
publish_docs:
docker:
- image: cimg/node:15.5.1
steps:
- checkout
- run:
name: Build Docs Site
command: |
set -e
cd ./docs
npm install
npm run check-links
npm run build
- run:
name: Install AWS CLI
command: |
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install
- run:
name: Publish Docs Site to S3
command: |
cd ./dist
aws s3 sync ./ s3://polaris.docs.fairwinds.com --delete
workflows:
version: 2
@@ -253,8 +271,7 @@ workflows:
ignore: /.*/
tags:
ignore: /^testing-.*/
- oss-docs/publish-docs:
repository: polaris
- publish_docs:
filters:
branches:
ignore: /.*/
-58
View File
@@ -1,58 +0,0 @@
name: Bug Report
description: File a bug report
labels: [bug, triage]
body:
- type: markdown
attributes:
value: |
Thanks for taking the time to fill out this bug report! Please fill the form below.
- type: textarea
id: what-happened
attributes:
label: What happened?
description: What happened?
validations:
required: true
- type: textarea
id: expected
attributes:
label: What did you expect to happen?
description: What is the expected or desired behavior?
validations:
required: true
- type: textarea
id: reproducible
attributes:
label: How can we reproduce this?
description: Please share the steps that we can take to reproduce this. Also include any relevant configuration.
validations:
required: true
- type: input
id: version
attributes:
label: Version
description: The version of the tool that you are using. If a helm chart, please share the name of the chart.
validations:
required: true
- type: checkboxes
id: search
attributes:
label: Search
options:
- label: I did search for other open and closed issues before opening this.
required: true
- type: checkboxes
id: terms
attributes:
label: Code of Conduct
description: By submitting this issue, you agree to follow the CODE_OF_CONDUCT in this repository.
options:
- label: I agree to follow this project's Code of Conduct
required: true
- type: textarea
id: ctx
attributes:
label: Additional context
description: Anything else you would like to add
validations:
required: false
+58
View File
@@ -0,0 +1,58 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
---
name: Bug report
about: Let us know about an unexpected error, a crash, or an incorrect behavior.
---
### Installation Process
<!---
Did you install polaris on your local machine, or in a kubernetes cluster? Did you use kubectl, helm, brew, a GitHub release, or the source code? Let us know below.
-->
### Polaris Version
<!---
If you are using polaris locally, run `polaris --version` to show the version, and paste the result between the ``` marks below.
If you are not running the latest version of Polaris, please try upgrading because your issue may have already been fixed.
-->
```
...
```
### Expected Behavior
<!--
What should have happened?
-->
### Actual Behavior
<!--
What actually happened?
-->
### Steps to Reproduce
<!--
Please list the full steps required to reproduce the issue, for example:
1. `polaris --audit --output-format score`
-->
### Additional Context
<!--
Are there anything atypical about your situation that we should know?
-->
### References
<!--
Are there any other GitHub issues (open or closed) or Pull Requests that should be linked here? For example:
- #6017
-->
+2
View File
@@ -6,3 +6,5 @@ labels: ''
assignees: ''
---
+2 -3
View File
@@ -3,16 +3,15 @@ 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 from " $POLARIS_URL
echo "Installing polaris to path."
fi
TARGET_FILE="polaris.tar.gz"
curl -LJ -o $TARGET_FILE $POLARIS_URL
curl -LJ -o $TARGET_FILE 'https://github.com/FairwindsOps/polaris/releases/download/'"$INPUT_VERSION"'/polaris_'"$INPUT_VERSION"'_linux_386.tar.gz'
mkdir polaris
tar -xzf $TARGET_FILE -C polaris
rm $TARGET_FILE
+42 -18
View File
@@ -1,20 +1,44 @@
## DO NOT EDIT - Managed by Terraform
version: 2
updates:
- package-ecosystem: "docker"
directory: "/"
schedule:
interval: "weekly"
- package-ecosystem: "npm"
directory: "/docs"
schedule:
interval: "weekly"
open-pull-requests-limit: 0
ignore:
- dependency-name: "*"
- package-ecosystem: "gomod"
directory: "/"
schedule:
interval: "weekly"
- 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
-13
View File
@@ -1,13 +0,0 @@
This PR fixes #
## Checklist
* [ ] I have signed the CLA
* [ ] I have updated/added any relevant documentation
## Description
### What's the goal of this PR?
### What changes did you make?
### What alternative solution should we consider, if any?
+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
-18
View File
@@ -1,18 +0,0 @@
name: 'Close stale issues and PRs'
on:
schedule:
- cron: '32 1 * * *'
permissions:
issues: write
pull-requests: write
jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v4
with:
exempt-issue-labels: pinned
stale-pr-label: stale
stale-issue-label: stale
+2 -2
View File
@@ -11,7 +11,7 @@ jobs:
- name: Setup polaris
uses: ./.github/actions/setup-polaris
with:
version: 4.2.0
version: 3.0.3
- name: Use command
run: polaris version
@@ -22,6 +22,6 @@ jobs:
- name: Setup polaris
uses: fairwindsops/polaris/.github/actions/setup-polaris@master
with:
version: 4.2.0
version: 3.0.3
- name: Use command
run: polaris version
-1
View File
@@ -1,5 +1,4 @@
# Binaries for programs and plugins
.go-version
*.exe
*.exe~
*.dll
+1 -19
View File
@@ -8,15 +8,9 @@ changelog:
- '^test:'
builds:
- id: polaris
ldflags:
- -X main.Version={{.Version}} -X main.Commit={{.Commit}} -s -w
env:
- CGO_ENABLED=0
- GO111MODULE=on
goos:
- linux
- darwin
- windows
goarch:
- amd64
- arm
@@ -28,21 +22,9 @@ archives:
- id: polaris
builds: ["polaris"]
name_template: "{{ .ProjectName }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}{{ if .Mips }}_{{ .Mips }}{{ end }}"
signs:
- cmd: cosign
args: ["sign-blob", "--key=hashivault://cosign", "-output-signature=${signature}", "${artifact}"]
artifacts: checksum
release:
prerelease: auto
footer: |
You can verify the signature of the checksums.txt file using [cosign](https://github.com/sigstore/cosign).
```
cosign verify-blob checksums.txt --signature=checksums.txt.sig --key https://artifacts.fairwinds.com/cosign.pub
```
brews:
- name: polaris
tap:
github:
owner: FairwindsOps
name: homebrew-tap
folder: Formula
-24
View File
@@ -1,24 +0,0 @@
header:
license:
spdx-id: Apache-2.0
copyright-owner: 'FairwindsOps, Inc.'
content: |
// 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.
paths:
- '**/*.go'
comment: on-failure
dependency:
files:
- go.mod
+1 -2
View File
@@ -1,2 +1 @@
## DO NOT EDIT - Managed by Terraform
* @rbren @makoscafee
* @rbren @makoscafee
-74
View File
@@ -1,74 +0,0 @@
# 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 -3
View File
@@ -1,4 +1,4 @@
FROM golang:1.17 AS build-env
FROM golang:1.16 AS build-env
WORKDIR /go/src/github.com/fairwindsops/polaris/
ENV GO111MODULE=on
@@ -15,9 +15,8 @@ RUN go get -u github.com/gobuffalo/packr/v2/packr2
COPY . .
RUN packr2 build -a -o polaris *.go
FROM alpine:3.16
FROM alpine:3.14
WORKDIR /usr/local/bin
RUN apk -U upgrade
RUN apk --no-cache add ca-certificates
RUN addgroup -S polaris && adduser -u 1200 -S polaris -G polaris
+10 -18
View File
@@ -2,8 +2,8 @@
<img src="https://polaris.docs.fairwinds.com/img/polaris-logo.png" alt="Polaris Logo">
<br>
<h3>Best Practices for Kubernetes Workload Configuration</h3>
<a href="https://github.com/FairwindsOps/polaris/releases">
<img src="https://img.shields.io/github/v/release/FairwindsOps/polaris">
<a href="https://github.com/FairwindsOps/polaris">
<img src="https://img.shields.io/static/v1.svg?label=Version&message=4.0.8&color=239922">
</a>
<a href="https://goreportcard.com/report/github.com/FairwindsOps/polaris">
<img src="https://goreportcard.com/badge/github.com/FairwindsOps/polaris">
@@ -32,18 +32,10 @@ Polaris can be run in three different modes:
## Documentation
Check out the [documentation at docs.fairwinds.com](https://polaris.docs.fairwinds.com)
<!-- Begin boilerplate -->
## Join the Fairwinds Open Source Community
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!
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!
<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>
## Other Projects from Fairwinds
@@ -53,14 +45,14 @@ Enjoying Polaris? Check out some of our other projects:
* [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
Or [check out the full list](https://www.fairwinds.com/open-source-software?utm_source=polaris&utm_medium=polaris&utm_campaign=polaris)
## Fairwinds Insights
<p align="center">
<a href="https://www.fairwinds.com/polaris-user-insights-demo?utm_source=polaris&utm_medium=ad&utm_campaign=polarisad">
<img src="https://polaris.docs.fairwinds.com/img/insights-banner.png" alt="Fairwinds Insights" width="550"/>
</a>
</p>
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>
[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.
-36
View File
@@ -1,36 +0,0 @@
successMessage: The ServiceAccount will not be automounted
failureMessage: The ServiceAccount will be automounted
category: Security
target: PodSpec
schema:
'$schema': http://json-schema.org/draft-07/schema
type: object
required: ["serviceAccountName"]
properties:
serviceAccountName:
type: string
automountServiceAccountToken:
type: boolean
not:
const: true
additionalSchemaStrings:
ServiceAccount: |
type: object
required:
- metadata
{{ if not (eq .Polaris.PodSpec.automountServiceAccountToken false) }}
- automountServiceAccountToken
{{ end }}
properties:
metadata:
type: object
required: ["name"]
properties:
name:
type: string
const: "{{ .Polaris.PodSpec.serviceAccountName }}"
{{ if not (eq .Polaris.PodSpec.automountServiceAccountToken false) }}
automountServiceAccountToken:
type: boolean
const: false
{{ end }}
-7
View File
@@ -25,10 +25,3 @@ schema:
type: string
not:
const: ''
mutations:
- op: add
path: /resources/limits/cpu
value: 100m
comments:
- find: "cpu: 100m"
comment: "TODO: Set this to the maximum amount of CPU you want your workload to use"
-7
View File
@@ -25,10 +25,3 @@ schema:
type: string
not:
const: ''
mutations:
- op: add
path: /resources/requests/cpu
value: 100m
comments:
- find: "cpu: 100m"
comment: "TODO: Set this to the amount of CPU you want to reserve for your workload"
+3 -8
View File
@@ -17,15 +17,10 @@ schema:
allOf:
- not:
contains:
pattern: '^(?i)ALL$'
const: ALL
- not:
contains:
pattern: '^(?i)SYS_ADMIN$'
const: SYS_ADMIN
- not:
contains:
pattern: '^(?i)NET_ADMIN$'
mutations:
- op: remove
path: /securityContext/capabilities
const: NET_ADMIN
+1 -4
View File
@@ -1,7 +1,7 @@
successMessage: Host IPC is not configured
failureMessage: Host IPC should not be configured
category: Security
target: PodSpec
target: Pod
schema:
'$schema': http://json-schema.org/draft-07/schema
type: object
@@ -9,6 +9,3 @@ schema:
hostIPC:
not:
const: true
mutations:
- op: remove
path: /hostIPC
+1 -4
View File
@@ -1,7 +1,7 @@
successMessage: Host network is not configured
failureMessage: Host network should not be configured
category: Security
target: PodSpec
target: Pod
schema:
'$schema': http://json-schema.org/draft-07/schema
type: object
@@ -9,6 +9,3 @@ schema:
hostNetwork:
not:
const: true
mutations:
- op: remove
path: /hostNetwork
+1 -4
View File
@@ -1,7 +1,7 @@
successMessage: Host PID is not configured
failureMessage: Host PID should not be configured
category: Security
target: PodSpec
target: Pod
schema:
'$schema': http://json-schema.org/draft-07/schema
type: object
@@ -9,6 +9,3 @@ schema:
hostPID:
not:
const: true
mutations:
- op: remove
path: /hostPID
+1 -1
View File
@@ -12,4 +12,4 @@ schema:
items:
properties:
hostPort:
const: 0
const: 0
+16 -22
View File
@@ -22,41 +22,35 @@ schema:
type: array
oneOf:
- contains:
pattern: '^(?i)ALL$'
const: ALL
- allOf:
- contains:
pattern: '^(?i)NET_ADMIN$'
const: NET_ADMIN
- contains:
pattern: '^(?i)CHOWN$'
const: CHOWN
- contains:
pattern: '^(?i)DAC_OVERRIDE$'
const: DAC_OVERRIDE
- contains:
pattern: '^(?i)FSETID$'
const: FSETID
- contains:
pattern: '^(?i)FOWNER$'
const: FOWNER
- contains:
pattern: '^(?i)MKNOD$'
const: MKNOD
- contains:
pattern: '^(?i)NET_RAW$'
const: NET_RAW
- contains:
pattern: '^(?i)SETGID$'
const: SETGID
- contains:
pattern: '^(?i)SETUID$'
const: SETUID
- contains:
pattern: '^(?i)SETFCAP$'
const: SETFCAP
- contains:
pattern: '^(?i)SETPCAP$'
const: SETPCAP
- contains:
pattern: '^(?i)NET_BIND_SERVICE$'
const: NET_BIND_SERVICE
- contains:
pattern: '^(?i)SYS_CHROOT$'
const: SYS_CHROOT
- contains:
pattern: '^(?i)KILL$'
const: KILL
- contains:
pattern: '^(?i)AUDIT_WRITE$'
mutations:
- op: remove
path: /securityContext/capabilities
- op: add
path: /securityContext/capabilities
value: {"drop": ["ALL"]}
const: AUDIT_WRITE
-89
View File
@@ -1,89 +0,0 @@
successMessage: One of AppArmor, Seccomp, SELinux, or dropping Linux Capabilities are used to restrict containers using unwanted privileges
FailureMessage: Use one of AppArmor, Seccomp, SELinux, or dropping Linux Capabilities to restrict containers using unwanted privileges
category: Security
target: Container
schemaString: |
'$schema': http://json-schema.org/draft-07/schema
definitions:
podOrContainerSeccompProfile:
type: object
{{ $podSeccompProfileType := .Polaris.PodSpec.securityContext.seccompProfile.type }}
required:
{{ if or (not $podSeccompProfileType) (eq $podSeccompProfileType "Unconfined") }}
- securityContext
{{ end }}
properties:
securityContext:
type: object
required:
{{ if or (not $podSeccompProfileType) (eq $podSeccompProfileType "Unconfined") }}
- seccompProfile
{{ end }}
properties:
seccompProfile:
type: object
required:
{{ if or (not $podSeccompProfileType) (eq $podSeccompProfileType "Unconfined") }}
- type
{{ end }}
properties:
type:
type: string
allOf:
- not:
const: "Unconfined"
{{ if or (not $podSeccompProfileType) (eq $podSeccompProfileType "Unconfined") }}
- minLength: 1
{{ end }}
podOrContainerSELinuxOptions:
type: object
{{ $podSELinuxOptions := .Polaris.PodSpec.securityContext.seLinuxOptions }}
{{ if not $podSELinuxOptions }}
required: ["securityContext"]
properties:
securityContext:
type: object
required: ["seLinuxOptions"]
properties:
seLinuxOptions:
type: object
minProperties: 1
{{ end }}
containerDropCapabilities:
type: object
required: ["securityContext"]
properties:
securityContext:
type: object
required: ["capabilities"]
properties:
capabilities:
type: object
required: ["drop"]
properties:
drop:
type: array
minItems: 1
add:
type: array
items:
type: string
not:
pattern: '^(?i)ALL$'
# End of definitions
{{/* Check for AppArmor which uses pod annotations. IF pod fields are missing,
require one of the other hardening measures. */}}
{{ $annotationName := (print "container.apparmor.security.beta.kubernetes.io/" .Polaris.Container.name) }}
{{/* Checking annotations before using index() avoids a nil panic when there are no annotations */}}
{{ $annotationExists := false }}
{{ if .Polaris.PodTemplate.metadata.annotations }}
{{ $annotationExists = index .Polaris "PodTemplate" "metadata" "annotations" $annotationName }}
{{ end }}
{{ if $annotationExists }}
type: object
{{ else }}
anyOf:
- $ref: "#/definitions/podOrContainerSeccompProfile"
- $ref: "#/definitions/podOrContainerSELinuxOptions"
- $ref: "#/definitions/containerDropCapabilities"
{{ end}}
-7
View File
@@ -19,10 +19,3 @@ schema:
type: object
not:
const: null
mutations:
- op: add
path: /livenessProbe
value: {"exec": { "command": [ "cat", "/tmp/healthy" ] }, "initialDelaySeconds": 5, "periodSeconds": 5 }
comments:
- find: "livenessProbe:"
comment: "TODO: Change livenessProbe setting to reflect your health endpoints"
-7
View File
@@ -25,10 +25,3 @@ schema:
type: string
not:
const: ''
mutations:
- op: add
path: /resources/limits/memory
value: "512Mi"
comments:
- find: "memory: 512Mi"
comment: "TODO: Set this to the maximum amount of memory you want your workload to use"
-7
View File
@@ -25,10 +25,3 @@ schema:
type: string
not:
const: ''
mutations:
- op: add
path: /resources/requests/memory
value: "512Mi"
comments:
- find: "memory: 512Mi"
comment: "TODO: Set this to the amount of Memory you want to reserve for your workload"
-49
View File
@@ -1,49 +0,0 @@
successMessage: A NetworkPolicy matches pod labels and contains egress and ingress rules
failureMessage: A NetworkPolicy should match pod labels and contain applied egress and ingress rules
category: Security
target: PodTemplate
schema:
'$schema': http://json-schema.org/draft-07/schema
type: object
properties:
metadata:
type: object
properties:
labels:
type: object
minProperties: 1
additionalSchemaStrings:
networking.k8s.io/NetworkPolicy: |
type: object
properties:
spec:
type: object
required: ["podSelector", "egress", "ingress"]
properties:
podSelector:
type: object
required: ["matchLabels"]
properties:
matchLabels:
type: object
oneOf:
{{ range $key, $value := .Polaris.PodTemplate.metadata.labels }}
- properties:
"{{ $key }}":
type: string
const: {{ $value }}
required: ["{{ $key }}"]
{{ end }}
egress:
type: array
minItems: 1
ingress:
minItems: 1
type: array
policyTypes:
type: array
allOf:
- contains:
pattern: '^(?i)Egress$'
- contains:
pattern: '^(?i)Ingress$'
@@ -19,7 +19,3 @@ schema:
replicas:
type: integer
minimum: 2
mutations:
- op: add
path: /spec/replicas
value: 3
+2 -7
View File
@@ -2,7 +2,7 @@ successMessage: Filesystem is read only
failureMessage: Filesystem should be read only
category: Security
target: Container
schemaTarget: PodSpec
schemaTarget: Pod
schema:
'$schema': http://json-schema.org/draft-07/schema
definitions:
@@ -40,9 +40,4 @@ schema:
- securityContext
properties:
securityContext:
$ref: "#/definitions/goodSecurityContext"
mutations:
- op: add
path: /securityContext/readOnlyRootFilesystem
value: true
$ref: "#/definitions/goodSecurityContext"
+9 -13
View File
@@ -1,22 +1,18 @@
successMessage: Voluntary evictions are possible
failureMessage: Voluntary evictions are not possible
successMessage: disruptionsAllowed is greater than zero
failureMessage: disruptionsAllowed is not greater than zero
category: Reliability
target: policy/PodDisruptionBudget
schema:
'$schema': http://json-schema.org/draft-07/schema
type: object
required:
- spec
- status
properties:
spec:
status:
type: object
required:
- disruptionsAllowed
properties:
minAvailable:
not:
const: '100%'
maxUnavailable:
allOf:
- not:
const: 0
- not:
const: '0%'
disruptionsAllowed:
type: integer
minimum: 1
+1 -5
View File
@@ -1,13 +1,9 @@
successMessage: Priority class has been set
failureMessage: Priority class should be set
category: Security
target: PodSpec
target: Pod
schema:
'$schema': http://json-schema.org/draft-07/schema
type: object
required:
- priorityClassName
mutations:
- op: add
path: /priorityClassName
value: high-priority
+1 -1
View File
@@ -2,7 +2,7 @@ successMessage: Privilege escalation not allowed
failureMessage: Privilege escalation should not be allowed
category: Security
target: Container
schemaTarget: PodSpec
schemaTarget: Pod
schema:
'$schema': http://json-schema.org/draft-07/schema
definitions:
-4
View File
@@ -9,7 +9,3 @@ schema:
properties:
imagePullPolicy:
const: Always
mutations:
- op: add
path: /imagePullPolicy
value: Always
-7
View File
@@ -19,10 +19,3 @@ schema:
type: object
not:
const: null
mutations:
- op: add
path: /readinessProbe
value: {"exec": { "command": [ "cat", "/tmp/healthy" ] }, "initialDelaySeconds": 5, "periodSeconds": 5 }
comments:
- find: "readinessProbe:"
comment: "TODO: Change livenessProbe setting to reflect your health endpoints"
+2 -6
View File
@@ -2,7 +2,7 @@ successMessage: Not running as privileged
failureMessage: Should not be running as privileged
category: Security
target: Container
schemaTarget: PodSpec
schemaTarget: Pod
schema:
'$schema': http://json-schema.org/draft-07/schema
definitions:
@@ -21,8 +21,4 @@ schema:
items:
properties:
securityContext:
$ref: "#/definitions/notBadSecurityContext"
mutations:
- op: add
path: /securityContext/privileged
value: false
$ref: "#/definitions/notBadSecurityContext"
+1 -5
View File
@@ -2,7 +2,7 @@ successMessage: Is not allowed to run as root
failureMessage: Should not be allowed to run as root
category: Security
target: Container
schemaTarget: PodSpec
schemaTarget: Pod
schema:
'$schema': http://json-schema.org/draft-07/schema
definitions:
@@ -50,7 +50,3 @@ schema:
properties:
securityContext:
$ref: "#/definitions/goodSecurityContext"
mutations:
- op: add
path: /securityContext/runAsNonRoot
value: true
-43
View File
@@ -1,43 +0,0 @@
successMessage: The ConfigMap does not contain potentially sensitive content in its keys and values
failureMessage: Potentially sensitive content is detected in the ConfigMap keys or values
category: Security
target: /ConfigMap
schemaString: |
'$schema': http://json-schema.org/draft-07/schema
type: object
required: ["metadata"]
properties:
metadata:
required: ["name"]
properties:
name:
type: string
data:
type: object
propertyNames:
'$comment': These ConfigMap keys will be disallowed.
allOf:
- not:
pattern: '(?i)^AWS_SECRET_ACCESS_KEY$'
- not:
pattern: '(?i)^GOOGLE_APPLICATION_CREDENTIALS$'
- not:
pattern: '(?i)^AZURE_.+KEY$'
- not:
pattern: '(?i)^OCI_CLI_KEY_CONTENT$'
- not:
pattern: '(?i)password'
- not:
pattern: '(?i)token'
- not:
pattern: '(?i)bearer'
- not:
pattern: '(?i)secret'
'$comment': This allows ConfigMap keys not excluded above.
- pattern: '(?i).*'
additionalProperties:
'$comment': These ConfigMap values will be disallowed.
allOf:
- not:
'$comment': THis matches variations like begin private key, begin rsa private key ...
pattern: '(?i)\s*-BEGIN\s+.*PRIVATE KEY-\s*'
-43
View File
@@ -1,43 +0,0 @@
successMessage: The container does not set potentially sensitive environment variables
failureMessage: The container sets potentially sensitive environment variables
category: Security
target: Container
schemaString: |
'$schema': http://json-schema.org/draft-07/schema
type: object
properties:
env:
type: array
items:
type: object
required: ["name"]
properties:
name:
type: string
'$comment': These environment variable names will be disallowed.
allOf:
- not:
pattern: '(?i)^AWS_SECRET_ACCESS_KEY$'
- not:
pattern: '(?i)^GOOGLE_APPLICATION_CREDENTIALS$'
- not:
pattern: '(?i)^AZURE_.+KEY$'
- not:
pattern: '(?i)^OCI_CLI_KEY_CONTENT$'
- not:
pattern: '(?i)password'
- not:
pattern: '(?i)token'
- not:
pattern: '(?i)bearer'
- not:
pattern: '(?i)secret'
'$comment': This allows variable names not excluded above.
- pattern: '(?i).*'
value:
type: string
'$comment': These environment variable values will be disallowed.
allOf:
- not:
'$comment': THis matches variations like begin private key, begin rsa private key ...
pattern: '(?i)\s*-BEGIN\s+.*PRIVATE KEY-\s*'
+10 -37
View File
@@ -24,7 +24,6 @@ import (
"os"
"os/exec"
cfg "github.com/fairwindsops/polaris/pkg/config"
"github.com/fairwindsops/polaris/pkg/kube"
"github.com/fairwindsops/polaris/pkg/validator"
"github.com/sirupsen/logrus"
@@ -32,20 +31,16 @@ import (
"sigs.k8s.io/yaml"
)
var (
setExitCode bool
onlyShowFailedTests bool
minScore int
auditOutputURL string
auditOutputFile string
auditOutputFormat string
resourceToAudit string
useColor bool
helmChart string
helmValues string
checks []string
auditNamespace string
)
var setExitCode bool
var onlyShowFailedTests bool
var minScore int
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)
@@ -61,8 +56,6 @@ func init() {
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")
auditCmd.PersistentFlags().StringSliceVar(&checks, "checks", []string{}, "Optional flag to specify specific checks to check")
auditCmd.PersistentFlags().StringVar(&auditNamespace, "namespace", "", "Namespace to audit. Only applies to in-cluster audits")
}
var auditCmd = &cobra.Command{
@@ -73,26 +66,6 @@ var auditCmd = &cobra.Command{
if displayName != "" {
config.DisplayName = displayName
}
if len(checks) > 0 {
targetChecks := make(map[string]bool)
for _, check := range checks {
targetChecks[check] = true
}
for key := range config.Checks {
if isTarget := targetChecks[key]; !isTarget {
config.Checks[key] = cfg.SeverityIgnore
}
}
}
if auditNamespace != "" {
if helmChart != "" {
logrus.Warn("--namespace and --helm-chart are mutually exclusive. --namespace will be ignored.")
}
if auditPath != "" {
logrus.Warn("--namespace and --audit-path are mutually exclusive. --namespace will be ignored.")
}
config.Namespace = auditNamespace
}
if helmChart != "" {
var err error
auditPath, err = ProcessHelmTemplates(helmChart, helmValues)
-179
View File
@@ -1,179 +0,0 @@
// Copyright 2020 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 cmd
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/fairwindsops/polaris/pkg/kube"
"github.com/fairwindsops/polaris/pkg/mutation"
"github.com/fairwindsops/polaris/pkg/validator"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
yamlV3 "gopkg.in/yaml.v3"
"sigs.k8s.io/yaml"
)
var (
filesPath string
checksToFix []string
fixAll bool
)
func init() {
rootCmd.AddCommand(fixCommand)
fixCommand.PersistentFlags().StringVar(&filesPath, "files-path", "", "mutate and fix one or more YAML files in a specified folder")
fixCommand.PersistentFlags().StringSliceVar(&checksToFix, "checks", []string{}, "Optional flag to specify specific checks to fix eg. checks=hostIPCSet,hostPIDSet and checks=all applies fix to all defined checks mutations")
}
var fixCommand = &cobra.Command{
Use: "fix",
Short: "Fix Infrastructure as code files.",
Long: `Fix Infrastructure as code files.`,
Run: func(cmd *cobra.Command, args []string) {
logrus.Debug("Setting up controller manager")
if filesPath == "" {
logrus.Error("Please specify a file-path flag")
cmd.Help()
os.Exit(1)
}
var yamlFiles []string
fileInfo, err := os.Stat(filesPath)
if err != nil {
logrus.Error(err)
os.Exit(1)
}
if fileInfo.IsDir() {
baseDir := filesPath
if !strings.HasSuffix(filesPath, "/") {
baseDir = baseDir + "/"
}
yamlFiles, err = getYamlFiles(baseDir)
if err != nil {
logrus.Error(err)
os.Exit(1)
}
} else {
yamlFiles = append(yamlFiles, filesPath)
}
var contentStr string
isFirstResource := true
if len(checksToFix) > 0 {
if len(checksToFix) == 1 && checksToFix[0] == "all" {
allchecks := []string{}
for key := range config.Checks {
allchecks = append(allchecks, key)
}
config.Mutations = allchecks
} else {
config.Mutations = checksToFix
}
}
for _, fullFilePath := range yamlFiles {
yamlFile, err := ioutil.ReadFile(fullFilePath)
if err != nil {
logrus.Fatalf("Error reading file with file path %s: %v", fullFilePath, err)
}
dec := yamlV3.NewDecoder(bytes.NewReader(yamlFile))
for {
data := map[string]interface{}{}
err := dec.Decode(&data)
// check it was parsed
if data == nil {
continue
}
// break the loop in case of EOF
if errors.Is(err, io.EOF) {
break
}
if err != nil {
logrus.Fatalf("Error decoding data for file with file path %s: %v", fullFilePath, err)
}
yamlContent, err := yamlV3.Marshal(data)
if err != nil {
logrus.Fatalf("Error marshalling %s: %v", fullFilePath, err)
}
kubeResources := kube.CreateResourceProviderFromYaml(string(yamlContent))
results, err := validator.ApplyAllSchemaChecksToResourceProvider(&config, kubeResources)
if err != nil {
logrus.Fatalf("Error applying schema check to the resources %s: %v", fullFilePath, err)
}
comments, allMutations := mutation.GetMutationsAndCommentsFromResults(results)
updatedYamlContent := string(yamlContent)
if len(allMutations) > 0 {
for _, resources := range kubeResources.Resources {
key := fmt.Sprintf("%s/%s/%s", resources[0].Kind, resources[0].Resource.GetName(), resources[0].Resource.GetNamespace())
mutations := allMutations[key]
mutated, err := mutation.ApplyAllSchemaMutations(&config, kubeResources, resources[0], mutations)
if err != nil {
logrus.Errorf("Error applying schema mutations to the resources: %v", err)
os.Exit(1)
}
mutatedYamlContent, err := yaml.JSONToYAML(mutated.OriginalObjectJSON)
if err != nil {
logrus.Errorf("Error converting JSON to Yaml : %v", err)
os.Exit(1)
}
updatedYamlContent = mutation.UpdateMutatedContentWithComments(string(mutatedYamlContent), comments)
}
}
if isFirstResource {
contentStr = updatedYamlContent
isFirstResource = false
} else {
contentStr += "\n"
contentStr += "---"
contentStr += "\n"
contentStr += updatedYamlContent
}
}
if contentStr != "" {
err = ioutil.WriteFile(fullFilePath, []byte(contentStr), 0644)
if err != nil {
logrus.Fatalf("Error writing output to file: %v", err)
}
}
}
},
}
func getYamlFiles(rootpath string) ([]string, error) {
var list []string
err := filepath.Walk(rootpath, func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
return nil
}
if filepath.Ext(path) == ".yaml" || filepath.Ext(path) == ".yml" {
list = append(list, path)
}
return nil
})
return list, err
}
+6 -10
View File
@@ -25,11 +25,10 @@ import (
)
var configPath string
var disallowExemptions, disallowConfigExemptions, disallowAnnotationExemptions, fixChecks bool
var disallowExemptions bool
var logLevel string
var auditPath string
var displayName string
var kubeContext string
var (
version string
@@ -38,10 +37,7 @@ var (
func init() {
// Flags
rootCmd.PersistentFlags().StringVarP(&configPath, "config", "c", "", "Location of Polaris configuration file.")
rootCmd.PersistentFlags().StringVarP(&kubeContext, "context", "x", "", "Set the kube context.")
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().BoolVarP(&disallowExemptions, "disallow-exemptions", "", false, "Disallow any exemptions from configuration file.")
rootCmd.PersistentFlags().StringVarP(&logLevel, "log-level", "", logrus.InfoLevel.String(), "Logrus log level.")
flag.Parse()
pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
@@ -67,10 +63,10 @@ var rootCmd = &cobra.Command{
os.Exit(1)
}
config.DisallowExemptions = disallowExemptions
config.DisallowConfigExemptions = disallowConfigExemptions
config.DisallowAnnotationExemptions = disallowAnnotationExemptions
config.KubeContext = kubeContext
if disallowExemptions {
config.DisallowExemptions = true
}
},
Run: func(cmd *cobra.Command, args []string) {
logrus.Error("You must specify a sub-command.")
+4 -15
View File
@@ -29,15 +29,11 @@ import (
var webhookPort int
var disableWebhookConfigInstaller bool
var enableMutations bool
var enableValidations bool
func init() {
rootCmd.AddCommand(webhookCmd)
webhookCmd.PersistentFlags().IntVarP(&webhookPort, "port", "p", 9876, "Port for the dashboard webserver.")
webhookCmd.PersistentFlags().BoolVar(&disableWebhookConfigInstaller, "disable-webhook-config-installer", false, "Disable the installer in the webhook server, so it won't install webhook configuration resources during bootstrapping.")
webhookCmd.PersistentFlags().BoolVar(&enableValidations, "validate", true, "Enable the validating webhook to reject workloads with issues")
webhookCmd.PersistentFlags().BoolVar(&enableMutations, "mutate", false, "Enable the mutating webhook to modify workloads with issues")
webhookCmd.PersistentFlags().BoolVar(&disableWebhookConfigInstaller, "disable-webhook-config-installer", false, "disable the installer in the webhook server, so it won't install webhook configuration resources during bootstrapping.")
}
var webhookCmd = &cobra.Command{
@@ -65,17 +61,10 @@ var webhookCmd = &cobra.Command{
server.CertName = "tls.crt"
server.KeyName = "tls.key"
if !enableMutations && !enableValidations {
logrus.Errorf("One of --mutate or --validate must be set to true")
os.Exit(1)
}
// Iterate all the configurations supported controllers to scan and register them for webhooks
// Should only register controllers that are configured to be scanned
fwebhook.NewWebhook(mgr, fwebhook.Validator{Config: config, Client: mgr.GetClient()})
if enableValidations {
fwebhook.NewValidateWebhook(mgr, fwebhook.Validator{Config: config, Client: mgr.GetClient()})
}
if enableMutations {
fwebhook.NewMutateWebhook(mgr, fwebhook.Mutator{Config: config, Client: mgr.GetClient()})
}
logrus.Infof("Polaris webhook server listening on port %d", webhookPort)
if err := mgr.Start(signals.SetupSignalHandler()); err != nil {
logrus.Errorf("Error starting manager: %v", err)
+156
View File
@@ -0,0 +1,156 @@
---
# Source: polaris/templates/0-namespace.yaml
apiVersion: v1
kind: Namespace
metadata:
name: polaris
---
# Source: polaris/templates/serviceaccount.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: polaris
namespace: polaris
labels:
app: polaris
---
# Source: polaris/templates/rbac.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: polaris
labels:
app: polaris
rules:
# required by controller-runtime code doing a cluster wide lookup
# when it seems namespace would suffice
- apiGroups:
- ''
resources:
- 'nodes'
verbs:
- 'get'
- 'list'
- apiGroups:
- 'monitoring.coreos.com'
resources:
- 'prometheuses'
- 'alertmanagers'
verbs:
- 'get'
- 'list'
---
# Source: polaris/templates/rbac.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: polaris-view
labels:
app: polaris
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: view
subjects:
- kind: ServiceAccount
name: polaris
namespace: polaris
---
# Source: polaris/templates/rbac.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: polaris
labels:
app: polaris
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: polaris
subjects:
- kind: ServiceAccount
name: polaris
namespace: polaris
---
# Source: polaris/templates/dashboard.service.yaml
apiVersion: v1
kind: Service
metadata:
name: polaris-dashboard
namespace: polaris
labels:
app: polaris
annotations:
spec:
ports:
- name: http-dashboard
port: 80
protocol: TCP
targetPort: 8080
selector:
app: polaris
component: dashboard
type: ClusterIP
---
# Source: polaris/templates/dashboard.deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: polaris-dashboard
namespace: polaris
labels:
app: polaris
component: dashboard
spec:
replicas: 1
selector:
matchLabels:
app: polaris
component: dashboard
template:
metadata:
labels:
app: polaris
component: dashboard
spec:
containers:
- command:
- polaris
- dashboard
- --port
- "8080"
image: 'quay.io/fairwinds/polaris:4.0'
imagePullPolicy: 'Always'
name: dashboard
ports:
- containerPort: 8080
livenessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 5
periodSeconds: 20
readinessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 5
periodSeconds: 20
resources:
limits:
cpu: 150m
memory: 512Mi
requests:
cpu: 100m
memory: 128Mi
securityContext:
allowPrivilegeEscalation: false
privileged: false
readOnlyRootFilesystem: true
runAsNonRoot: true
capabilities:
drop:
- ALL
serviceAccountName: polaris
nodeSelector:
tolerations:
+270
View File
@@ -0,0 +1,270 @@
---
# Source: polaris/templates/0-namespace.yaml
apiVersion: v1
kind: Namespace
metadata:
name: polaris
---
# Source: polaris/templates/serviceaccount.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: polaris
namespace: polaris
labels:
app: polaris
---
# Source: polaris/templates/rbac.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: polaris
labels:
app: polaris
rules:
# required by controller-runtime code doing a cluster wide lookup
# when it seems namespace would suffice
- apiGroups:
- ''
resources:
- 'nodes'
verbs:
- 'get'
- 'list'
- apiGroups:
- 'monitoring.coreos.com'
resources:
- 'prometheuses'
- 'alertmanagers'
verbs:
- 'get'
- 'list'
---
# Source: polaris/templates/rbac.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: polaris-view
labels:
app: polaris
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: view
subjects:
- kind: ServiceAccount
name: polaris
namespace: polaris
---
# Source: polaris/templates/rbac.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: polaris
labels:
app: polaris
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: polaris
subjects:
- kind: ServiceAccount
name: polaris
namespace: polaris
---
# Source: polaris/templates/webhook.service.yaml
apiVersion: v1
kind: Service
metadata:
name: polaris-webhook
namespace: polaris
labels:
app: polaris
spec:
ports:
- name: webhook
port: 443
protocol: TCP
targetPort: 9876
selector:
app: polaris
component: webhook
type: ClusterIP
---
# Source: polaris/templates/webhook.deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: polaris-webhook
namespace: polaris
labels:
app: polaris
component: webhook
spec:
replicas: 1
selector:
matchLabels:
app: polaris
component: webhook
template:
metadata:
labels:
app: polaris
component: webhook
spec:
containers:
- name: webhook
command:
- polaris
- webhook
image: 'quay.io/fairwinds/polaris:4.0'
imagePullPolicy: 'Always'
ports:
- containerPort: 9876
# These are fairly useless readiness/liveness probes for now
# Follow this issue for potential improvements:
# https://github.com/kubernetes-sigs/controller-runtime/issues/356
livenessProbe:
exec:
command:
- sh
- -c
- ps -ef | grep polaris
initialDelaySeconds: 5
periodSeconds: 5
readinessProbe:
exec:
command:
- sh
- -c
- ps -ef | grep polaris
initialDelaySeconds: 5
periodSeconds: 5
resources:
limits:
cpu: 100m
memory: 128Mi
requests:
cpu: 100m
memory: 128Mi
securityContext:
allowPrivilegeEscalation: false
privileged: false
readOnlyRootFilesystem: true
runAsNonRoot: true
capabilities:
drop:
- ALL
volumeMounts:
- name: secret
mountPath: /opt/cert/
readOnly: true
- name: cr-logs
mountPath: /tmp/
readOnly: false
serviceAccountName: polaris
nodeSelector:
tolerations:
volumes:
- name: secret
secret:
secretName: polaris
- name: cr-logs
emptyDir: {}
---
# Source: polaris/templates/webhook.cert.yaml
apiVersion: cert-manager.io/v1alpha2
kind: Certificate
metadata:
name: polaris-cert
namespace: polaris
labels:
app: polaris
spec:
commonName: polaris-webhook.polaris.svc
dnsNames:
- polaris-webhook.polaris.svc
- polaris-webhook.polaris
- polaris-webhook
- polaris-webhook.polaris.svc.
issuerRef:
kind: Issuer
name: polaris-selfsigned
secretName: polaris
---
# Source: polaris/templates/webhook.cert.yaml
apiVersion: cert-manager.io/v1alpha2
kind: Issuer
metadata:
name: polaris-selfsigned
namespace: polaris
spec:
selfSigned: {}
---
# Source: polaris/templates/webhook.configuration.yaml
apiVersion: admissionregistration.k8s.io/v1beta1
kind: ValidatingWebhookConfiguration
metadata:
name: polaris-webhook
annotations:
cert-manager.io/inject-ca-from: polaris/polaris-cert
webhooks:
- admissionReviewVersions:
- v1beta1
clientConfig:
service:
name: polaris-webhook
namespace: polaris
path: /validate
port: 443
failurePolicy: Fail
matchPolicy: Exact
name: polaris.fairwinds.com
namespaceSelector:
matchExpressions:
- key: control-plane
operator: DoesNotExist
objectSelector:
{}
rules:
- apiGroups:
- apps
apiVersions:
- v1
- v1beta1
- v1beta2
operations:
- CREATE
- UPDATE
resources:
- daemonsets
- deployments
- statefulsets
scope: Namespaced
- apiGroups:
- batch
apiVersions:
- v1
- v1beta1
operations:
- CREATE
- UPDATE
resources:
- jobs
- cronjobs
scope: Namespaced
- apiGroups:
- ""
apiVersions:
- v1
operations:
- CREATE
- UPDATE
resources:
- pods
- replicationcontrollers
scope: Namespaced
sideEffects: None
timeoutSeconds: 10
+5 -14
View File
@@ -25,6 +25,11 @@ If you don't use cert-manager, you'll need to:
* Create a TLS secret in your cluster with a valid certificate that uses that CA
* Pass the name of that secret with the webhook.secretName parameter.
### kubectl
```bash
kubectl apply -f https://github.com/fairwindsops/polaris/releases/latest/download/webhook.yaml
```
### Helm
```bash
helm repo add fairwinds-stable https://charts.fairwinds.com/stable
@@ -45,17 +50,3 @@ output unless we are rejecting a workload altogether.
This 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. This will change in a future version of Kubernetes.
## Mutating Webhook
By default, the Admission Controller is just pass/fail, but
Polaris can also operate as a mutating webhook for many of the issues it checks for.
This means Polaris will remediate the issue it finds, rather than rejecting
the deployment.
To enable the mutating webhook, add `--set webhook.mutate=true` to your
Helm instlallation command.
By default, the only mutation enabled is `pullPolicyNotAlways`. If you'd like to
enable other mutations, you can set the `webhook.mutations` flag.
-32
View File
@@ -5,38 +5,6 @@ meta:
content: "Fairwinds Polaris | Changelog"
---
## 7.0.1
* Documentation updates
## 7.0.0
* Better support for `polaris fix`
* `target: Pod` is now `target: PodSpec` (to differentiate naked Pods from Controllers)
## 6.0.0
* Preliminary support for `polaris fix` command
* Changes to how Pod owners are determined
* Removed YAML manifests from the `deploy/` directory - Helm is now the default install mechanism
## 5.1.0
* Support `--context` flag for kubecontext
* Treat core Kubernetes controllers (`Deployments`, `StatefulSets`, `DaemonSets`, `CronJobs`) as top-level objects, instead of following owner refs
## 5.0.0
* Renamed `multipleReplicasForDeployment` to `deploymentMissingReplicas`
* Changed `RunAsRootAllowed` and `hostNetworkSet` default severity to `danger`
* Changed `deploymentMissingReplicas` default severity to `warning`
## 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
+1 -1
View File
@@ -15,7 +15,7 @@ key | default | description
`tagNotSpecified` | `danger` | Fails when an image tag is either not specified or `latest`.
`pullPolicyNotAlways` | `warning` | Fails when an image pull policy is not `always`.
`priorityClassNotSet` | `ignore` | Fails when a priorityClassName is not set for a pod.
`deploymentMissingReplicas` | `warning` | Fails when there is only one replica for a deployment.
`multipleReplicasForDeployment` | `ignore` | Fails when there is only one replica for a deployment.
`missingPodDisruptionBudget` | `ignore`
## Background
+4 -9
View File
@@ -19,13 +19,10 @@ webhook
Runs the webhook webserver
# global flags
-c, --config string Location of Polaris configuration file.
-x, --context string Set the kube context.
--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")
-c, --config string Location of Polaris configuration file.
--disallow-exemptions Disallow any exemptions from configuration file.
--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.
@@ -38,14 +35,12 @@ webhook
# audit flags
--audit-path string If specified, audits one or more YAML files instead of a cluster.
--checks stringArray Optional flag to specify specific checks to check
--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
--namespace string Namespace to audit. Only applies to in-cluster audits
--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.
+46 -3
View File
@@ -73,7 +73,50 @@ Each new pull request should:
- Be up to date and/or rebased on the master branch
## Creating a new release
To create a new release, simply tag this repo with the new version.
For major and minor releases, don't forget to update the Helm chart at
https://github.com/FairwindsOps/charts
### Patch releases
Patch releases only need to change this repo. The Helm chart and deploy scripts
will automatically pull in the latest changes.
If the release involves changes to anything in the `deploy/` folder (e.g. new RBAC permissions),
it needs to be a minor or major release in order to prevent breaking the Helm chart.
1. Create a PR for this repo
1. Bump the version number in:
1. main.go
2. README.md
2. Update CHANGELOG.md
3. Merge your PR
2. Tag the latest branch for this repo
1. Pull the latest commit for the `master` branch (which you just merged in your PR)
2. Run `git tag $VERSION && git push --tags`
3. Make sure CircleCI runs successfully for the new tag - this will push images to quay.io and create a release in GitHub
1. If CircleCI fails, check with Codeowners ASAP
### Minor/Major releases
Minor and major releases need to change both this repository and the
[Helm chart repo](https://github.com/FairwindsOps/charts/).
The steps are:
1. Modify the [Helm chart](https://github.com/FairwindsOps/charts/stable/polaris)
1. Clone the helm charts repo
1. `git clone https://github.com/FairwindsOps/charts`
2. `git checkout -b yourname/update-polaris`
1. Bump the version number in `stable/polaris/Chart.yaml`
2. Make any necessary changes to the chart to support the new version of Polaris (e.g. new RBAC permissions)
3. **Don't merge yet!**
2. Create a PR for this repo
1. Create a new branch named `yourname/update-version`
2. Bump the version number in:
1. main.go
2. README.md
3. Regenerate the deployment files. Assuming you've cloned the charts repo to `~/git/charts`:
1. `CHARTS_DIR=~/git/charts ./scripts/generate-deployment-files.sh`
4. Update CHANGELOG.md
5. Merge your PR
3. Tag the latest branch for this repo
1. Pull the latest for the `master` branch
2. Run `git tag $VERSION && git push --tags`
3. Make sure CircleCI runs successfully for the new tag - this will push images to quay.io and create a release in GitHub
1. If CircleCI fails, check with Codeowners ASAP
4. Create and merge a PR for your changes to the Helm chart
+3 -9
View File
@@ -43,11 +43,10 @@ check ID. Note that you'll also have to set its severity in the `checks` section
* `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 creates Pods (e.g. Deployments, CronJobs, StatefulSets), as well as naked Pods
* `PodTemplate`, same as `Controller`, but the schema applies to the Pod template rather than the top-level controller
* `PodSpec`, same as `Controller`, but the schema applies to the Pod spec rather than the top-level controller
* `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`, `PodSpec` or `Container`, you can use this to change which types of controllers are checked
* `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
@@ -135,11 +134,6 @@ schema:
const: "{{ .metadata.name }}"
```
* The object available via the go template is the full object, and not limited by `target`.
* A check of `target: PodSpec` can directly access the pod specification via the go template variable `.Polaris.PodSpec`.
* A check of `target: PodTemplate` can directly access the pod template via the go template variable `.Polaris.PodTemplate`.
* A check of `target: Container` can directly access the container being checked via the go template variable `.Polaris.container`. The pod template and pod specification can also be accessed via the respective variables `.Polaris.PodTemplate` and `.Polaris.PodSpec`. Access to pod-level fields allows a container check to consult related fields from the pod, such as `securityContext`.
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`:
+5
View File
@@ -16,6 +16,11 @@ don't conform to best practices.
## Installation
### kubectl
```bash
kubectl apply -f https://github.com/fairwindsops/polaris/releases/latest/download/dashboard.yaml
kubectl port-forward --namespace polaris svc/polaris-dashboard 8080:80
```
### Helm
```bash
helm repo add fairwinds-stable https://charts.fairwinds.com/stable
+4 -30
View File
@@ -25,32 +25,6 @@ brew install FairwindsOps/tap/polaris
polaris version
```
## Checking Infrastructure as Code files
You can audit Kubernetes YAML files by running:
```bash
polaris audit --audit-path ./deploy/ --format=pretty
```
This will print out any issues Polaris finds in your manifests.
Polaris can only check raw YAML manifests. If you'd like to check a Helm template,
you can run `helm template` to generate a manifest that Polaris can check.
## Fixing Issues
Polaris can automatically fix many of the issues it finds. For example, you can run
```bash
polaris fix --files-path ./deploy/ --checks=all
```
to fix any issues inside the `deploy` directory. Polaris may leave
comments next to some changes (e.g. liveness and readiness probes) prompting
the user to set them to something more appropriate given the context of their
application.
Note that not all issues can be automatically fixed.
Currently only raw YAML manifests can be mutated. Helm charts etc.
still need to be changed manually.
## Running in a CI pipeline
### Set minimum score for an exit code
@@ -114,9 +88,9 @@ The version number of the release tag.
##### Example usage
```yaml
uses: fairwindsops/polaris/.github/actions/setup-polaris@master
uses: fairwindsops/polaris@master
with:
version: 5.0.0
version: "3.0.3"
```
Example inside a job:
@@ -125,9 +99,9 @@ Example inside a job:
steps:
- uses: actions/checkout@v2
- name: Setup polaris
uses: fairwindsops/polaris/.github/actions/setup-polaris@master
uses: fairwindsops/polaris@master
with:
version: 5.0.0
version: 3.0.3
- name: Use command
run: polaris version
+1780 -16574
View File
File diff suppressed because it is too large Load Diff
+4 -9
View File
@@ -1,6 +1,6 @@
checks:
# reliability
deploymentMissingReplicas: warning
multipleReplicasForDeployment: warning
priorityClassNotSet: warning
tagNotSpecified: danger
pullPolicyNotAlways: warning
@@ -12,26 +12,20 @@ checks:
memoryRequestsMissing: warning
memoryLimitsMissing: warning
# security
automountServiceAccountToken: warning
hostIPCSet: danger
hostPIDSet: danger
linuxHardening: danger
missingNetworkPolicy: warning
notReadOnlyRootFilesystem: warning
privilegeEscalationAllowed: danger
runAsRootAllowed: danger
runAsRootAllowed: warning
runAsPrivileged: danger
dangerousCapabilities: danger
insecureCapabilities: warning
hostNetworkSet: danger
hostNetworkSet: warning
hostPortSet: warning
sensitiveContainerEnvVar: danger
sensitiveConfigmapContent: danger
# custom
resourceLimits: warning
imageRegistry: danger
exemptions:
- controllerNames:
- my-network-controller
@@ -92,3 +86,4 @@ customChecks:
type: string
not:
pattern: ^quay.io
+3 -6
View File
@@ -1,6 +1,6 @@
checks:
# reliability
deploymentMissingReplicas: warning
multipleReplicasForDeployment: ignore
priorityClassNotSet: ignore
tagNotSpecified: danger
pullPolicyNotAlways: warning
@@ -20,17 +20,14 @@ checks:
hostPIDSet: danger
notReadOnlyRootFilesystem: warning
privilegeEscalationAllowed: danger
runAsRootAllowed: danger
runAsRootAllowed: warning
runAsPrivileged: danger
dangerousCapabilities: danger
insecureCapabilities: warning
hostNetworkSet: danger
hostNetworkSet: warning
hostPortSet: warning
tlsSettingsMissing: warning
mutations:
- pullPolicyNotAlways
exemptions:
- namespace: kube-system
controllerNames:
+8 -1
View File
@@ -1,7 +1,14 @@
options:
organization: fairwinds-production
organization: fairwinds-opensource
baseBranch: master
# These images will be scanned for vulnerabilities.
images:
docker:
- quay.io/fairwinds/polaris:$CI_SHA1
# These manifests will be scanned for configuration issues.
manifests:
yaml:
- ./deploy/dashboard.yaml
- ./deploy/webhook.yaml
+19 -87
View File
@@ -1,93 +1,25 @@
module github.com/fairwindsops/polaris
go 1.17
go 1.15
require (
github.com/evanphx/json-patch/v5 v5.6.0
github.com/fatih/color v1.13.0
github.com/gobuffalo/packr/v2 v2.8.3
github.com/gorilla/mux v1.8.0
github.com/qri-io/jsonschema v0.1.1
github.com/sirupsen/logrus v1.9.0
github.com/spf13/cobra v1.5.0
github.com/spf13/pflag v1.0.5
github.com/stretchr/testify v1.8.0
github.com/thoas/go-funk v0.9.2
golang.org/x/text v0.3.7 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1
k8s.io/api v0.24.3
k8s.io/apimachinery v0.24.3
k8s.io/client-go v0.24.3
sigs.k8s.io/controller-runtime v0.12.3
sigs.k8s.io/yaml v1.3.0
)
require gomodules.xyz/jsonpatch/v2 v2.2.0
require (
cloud.google.com/go/compute v1.6.1 // indirect
github.com/Azure/go-autorest v14.2.0+incompatible // indirect
github.com/Azure/go-autorest/autorest v0.11.27 // indirect
github.com/Azure/go-autorest/autorest/adal v0.9.20 // indirect
github.com/Azure/go-autorest/autorest/date v0.3.0 // indirect
github.com/Azure/go-autorest/logger v0.2.1 // indirect
github.com/Azure/go-autorest/tracing v0.6.0 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/emicklei/go-restful/v3 v3.8.0 // indirect
github.com/evanphx/json-patch v5.6.0+incompatible // indirect
github.com/fsnotify/fsnotify v1.5.4 // indirect
github.com/go-logr/logr v1.2.3 // indirect
github.com/go-openapi/jsonpointer v0.19.5 // indirect
github.com/go-openapi/jsonreference v0.20.0 // indirect
github.com/go-openapi/swag v0.21.1 // indirect
github.com/gobuffalo/logger v1.0.6 // indirect
github.com/gobuffalo/packd v1.0.1 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang-jwt/jwt/v4 v4.4.1 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/google/gnostic v0.6.9 // indirect
github.com/google/go-cmp v0.5.8 // indirect
github.com/fatih/color v1.12.0
github.com/gobuffalo/packr/v2 v2.8.1
github.com/google/gofuzz v1.2.0 // indirect
github.com/google/uuid v1.3.0 // indirect
github.com/imdario/mergo v0.3.13 // indirect
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/karrick/godirwalk v1.17.0 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/markbates/errx v1.1.0 // indirect
github.com/markbates/oncer v1.0.0 // indirect
github.com/markbates/safe v1.0.1 // indirect
github.com/mattn/go-colorable v0.1.12 // indirect
github.com/mattn/go-isatty v0.0.14 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/prometheus/client_golang v1.12.2 // indirect
github.com/prometheus/client_model v0.2.0 // indirect
github.com/prometheus/common v0.34.0 // indirect
github.com/prometheus/procfs v0.7.3 // indirect
github.com/qri-io/jsonpointer v0.1.1 // indirect
golang.org/x/crypto v0.0.0-20220525230936-793ad666bf5e // indirect
golang.org/x/net v0.0.0-20220607020251-c690dde0001d // indirect
golang.org/x/oauth2 v0.0.0-20220524215830-622c5d57e401 // indirect
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 // indirect
golang.org/x/term v0.0.0-20220526004731-065cf7ba2467 // indirect
golang.org/x/time v0.0.0-20220411224347-583f2d630306 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/protobuf v1.28.0 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
k8s.io/component-base v0.24.2 // indirect
k8s.io/klog/v2 v2.60.1 // indirect
k8s.io/kube-openapi v0.0.0-20220603121420-31174f50af60 // indirect
k8s.io/utils v0.0.0-20220210201930-3a6ce19ff2f9 // indirect
sigs.k8s.io/json v0.0.0-20220525155127-227cbc7cc124 // indirect
sigs.k8s.io/structured-merge-diff/v4 v4.2.1 // indirect
github.com/google/uuid v1.1.3 // indirect
github.com/gorilla/mux v1.8.0
github.com/karrick/godirwalk v1.16.1 // indirect
github.com/qri-io/jsonschema v0.1.1
github.com/rogpeppe/go-internal v1.6.2 // indirect
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
github.com/thoas/go-funk v0.9.0
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b
k8s.io/api v0.22.0
k8s.io/apimachinery v0.22.0
k8s.io/client-go v0.22.0
sigs.k8s.io/controller-runtime v0.9.6
sigs.k8s.io/yaml v1.2.0
)
+177 -367
View File
File diff suppressed because it is too large Load Diff
+4 -6
View File
@@ -15,14 +15,12 @@
package main
import (
cmd "github.com/fairwindsops/polaris/cmd/polaris"
"github.com/fairwindsops/polaris/cmd/polaris"
)
var (
// Version is set during build
Version = "development"
// Commit is set during build
Commit = ""
const (
// Version represents the current release version of Polaris
Version = "4.0.8"
)
func main() {
+1 -20
View File
@@ -1,17 +1,3 @@
// Copyright 2022 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 (
@@ -27,12 +13,11 @@ var (
// tests as we migrate toward JSON schema
checkOrder = []string{
// Controller Checks
"deploymentMissingReplicas",
"multipleReplicasForDeployment",
// Pod checks
"hostIPCSet",
"hostPIDSet",
"hostNetworkSet",
"automountServiceAccountToken",
// Container checks
"memoryLimitsMissing",
"memoryRequestsMissing",
@@ -50,15 +35,11 @@ var (
"dangerousCapabilities",
"insecureCapabilities",
"priorityClassNotSet",
"linuxHardening",
"sensitiveContainerEnvVar",
// Other checks
"tlsSettingsMissing",
"pdbDisruptionsIsZero",
"metadataAndNameMismatched",
"missingPodDisruptionBudget",
"missingNetworkPolicy",
"sensitiveConfigmapContent",
}
)
+5 -10
View File
@@ -29,16 +29,11 @@ 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"`
DisallowConfigExemptions bool `json:"disallowConfigExemptions"`
DisallowAnnotationExemptions bool `json:"disallowAnnotationExemptions"`
Mutations []string `json:"mutations"`
KubeContext string `json:"kubeContext"`
Namespace string `json:"namespace"`
DisplayName string `json:"displayName"`
Checks map[string]Severity `json:"checks"`
CustomChecks map[string]SchemaCheck `json:"customChecks"`
Exemptions []Exemption `json:"exemptions"`
DisallowExemptions bool `json:"disallowExemptions"`
}
// Exemption represents an exemption to normal rules
+1 -15
View File
@@ -1,17 +1,3 @@
// Copyright 2022 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 (
@@ -25,7 +11,7 @@ func (conf Configuration) IsActionable(ruleID string, objMeta metav1.Object, con
if severity, ok := conf.Checks[ruleID]; !ok || !severity.IsActionable() {
return false
}
if conf.DisallowExemptions || conf.DisallowConfigExemptions {
if conf.DisallowExemptions {
return true
}
for _, exemption := range conf.Exemptions {
+51 -51
View File
@@ -25,40 +25,40 @@ import (
var confContainerTest = `
checks:
deploymentMissingReplicas: warning
multipleReplicasForDeployment: warning
priorityClassNotSet: warning
pullPolicyNotAlways: warning
exemptions:
- namespace: prometheus
rules:
- deploymentMissingReplicas
- multipleReplicasForDeployment
- controllerNames:
- controller2
rules:
- deploymentMissingReplicas
- multipleReplicasForDeployment
- namespace: kube-system
controllerNames:
- controller3
rules:
- deploymentMissingReplicas
- multipleReplicasForDeployment
- containerNames:
- container41
- container42
rules:
- deploymentMissingReplicas
- multipleReplicasForDeployment
- namespace: kube-system
containerNames:
- container51
- container52
rules:
- deploymentMissingReplicas
- multipleReplicasForDeployment
- controllerNames:
- controller6
containerNames:
- container61
- container62
rules:
- deploymentMissingReplicas
- multipleReplicasForDeployment
- namespace: kube-system
controllerNames:
- controller7
@@ -66,7 +66,7 @@ exemptions:
- container71
- container72
rules:
- deploymentMissingReplicas
- multipleReplicasForDeployment
- priorityClassNotSet
- namespace: polaris
`
@@ -86,22 +86,22 @@ func TestNamespaceExemptionForSpecifiedRules(t *testing.T) {
parsedConf, err := Parse([]byte(confContainerTest))
assert.NoError(t, err)
actionable := parsedConf.IsActionable("deploymentMissingReplicas", createMeta("prometheus", ""), "")
actionable := parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("prometheus", ""), "")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("prometheus", "controller1"), "container11")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("prometheus", "controller1"), "container11")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("prometheus", ""), "container11")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("prometheus", ""), "container11")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("prometheus", "controller1"), "")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("prometheus", "controller1"), "")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("pullPolicyNotAlways", createMeta("prometheus", "controller1"), "")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("kube-system", ""), "")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", ""), "")
assert.True(t, actionable)
}
@@ -109,16 +109,16 @@ func TestNamespaceExemptionForAllRules(t *testing.T) {
parsedConf, err := Parse([]byte(confContainerTest))
assert.NoError(t, err)
actionable := parsedConf.IsActionable("deploymentMissingReplicas", createMeta("polaris", ""), "")
actionable := parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("polaris", ""), "")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("polaris", "controller1"), "container11")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("polaris", "controller1"), "container11")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("polaris", ""), "container11")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("polaris", ""), "container11")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("polaris", "controller1"), "")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("polaris", "controller1"), "")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("pullPolicyNotAlways", createMeta("polaris", "controller1"), "")
@@ -129,28 +129,28 @@ func TestControllerExemption(t *testing.T) {
parsedConf, err := Parse([]byte(confContainerTest))
assert.NoError(t, err)
actionable := parsedConf.IsActionable("deploymentMissingReplicas", createMeta("", "controller2"), "")
actionable := parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("", "controller2"), "")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("", "controller2"), "container21")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("", "controller2"), "container21")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("prometheus", "controller2"), "container21")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("prometheus", "controller2"), "container21")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("prometheus", "controller2"), "")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("prometheus", "controller2"), "")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("", "controller3"), "")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("", "controller3"), "")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("kube-system", "controller3"), "")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", "controller3"), "")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("kube-system", "controller3"), "container31")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", "controller3"), "container31")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("kube-system", "controller4"), "")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", "controller4"), "")
assert.True(t, actionable)
}
@@ -158,22 +158,22 @@ func TestOnlyContainerExemption(t *testing.T) {
parsedConf, err := Parse([]byte(confContainerTest))
assert.NoError(t, err)
actionable := parsedConf.IsActionable("deploymentMissingReplicas", createMeta("", ""), "container41")
actionable := parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("", ""), "container41")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("", ""), "container42")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("", ""), "container42")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("", "controller4"), "container41")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("", "controller4"), "container41")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("kube-system", ""), "container41")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", ""), "container41")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("kube-system", "controller4"), "container41")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", "controller4"), "container41")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("", ""), "container51")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("", ""), "container51")
assert.True(t, actionable)
}
@@ -181,25 +181,25 @@ func TestNamespaceAndContainerExemption(t *testing.T) {
parsedConf, err := Parse([]byte(confContainerTest))
assert.NoError(t, err)
actionable := parsedConf.IsActionable("deploymentMissingReplicas", createMeta("kube-system", ""), "container51")
actionable := parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", ""), "container51")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("priorityClassNotSet", createMeta("kube-system", ""), "container51")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("kube-system", "controller5"), "container51")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", "controller5"), "container51")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("kube-system", "controller5"), "")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", "controller5"), "")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("insights-agent", ""), "container51")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("insights-agent", ""), "container51")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("", ""), "container51")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("", ""), "container51")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("", "controller5"), "container51")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("", "controller5"), "container51")
assert.True(t, actionable)
}
@@ -207,25 +207,25 @@ func TestControllerAndContainerExemption(t *testing.T) {
parsedConf, err := Parse([]byte(confContainerTest))
assert.NoError(t, err)
actionable := parsedConf.IsActionable("deploymentMissingReplicas", createMeta("", "controller6"), "container61")
actionable := parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("", "controller6"), "container61")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("priorityClassNotSet", createMeta("", "controller6"), "container61")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("kube-system", "controller6"), "container61")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", "controller6"), "container61")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("kube-system", "controller6"), "")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", "controller6"), "")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("", "controller7"), "container61")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("", "controller7"), "container61")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("", ""), "container61")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("", ""), "container61")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("kube-system", ""), "container61")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", ""), "container61")
assert.True(t, actionable)
}
@@ -233,28 +233,28 @@ func TestContainerExemption(t *testing.T) {
parsedConf, err := Parse([]byte(confContainerTest))
assert.NoError(t, err)
actionable := parsedConf.IsActionable("deploymentMissingReplicas", createMeta("", ""), "container71")
actionable := parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("", ""), "container71")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("kube-system", ""), "container71")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", ""), "container71")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("", "controller7"), "container71")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("", "controller7"), "container71")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("kube-system", "controller7"), "")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", "controller7"), "")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("kube-system", "controller7"), "container71")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", "controller7"), "container71")
assert.False(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("insights-agent", "controller7"), "container71")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("insights-agent", "controller7"), "container71")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("kube-system", "controller6"), "container71")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", "controller6"), "container71")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("deploymentMissingReplicas", createMeta("kube-system", "controller7"), "container61")
actionable = parsedConf.IsActionable("multipleReplicasForDeployment", createMeta("kube-system", "controller7"), "container61")
assert.True(t, actionable)
actionable = parsedConf.IsActionable("priorityClassNotSet", createMeta("kube-system", "controller7"), "container71")
+5 -41
View File
@@ -1,17 +1,3 @@
// Copyright 2022 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 (
@@ -25,7 +11,6 @@ import (
"github.com/qri-io/jsonschema"
"github.com/thoas/go-funk"
"gomodules.xyz/jsonpatch/v2"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
k8sYaml "k8s.io/apimachinery/pkg/util/yaml"
@@ -39,24 +24,15 @@ const (
TargetController TargetKind = "Controller"
// TargetContainer points to the container spec
TargetContainer TargetKind = "Container"
// TargetPodSpec points to the pod spec
TargetPodSpec TargetKind = "PodSpec"
// TargetPodTemplate points to the pod template
TargetPodTemplate TargetKind = "PodTemplate"
// TargetPod points to the pod spec
TargetPod TargetKind = "Pod"
)
// HandledTargets is a list of target names that are explicitly handled
var HandledTargets = []TargetKind{
TargetController,
TargetContainer,
TargetPodSpec,
TargetPodTemplate,
}
// MutationComment is the comments added to a mutated file
type MutationComment struct {
Find string `yaml:"find" json:"find"`
Comment string `yaml:"comment" json:"comment"`
TargetPod,
}
// SchemaCheck is a Polaris check that runs using JSON Schema
@@ -75,8 +51,6 @@ type SchemaCheck struct {
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:"-"`
Mutations []jsonpatch.Operation `yaml:"mutations" json:"mutations"`
Comments []MutationComment `yaml:"comments" json:"comments"`
}
type resourceMinimum string
@@ -256,16 +230,11 @@ func (check SchemaCheck) TemplateForResource(res interface{}) (*SchemaCheck, err
return &newCheck, err
}
// CheckPodSpec checks a pod spec against the schema
func (check SchemaCheck) CheckPodSpec(pod *corev1.PodSpec) (bool, []jsonschema.ValError, error) {
// CheckPod checks a pod spec against the schema
func (check SchemaCheck) CheckPod(pod *corev1.PodSpec) (bool, []jsonschema.ValError, error) {
return check.CheckObject(pod)
}
// CheckPodTemplate checks a pod template against the schema
func (check SchemaCheck) CheckPodTemplate(podTemplate interface{}) (bool, []jsonschema.ValError, error) {
return check.CheckObject(podTemplate)
}
// CheckController checks a controler's spec against the schema
func (check SchemaCheck) CheckController(bytes []byte) (bool, []jsonschema.ValError, error) {
errs, err := check.Validator.ValidateBytes(bytes)
@@ -312,11 +281,6 @@ func (check SchemaCheck) CheckAdditionalObjects(groupkind string, objects []inte
// IsActionable decides if this check applies to a particular target
func (check SchemaCheck) IsActionable(target TargetKind, kind string, isInit bool) bool {
if funk.Contains(HandledTargets, target) {
if check.Target == TargetPodTemplate && target == TargetPodSpec {
// A target=PodSpec and check.Target=PodTemplate is expected
// because applyPodSchemaChecks() explicitly sets check.Target
return true
}
if check.Target != target {
return false
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

+5 -9
View File
@@ -130,17 +130,13 @@ func writeTemplate(tmpl *template.Template, data *templateData, w http.ResponseW
func getConfigForQuery(base config.Configuration, query url.Values) config.Configuration {
c := base
switch query.Get("disallowExemptions") {
case "true":
c.DisallowExemptions = true
c.DisallowConfigExemptions = true
c.DisallowAnnotationExemptions = true
default:
exemptions := query.Get("disallowExemptions")
if exemptions == "false" {
c.DisallowExemptions = false
c.DisallowConfigExemptions = false
c.DisallowAnnotationExemptions = false
}
if exemptions == "true" {
c.DisallowExemptions = true
}
return c
}
+1 -14
View File
@@ -1,17 +1,3 @@
// Copyright 2022 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 dashboard
import (
@@ -252,3 +238,4 @@ func TestStringInSlice(t *testing.T) {
assert.Equal(t, expectedOutput, actual)
assert.NotEqual(t, true, actual)
}
+1 -1
View File
@@ -87,7 +87,7 @@
<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/benchmark.png" />
<img src="static/images/FW_Insights_Polaris.svg" />
</a>
</div>
+8 -74
View File
@@ -1,17 +1,3 @@
// Copyright 2022 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 kube
import (
@@ -35,29 +21,21 @@ type GenericResource struct {
ObjectMeta kubeAPIMetaV1.Object
Resource unstructured.Unstructured
PodSpec *kubeAPICoreV1.PodSpec
PodTemplate interface{}
OriginalObjectJSON []byte
}
// NewGenericResourceFromUnstructured creates a workload from an unstructured.Unstructured
func NewGenericResourceFromUnstructured(unst unstructured.Unstructured, podSpecMap interface{}) (GenericResource, error) {
if unst.GetCreationTimestamp().Time.IsZero() {
unstructured.RemoveNestedField(unst.Object, "metadata", "creationTimestamp")
unstructured.RemoveNestedField(unst.Object, "status")
}
func NewGenericResourceFromUnstructured(unst unstructured.Unstructured) (GenericResource, error) {
workload := GenericResource{
Kind: unst.GetKind(),
Resource: unst,
}
objMeta, err := meta.Accessor(&unst)
if err != nil {
return workload, err
}
workload.ObjectMeta = objMeta
workload.PodTemplate, err = GetPodTemplate(unst.UnstructuredContent())
if err != nil {
return workload, err
}
b, err := json.Marshal(&unst)
if err != nil {
@@ -69,9 +47,7 @@ func NewGenericResourceFromUnstructured(unst unstructured.Unstructured, podSpecM
if err != nil {
return workload, err
}
if podSpecMap == nil {
podSpecMap = GetPodSpec(m)
}
podSpecMap := GetPodSpec(m)
if podSpecMap != nil {
b, err = json.Marshal(podSpecMap)
if err != nil {
@@ -89,15 +65,10 @@ func NewGenericResourceFromUnstructured(unst unstructured.Unstructured, podSpecM
// NewGenericResourceFromPod builds a new workload for a given Pod without looking at parents
func NewGenericResourceFromPod(podResource kubeAPICoreV1.Pod, originalObject interface{}) (GenericResource, error) {
podMap, err := SerializePod(&podResource)
if err != nil {
return GenericResource{}, err
}
workload := GenericResource{
Kind: "Pod",
PodSpec: &podResource.Spec,
PodTemplate: podMap,
ObjectMeta: podResource.ObjectMeta.GetObjectMeta(),
Kind: "Pod",
PodSpec: &podResource.Spec,
ObjectMeta: podResource.ObjectMeta.GetObjectMeta(),
}
if originalObject != nil {
bytes, err := json.Marshal(originalObject)
@@ -128,7 +99,7 @@ func NewGenericResourceFromBytes(contentBytes []byte) (GenericResource, error) {
if err != nil {
return GenericResource{}, err
}
return NewGenericResourceFromUnstructured(unst, nil)
return NewGenericResourceFromUnstructured(unst)
}
// ResolveControllerFromPod builds a new workload for a given Pod
@@ -150,8 +121,6 @@ func resolveControllerFromPod(ctx context.Context, podResource kubeAPICoreV1.Pod
}
topKind := "Pod"
topMeta := podWorkload.ObjectMeta
var topPodSpec interface{}
topPodSpec = podWorkload.Resource.Object
owners := podResource.ObjectMeta.GetOwnerReferences()
lastKey := ""
for len(owners) > 0 {
@@ -184,17 +153,13 @@ func resolveControllerFromPod(ctx context.Context, podResource kubeAPICoreV1.Pod
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 GenericResource{}, err
}
podSpec := GetPodSpec(abstractObject.Object)
if podSpec != nil {
topPodSpec = podSpec
}
topMeta = objMeta
owners = abstractObject.GetOwnerReferences()
}
if lastKey != "" {
unst := objectCache[lastKey]
return NewGenericResourceFromUnstructured(unst, topPodSpec)
return NewGenericResourceFromUnstructured(unst)
}
workload, err := NewGenericResourceFromPod(podResource, podResource)
if err != nil {
@@ -247,34 +212,3 @@ func GetPodSpec(yaml map[string]interface{}) interface{} {
}
return nil
}
// GetPodTemplate looks inside arbitrary YAML for a Pod template, containing
// fields `spec.containers`.
// For example, it returns the `spec.template` level of a Kubernetes Deployment yaml.
func GetPodTemplate(yaml map[string]interface{}) (podTemplate interface{}, err error) {
if yamlSpec, ok := yaml["spec"]; ok {
if yamlSpecMap, ok := yamlSpec.(map[string]interface{}); ok {
if _, ok := yamlSpecMap["containers"]; ok {
// This is a hack around unstructured.SetNestedField using DeepCopy which does
// not support the type int, and panics.
// Related: https://github.com/kubernetes/kubernetes/issues/62769
podTemplateJSON, err := json.Marshal(yaml)
if err != nil {
return nil, err
}
podTemplateMap := make(map[string]interface{})
err = json.Unmarshal(podTemplateJSON, &podTemplateMap)
if err != nil {
return nil, err
}
return podTemplateMap, nil
}
}
}
for _, podSpecField := range podSpecFields {
if childYaml, ok := yaml[podSpecField]; ok {
return GetPodTemplate(childYaml.(map[string]interface{}))
}
}
return nil, nil
}
+18 -113
View File
@@ -1,23 +1,8 @@
// Copyright 2022 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 kube
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
@@ -59,12 +44,7 @@ type resourceKindMap map[string][]GenericResource
func (rkm resourceKindMap) addResource(r GenericResource) {
gvk := r.Resource.GroupVersionKind()
var key string
if gvk.Group != "" {
key = gvk.Group + "/" + gvk.Kind
} else {
key = gvk.Kind
}
key := gvk.Group + "/" + gvk.Kind
rkm[key] = append(rkm[key], r)
}
@@ -188,7 +168,7 @@ func CreateResourceProviderFromResource(ctx context.Context, workload string) (*
logrus.Errorf("Could not find workload %s: %v", workload, err)
return nil, err
}
workloadObj, err := NewGenericResourceFromUnstructured(*obj, nil)
workloadObj, err := NewGenericResourceFromUnstructured(*obj)
if err != nil {
logrus.Errorf("Could not parse workload %s: %v", workload, err)
return nil, err
@@ -221,11 +201,7 @@ func CreateResourceProviderFromPath(directory string) (*ResourceProvider, error)
logrus.Errorf("Error reading file: %v", path)
return err
}
err = resources.addResourcesFromYaml(string(contents))
if err != nil {
logrus.Warnf("Skipping %s: cannot add resource from YAML: %v", path, err)
}
return nil
return resources.addResourcesFromYaml(string(contents))
}
err := filepath.Walk(directory, visitFile)
@@ -235,16 +211,9 @@ func CreateResourceProviderFromPath(directory string) (*ResourceProvider, error)
return &resources, nil
}
// CreateResourceProviderFromYaml returns a new ResourceProvider using the yaml
func CreateResourceProviderFromYaml(yamlContent string) *ResourceProvider {
resources := newResourceProvider("unknown", "Content", "unknown")
resources.addResourcesFromYaml(string(yamlContent))
return &resources
}
// CreateResourceProviderFromCluster creates a new ResourceProvider using live data from a cluster
func CreateResourceProviderFromCluster(ctx context.Context, c conf.Configuration) (*ResourceProvider, error) {
kubeConf, configError := config.GetConfigWithContext(c.KubeContext)
kubeConf, configError := config.GetConfig()
if configError != nil {
logrus.Errorf("Error fetching KubeConfig: %v", configError)
return nil, configError
@@ -270,38 +239,19 @@ func CreateResourceProviderFromAPI(ctx context.Context, kube kubernetes.Interfac
logrus.Errorf("Error fetching Cluster API version: %v", err)
return nil, err
}
sourceType := "Cluster"
if c.Namespace != "" {
logrus.Debug("namespace is specififed in config, setting source type to ClusterNamespace")
sourceType = "ClusterNamespace"
}
provider := newResourceProvider(serverVersion.Major+"."+serverVersion.Minor, sourceType, clusterName)
provider := newResourceProvider(serverVersion.Major+"."+serverVersion.Minor, "Cluster", clusterName)
nodes, err := kube.CoreV1().Nodes().List(ctx, listOpts)
if err != nil {
logrus.Errorf("Error fetching Nodes: %v", err)
return nil, err
}
var namespaces *corev1.NamespaceList
if c.Namespace != "" {
ns, err := kube.CoreV1().Namespaces().Get(ctx, c.Namespace, metav1.GetOptions{})
if err != nil {
return nil, err
}
namespaces = &corev1.NamespaceList{
Items: []corev1.Namespace{*ns},
}
} else {
nsList, err := kube.CoreV1().Namespaces().List(ctx, listOpts)
if err != nil {
logrus.Errorf("Error fetching Namespaces: %v", err)
return nil, err
}
namespaces = nsList
namespaces, err := kube.CoreV1().Namespaces().List(ctx, listOpts)
if err != nil {
logrus.Errorf("Error fetching Namespaces: %v", err)
return nil, err
}
pods, err := kube.CoreV1().Pods(c.Namespace).List(ctx, listOpts)
pods, err := kube.CoreV1().Pods("").List(ctx, listOpts)
if err != nil {
logrus.Errorf("Error fetching Pods: %v", err)
return nil, err
@@ -337,7 +287,6 @@ func CreateResourceProviderFromAPI(ctx context.Context, kube kubernetes.Interfac
}
}
var kubernetesResources []GenericResource
for _, kind := range additionalKinds {
groupKind := parseGroupKind(maybeTransformKindIntoGroupKind(string(kind)))
mapping, err := (restMapper).RESTMapping(groupKind)
@@ -346,17 +295,17 @@ func CreateResourceProviderFromAPI(ctx context.Context, kube kubernetes.Interfac
return nil, err
}
objects, err := (*dynamic).Resource(mapping.Resource).Namespace(c.Namespace).List(ctx, metav1.ListOptions{})
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, nil)
res, err := NewGenericResourceFromUnstructured(obj)
if err != nil {
return nil, err
}
kubernetesResources = append(kubernetesResources, res)
provider.Resources.addResource(res)
}
}
@@ -367,12 +316,9 @@ func CreateResourceProviderFromAPI(ctx context.Context, kube kubernetes.Interfac
logrus.Errorf("Error loading controllers from pods: %v", err)
return nil, err
}
// resources loaded from custom checks can also contain controllers and thus would be added twice to the provider
kubernetesResources = deduplicateControllers(append(kubernetesResources, controllers...))
provider.Nodes = nodes.Items
provider.Namespaces = namespaces.Items
provider.Resources.addResources(kubernetesResources)
provider.Resources.addResources(controllers)
return &provider, nil
}
@@ -395,14 +341,14 @@ func LoadControllers(ctx context.Context, pods []corev1.Pod, dynamicClientPointe
}
interfaces = append(interfaces, workload)
}
return interfaces, nil
return deduplicateControllers(interfaces), nil
}
// 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(inputResources []GenericResource) []GenericResource {
func deduplicateControllers(inputControllers []GenericResource) []GenericResource {
controllerMap := make(map[string]GenericResource)
for _, controller := range inputResources {
for _, controller := range inputControllers {
key := controller.ObjectMeta.GetNamespace() + "/" + controller.Kind + "/" + controller.ObjectMeta.GetName()
oldController, ok := controllerMap[key]
if !ok || controller.ObjectMeta.GetCreationTimestamp().Time.After(oldController.ObjectMeta.GetCreationTimestamp().Time) {
@@ -453,6 +399,7 @@ func (resources *ResourceProvider) addResourceFromString(contents string) error
decoder = k8sYaml.NewYAMLOrJSONDecoder(bytes.NewReader(contentBytes), 1000)
if err != nil {
logrus.Errorf("Invalid YAML: %s", string(contents))
return err
}
if resource.Kind == "Namespace" {
@@ -481,45 +428,3 @@ func (resources *ResourceProvider) addResourceFromString(contents string) error
}
return err
}
// SerializePodSpec converts a typed PodSpec into a map[string]interface{}
func SerializePodSpec(pod *corev1.PodSpec) (map[string]interface{}, error) {
podJSON, err := json.Marshal(pod)
if err != nil {
return nil, err
}
podMap := make(map[string]interface{})
err = json.Unmarshal(podJSON, &podMap)
if err != nil {
return nil, err
}
return podMap, nil
}
// SerializePod converts a typed Pod into a map[string]interface{}
func SerializePod(pod *corev1.Pod) (map[string]interface{}, error) {
podJSON, err := json.Marshal(pod)
if err != nil {
return nil, err
}
podMap := make(map[string]interface{})
err = json.Unmarshal(podJSON, &podMap)
if err != nil {
return nil, err
}
return podMap, nil
}
// SerializeContainer converts a typed Container into a map[string]interface{}
func SerializeContainer(container *corev1.Container) (map[string]interface{}, error) {
containerJSON, err := json.Marshal(container)
if err != nil {
return nil, err
}
containerMap := make(map[string]interface{})
err = json.Unmarshal(containerJSON, &containerMap)
if err != nil {
return nil, err
}
return containerMap, nil
}
+16 -77
View File
@@ -1,17 +1,3 @@
// Copyright 2022 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 kube
import (
@@ -74,7 +60,7 @@ func TestGetMultipleResourceFromSingleFile(t *testing.T) {
func TestGetMultipleResourceFromBadFile(t *testing.T) {
_, err := CreateResourceProviderFromPath("./test_files/test_3")
assert.Equal(t, nil, err, "CreateResource From Path should not fail with bad yaml")
assert.NotEqual(t, nil, err, "CreateResource From Path should fail with bad yaml")
}
func TestAddResourcesFromReader(t *testing.T) {
@@ -97,6 +83,15 @@ 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, conf.Configuration{})
assert.Equal(t, nil, err, "Error should be nil")
assert.Equal(t, "Cluster", resources.SourceType, "Should have type Path")
assert.Equal(t, "test", resources.SourceName, "Should have source name")
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, 5, len(resources.Resources), "Should have 5 controllers")
expectedNames := map[string]bool{
"deploy": false,
@@ -105,68 +100,12 @@ func TestGetResourceFromAPI(t *testing.T) {
"statefulset": false,
"daemonset": false,
}
tests := []struct {
name string
config conf.Configuration
want *ResourceProvider
wantErr bool
clusterName string
}{
{
name: "standard",
config: conf.Configuration{},
clusterName: "test1",
want: &ResourceProvider{
SourceType: "Cluster",
SourceName: "test1",
CreationTime: time.Now(),
},
},
{
name: "namespaced",
config: conf.Configuration{
Namespace: "test",
},
clusterName: "test2",
want: &ResourceProvider{
SourceType: "ClusterNamespace",
SourceName: "test2",
CreationTime: time.Now(),
},
},
{
name: "namespace does not exist",
config: conf.Configuration{
Namespace: "test3",
},
clusterName: "test3",
wantErr: true,
},
for _, controllers := range resources.Resources {
for _, ctrl := range controllers {
expectedNames[ctrl.ObjectMeta.GetName()] = true
}
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
resources, err := CreateResourceProviderFromAPI(context.Background(), k8s, tt.clusterName, &dynamicInterface, tt.config)
if tt.wantErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
assert.Equal(t, tt.want.SourceType, resources.SourceType)
assert.Equal(t, tt.want.SourceName, resources.SourceName)
assert.IsType(t, tt.want.CreationTime, resources.CreationTime)
assert.Equal(t, 0, len(resources.Nodes), "Should not have any nodes")
assert.Equal(t, 5, len(resources.Resources), "Should have 5 controllers")
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)
}
}
})
for name, val := range expectedNames {
assert.Equal(t, true, val, name)
}
}
-118
View File
@@ -1,118 +0,0 @@
package mutation
import (
"bufio"
"encoding/json"
"fmt"
"strings"
jsonpatchV5 "github.com/evanphx/json-patch/v5"
"github.com/fairwindsops/polaris/pkg/config"
"github.com/fairwindsops/polaris/pkg/kube"
"github.com/fairwindsops/polaris/pkg/validator"
"github.com/thoas/go-funk"
"gomodules.xyz/jsonpatch/v2"
)
// ApplyAllSchemaMutations applies available mutation to a single resource
func ApplyAllSchemaMutations(conf *config.Configuration, resourceProvider *kube.ResourceProvider, resource kube.GenericResource, mutations []jsonpatch.Operation) (kube.GenericResource, error) {
resByte := resource.OriginalObjectJSON
var jsonByte []byte
mutationByte, err := json.Marshal(mutations)
if err != nil {
return resource, err
}
patch, err := jsonpatchV5.DecodePatch(mutationByte)
if err != nil {
return resource, err
}
jsonByte, err = patch.ApplyWithOptions(resByte, &jsonpatchV5.ApplyOptions{
AllowMissingPathOnRemove: true,
EnsurePathExistsOnAdd: true,
})
if err != nil {
return resource, err
}
mutated, err := kube.NewGenericResourceFromBytes(jsonByte)
if err != nil {
return resource, err
}
return mutated, nil
}
// GetMutationsAndCommentsFromResults returns all mutations from results
func GetMutationsAndCommentsFromResults(results []validator.Result) ([]config.MutationComment, map[string][]jsonpatch.Operation) {
allMutationsFromResults := make(map[string][]jsonpatch.Operation)
comments := []config.MutationComment{}
for _, result := range results {
key := fmt.Sprintf("%s/%s/%s", result.Kind, result.Name, result.Namespace)
mutations, resultsComments := GetMutationsAndCommentsFromResult(&result)
allMutationsFromResults[key] = mutations
comments = append(comments, resultsComments...)
}
return comments, allMutationsFromResults
}
// GetMutationsAndCommentsFromResult returns all mutations from single result
func GetMutationsAndCommentsFromResult(result *validator.Result) ([]jsonpatch.Operation, []config.MutationComment) {
mutations := []jsonpatch.Operation{}
comments := []config.MutationComment{}
for _, resultMessage := range result.Results {
if len(resultMessage.Mutations) > 0 {
mutations = append(mutations, resultMessage.Mutations...)
}
if len(resultMessage.Comments) > 0 {
comments = append(comments, resultMessage.Comments...)
}
}
for _, resultMessage := range result.PodResult.Results {
if len(resultMessage.Mutations) > 0 {
mutations = append(mutations, resultMessage.Mutations...)
}
if len(resultMessage.Comments) > 0 {
comments = append(comments, resultMessage.Comments...)
}
}
for _, containerResult := range result.PodResult.ContainerResults {
for _, resultMessage := range containerResult.Results {
if len(resultMessage.Mutations) > 0 {
mutations = append(mutations, resultMessage.Mutations...)
}
if len(resultMessage.Comments) > 0 {
comments = append(comments, resultMessage.Comments...)
}
}
}
return mutations, comments
}
// UpdateMutatedContentWithComments Updates mutated object with comments
func UpdateMutatedContentWithComments(yamlContent string, comments []config.MutationComment) string {
var lines []string
scanner := bufio.NewScanner(strings.NewReader(yamlContent))
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
line := scanner.Text()
lines = append(lines, line)
}
commentMap := funk.Map(comments, func(c config.MutationComment) (string, string) {
return c.Find, c.Comment
}).(map[string]string)
fileContent := ""
for _, line := range lines {
comment, ok := commentMap[strings.TrimSpace(line)]
if ok {
line += (" #" + comment)
}
fileContent += line
fileContent += "\n"
}
return fileContent
}
+3 -3
View File
@@ -33,7 +33,7 @@ func TestValidatePDB(t *testing.T) {
},
}
pdb := unstructured.Unstructured{}
res, err := kube.NewGenericResourceFromUnstructured(pdb, nil)
res, err := kube.NewGenericResourceFromUnstructured(pdb)
res.Kind = "PodDisruptionBudget"
actualResult, err := applyNonControllerSchemaChecks(&c, nil, res)
@@ -45,7 +45,7 @@ func TestValidatePDB(t *testing.T) {
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)
assert.EqualValues(t, "disruptionsAllowed is not greater than zero", results.Message)
}
func TestValidateIngress(t *testing.T) {
@@ -70,7 +70,7 @@ func TestValidateIngress(t *testing.T) {
if err != nil {
panic(err)
}
res, err := kube.NewGenericResourceFromUnstructured(unst, nil)
res, err := kube.NewGenericResourceFromUnstructured(unst)
if err != nil {
panic(err)
}
+3 -3
View File
@@ -64,11 +64,11 @@ func TestControllerLevelChecks(t *testing.T) {
testResources := func(res *kube.ResourceProvider) {
c := conf.Configuration{
Checks: map[string]conf.Severity{
"deploymentMissingReplicas": conf.SeverityDanger,
"multipleReplicasForDeployment": conf.SeverityDanger,
},
}
expectedResult := ResultMessage{
ID: "deploymentMissingReplicas",
ID: "multipleReplicasForDeployment",
Severity: "danger",
Category: "Reliability",
}
@@ -85,7 +85,7 @@ func TestControllerLevelChecks(t *testing.T) {
expectedResult.Message = "Only one replica is scheduled"
}
expectedResults := ResultSet{
"deploymentMissingReplicas": expectedResult,
"multipleReplicasForDeployment": expectedResult,
}
assert.Equal(t, "Deployment", actualResult.Kind)
-14
View File
@@ -1,17 +1,3 @@
// Copyright 2022 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 (
-14
View File
@@ -1,17 +1,3 @@
// Copyright 2022 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 (
+10 -47
View File
@@ -16,12 +16,10 @@ package validator
import (
"fmt"
"strings"
"time"
"github.com/fatih/color"
"github.com/thoas/go-funk"
"gomodules.xyz/jsonpatch/v2"
"github.com/fairwindsops/polaris/pkg/config"
)
@@ -54,21 +52,12 @@ type AuditData struct {
Score uint
}
// RemoveSuccessfulResults removes all tests that have passed
// RemoveSuccessfulResults remove all test that have passed.
func (res AuditData) RemoveSuccessfulResults() AuditData {
resCopy := res
resCopy.Results = []Result{}
filteredResults := funk.Map(res.Results, func(auditDataResult Result) Result {
resCopy.Results = funk.Map(res.Results, func(auditDataResult Result) Result {
return auditDataResult.removeSuccessfulResults()
}).([]Result)
for _, result := range filteredResults {
if result.isNotEmpty() {
resCopy.Results = append(resCopy.Results, result)
}
}
return resCopy
}
@@ -83,23 +72,17 @@ type ClusterInfo struct {
// ResultMessage is the result of a given check
type ResultMessage struct {
ID string
Message string
Details []string
Success bool
Severity config.Severity
Category string
Mutations []jsonpatch.Operation
Comments []config.MutationComment
ID string
Message string
Details []string
Success bool
Severity config.Severity
Category string
}
// ResultSet contiains the results for a set of checks
type ResultSet map[string]ResultMessage
func (res ResultSet) isNotEmpty() bool {
return len(res) > 0
}
func (res ResultSet) removeSuccessfulResults() ResultSet {
newResults := ResultSet{}
for k, resultMessage := range res {
@@ -130,13 +113,6 @@ func (res Result) removeSuccessfulResults() Result {
return resCopy
}
func (res Result) isNotEmpty() bool {
if res.PodResult != nil {
return res.PodResult.isNotEmpty()
}
return res.Results.isNotEmpty()
}
// PodResult provides a list of validation messages for each pod.
type PodResult struct {
Name string
@@ -153,15 +129,6 @@ func (res PodResult) removeSuccessfulResults() PodResult {
return resCopy
}
func (res PodResult) isNotEmpty() bool {
for _, cr := range res.ContainerResults {
if cr.isNotEmpty() {
return true
}
}
return res.Results.isNotEmpty()
}
// ContainerResult provides a list of validation messages for each container.
type ContainerResult struct {
Name string
@@ -174,10 +141,6 @@ func (res ContainerResult) removeSuccessfulResults() ContainerResult {
return resCopy
}
func (res ContainerResult) isNotEmpty() bool {
return res.Results.isNotEmpty()
}
func fillString(id string, l int) string {
for len(id) < l {
id += " "
@@ -203,7 +166,7 @@ func (res AuditData) GetPrettyOutput(useColor bool) string {
func (res Result) GetPrettyOutput() string {
str := titleColor.Sprint(fmt.Sprintf("%s %s", res.Kind, res.Name))
if res.Namespace != "" {
str += titleColor.Sprint(fmt.Sprintf(" in namespace %s", res.Namespace))
str += titleColor.Sprint(fmt.Sprintf("in namespace %s", res.Namespace))
}
str += "\n"
str += res.Results.GetPrettyOutput()
@@ -245,7 +208,7 @@ func (res ResultSet) GetPrettyOutput() string {
}
}
if color.NoColor {
status = strings.Fields(status)[1] // remove emoji
status = status[2:] // remove emoji
}
str += fmt.Sprintf("%s%s %s\n", indent, checkColor.Sprint(fillString(msg.ID, minIDLength-len(indent))), status)
str += fmt.Sprintf("%s %s - %s\n", indent, msg.Category, msg.Message)
@@ -1,50 +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 (
"testing"
conf "github.com/fairwindsops/polaris/pkg/config"
"github.com/fairwindsops/polaris/pkg/kube"
"github.com/fairwindsops/polaris/test"
"github.com/stretchr/testify/require"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
)
func TestGetTemplateInputReturnsPolarisSubKeys(t *testing.T) {
pod := test.MockPod() // Includes a container, required by GetPodSpec
pod.Spec.NodeName = "testNodeName"
pod.ObjectMeta.Name = "testpod"
genRes, err := kube.NewGenericResourceFromPod(pod, pod)
require.NoError(t, err, "creating new generic resource from a pod")
schemaTest := schemaTestCase{
Target: conf.TargetPodSpec, // ends up being set in the case of target: PodTemplate
Resource: genRes,
}
templateInput, err := getTemplateInput(schemaTest)
require.NoError(t, err, "getting template input from a generic resource")
require.NotNil(t, templateInput)
nodeName, ok, err := unstructured.NestedString(templateInput, "Polaris", "PodSpec", "nodeName")
require.NoError(t, err, "getting Polaris.PodSpec.nodeName from template input")
require.True(t, ok, "getting Polaris.PodSpec.nodeName from template input")
require.Equal(t, "testNodeName", nodeName, "the nodeName from template output")
podName, ok, err := unstructured.NestedString(templateInput, "Polaris", "PodTemplate", "metadata", "name")
require.NoError(t, err, "getting Polaris.PodTemplate.metadata.name from template input")
require.True(t, ok, "getting Polaris.PodTemplate.metadata.name from template input")
require.Equal(t, "testpod", podName, "the pod from template input")
}
+8 -135
View File
@@ -1,33 +1,14 @@
// Copyright 2022 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 (
"errors"
"fmt"
"sort"
"strconv"
"strings"
"github.com/qri-io/jsonschema"
"github.com/sirupsen/logrus"
"github.com/thoas/go-funk"
"gomodules.xyz/jsonpatch/v2"
corev1 "k8s.io/api/core/v1"
metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"github.com/fairwindsops/polaris/pkg/config"
"github.com/fairwindsops/polaris/pkg/kube"
@@ -42,9 +23,7 @@ type schemaTestCase struct {
}
func resolveCheck(conf *config.Configuration, checkID string, test schemaTestCase) (*config.SchemaCheck, error) {
if !conf.DisallowExemptions &&
!conf.DisallowAnnotationExemptions &&
hasExemptionAnnotation(test.Resource.ObjectMeta, checkID) {
if !conf.DisallowExemptions && hasExemptionAnnotation(test.Resource.ObjectMeta, checkID) {
return nil, nil
}
check, ok := conf.CustomChecks[checkID]
@@ -65,55 +44,13 @@ func resolveCheck(conf *config.Configuration, checkID string, test schemaTestCas
if !check.IsActionable(test.Target, test.Resource.Kind, test.IsInitContianer) {
return nil, nil
}
templateInput, err := getTemplateInput(test)
if err != nil {
return nil, err
}
checkPtr, err := check.TemplateForResource(templateInput)
checkPtr, err := check.TemplateForResource(test.Resource.Resource.Object)
if err != nil {
return nil, err
}
return checkPtr, nil
}
// getTemplateInput augments a schemaTestCase.Resource.Resource.Object with
// Polaris built-in variables. The result can be used as input for
// CheckSchema.TemplateForResource().
func getTemplateInput(test schemaTestCase) (map[string]interface{}, error) {
templateInput := test.Resource.Resource.Object
if templateInput == nil {
return nil, nil
}
if test.Target == config.TargetPodSpec || test.Target == config.TargetContainer {
podSpecMap, err := kube.SerializePodSpec(test.Resource.PodSpec)
if err != nil {
return nil, err
}
err = unstructured.SetNestedMap(templateInput, podSpecMap, "Polaris", "PodSpec")
if err != nil {
return nil, err
}
podTemplateMap, ok := test.Resource.PodTemplate.(map[string]interface{})
if ok {
err := unstructured.SetNestedMap(templateInput, podTemplateMap, "Polaris", "PodTemplate")
if err != nil {
return nil, err
}
}
if test.Target == config.TargetContainer {
containerMap, err := kube.SerializeContainer(test.Container)
if err != nil {
return nil, err
}
err = unstructured.SetNestedMap(templateInput, containerMap, "Polaris", "Container")
if err != nil {
return nil, err
}
}
}
return templateInput, nil
}
func makeResult(conf *config.Configuration, check *config.SchemaCheck, passes bool, issues []jsonschema.ValError) ResultMessage {
details := []string{}
for _, issue := range issues {
@@ -209,17 +146,6 @@ func applyControllerSchemaChecks(conf *config.Configuration, resourceProvider *k
}
finalResult.Results = resultSet
nonControllerResults, err := applyTopLevelSchemaChecks(conf, resourceProvider, resource, false)
if err != nil {
return finalResult, err
}
for key, val := range nonControllerResults {
if _, ok := finalResult.Results[key]; ok {
return finalResult, errors.New("Duplicate finding for check " + key)
}
finalResult.Results[key] = val
}
podRS, err := applyPodSchemaChecks(conf, resourceProvider, resource)
if err != nil {
return finalResult, err
@@ -269,7 +195,7 @@ func applyTopLevelSchemaChecks(conf *config.Configuration, resources *kube.Resou
func applyPodSchemaChecks(conf *config.Configuration, resources *kube.ResourceProvider, controller kube.GenericResource) (ResultSet, error) {
test := schemaTestCase{
Target: config.TargetPodSpec,
Target: config.TargetPod,
ResourceProvider: resources,
Resource: controller,
}
@@ -311,37 +237,18 @@ func applySchemaCheck(conf *config.Configuration, checkID string, test schemaTes
}
var passes bool
var issues []jsonschema.ValError
var prefix string
if check.SchemaTarget != "" {
if check.SchemaTarget == config.TargetPodSpec && check.Target == config.TargetContainer {
if check.SchemaTarget == config.TargetPod && check.Target == config.TargetContainer {
podCopy := *test.Resource.PodSpec
podCopy.InitContainers = []corev1.Container{}
podCopy.Containers = []corev1.Container{*test.Container}
containerIndex := funk.IndexOf(test.Resource.PodSpec.Containers, func(value corev1.Container) bool {
return value.Name == test.Container.Name
})
prefix = getJSONSchemaPrefix(test.Resource.Kind)
if prefix != "" {
prefix += "/containers/" + strconv.Itoa(containerIndex)
}
passes, issues, err = check.CheckPodSpec(&podCopy)
passes, issues, err = check.CheckPod(&podCopy)
} else {
return nil, fmt.Errorf("Unknown combination of target (%s) and schema target (%s)", check.Target, check.SchemaTarget)
}
} else if check.Target == config.TargetPodSpec {
passes, issues, err = check.CheckPodSpec(test.Resource.PodSpec)
prefix = getJSONSchemaPrefix(test.Resource.Kind)
} else if check.Target == config.TargetPodTemplate {
passes, issues, err = check.CheckPodTemplate(test.Resource.PodTemplate)
prefix = getJSONSchemaPrefix(test.Resource.Kind)
} else if check.Target == config.TargetPod {
passes, issues, err = check.CheckPod(test.Resource.PodSpec)
} else if check.Target == config.TargetContainer {
containerIndex := funk.IndexOf(test.Resource.PodSpec.Containers, func(value corev1.Container) bool {
return value.Name == test.Container.Name
})
prefix = getJSONSchemaPrefix(test.Resource.Kind)
if prefix != "" {
prefix += "/containers/" + strconv.Itoa(containerIndex)
}
passes, issues, err = check.CheckContainer(test.Container)
} else {
passes, issues, err = check.CheckObject(test.Resource.Resource.Object)
@@ -359,7 +266,7 @@ func applySchemaCheck(conf *config.Configuration, checkID string, test schemaTes
namespace = test.Resource.ObjectMeta.GetName()
}
resources = funk.Filter(resources, func(res kube.GenericResource) bool {
return res.ObjectMeta.GetNamespace() == "" || res.ObjectMeta.GetNamespace() == namespace
return res.ObjectMeta.GetNamespace() == namespace
}).([]kube.GenericResource)
objects := funk.Map(resources, func(res kube.GenericResource) interface{} {
return res.Resource.Object
@@ -370,17 +277,6 @@ func applySchemaCheck(conf *config.Configuration, checkID string, test schemaTes
}
}
result := makeResult(conf, check, passes, issues)
if !passes {
if funk.Contains(conf.Mutations, checkID) && len(check.Mutations) > 0 {
mutations := funk.Map(check.Mutations, func(mutation jsonpatch.Operation) jsonpatch.Operation {
mutationCopy := deepCopyMutation(mutation)
mutationCopy.Path = prefix + mutationCopy.Path
return mutationCopy
}).([]jsonpatch.Operation)
result.Mutations = mutations
result.Comments = check.Comments
}
}
return &result, nil
}
@@ -392,26 +288,3 @@ func getSortedKeys(m map[string]config.Severity) []string {
sort.Strings(keys)
return keys
}
func deepCopyMutation(source jsonpatch.Operation) jsonpatch.Operation {
destination := jsonpatch.Operation{
Operation: source.Operation,
Path: source.Path,
Value: source.Value,
}
return destination
}
func getJSONSchemaPrefix(kind string) (prefix string) {
if kind == "CronJob" {
prefix = "/spec/jobTemplate/spec/template/spec"
} else if kind == "Pod" {
prefix = "/spec"
} else if (kind == "Deployment") || (kind == "DaemonSet") ||
(kind == "StatefulSet") || (kind == "Job") || (kind == "ReplicationController") {
prefix = "/spec/template/spec"
} else {
logrus.Warningf("Mutation for this this resource (%s) is not supported", kind)
}
return prefix
}
-14
View File
@@ -1,17 +1,3 @@
// Copyright 2022 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 (
-14
View File
@@ -1,17 +1,3 @@
// Copyright 2022 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 (
-66
View File
@@ -1,66 +0,0 @@
// Copyright 2022 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 webhook
import (
"context"
"github.com/fairwindsops/polaris/pkg/config"
"github.com/fairwindsops/polaris/pkg/mutation"
"github.com/sirupsen/logrus"
"gomodules.xyz/jsonpatch/v2"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/webhook"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
)
// Mutator mutate k8s resources.
type Mutator struct {
Client client.Client
Config config.Configuration
decoder *admission.Decoder
}
var _ admission.Handler = &Mutator{}
// NewMutateWebhook creates a mutating admission webhook for the apiType.
func NewMutateWebhook(mgr manager.Manager, mutator Mutator) {
path := "/mutate"
mgr.GetWebhookServer().Register(path, &webhook.Admission{Handler: &mutator})
}
func (m *Mutator) mutate(req admission.Request) ([]jsonpatch.Operation, error) {
results, err := GetValidatedResults(req.AdmissionRequest.Kind.Kind, m.decoder, req, m.Config)
if err != nil {
return nil, err
}
patches, _ := mutation.GetMutationsAndCommentsFromResult(results)
return patches, nil
}
// Handle for Validator to run validation checks.
func (m *Mutator) Handle(ctx context.Context, req admission.Request) admission.Response {
logrus.Info("Starting request")
patches, err := m.mutate(req)
if err != nil {
return admission.Errored(403, err)
}
if patches == nil {
return admission.Allowed("Allowed")
}
return admission.Patched("", patches...)
}
+5 -10
View File
@@ -47,24 +47,19 @@ func (v *Validator) InjectDecoder(d *admission.Decoder) error {
var _ admission.Handler = &Validator{}
// NewValidateWebhook creates a validating admission webhook for the apiType.
func NewValidateWebhook(mgr manager.Manager, validator Validator) {
// NewWebhook creates a validating admission webhook for the apiType.
func NewWebhook(mgr manager.Manager, validator Validator) {
path := "/validate"
mgr.GetWebhookServer().Register(path, &webhook.Admission{Handler: &validator})
}
func (v *Validator) handleInternal(req admission.Request) (*validator.Result, error) {
return GetValidatedResults(req.AdmissionRequest.Kind.Kind, v.decoder, req, v.Config)
}
// GetValidatedResults returns the validated results.
func GetValidatedResults(kind string, decoder *admission.Decoder, req admission.Request, config config.Configuration) (*validator.Result, error) {
var controller kube.GenericResource
var err error
if kind == "Pod" {
if req.AdmissionRequest.Kind.Kind == "Pod" {
pod := corev1.Pod{}
err := decoder.Decode(req, &pod)
err := v.decoder.Decode(req, &pod)
if err != nil {
return nil, err
}
@@ -80,7 +75,7 @@ func GetValidatedResults(kind string, decoder *admission.Decoder, req admission.
return nil, err
}
// TODO: consider enabling multi-resource checks
controllerResult, err := validator.ApplyAllSchemaChecks(&config, nil, controller)
controllerResult, err := validator.ApplyAllSchemaChecks(&v.Config, nil, controller)
if err != nil {
return nil, err
}
@@ -1,19 +0,0 @@
# This fails because automounting is true for both the pod and ServiceAccount.
apiVersion: v1
kind: Pod
metadata:
name: test-pod
spec:
automountServiceAccountToken: true
serviceAccountName: test
containers:
- name: nginx
image: nginx
ports:
- containerPort: 80
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: test
automountServiceAccountToken: true
@@ -1,19 +0,0 @@
# This fails because automounting is true for the pod, overriding the ServiceAccount.
apiVersion: v1
kind: Pod
metadata:
name: test-pod
spec:
automountServiceAccountToken: true
serviceAccountName: test
containers:
- name: nginx
image: nginx
ports:
- containerPort: 80
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: test
automountServiceAccountToken: false
@@ -1,17 +0,0 @@
# This fails because automounting is not disabled anywhere.
apiVersion: v1
kind: Pod
metadata:
name: test-pod
spec:
serviceAccountName: test
containers:
- name: nginx
image: nginx
ports:
- containerPort: 80
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: test
@@ -1,19 +0,0 @@
# This succeeds because automounting is disabled at the pod.
apiVersion: v1
kind: Pod
metadata:
name: test-pod
spec:
automountServiceAccountToken: false
serviceAccountName: test
containers:
- name: nginx
image: nginx
ports:
- containerPort: 80
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: test
@@ -1,19 +0,0 @@
# This succeeds because automounting is disabled at the pod and ServiceAccount.
apiVersion: v1
kind: Pod
metadata:
name: test-pod
spec:
automountServiceAccountToken: false
serviceAccountName: test
containers:
- name: nginx
image: nginx
ports:
- containerPort: 80
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: test
automountServiceAccountToken: false
@@ -1,19 +0,0 @@
# This succeeds because automounting is disabled at the pod, overriding the ServiceAccount.
apiVersion: v1
kind: Pod
metadata:
name: test-pod
spec:
automountServiceAccountToken: false
serviceAccountName: test
containers:
- name: nginx
image: nginx
ports:
- containerPort: 80
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: test
automountServiceAccountToken: true
@@ -1,18 +0,0 @@
# This succeeds because automounting is disabled at the ServiceAccount.
apiVersion: v1
kind: Pod
metadata:
name: test-pod
spec:
serviceAccountName: test
containers:
- name: nginx
image: nginx
ports:
- containerPort: 80
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: test
automountServiceAccountToken: false
-14
View File
@@ -1,14 +0,0 @@
apiVersion: v1
kind: Pod
metadata:
labels:
app.kubernetes.io/name: nginx
name: nginx
spec:
containers:
- image: nginx
name: nginx
resources:
limits:
cpu: 100m #TODO: Set this to the maximum amount of CPU you want your workload to use
memory: 128Mi
+1 -1
View File
@@ -10,5 +10,5 @@ spec:
image: nginx
resources:
limits:
memory: 128Mi
memory: 256Mi
cpu: 100m
@@ -1,14 +0,0 @@
apiVersion: v1
kind: Pod
metadata:
labels:
app.kubernetes.io/name: nginx
name: nginx
spec:
containers:
- image: nginx
name: nginx
resources:
requests:
cpu: 100m #TODO: Set this to the amount of CPU you want to reserve for your workload
memory: 128Mi
+1 -1
View File
@@ -10,5 +10,5 @@ spec:
image: nginx
resources:
requests:
memory: 128Mi
memory: 256Mi
cpu: 100m
@@ -1,13 +0,0 @@
apiVersion: v1
kind: Pod
metadata:
name: nginx
labels:
app.kubernetes.io/name: nginx
spec:
containers:
- name: nginx
image: nginx
securityContext:
capabilities:
add: ["all"]

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