1
0
Fork 0
mirror of https://github.com/kyverno/kyverno.git synced 2025-03-09 17:37:12 +00:00
kyverno/cmd/cli/kubectl-kyverno/apply/apply_command.go

611 lines
23 KiB
Go
Raw Normal View History

2020-03-06 03:00:18 +05:30
package apply
import (
"context"
2020-03-06 03:00:18 +05:30
"fmt"
"net/url"
"os"
"path/filepath"
"sort"
"strings"
2020-04-03 10:30:52 +05:30
"time"
"github.com/go-git/go-billy/v5/memfs"
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
feat: mutate existing resources (#3669) * feat: mutate existing, replace GR by UR in webhook server (#3601) * add attributes for post mutation Signed-off-by: ShutingZhao <shuting@nirmata.com> * add UR informer to webhook server Signed-off-by: ShutingZhao <shuting@nirmata.com> * - replace gr with ur in the webhook server; - create ur for mutateExsiting policies Signed-off-by: ShutingZhao <shuting@nirmata.com> * replace gr by ur across entire packages Signed-off-by: ShutingZhao <shuting@nirmata.com> * add YAMLs Signed-off-by: ShutingZhao <shuting@nirmata.com> * update api docs & fix unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * add UR deletion handler Signed-off-by: ShutingZhao <shuting@nirmata.com> * add api docs for v1beta1 Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix clientset method Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix v1beta1 client registration Signed-off-by: ShutingZhao <shuting@nirmata.com> * feat: mutate existing - generates UR for admission requests (#3623) Signed-off-by: ShutingZhao <shuting@nirmata.com> * replace with UR in policy controller generate rules (#3635) Signed-off-by: prateekpandey14 <prateek.pandey@nirmata.com> * - enable mutate engine to process mutateExisting rules; - add unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * implemented ur background reconciliation for mutateExisting policies Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix webhook update error Signed-off-by: ShutingZhao <shuting@nirmata.com> * temporary comment out new unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * feat: mutate existing, replace GR by UR in webhook server (#3601) * add attributes for post mutation Signed-off-by: ShutingZhao <shuting@nirmata.com> * add UR informer to webhook server Signed-off-by: ShutingZhao <shuting@nirmata.com> * - replace gr with ur in the webhook server; - create ur for mutateExsiting policies Signed-off-by: ShutingZhao <shuting@nirmata.com> * replace gr by ur across entire packages Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix missing policy.kyverno.io/policy-name label (#3599) Signed-off-by: prateekpandey14 <prateek.pandey@nirmata.com> * refactor cli code from pkg to cmd (#3591) * refactor cli code from pkg to cmd Signed-off-by: Mritunjay Sharma <mritunjaysharma394@gmail.com> * fixes in imports Signed-off-by: Mritunjay Sharma <mritunjaysharma394@gmail.com> * fixes tests Signed-off-by: Mritunjay Sharma <mritunjaysharma394@gmail.com> * fixed conflicts Signed-off-by: Mritunjay Sharma <mritunjaysharma394@gmail.com> * moved non-commands to utils Signed-off-by: Mritunjay Sharma <mritunjaysharma394@gmail.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com> * add YAMLs Signed-off-by: ShutingZhao <shuting@nirmata.com> * update api docs & fix unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * add UR deletion handler Signed-off-by: ShutingZhao <shuting@nirmata.com> * add api docs for v1beta1 Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix clientset method Signed-off-by: ShutingZhao <shuting@nirmata.com> * add-kms-libraries for cosign (#3603) * add-kms-libraries Signed-off-by: anushkamittal20 <anumittal4641@gmail.com> * Shifted providers to cosign package Signed-off-by: anushkamittal20 <anumittal4641@gmail.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> * Add support for custom image extractors (#3596) Signed-off-by: Sambhav Kothari <skothari44@bloomberg.net> * Update vulnerable dependencies (#3577) Signed-off-by: Shubham Gupta <shubham.gupta2956@gmail.com> Co-authored-by: Jim Bugwadia <jim@nirmata.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix v1beta1 client registration Signed-off-by: ShutingZhao <shuting@nirmata.com> * feat: mutate existing - generates UR for admission requests (#3623) Signed-off-by: ShutingZhao <shuting@nirmata.com> * updating version in Chart.yaml (#3618) * updatimg version in Chart.yaml Signed-off-by: Prateeknandle <prateeknandle@gmail.com> * changes from, make gen-helm Signed-off-by: Prateeknandle <prateeknandle@gmail.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> * Allow kyverno-policies to have preconditions defined (#3606) * Allow kyverno-policies to have preconditions defined Signed-off-by: Trey Dockendorf <tdockendorf@osc.edu> * Fix docs Signed-off-by: Trey Dockendorf <tdockendorf@osc.edu> Signed-off-by: ShutingZhao <shuting@nirmata.com> * replace with UR in policy controller generate rules (#3635) Signed-off-by: prateekpandey14 <prateek.pandey@nirmata.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> * - enable mutate engine to process mutateExisting rules; - add unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * implemented ur background reconciliation for mutateExisting policies Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix webhook update error Signed-off-by: ShutingZhao <shuting@nirmata.com> * temporary comment out new unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * Image verify attestors (#3614) * fix logs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix logs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * support multiple attestors Signed-off-by: Jim Bugwadia <jim@nirmata.com> * rm CLI tests (not currently supported) Signed-off-by: Jim Bugwadia <jim@nirmata.com> * apply attestor repo Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix linter issues Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix entryError assignment Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add intermediary certs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * Allow defining imagePullSecrets (#3633) * Allow defining imagePullSecrets Signed-off-by: Trey Dockendorf <tdockendorf@osc.edu> * Use dict for imagePullSecrets Signed-off-by: Trey Dockendorf <tdockendorf@osc.edu> * Simplify how imagePullSecrets is defined Signed-off-by: Trey Dockendorf <tdockendorf@osc.edu> Signed-off-by: ShutingZhao <shuting@nirmata.com> * Fix race condition in pCache (#3632) * fix race condition in pCache Signed-off-by: ShutingZhao <shuting@nirmata.com> * refact: remove unused Run function from generate (#3638) Signed-off-by: prateekpandey14 <prateek.pandey@nirmata.com> * Remove helm mode setting (#3628) Signed-off-by: Charles-Edouard Brétéché <charled.breteche@gmail.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> * refactor: image utils (#3630) Signed-off-by: Charles-Edouard Brétéché <charled.breteche@gmail.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> * -resolve lift comments; -fix informer sync issue Signed-off-by: ShutingZhao <shuting@nirmata.com> * refact the update request cleanup controller Signed-off-by: prateekpandey14 <prateek.pandey@nirmata.com> * - fix delete request for mutateExisting; - fix context variable substitution; - improve logging Signed-off-by: ShutingZhao <shuting@nirmata.com> * - enable events; - add last applied annotation Signed-off-by: ShutingZhao <shuting@nirmata.com> * enable mutate existing on policy creation Signed-off-by: ShutingZhao <shuting@nirmata.com> * update autogen code Signed-off-by: ShutingZhao <shuting@nirmata.com> * merge main Signed-off-by: ShutingZhao <shuting@nirmata.com> * add unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * address list comments Signed-off-by: ShutingZhao <shuting@nirmata.com> * update api docs Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix "Implicit memory aliasing in for loop" Signed-off-by: ShutingZhao <shuting@nirmata.com> * remove unused definitions Signed-off-by: ShutingZhao <shuting@nirmata.com> * update api docs Signed-off-by: ShutingZhao <shuting@nirmata.com> Co-authored-by: Prateek Pandey <prateek.pandey@nirmata.com> Co-authored-by: Mritunjay Kumar Sharma <mritunjaysharma394@gmail.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com> Co-authored-by: Anushka Mittal <55237170+anushkamittal20@users.noreply.github.com> Co-authored-by: Sambhav Kothari <sambhavs.email@gmail.com> Co-authored-by: Shubham Gupta <shubham.gupta2956@gmail.com> Co-authored-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Prateek Nandle <56027872+Prateeknandle@users.noreply.github.com> Co-authored-by: treydock <tdockendorf@osc.edu> Co-authored-by: Charles-Edouard Brétéché <charled.breteche@gmail.com>
2022-04-25 20:20:40 +08:00
"github.com/kyverno/kyverno/api/kyverno/v1beta1"
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/utils/common"
sanitizederror "github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/utils/sanitizedError"
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/utils/store"
"github.com/kyverno/kyverno/pkg/autogen"
"github.com/kyverno/kyverno/pkg/clients/dclient"
"github.com/kyverno/kyverno/pkg/config"
engineapi "github.com/kyverno/kyverno/pkg/engine/api"
2020-10-15 17:29:07 -07:00
"github.com/kyverno/kyverno/pkg/openapi"
gitutils "github.com/kyverno/kyverno/pkg/utils/git"
policyvalidation "github.com/kyverno/kyverno/pkg/validation/policy"
2020-03-06 03:00:18 +05:30
"github.com/spf13/cobra"
2020-10-15 17:29:07 -07:00
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
"sigs.k8s.io/controller-runtime/pkg/log"
2020-11-10 10:49:29 +05:30
yaml1 "sigs.k8s.io/yaml"
2020-03-06 03:00:18 +05:30
)
type Resource struct {
Name string `json:"name"`
Values map[string]string `json:"values"`
}
type Policy struct {
Name string `json:"name"`
Resources []Resource `json:"resources"`
}
type Values struct {
Policies []Policy `json:"policies"`
}
type SkippedInvalidPolicies struct {
skipped []string
invalid []string
}
type ApplyCommandConfig struct {
KubeConfig string
Context string
Namespace string
MutateLogPath string
VariablesString string
ValuesFile string
UserInfoPath string
Cluster bool
PolicyReport bool
Stdin bool
RegistryAccess bool
AuditWarn bool
ResourcePaths []string
PolicyPaths []string
GitBranch string
warnExitCode int
warnNoPassed bool
}
var (
applyHelp = `
To apply on a resource:
kyverno apply /path/to/policy.yaml /path/to/folderOfPolicies --resource=/path/to/resource1 --resource=/path/to/resource2
To apply on a folder of resources:
kyverno apply /path/to/policy.yaml /path/to/folderOfPolicies --resource=/path/to/resources/
To apply on a cluster:
kyverno apply /path/to/policy.yaml /path/to/folderOfPolicies --cluster
To apply policies from a gitSourceURL on a cluster:
Example: Taking github.com as a gitSourceURL here. Some other standards gitSourceURL are: gitlab.com , bitbucket.org , etc.
kyverno apply https://github.com/kyverno/policies/openshift/ --git-branch main --cluster
To apply policy with variables:
1. To apply single policy with variable on single resource use flag "set".
Example:
kyverno apply /path/to/policy.yaml --resource /path/to/resource.yaml --set <variable1>=<value1>,<variable2>=<value2>
2. To apply multiple policy with variable on multiple resource use flag "values_file".
Example:
kyverno apply /path/to/policy1.yaml /path/to/policy2.yaml --resource /path/to/resource1.yaml --resource /path/to/resource2.yaml -f /path/to/value.yaml
Format of value.yaml:
policies:
- name: <policy1 name>
rules:
- name: <rule1 name>
values:
<context variable1 in policy1 rule1>: <value>
<context variable2 in policy1 rule1>: <value>
- name: <rule2 name>
values:
<context variable1 in policy1 rule2>: <value>
<context variable2 in policy1 rule2>: <value>
resources:
- name: <resource1 name>
values:
<variable1 in policy1>: <value>
<variable2 in policy1>: <value>
- name: <resource2 name>
values:
<variable1 in policy1>: <value>
<variable2 in policy1>: <value>
- name: <policy2 name>
resources:
- name: <resource1 name>
values:
<variable1 in policy2>: <value>
<variable2 in policy2>: <value>
- name: <resource2 name>
values:
<variable1 in policy2>: <value>
<variable2 in policy2>: <value>
namespaceSelector:
- name: <namespace1 name>
labels:
<label key>: <label value>
- name: <namespace2 name>
labels:
<label key>: <label value>
# If policy is matching on Kind/Subresource, then this is required
subresources:
- subresource:
name: <name of subresource>
kind: <kind of subresource>
group: <group of subresource>
version: <version of subresource>
parentResource:
name: <name of parent resource>
kind: <kind of parent resource>
group: <group of parent resource>
version: <version of parent resource>
More info: https://kyverno.io/docs/kyverno-cli/
`
// allow os.exit to be overwritten during unit tests
osExit = os.Exit
)
func Command() *cobra.Command {
var cmd *cobra.Command
applyCommandConfig := &ApplyCommandConfig{}
cmd = &cobra.Command{
Use: "apply",
Short: "Applies policies on resources.",
Example: applyHelp,
2020-03-06 03:00:18 +05:30
RunE: func(cmd *cobra.Command, policyPaths []string) (err error) {
defer func() {
if err != nil {
if !sanitizederror.IsErrorSanitized(err) {
2020-03-20 11:43:21 -07:00
log.Log.Error(err, "failed to sanitize")
2020-08-05 23:53:27 +05:30
err = fmt.Errorf("internal error")
2020-03-06 03:00:18 +05:30
}
}
}()
applyCommandConfig.PolicyPaths = policyPaths
rc, resources, skipInvalidPolicies, pvInfos, err := applyCommandConfig.applyCommandHelper()
if err != nil {
return err
}
PrintReportOrViolation(applyCommandConfig.PolicyReport, rc, applyCommandConfig.ResourcePaths, len(resources), skipInvalidPolicies, applyCommandConfig.Stdin, pvInfos, applyCommandConfig.warnExitCode, applyCommandConfig.warnNoPassed, applyCommandConfig.AuditWarn)
2020-12-20 01:21:31 +05:30
return nil
},
}
cmd.Flags().StringArrayVarP(&applyCommandConfig.ResourcePaths, "resource", "r", []string{}, "Path to resource files")
cmd.Flags().BoolVarP(&applyCommandConfig.Cluster, "cluster", "c", false, "Checks if policies should be applied to cluster in the current context")
cmd.Flags().StringVarP(&applyCommandConfig.MutateLogPath, "output", "o", "", "Prints the mutated resources in provided file/directory")
// currently `set` flag supports variable for single policy applied on single resource
cmd.Flags().StringVarP(&applyCommandConfig.UserInfoPath, "userinfo", "u", "", "Admission Info including Roles, Cluster Roles and Subjects")
cmd.Flags().StringVarP(&applyCommandConfig.VariablesString, "set", "s", "", "Variables that are required")
cmd.Flags().StringVarP(&applyCommandConfig.ValuesFile, "values-file", "f", "", "File containing values for policy variables")
cmd.Flags().BoolVarP(&applyCommandConfig.PolicyReport, "policy-report", "p", false, "Generates policy report when passed (default policyviolation)")
cmd.Flags().StringVarP(&applyCommandConfig.Namespace, "namespace", "n", "", "Optional Policy parameter passed with cluster flag")
cmd.Flags().BoolVarP(&applyCommandConfig.Stdin, "stdin", "i", false, "Optional mutate policy parameter to pipe directly through to kubectl")
cmd.Flags().BoolVarP(&applyCommandConfig.RegistryAccess, "registry", "", false, "If set to true, access the image registry using local docker credentials to populate external data")
cmd.Flags().StringVarP(&applyCommandConfig.KubeConfig, "kubeconfig", "", "", "path to kubeconfig file with authorization and master location information")
cmd.Flags().StringVarP(&applyCommandConfig.Context, "context", "", "", "The name of the kubeconfig context to use")
cmd.Flags().StringVarP(&applyCommandConfig.GitBranch, "git-branch", "b", "", "test git repository branch")
cmd.Flags().BoolVarP(&applyCommandConfig.AuditWarn, "audit-warn", "", false, "If set to true, will flag audit policies as warnings instead of failures")
cmd.Flags().IntVar(&applyCommandConfig.warnExitCode, "warn-exit-code", 0, "Set the exit code for warnings; if failures or errors are found, will exit 1")
cmd.Flags().BoolVarP(&applyCommandConfig.warnNoPassed, "warn-no-pass", "", false, "Specify if warning exit code should be raised if no objects satisfied a policy; can be used together with --warn-exit-code flag")
2020-12-20 01:21:31 +05:30
return cmd
}
2020-08-05 23:53:27 +05:30
func (c *ApplyCommandConfig) applyCommandHelper() (rc *common.ResultCounts, resources []*unstructured.Unstructured, skipInvalidPolicies SkippedInvalidPolicies, responses []engineapi.EngineResponse, err error) {
store.SetMock(true)
store.SetRegistryAccess(c.RegistryAccess)
if c.Cluster {
store.AllowApiCall(true)
}
fs := memfs.New()
2020-10-16 19:56:32 +05:30
if c.ValuesFile != "" && c.VariablesString != "" {
return rc, resources, skipInvalidPolicies, responses, sanitizederror.NewWithError("pass the values either using set flag or values_file flag", err)
2020-12-20 01:21:31 +05:30
}
variables, globalValMap, valuesMap, namespaceSelectorMap, subresources, err := common.GetVariable(c.VariablesString, c.ValuesFile, fs, false, "")
2020-12-20 01:21:31 +05:30
if err != nil {
if !sanitizederror.IsErrorSanitized(err) {
return rc, resources, skipInvalidPolicies, responses, sanitizederror.NewWithError("failed to decode yaml", err)
2020-12-20 01:21:31 +05:30
}
return rc, resources, skipInvalidPolicies, responses, err
2020-12-20 01:21:31 +05:30
}
2020-10-16 19:56:32 +05:30
openApiManager, err := openapi.NewManager(log.Log)
2020-12-20 01:21:31 +05:30
if err != nil {
return rc, resources, skipInvalidPolicies, responses, sanitizederror.NewWithError("failed to initialize openAPIController", err)
2020-12-20 01:21:31 +05:30
}
var dClient dclient.Interface
if c.Cluster {
restConfig, err := config.CreateClientConfigWithContext(c.KubeConfig, c.Context)
2020-12-20 01:21:31 +05:30
if err != nil {
return rc, resources, skipInvalidPolicies, responses, err
2020-12-20 01:21:31 +05:30
}
kubeClient, err := kubernetes.NewForConfig(restConfig)
if err != nil {
return rc, resources, skipInvalidPolicies, responses, err
}
dynamicClient, err := dynamic.NewForConfig(restConfig)
if err != nil {
return rc, resources, skipInvalidPolicies, responses, err
}
dClient, err = dclient.NewClient(context.Background(), dynamicClient, kubeClient, 15*time.Minute)
2020-12-20 01:21:31 +05:30
if err != nil {
return rc, resources, skipInvalidPolicies, responses, err
2020-12-20 01:21:31 +05:30
}
}
2020-03-06 03:00:18 +05:30
if len(c.PolicyPaths) == 0 {
return rc, resources, skipInvalidPolicies, responses, sanitizederror.NewWithError("require policy", err)
2020-12-20 01:21:31 +05:30
}
2020-11-11 17:10:38 +05:30
if (len(c.PolicyPaths) > 0 && c.PolicyPaths[0] == "-") && len(c.ResourcePaths) > 0 && c.ResourcePaths[0] == "-" {
return rc, resources, skipInvalidPolicies, responses, sanitizederror.NewWithError("a stdin pipe can be used for either policies or resources, not both", err)
2020-12-20 01:21:31 +05:30
}
2020-11-11 11:57:23 +05:30
var policies []kyvernov1.PolicyInterface
isGit := common.IsGitSourcePath(c.PolicyPaths)
if isGit {
gitSourceURL, err := url.Parse(c.PolicyPaths[0])
if err != nil {
fmt.Printf("Error: failed to load policies\nCause: %s\n", err)
osExit(1)
}
pathElems := strings.Split(gitSourceURL.Path[1:], "/")
if len(pathElems) <= 1 {
err := fmt.Errorf("invalid URL path %s - expected https://<any_git_source_domain>/:owner/:repository/:branch (without --git-branch flag) OR https://<any_git_source_domain>/:owner/:repository/:directory (with --git-branch flag)", gitSourceURL.Path)
fmt.Printf("Error: failed to parse URL \nCause: %s\n", err)
osExit(1)
}
gitSourceURL.Path = strings.Join([]string{pathElems[0], pathElems[1]}, "/")
repoURL := gitSourceURL.String()
var gitPathToYamls string
c.GitBranch, gitPathToYamls = common.GetGitBranchOrPolicyPaths(c.GitBranch, repoURL, c.PolicyPaths)
_, cloneErr := gitutils.Clone(repoURL, fs, c.GitBranch)
if cloneErr != nil {
fmt.Printf("Error: failed to clone repository \nCause: %s\n", cloneErr)
log.Log.V(3).Info(fmt.Sprintf("failed to clone repository %v as it is not valid", repoURL), "error", cloneErr)
osExit(1)
}
policyYamls, err := gitutils.ListYamls(fs, gitPathToYamls)
if err != nil {
return rc, resources, skipInvalidPolicies, responses, sanitizederror.NewWithError("failed to list YAMLs in repository", err)
}
sort.Strings(policyYamls)
c.PolicyPaths = policyYamls
}
policies, err = common.GetPoliciesFromPaths(fs, c.PolicyPaths, isGit, "")
2020-12-20 01:21:31 +05:30
if err != nil {
fmt.Printf("Error: failed to load policies\nCause: %s\n", err)
osExit(1)
2020-12-20 01:21:31 +05:30
}
2020-07-10 14:56:07 +05:30
if len(c.ResourcePaths) == 0 && !c.Cluster {
return rc, resources, skipInvalidPolicies, responses, sanitizederror.NewWithError("resource file(s) or cluster required", err)
2020-12-20 01:21:31 +05:30
}
2020-08-18 21:03:00 -07:00
mutateLogPathIsDir, err := checkMutateLogPath(c.MutateLogPath)
2020-12-20 01:21:31 +05:30
if err != nil {
if !sanitizederror.IsErrorSanitized(err) {
return rc, resources, skipInvalidPolicies, responses, sanitizederror.NewWithError("failed to create file/folder", err)
2020-12-20 01:21:31 +05:30
}
return rc, resources, skipInvalidPolicies, responses, err
2020-12-20 01:21:31 +05:30
}
2020-08-18 21:03:00 -07:00
// empty the previous contents of the file just in case if the file already existed before with some content(so as to perform overwrites)
// the truncation of files for the case when mutateLogPath is dir, is handled under pkg/kyverno/apply/common.go
if !mutateLogPathIsDir && c.MutateLogPath != "" {
c.MutateLogPath = filepath.Clean(c.MutateLogPath)
// Necessary for us to include the file via variable as it is part of the CLI.
_, err := os.OpenFile(c.MutateLogPath, os.O_TRUNC|os.O_WRONLY, 0o600) // #nosec G304
if err != nil {
if !sanitizederror.IsErrorSanitized(err) {
return rc, resources, skipInvalidPolicies, responses, sanitizederror.NewWithError("failed to truncate the existing file at "+c.MutateLogPath, err)
}
return rc, resources, skipInvalidPolicies, responses, err
}
}
err = common.PrintMutatedPolicy(policies)
if err != nil {
return rc, resources, skipInvalidPolicies, responses, sanitizederror.NewWithError("failed to marshal mutated policy", err)
}
resources, err = common.GetResourceAccordingToResourcePath(fs, c.ResourcePaths, c.Cluster, policies, dClient, c.Namespace, c.PolicyReport, false, "")
2020-12-20 01:21:31 +05:30
if err != nil {
fmt.Printf("Error: failed to load resources\nCause: %s\n", err)
osExit(1)
2020-12-20 01:21:31 +05:30
}
2020-03-06 03:00:18 +05:30
if (len(resources) > 1 || len(policies) > 1) && c.VariablesString != "" {
return rc, resources, skipInvalidPolicies, responses, sanitizederror.NewWithError("currently `set` flag supports variable for single policy applied on single resource ", nil)
}
// get the user info as request info from a different file
feat: mutate existing resources (#3669) * feat: mutate existing, replace GR by UR in webhook server (#3601) * add attributes for post mutation Signed-off-by: ShutingZhao <shuting@nirmata.com> * add UR informer to webhook server Signed-off-by: ShutingZhao <shuting@nirmata.com> * - replace gr with ur in the webhook server; - create ur for mutateExsiting policies Signed-off-by: ShutingZhao <shuting@nirmata.com> * replace gr by ur across entire packages Signed-off-by: ShutingZhao <shuting@nirmata.com> * add YAMLs Signed-off-by: ShutingZhao <shuting@nirmata.com> * update api docs & fix unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * add UR deletion handler Signed-off-by: ShutingZhao <shuting@nirmata.com> * add api docs for v1beta1 Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix clientset method Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix v1beta1 client registration Signed-off-by: ShutingZhao <shuting@nirmata.com> * feat: mutate existing - generates UR for admission requests (#3623) Signed-off-by: ShutingZhao <shuting@nirmata.com> * replace with UR in policy controller generate rules (#3635) Signed-off-by: prateekpandey14 <prateek.pandey@nirmata.com> * - enable mutate engine to process mutateExisting rules; - add unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * implemented ur background reconciliation for mutateExisting policies Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix webhook update error Signed-off-by: ShutingZhao <shuting@nirmata.com> * temporary comment out new unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * feat: mutate existing, replace GR by UR in webhook server (#3601) * add attributes for post mutation Signed-off-by: ShutingZhao <shuting@nirmata.com> * add UR informer to webhook server Signed-off-by: ShutingZhao <shuting@nirmata.com> * - replace gr with ur in the webhook server; - create ur for mutateExsiting policies Signed-off-by: ShutingZhao <shuting@nirmata.com> * replace gr by ur across entire packages Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix missing policy.kyverno.io/policy-name label (#3599) Signed-off-by: prateekpandey14 <prateek.pandey@nirmata.com> * refactor cli code from pkg to cmd (#3591) * refactor cli code from pkg to cmd Signed-off-by: Mritunjay Sharma <mritunjaysharma394@gmail.com> * fixes in imports Signed-off-by: Mritunjay Sharma <mritunjaysharma394@gmail.com> * fixes tests Signed-off-by: Mritunjay Sharma <mritunjaysharma394@gmail.com> * fixed conflicts Signed-off-by: Mritunjay Sharma <mritunjaysharma394@gmail.com> * moved non-commands to utils Signed-off-by: Mritunjay Sharma <mritunjaysharma394@gmail.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com> * add YAMLs Signed-off-by: ShutingZhao <shuting@nirmata.com> * update api docs & fix unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * add UR deletion handler Signed-off-by: ShutingZhao <shuting@nirmata.com> * add api docs for v1beta1 Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix clientset method Signed-off-by: ShutingZhao <shuting@nirmata.com> * add-kms-libraries for cosign (#3603) * add-kms-libraries Signed-off-by: anushkamittal20 <anumittal4641@gmail.com> * Shifted providers to cosign package Signed-off-by: anushkamittal20 <anumittal4641@gmail.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> * Add support for custom image extractors (#3596) Signed-off-by: Sambhav Kothari <skothari44@bloomberg.net> * Update vulnerable dependencies (#3577) Signed-off-by: Shubham Gupta <shubham.gupta2956@gmail.com> Co-authored-by: Jim Bugwadia <jim@nirmata.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix v1beta1 client registration Signed-off-by: ShutingZhao <shuting@nirmata.com> * feat: mutate existing - generates UR for admission requests (#3623) Signed-off-by: ShutingZhao <shuting@nirmata.com> * updating version in Chart.yaml (#3618) * updatimg version in Chart.yaml Signed-off-by: Prateeknandle <prateeknandle@gmail.com> * changes from, make gen-helm Signed-off-by: Prateeknandle <prateeknandle@gmail.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> * Allow kyverno-policies to have preconditions defined (#3606) * Allow kyverno-policies to have preconditions defined Signed-off-by: Trey Dockendorf <tdockendorf@osc.edu> * Fix docs Signed-off-by: Trey Dockendorf <tdockendorf@osc.edu> Signed-off-by: ShutingZhao <shuting@nirmata.com> * replace with UR in policy controller generate rules (#3635) Signed-off-by: prateekpandey14 <prateek.pandey@nirmata.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> * - enable mutate engine to process mutateExisting rules; - add unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * implemented ur background reconciliation for mutateExisting policies Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix webhook update error Signed-off-by: ShutingZhao <shuting@nirmata.com> * temporary comment out new unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * Image verify attestors (#3614) * fix logs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix logs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * support multiple attestors Signed-off-by: Jim Bugwadia <jim@nirmata.com> * rm CLI tests (not currently supported) Signed-off-by: Jim Bugwadia <jim@nirmata.com> * apply attestor repo Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix linter issues Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix entryError assignment Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add intermediary certs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * Allow defining imagePullSecrets (#3633) * Allow defining imagePullSecrets Signed-off-by: Trey Dockendorf <tdockendorf@osc.edu> * Use dict for imagePullSecrets Signed-off-by: Trey Dockendorf <tdockendorf@osc.edu> * Simplify how imagePullSecrets is defined Signed-off-by: Trey Dockendorf <tdockendorf@osc.edu> Signed-off-by: ShutingZhao <shuting@nirmata.com> * Fix race condition in pCache (#3632) * fix race condition in pCache Signed-off-by: ShutingZhao <shuting@nirmata.com> * refact: remove unused Run function from generate (#3638) Signed-off-by: prateekpandey14 <prateek.pandey@nirmata.com> * Remove helm mode setting (#3628) Signed-off-by: Charles-Edouard Brétéché <charled.breteche@gmail.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> * refactor: image utils (#3630) Signed-off-by: Charles-Edouard Brétéché <charled.breteche@gmail.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> * -resolve lift comments; -fix informer sync issue Signed-off-by: ShutingZhao <shuting@nirmata.com> * refact the update request cleanup controller Signed-off-by: prateekpandey14 <prateek.pandey@nirmata.com> * - fix delete request for mutateExisting; - fix context variable substitution; - improve logging Signed-off-by: ShutingZhao <shuting@nirmata.com> * - enable events; - add last applied annotation Signed-off-by: ShutingZhao <shuting@nirmata.com> * enable mutate existing on policy creation Signed-off-by: ShutingZhao <shuting@nirmata.com> * update autogen code Signed-off-by: ShutingZhao <shuting@nirmata.com> * merge main Signed-off-by: ShutingZhao <shuting@nirmata.com> * add unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * address list comments Signed-off-by: ShutingZhao <shuting@nirmata.com> * update api docs Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix "Implicit memory aliasing in for loop" Signed-off-by: ShutingZhao <shuting@nirmata.com> * remove unused definitions Signed-off-by: ShutingZhao <shuting@nirmata.com> * update api docs Signed-off-by: ShutingZhao <shuting@nirmata.com> Co-authored-by: Prateek Pandey <prateek.pandey@nirmata.com> Co-authored-by: Mritunjay Kumar Sharma <mritunjaysharma394@gmail.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com> Co-authored-by: Anushka Mittal <55237170+anushkamittal20@users.noreply.github.com> Co-authored-by: Sambhav Kothari <sambhavs.email@gmail.com> Co-authored-by: Shubham Gupta <shubham.gupta2956@gmail.com> Co-authored-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Prateek Nandle <56027872+Prateeknandle@users.noreply.github.com> Co-authored-by: treydock <tdockendorf@osc.edu> Co-authored-by: Charles-Edouard Brétéché <charled.breteche@gmail.com>
2022-04-25 20:20:40 +08:00
var userInfo v1beta1.RequestInfo
if c.UserInfoPath != "" {
userInfo, err = common.GetUserInfoFromPath(fs, c.UserInfoPath, false, "")
if err != nil {
fmt.Printf("Error: failed to load request info\nCause: %s\n", err)
osExit(1)
}
}
if c.VariablesString != "" {
variables = common.SetInStoreContext(policies, variables)
}
var policyRulesCount, mutatedPolicyRulesCount int
for _, policy := range policies {
policyRulesCount += len(policy.GetSpec().Rules)
}
for _, policy := range policies {
mutatedPolicyRulesCount += len(policy.GetSpec().Rules)
}
msgPolicyRules := "1 policy rule"
if policyRulesCount > 1 {
msgPolicyRules = fmt.Sprintf("%d policy rules", policyRulesCount)
}
if mutatedPolicyRulesCount > policyRulesCount {
msgPolicyRules = fmt.Sprintf("%d policy rules", mutatedPolicyRulesCount)
2020-12-20 01:21:31 +05:30
}
2020-11-19 15:03:15 +05:30
2020-12-20 01:21:31 +05:30
msgResources := "1 resource"
if len(resources) > 1 {
msgResources = fmt.Sprintf("%d resources", len(resources))
}
2020-08-22 01:21:29 +05:30
if len(policies) > 0 && len(resources) > 0 {
if !c.Stdin {
if mutatedPolicyRulesCount > policyRulesCount {
fmt.Printf("\nauto-generated pod policies\nApplying %s to %s...\n", msgPolicyRules, msgResources)
} else {
fmt.Printf("\nApplying %s to %s...\n", msgPolicyRules, msgResources)
}
}
2020-12-20 01:21:31 +05:30
}
rc = &common.ResultCounts{}
skipInvalidPolicies.skipped = make([]string, 0)
skipInvalidPolicies.invalid = make([]string, 0)
for _, policy := range policies {
_, err := policyvalidation.Validate(policy, nil, nil, true, openApiManager, config.KyvernoUserName(config.KyvernoServiceAccountName()))
2020-12-20 01:21:31 +05:30
if err != nil {
updates for foreach and mutate (#2891) * updates for foreach and mutate Signed-off-by: Jim Bugwadia <jim@nirmata.com> * allow tests to pass on Windows Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix linter check Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add elementIndex variable Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix jsonResult usage Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add mutate validation and fix error in validate.foreach Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * do not skip validation for all array entries when one is skipped Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add foreach tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix format errors Signed-off-by: Jim Bugwadia <jim@nirmata.com> * remove unused declarations Signed-off-by: Jim Bugwadia <jim@nirmata.com> * revert namespaceWithLabelYaml Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix mutate of element list Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update CRDs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * Update api/kyverno/v1/policy_types.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/custom-functions/policy.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/foreach/policies.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * accept review comments and format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add comments to strategicMergePatch buffer Signed-off-by: Jim Bugwadia <jim@nirmata.com> * load context and evaluate preconditions foreach element Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add test for foreach mutate context and precondition * precondition testcase * address review comments Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Steven E. Harris <seh@panix.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com>
2022-01-04 17:36:33 -08:00
log.Log.Error(err, "policy validation error")
if strings.HasPrefix(err.Error(), "variable 'element.name'") {
skipInvalidPolicies.invalid = append(skipInvalidPolicies.invalid, policy.GetName())
} else {
skipInvalidPolicies.skipped = append(skipInvalidPolicies.skipped, policy.GetName())
}
updates for foreach and mutate (#2891) * updates for foreach and mutate Signed-off-by: Jim Bugwadia <jim@nirmata.com> * allow tests to pass on Windows Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix linter check Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add elementIndex variable Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix jsonResult usage Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add mutate validation and fix error in validate.foreach Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * do not skip validation for all array entries when one is skipped Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add foreach tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix format errors Signed-off-by: Jim Bugwadia <jim@nirmata.com> * remove unused declarations Signed-off-by: Jim Bugwadia <jim@nirmata.com> * revert namespaceWithLabelYaml Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix mutate of element list Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update CRDs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * Update api/kyverno/v1/policy_types.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/custom-functions/policy.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/foreach/policies.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * accept review comments and format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add comments to strategicMergePatch buffer Signed-off-by: Jim Bugwadia <jim@nirmata.com> * load context and evaluate preconditions foreach element Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add test for foreach mutate context and precondition * precondition testcase * address review comments Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Steven E. Harris <seh@panix.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com>
2022-01-04 17:36:33 -08:00
2020-12-20 01:21:31 +05:30
continue
}
2020-08-12 13:39:06 +05:30
matches := common.HasVariables(policy)
variable := common.RemoveDuplicateAndObjectVariables(matches)
if len(variable) > 0 {
if len(variables) == 0 {
// check policy in variable file
if c.ValuesFile == "" || valuesMap[policy.GetName()] == nil {
skipInvalidPolicies.skipped = append(skipInvalidPolicies.skipped, policy.GetName())
continue
}
2020-03-06 03:00:18 +05:30
}
2020-12-20 01:21:31 +05:30
}
2020-03-06 03:00:18 +05:30
kindOnwhichPolicyIsApplied := common.GetKindsFromPolicy(policy, subresources, dClient)
2020-12-20 01:21:31 +05:30
for _, resource := range resources {
thisPolicyResourceValues, err := common.CheckVariableForPolicy(valuesMap, globalValMap, policy.GetName(), resource.GetName(), resource.GetKind(), variables, kindOnwhichPolicyIsApplied, variable)
if err != nil {
return rc, resources, skipInvalidPolicies, responses, sanitizederror.NewWithError(fmt.Sprintf("policy `%s` have variables. pass the values for the variables for resource `%s` using set/values_file flag", policy.GetName(), resource.GetName()), err)
2020-12-20 01:21:31 +05:30
}
applyPolicyConfig := common.ApplyPolicyConfig{
Policy: policy,
Resource: resource,
MutateLogPath: c.MutateLogPath,
MutateLogPathIsDir: mutateLogPathIsDir,
Variables: thisPolicyResourceValues,
UserInfo: userInfo,
PolicyReport: c.PolicyReport,
NamespaceSelectorMap: namespaceSelectorMap,
Stdin: c.Stdin,
Rc: rc,
PrintPatchResource: true,
Client: dClient,
AuditWarn: c.AuditWarn,
Subresources: subresources,
}
ers, err := common.ApplyPolicyOnResource(applyPolicyConfig)
2020-12-20 01:21:31 +05:30
if err != nil {
return rc, resources, skipInvalidPolicies, responses, sanitizederror.NewWithError(fmt.Errorf("failed to apply policy %v on resource %v", policy.GetName(), resource.GetName()).Error(), err)
}
for _, response := range ers {
if !response.IsEmpty() {
for _, rule := range autogen.ComputeRules(response.Policy()) {
if rule.HasValidate() || rule.HasVerifyImageChecks() || rule.HasVerifyImages() {
ruleFoundInEngineResponse := false
for _, valResponseRule := range response.PolicyResponse.Rules {
if rule.Name == valResponseRule.Name() {
ruleFoundInEngineResponse = true
switch valResponseRule.Status() {
case engineapi.RuleStatusPass:
rc.Pass++
case engineapi.RuleStatusFail:
ann := policy.GetAnnotations()
if scored, ok := ann[kyvernov1.AnnotationPolicyScored]; ok && scored == "false" {
rc.Warn++
break
} else if applyPolicyConfig.AuditWarn && response.GetValidationFailureAction().Audit() {
rc.Warn++
} else {
rc.Fail++
}
case engineapi.RuleStatusError:
rc.Error++
case engineapi.RuleStatusWarn:
rc.Warn++
case engineapi.RuleStatusSkip:
rc.Skip++
}
continue
}
}
if !ruleFoundInEngineResponse {
rc.Skip++
response.PolicyResponse.Rules = append(response.PolicyResponse.Rules,
*engineapi.RuleSkip(
rule.Name,
engineapi.Validation,
rule.Validation.Message,
),
)
}
}
}
}
responses = append(responses, response)
2020-12-20 01:21:31 +05:30
}
}
2020-03-06 03:00:18 +05:30
}
return rc, resources, skipInvalidPolicies, responses, nil
2020-03-06 03:00:18 +05:30
}
// checkMutateLogPath - checking path for printing mutated resource (-o flag)
2020-11-03 01:25:32 +05:30
func checkMutateLogPath(mutateLogPath string) (mutateLogPathIsDir bool, err error) {
if mutateLogPath != "" {
spath := strings.Split(mutateLogPath, "/")
sfileName := strings.Split(spath[len(spath)-1], ".")
if sfileName[len(sfileName)-1] == "yml" || sfileName[len(sfileName)-1] == "yaml" {
mutateLogPathIsDir = false
} else {
mutateLogPathIsDir = true
}
err := createFileOrFolder(mutateLogPath, mutateLogPathIsDir)
if err != nil {
if !sanitizederror.IsErrorSanitized(err) {
return mutateLogPathIsDir, sanitizederror.NewWithError("failed to create file/folder.", err)
}
return mutateLogPathIsDir, err
}
}
return mutateLogPathIsDir, err
}
// PrintReportOrViolation - printing policy report/violations
func PrintReportOrViolation(policyReport bool, rc *common.ResultCounts, resourcePaths []string, resourcesLen int, skipInvalidPolicies SkippedInvalidPolicies, stdin bool, engineResponses []engineapi.EngineResponse, warnExitCode int, warnNoPassed bool, auditWarn bool) {
divider := "----------------------------------------------------------------------"
if len(skipInvalidPolicies.skipped) > 0 {
fmt.Println(divider)
fmt.Println("Policies Skipped (as required variables are not provided by the user):")
for i, policyName := range skipInvalidPolicies.skipped {
fmt.Printf("%d. %s\n", i+1, policyName)
}
fmt.Println(divider)
}
if len(skipInvalidPolicies.invalid) > 0 {
fmt.Println(divider)
fmt.Println("Invalid Policies:")
for i, policyName := range skipInvalidPolicies.invalid {
fmt.Printf("%d. %s\n", i+1, policyName)
}
fmt.Println(divider)
}
if policyReport {
resps := buildPolicyReports(auditWarn, engineResponses...)
2020-11-19 11:52:31 +05:30
if len(resps) > 0 || resourcesLen == 0 {
fmt.Println(divider)
fmt.Println("POLICY REPORT:")
fmt.Println(divider)
Feature/cosign (#2078) * add image verification * inline policy list Signed-off-by: Jim Bugwadia <jim@nirmata.com> * cosign version and dependencies updates Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add registry initialization Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add build tag to exclude k8schain for cloud providers Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add build tag to exclude k8schain for cloud providers Signed-off-by: Jim Bugwadia <jim@nirmata.com> * generate deep copy and other fixtures Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix deep copy issues Signed-off-by: Jim Bugwadia <jim@nirmata.com> * mutate images to add digest Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add certificates to Kyverno container for HTTPS lookups Signed-off-by: Jim Bugwadia <jim@nirmata.com> * align flag syntax Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update docs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update dependencies Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update dependencies Signed-off-by: Jim Bugwadia <jim@nirmata.com> * patch image with digest and fix checks Signed-off-by: Jim Bugwadia <jim@nirmata.com> * hardcode image for demos Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add default registry (docker.io) before calling reference.Parse Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix definition Signed-off-by: Jim Bugwadia <jim@nirmata.com> * increase webhook timeout Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix args Signed-off-by: Jim Bugwadia <jim@nirmata.com> * run gofmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * rename for clarity Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix HasImageVerify check Signed-off-by: Jim Bugwadia <jim@nirmata.com> * align make test commands Signed-off-by: Jim Bugwadia <jim@nirmata.com> * align make test commands Signed-off-by: Jim Bugwadia <jim@nirmata.com> * align make test commands Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix linter error Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * handle API conflict and retry Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix reviewdog issues Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix make for unit tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * improve error message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix durations Signed-off-by: Jim Bugwadia <jim@nirmata.com> * handle errors in tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * print policy name Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add retries and duration to error log Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix time check in tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * round creation times in test Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix retry loop Signed-off-by: Jim Bugwadia <jim@nirmata.com> * remove timing check for policy creation Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix e2e error - policy not found Signed-off-by: Shuting Zhao <shutting06@gmail.com> * update string comparison method Signed-off-by: Shuting Zhao <shutting06@gmail.com> * fix test Generate_Namespace_Label_Actions Signed-off-by: Shuting Zhao <shutting06@gmail.com> * add debug info for e2e tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix error Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix generate bug Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add check for update operations Signed-off-by: Jim Bugwadia <jim@nirmata.com> * increase time for deleteing a resource Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix check Signed-off-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Shuting Zhao <shutting06@gmail.com>
2021-07-09 18:01:46 -07:00
report, _ := generateCLIRaw(resps)
2020-11-01 22:32:12 +05:30
yamlReport, _ := yaml1.Marshal(report)
fmt.Println(string(yamlReport))
} else {
fmt.Println(divider)
fmt.Println("POLICY REPORT: skip generating policy report (no validate policy found/resource skipped)")
}
} else {
if !stdin {
fmt.Printf("\npass: %d, fail: %d, warn: %d, error: %d, skip: %d \n", rc.Pass, rc.Fail, rc.Warn, rc.Error, rc.Skip)
}
}
if rc.Fail > 0 || rc.Error > 0 {
osExit(1)
} else if rc.Warn > 0 && warnExitCode != 0 {
osExit(warnExitCode)
} else if rc.Pass == 0 && warnNoPassed {
osExit(warnExitCode)
}
}
2020-08-18 21:03:00 -07:00
// createFileOrFolder - creating file or folder according to path provided
2020-08-22 01:21:29 +05:30
func createFileOrFolder(mutateLogPath string, mutateLogPathIsDir bool) error {
mutateLogPath = filepath.Clean(mutateLogPath)
_, err := os.Stat(mutateLogPath)
if err != nil {
if os.IsNotExist(err) {
2020-08-22 01:21:29 +05:30
if !mutateLogPathIsDir {
2020-11-17 12:01:01 -08:00
// check the folder existence, then create the file
2020-07-21 10:33:38 +05:30
var folderPath string
2020-08-22 01:21:29 +05:30
s := strings.Split(mutateLogPath, "/")
2020-07-21 10:33:38 +05:30
if len(s) > 1 {
2020-08-22 01:21:29 +05:30
folderPath = mutateLogPath[:len(mutateLogPath)-len(s[len(s)-1])-1]
2020-07-21 10:33:38 +05:30
_, err := os.Stat(folderPath)
if os.IsNotExist(err) {
errDir := os.MkdirAll(folderPath, 0o750)
2020-07-21 10:33:38 +05:30
if errDir != nil {
return sanitizederror.NewWithError("failed to create directory", err)
2020-07-21 10:33:38 +05:30
}
}
}
mutateLogPath = filepath.Clean(mutateLogPath)
// Necessary for us to create the file via variable as it is part of the CLI.
file, err := os.OpenFile(mutateLogPath, os.O_RDONLY|os.O_CREATE, 0o600) // #nosec G304
if err != nil {
return sanitizederror.NewWithError("failed to create file", err)
}
err = file.Close()
if err != nil {
return sanitizederror.NewWithError("failed to close file", err)
}
} else {
errDir := os.MkdirAll(mutateLogPath, 0o750)
if errDir != nil {
return sanitizederror.NewWithError("failed to create directory", err)
}
}
} else {
return sanitizederror.NewWithError("failed to describe file", err)
}
}
return nil
}