Skip to content

Commit

Permalink
added skipped policy in policy report
Browse files Browse the repository at this point in the history
  • Loading branch information
NoSkillGirl committed Nov 19, 2020
1 parent 5ae1a7a commit 3571260
Show file tree
Hide file tree
Showing 4 changed files with 70 additions and 10 deletions.
41 changes: 35 additions & 6 deletions pkg/kyverno/apply/command.go
Expand Up @@ -53,6 +53,11 @@ type Values struct {
Policies []Policy `json:"policies"`
}

type SkippedPolicy struct {
Name string `json:"name"`
Variable string `json:"variable"`
}

func Command() *cobra.Command {
var cmd *cobra.Command
var resourcePaths []string
Expand Down Expand Up @@ -158,6 +163,8 @@ func Command() *cobra.Command {
rc := &resultCounts{}
engineResponses := make([]response.EngineResponse, 0)
validateEngineResponses := make([]response.EngineResponse, 0)
skippedPolicies := make([]SkippedPolicy, 0)

for _, policy := range mutatedPolicies {
err := policy2.Validate(utils.MarshalPolicy(*policy), nil, true, openAPIController)
if err != nil {
Expand All @@ -166,8 +173,16 @@ func Command() *cobra.Command {
continue
}

if common.PolicyHasVariables(*policy) && variablesString == "" && valuesFile == "" {
fmt.Printf("\n------------------------\nskipping policy %s as it has variable. pass the values for the variables using set/values_file flag\n------------------------\n", policy.Name)
matches := common.PolicyHasVariables(*policy)
variable := removeDuplicatevariables(matches)

if len(matches) > 0 && variablesString == "" && valuesFile == "" {
skipPolicy := SkippedPolicy{
Name: policy.GetName(),
Variable: variable,
}
skippedPolicies = append(skippedPolicies, skipPolicy)
// fmt.Printf("\n------------------------\nskipping policy %s as it has variable. pass the values for the variables using set/values_file flag\n------------------------\n", policy.Name)
continue
}

Expand All @@ -182,7 +197,7 @@ func Command() *cobra.Command {
thisPolicyResourceValues[k] = v
}

if common.PolicyHasVariables(*policy) && len(thisPolicyResourceValues) == 0 {
if len(common.PolicyHasVariables(*policy)) > 0 && len(thisPolicyResourceValues) == 0 {
return sanitizedError.NewWithError(fmt.Sprintf("policy %s have variables. pass the values for the variables using set/values_file flag", policy.Name), err)
}

Expand All @@ -195,7 +210,7 @@ func Command() *cobra.Command {
}
}

printReportOrViolation(policyReport, validateEngineResponses, rc, resourcePaths, len(resources))
printReportOrViolation(policyReport, validateEngineResponses, rc, resourcePaths, len(resources), skippedPolicies)

return nil
},
Expand Down Expand Up @@ -297,10 +312,10 @@ func getResourceAccordingToResourcePath(resourcePaths []string, cluster bool, po
}

// printReportOrViolation - printing policy report/violations
func printReportOrViolation(policyReport bool, validateEngineResponses []response.EngineResponse, rc *resultCounts, resourcePaths []string, resourcesLen int) {
func printReportOrViolation(policyReport bool, validateEngineResponses []response.EngineResponse, rc *resultCounts, resourcePaths []string, resourcesLen int, skippedPolicies []SkippedPolicy) {
if policyReport {
os.Setenv("POLICY-TYPE", pkgCommon.PolicyReport)
resps := buildPolicyReports(validateEngineResponses)
resps := buildPolicyReports(validateEngineResponses, skippedPolicies)
if len(resps) > 0 || resourcesLen == 0 {
fmt.Println("----------------------------------------------------------------------\nPOLICY REPORT:\n----------------------------------------------------------------------")
report, _ := generateCLIraw(resps)
Expand Down Expand Up @@ -525,3 +540,17 @@ func createFileOrFolder(mutateLogPath string, mutateLogPathIsDir bool) error {

return nil
}

// removeDuplicatevariables - remove duplicate variables
func removeDuplicatevariables(matches [][]string) string {
var variableStr string
for _, m := range matches {
for _, v := range m {
foundVariable := strings.Contains(variableStr, v)
if !foundVariable {
variableStr = variableStr + " " + v
}
}
}
return variableStr
}
33 changes: 32 additions & 1 deletion pkg/kyverno/apply/report.go
Expand Up @@ -18,10 +18,41 @@ import (
const clusterpolicyreport = "clusterpolicyreport"

// resps is the engine responses generated for a single policy
func buildPolicyReports(resps []response.EngineResponse) (res []*unstructured.Unstructured) {
func buildPolicyReports(resps []response.EngineResponse, skippedPolicies []SkippedPolicy) (res []*unstructured.Unstructured) {
var raw []byte
var err error

for _, sp := range skippedPolicies {
result := []*report.PolicyReportResult{
{
Message: fmt.Sprintln("policy skipped. policy has variable -", sp.Variable),
Policy: sp.Name,
Status: "skip",
},
}

report := &report.PolicyReport{
TypeMeta: metav1.TypeMeta{
APIVersion: report.SchemeGroupVersion.String(),
Kind: "PolicyReport",
},
Results: result,
}

if raw, err = json.Marshal(report); err != nil {
log.Log.Error(err, "failed to serilize policy report")
continue
}

reportUnstructured, err := engineutils.ConvertToUnstructured(raw)
if err != nil {
log.Log.Error(err, "failed to convert policy report")
continue
}

res = append(res, reportUnstructured)
}

resultsMap := buildPolicyResults(resps)
for scope, result := range resultsMap {
if scope == clusterpolicyreport {
Expand Down
4 changes: 2 additions & 2 deletions pkg/kyverno/common/common.go
Expand Up @@ -81,10 +81,10 @@ func ValidateAndGetPolicies(policyPaths []string) ([]*v1.ClusterPolicy, error) {
}

// PolicyHasVariables - check for variables in the policy
func PolicyHasVariables(policy v1.ClusterPolicy) bool {
func PolicyHasVariables(policy v1.ClusterPolicy) [][]string {
policyRaw, _ := json.Marshal(policy)
matches := RegexVariables.FindAllStringSubmatch(string(policyRaw), -1)
return len(matches) > 0
return matches
}

// PolicyHasNonAllowedVariables - checks for unexpected variables in the policy
Expand Down
2 changes: 1 addition & 1 deletion pkg/policy/validate.go
Expand Up @@ -33,7 +33,7 @@ func Validate(policyRaw []byte, client *dclient.Client, mock bool, openAPIContro
return fmt.Errorf("failed to unmarshal policy: %v", err)
}

if common.PolicyHasVariables(p) && common.PolicyHasNonAllowedVariables(p) {
if len(common.PolicyHasVariables(p)) > 0 && common.PolicyHasNonAllowedVariables(p) {
return fmt.Errorf("policy contains unknown variables")
}

Expand Down

0 comments on commit 3571260

Please sign in to comment.