mirror of
https://github.com/kyverno/kyverno.git
synced 2025-03-28 18:38:40 +00:00
remove Validate Cmd (#3674)
This commit is contained in:
parent
56c90fd087
commit
4cbfecc0d9
5 changed files with 0 additions and 1352 deletions
|
@ -7,7 +7,6 @@ import (
|
|||
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/apply"
|
||||
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/jp"
|
||||
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/test"
|
||||
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/validate"
|
||||
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/version"
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/klog/v2"
|
||||
|
@ -27,7 +26,6 @@ func main() {
|
|||
commands := []*cobra.Command{
|
||||
version.Command(),
|
||||
apply.Command(),
|
||||
validate.Command(),
|
||||
test.Command(),
|
||||
jp.Command(),
|
||||
}
|
||||
|
|
|
@ -2,10 +2,8 @@ package common
|
|||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"os"
|
||||
|
@ -35,7 +33,6 @@ import (
|
|||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
"k8s.io/apimachinery/pkg/util/yaml"
|
||||
"sigs.k8s.io/controller-runtime/pkg/log"
|
||||
k8syaml "sigs.k8s.io/yaml"
|
||||
)
|
||||
|
||||
type ResultCounts struct {
|
||||
|
@ -201,79 +198,6 @@ func MutatePolicy(policy v1.PolicyInterface, logger logr.Logger) (v1.PolicyInter
|
|||
return &p, nil
|
||||
}
|
||||
|
||||
// GetCRDs - Extracting the crds from multiple YAML
|
||||
func GetCRDs(paths []string) (unstructuredCrds []*unstructured.Unstructured, err error) {
|
||||
unstructuredCrds = make([]*unstructured.Unstructured, 0)
|
||||
for _, path := range paths {
|
||||
path = filepath.Clean(path)
|
||||
|
||||
fileDesc, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if fileDesc.IsDir() {
|
||||
files, err := ioutil.ReadDir(path)
|
||||
if err != nil {
|
||||
return nil, sanitizederror.NewWithError(fmt.Sprintf("failed to parse %v", path), err)
|
||||
}
|
||||
|
||||
listOfFiles := make([]string, 0)
|
||||
for _, file := range files {
|
||||
listOfFiles = append(listOfFiles, filepath.Join(path, file.Name()))
|
||||
}
|
||||
|
||||
policiesFromDir, err := GetCRDs(listOfFiles)
|
||||
if err != nil {
|
||||
return nil, sanitizederror.NewWithError(fmt.Sprintf("failed to extract crds from %v", listOfFiles), err)
|
||||
}
|
||||
|
||||
unstructuredCrds = append(unstructuredCrds, policiesFromDir...)
|
||||
} else {
|
||||
getCRDs, err := GetCRD(path)
|
||||
if err != nil {
|
||||
fmt.Printf("\nError: failed to extract crds from %s. \nCause: %s\n", path, err)
|
||||
os.Exit(2)
|
||||
}
|
||||
unstructuredCrds = append(unstructuredCrds, getCRDs...)
|
||||
}
|
||||
}
|
||||
return unstructuredCrds, nil
|
||||
}
|
||||
|
||||
// GetCRD - Extracts crds from a YAML
|
||||
func GetCRD(path string) (unstructuredCrds []*unstructured.Unstructured, err error) {
|
||||
path = filepath.Clean(path)
|
||||
unstructuredCrds = make([]*unstructured.Unstructured, 0)
|
||||
// We accept the risk of including a user provided file here.
|
||||
yamlbytes, err := ioutil.ReadFile(path) // #nosec G304
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
buf := bytes.NewBuffer(yamlbytes)
|
||||
reader := yaml.NewYAMLReader(bufio.NewReader(buf))
|
||||
|
||||
for {
|
||||
// Read one YAML document at a time, until io.EOF is returned
|
||||
b, err := reader.Read()
|
||||
if err == io.EOF || len(b) == 0 {
|
||||
break
|
||||
} else if err != nil {
|
||||
fmt.Printf("\nError: unable to read crd from %s. Cause: %s\n", path, err)
|
||||
os.Exit(2)
|
||||
}
|
||||
var u unstructured.Unstructured
|
||||
err = k8syaml.Unmarshal(b, &u)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
unstructuredCrds = append(unstructuredCrds, &u)
|
||||
}
|
||||
|
||||
return unstructuredCrds, nil
|
||||
}
|
||||
|
||||
// IsInputFromPipe - check if input is passed using pipe
|
||||
func IsInputFromPipe() bool {
|
||||
fileInfo, _ := os.Stdin.Stat()
|
||||
|
|
|
@ -1,691 +0,0 @@
|
|||
package crds
|
||||
|
||||
const PolicyCRD = `
|
||||
{
|
||||
"group": "kyverno.io",
|
||||
"names": {
|
||||
"kind": "Policy",
|
||||
"listKind": "PolicyList",
|
||||
"plural": "policies",
|
||||
"shortNames": [
|
||||
"pol"
|
||||
],
|
||||
"singular": "policy"
|
||||
},
|
||||
"scope": "Namespaced",
|
||||
"versions": [
|
||||
{
|
||||
"additionalPrinterColumns": [
|
||||
{
|
||||
"jsonPath": ".spec.background",
|
||||
"name": "Background",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"jsonPath": ".spec.validationFailureAction",
|
||||
"name": "Action",
|
||||
"type": "string"
|
||||
}
|
||||
],
|
||||
"name": "v1",
|
||||
"schema": {
|
||||
"openAPIV3Schema": {
|
||||
"description": "Policy declares validation, mutation, and generation behaviors for matching resources. See: https://kyverno.io/docs/writing-policies/ for more information.",
|
||||
"properties": {
|
||||
"apiVersion": {
|
||||
"description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources",
|
||||
"type": "string"
|
||||
},
|
||||
"kind": {
|
||||
"description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds",
|
||||
"type": "string"
|
||||
},
|
||||
"metadata": {
|
||||
"type": "object"
|
||||
},
|
||||
"spec": {
|
||||
"description": "Spec defines policy behaviors and contains one or rules.",
|
||||
"properties": {
|
||||
"background": {
|
||||
"description": "Background controls if rules are applied to existing resources during a background scan. Optional. Default value is \"true\". The value must be set to \"false\" if the policy rule uses variables that are only available in the admission review request (e.g. user name).",
|
||||
"type": "boolean"
|
||||
},
|
||||
"rules": {
|
||||
"description": "Rules is a list of Rule instances. A Policy contains multiple rules and each rule can validate, mutate, or generate resources.",
|
||||
"items": {
|
||||
"schema": {
|
||||
"description": "Rule defines a validation, mutation, or generation control for matching resources. Each rules contains a match declaration to select resources, and an optional exclude declaration to specify which resources to exclude.",
|
||||
"properties": {
|
||||
"context": {
|
||||
"description": "Context defines variables and data sources that can be used during rule execution.",
|
||||
"items": {
|
||||
"schema": {
|
||||
"description": "ContextEntry adds variables and data sources to a rule Context. Either a ConfigMap reference or a APILookup must be provided.",
|
||||
"properties": {
|
||||
"apiCall": {
|
||||
"description": "APICall defines an HTTP request to the Kubernetes API server. The JSON data retrieved is stored in the context.",
|
||||
"properties": {
|
||||
"jmesPath": {
|
||||
"description": "JMESPath is an optional JSON Match Expression that can be used to transform the JSON response returned from the API server. For example a JMESPath of \"items | length(@)\" applied to the API server response to the URLPath \"/apis/apps/v1/deployments\" will return the total count of deployments across all namespaces.",
|
||||
"type": "string"
|
||||
},
|
||||
"urlPath": {
|
||||
"description": "URLPath is the URL path to be used in the HTTP GET request to the Kubernetes API server (e.g. \"/api/v1/namespaces\" or \"/apis/apps/v1/deployments\"). The format required is the same format used by the 'kubectl get --raw' command.",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"urlPath"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"configMap": {
|
||||
"description": "ConfigMap is the ConfigMap reference.",
|
||||
"properties": {
|
||||
"name": {
|
||||
"description": "Name is the ConfigMap name.",
|
||||
"type": "string"
|
||||
},
|
||||
"namespace": {
|
||||
"description": "Namespace is the ConfigMap namespace.",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"name"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"name": {
|
||||
"description": "Name is the variable name.",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"exclude": {
|
||||
"description": "ExcludeResources defines when this policy rule should not be applied. The exclude criteria can include resource information (e.g. kind, name, namespace, labels) and admission review request information like the name or role.",
|
||||
"properties": {
|
||||
"clusterRoles": {
|
||||
"description": "ClusterRoles is the list of cluster-wide role names for the user.",
|
||||
"items": {
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"resources": {
|
||||
"description": "ResourceDescription contains information about the resource being created or modified.",
|
||||
"properties": {
|
||||
"annotations": {
|
||||
"description": "Annotations is a map of annotations (key-value pairs of type string). Annotation keys and values support the wildcard characters \"*\" (matches zero or many characters) and \"?\" (matches at least one character).",
|
||||
"type": "object"
|
||||
},
|
||||
"kinds": {
|
||||
"description": "Kinds is a list of resource kinds.",
|
||||
"items": {
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"name": {
|
||||
"description": "Name is the name of the resource. The name supports wildcard characters \"*\" (matches zero or many characters) and \"?\" (at least one character).",
|
||||
"type": "string"
|
||||
},
|
||||
"namespaceSelector": {
|
||||
"description": "NamespaceSelector is a label selector for the resource namespace. Label keys and values in 'matchLabels' support the wildcard characters '*' (matches zero or many characters) and '?' (matches one character).Wildcards allows writing label selectors like [\"storage.k8s.io/*\": \"*\"]. Note that using [\"*\" : \"*\"] matches any key and value but does not match an empty label set.",
|
||||
"properties": {
|
||||
"matchExpressions": {
|
||||
"description": "matchExpressions is a list of label selector requirements. The requirements are ANDed.",
|
||||
"items": {
|
||||
"schema": {
|
||||
"description": "A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values.",
|
||||
"properties": {
|
||||
"key": {
|
||||
"description": "key is the label key that the selector applies to.",
|
||||
"type": "string"
|
||||
},
|
||||
"operator": {
|
||||
"description": "operator represents a key's relationship to a set of values. Valid operators are In, AnyIn, AllIn, AnyIn, AllIn, NotIn, AnyNotIn, AllNotIn AnyNotIn, AllNotIn, Exists and DoesNotExist.",
|
||||
"type": "string"
|
||||
},
|
||||
"values": {
|
||||
"description": "values is an array of string values. If the operator is In, AnyIn, AllIn, NotIn, AnyNotIn or AllNotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. This array is replaced during a strategic merge patch.",
|
||||
"items": {
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"key",
|
||||
"operator"
|
||||
],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"matchLabels": {
|
||||
"description": "matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is \"key\", the operator is \"In\", and the values array contains only \"value\". The requirements are ANDed.",
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"namespaces": {
|
||||
"description": "Namespaces is a list of namespaces names. Each name supports wildcard characters \"*\" (matches zero or many characters) and \"?\" (at least one character).",
|
||||
"items": {
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"selector": {
|
||||
"description": "Selector is a label selector. Label keys and values in 'matchLabels' support the wildcard characters '*' (matches zero or many characters) and '?' (matches one character). Wildcards allows writing label selectors like [\"storage.k8s.io/*\": \"*\"]. Note that using [\"*\" : \"*\"] matches any key and value but does not match an empty label set.",
|
||||
"properties": {
|
||||
"matchExpressions": {
|
||||
"description": "matchExpressions is a list of label selector requirements. The requirements are ANDed.",
|
||||
"items": {
|
||||
"schema": {
|
||||
"description": "A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values.",
|
||||
"properties": {
|
||||
"key": {
|
||||
"description": "key is the label key that the selector applies to.",
|
||||
"type": "string"
|
||||
},
|
||||
"operator": {
|
||||
"description": "operator represents a key's relationship to a set of values. Valid operators are In, AnyIn, AllIn, AnyIn, AllIn, NotIn, AnyNotIn, AllNotIn AnyNotIn, AllNotIn, Exists and DoesNotExist.",
|
||||
"type": "string"
|
||||
},
|
||||
"values": {
|
||||
"description": "values is an array of string values. If the operator is In, AnyIn, AllIn, NotIn, AnyNotIn or AllNotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. This array is replaced during a strategic merge patch.",
|
||||
"items": {
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"key",
|
||||
"operator"
|
||||
],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"matchLabels": {
|
||||
"description": "matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is \"key\", the operator is \"In\", and the values array contains only \"value\". The requirements are ANDed.",
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"roles": {
|
||||
"description": "Roles is the list of namespaced role names for the user.",
|
||||
"items": {
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"subjects": {
|
||||
"description": "Subjects is the list of subject names like users, user groups, and service accounts.",
|
||||
"items": {
|
||||
"schema": {
|
||||
"description": "Subject contains a reference to the object or user identities a role binding applies to. This can either hold a direct API object reference, or a value for non-objects such as user and group names.",
|
||||
"properties": {
|
||||
"apiGroup": {
|
||||
"description": "APIGroup holds the API group of the referenced subject. Defaults to \"\" for ServiceAccount subjects. Defaults to \"rbac.authorization.k8s.io\" for User and Group subjects.",
|
||||
"type": "string"
|
||||
},
|
||||
"kind": {
|
||||
"description": "Kind of object being referenced. Values defined by this API group are \"User\", \"Group\", and \"ServiceAccount\". If the Authorizer does not recognized the kind value, the Authorizer should report an error.",
|
||||
"type": "string"
|
||||
},
|
||||
"name": {
|
||||
"description": "Name of the object being referenced.",
|
||||
"type": "string"
|
||||
},
|
||||
"namespace": {
|
||||
"description": "Namespace of the referenced object. If the object kind is non-namespace, such as \"User\" or \"Group\", and this value is not empty the Authorizer should report an error.",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"kind",
|
||||
"name"
|
||||
],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"generate": {
|
||||
"description": "Generation is used to create new resources.",
|
||||
"properties": {
|
||||
"apiVersion": {
|
||||
"description": "APIVersion specifies resource apiVersion.",
|
||||
"type": "string"
|
||||
},
|
||||
"clone": {
|
||||
"description": "Clone specifies the source resource used to populate each generated resource. At most one of Data or Clone can be specified. If neither are provided, the generated resource will be created with default data only.",
|
||||
"properties": {
|
||||
"name": {
|
||||
"description": "Name specifies name of the resource.",
|
||||
"type": "string"
|
||||
},
|
||||
"namespace": {
|
||||
"description": "Namespace specifies source resource namespace.",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"data": {
|
||||
"description": "Data provides the resource declaration used to populate each generated resource. At most one of Data or Clone must be specified. If neither are provided, the generated resource will be created with default data only.",
|
||||
"x-kubernetes-preserve-unknown-fields": true
|
||||
},
|
||||
"kind": {
|
||||
"description": "Kind specifies resource kind.",
|
||||
"type": "string"
|
||||
},
|
||||
"name": {
|
||||
"description": "Name specifies the resource name.",
|
||||
"type": "string"
|
||||
},
|
||||
"namespace": {
|
||||
"description": "Namespace specifies resource namespace.",
|
||||
"type": "string"
|
||||
},
|
||||
"synchronize": {
|
||||
"description": "Synchronize controls if generated resources should be kept in-sync with their source resource. If Synchronize is set to \"true\" changes to generated resources will be overwritten with resource data from Data or the resource specified in the Clone declaration. Optional. Defaults to \"false\" if not specified.",
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"match": {
|
||||
"description": "MatchResources defines when this policy rule should be applied. The match criteria can include resource information (e.g. kind, name, namespace, labels) and admission review request information like the user name or role. At least one kind is required.",
|
||||
"properties": {
|
||||
"clusterRoles": {
|
||||
"description": "ClusterRoles is the list of cluster-wide role names for the user.",
|
||||
"items": {
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"resources": {
|
||||
"description": "ResourceDescription contains information about the resource being created or modified. Requires at least one tag to be specified when under MatchResources.",
|
||||
"properties": {
|
||||
"annotations": {
|
||||
"description": "Annotations is a map of annotations (key-value pairs of type string). Annotation keys and values support the wildcard characters \"*\" (matches zero or many characters) and \"?\" (matches at least one character).",
|
||||
"type": "object"
|
||||
},
|
||||
"kinds": {
|
||||
"description": "Kinds is a list of resource kinds.",
|
||||
"items": {
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"name": {
|
||||
"description": "Name is the name of the resource. The name supports wildcard characters \"*\" (matches zero or many characters) and \"?\" (at least one character).",
|
||||
"type": "string"
|
||||
},
|
||||
"namespaceSelector": {
|
||||
"description": "NamespaceSelector is a label selector for the resource namespace. Label keys and values in 'matchLabels' support the wildcard characters '*' (matches zero or many characters) and '?' (matches one character).Wildcards allows writing label selectors like [\"storage.k8s.io/*\": \"*\"]. Note that using [\"*\" : \"*\"] matches any key and value but does not match an empty label set.",
|
||||
"properties": {
|
||||
"matchExpressions": {
|
||||
"description": "matchExpressions is a list of label selector requirements. The requirements are ANDed.",
|
||||
"items": {
|
||||
"schema": {
|
||||
"description": "A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values.",
|
||||
"properties": {
|
||||
"key": {
|
||||
"description": "key is the label key that the selector applies to.",
|
||||
"type": "string"
|
||||
},
|
||||
"operator": {
|
||||
"description": "operator represents a key's relationship to a set of values. Valid operators are In, AnyIn, AllIn, AnyIn, AllIn, NotIn, AnyNotIn, AllNotIn AnyNotIn, AllNotIn, Exists and DoesNotExist.",
|
||||
"type": "string"
|
||||
},
|
||||
"values": {
|
||||
"description": "values is an array of string values. If the operator is In, AnyIn, AllIn, NotIn, AnyNotIn or AllNotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. This array is replaced during a strategic merge patch.",
|
||||
"items": {
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"key",
|
||||
"operator"
|
||||
],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"matchLabels": {
|
||||
"description": "matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is \"key\", the operator is \"In\", and the values array contains only \"value\". The requirements are ANDed.",
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"namespaces": {
|
||||
"description": "Namespaces is a list of namespaces names. Each name supports wildcard characters \"*\" (matches zero or many characters) and \"?\" (at least one character).",
|
||||
"items": {
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"selector": {
|
||||
"description": "Selector is a label selector. Label keys and values in 'matchLabels' support the wildcard characters '*' (matches zero or many characters) and '?' (matches one character). Wildcards allows writing label selectors like [\"storage.k8s.io/*\": \"*\"]. Note that using [\"*\" : \"*\"] matches any key and value but does not match an empty label set.",
|
||||
"properties": {
|
||||
"matchExpressions": {
|
||||
"description": "matchExpressions is a list of label selector requirements. The requirements are ANDed.",
|
||||
"items": {
|
||||
"schema": {
|
||||
"description": "A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values.",
|
||||
"properties": {
|
||||
"key": {
|
||||
"description": "key is the label key that the selector applies to.",
|
||||
"type": "string"
|
||||
},
|
||||
"operator": {
|
||||
"description": "operator represents a key's relationship to a set of values. Valid operators are In, AnyIn, AllIn, AnyIn, AllIn, NotIn, AnyNotIn, AllNotIn AnyNotIn, AllNotIn, Exists and DoesNotExist.",
|
||||
"type": "string"
|
||||
},
|
||||
"values": {
|
||||
"description": "values is an array of string values. If the operator is In, AnyIn, AllIn, NotIn, AnyNotIn or AllNotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. This array is replaced during a strategic merge patch.",
|
||||
"items": {
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"key",
|
||||
"operator"
|
||||
],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"matchLabels": {
|
||||
"description": "matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is \"key\", the operator is \"In\", and the values array contains only \"value\". The requirements are ANDed.",
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"roles": {
|
||||
"description": "Roles is the list of namespaced role names for the user.",
|
||||
"items": {
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"subjects": {
|
||||
"description": "Subjects is the list of subject names like users, user groups, and service accounts.",
|
||||
"items": {
|
||||
"schema": {
|
||||
"description": "Subject contains a reference to the object or user identities a role binding applies to. This can either hold a direct API object reference, or a value for non-objects such as user and group names.",
|
||||
"properties": {
|
||||
"apiGroup": {
|
||||
"description": "APIGroup holds the API group of the referenced subject. Defaults to \"\" for ServiceAccount subjects. Defaults to \"rbac.authorization.k8s.io\" for User and Group subjects.",
|
||||
"type": "string"
|
||||
},
|
||||
"kind": {
|
||||
"description": "Kind of object being referenced. Values defined by this API group are \"User\", \"Group\", and \"ServiceAccount\". If the Authorizer does not recognized the kind value, the Authorizer should report an error.",
|
||||
"type": "string"
|
||||
},
|
||||
"name": {
|
||||
"description": "Name of the object being referenced.",
|
||||
"type": "string"
|
||||
},
|
||||
"namespace": {
|
||||
"description": "Namespace of the referenced object. If the object kind is non-namespace, such as \"User\" or \"Group\", and this value is not empty the Authorizer should report an error.",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"kind",
|
||||
"name"
|
||||
],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"mutate": {
|
||||
"description": "Mutation is used to modify matching resources.",
|
||||
"properties": {
|
||||
"overlay": {
|
||||
"description": "Overlay specifies an overlay pattern to modify resources. DEPRECATED. Use PatchStrategicMerge instead. Scheduled for removal in release 1.5+.",
|
||||
"x-kubernetes-preserve-unknown-fields": true
|
||||
},
|
||||
"patchStrategicMerge": {
|
||||
"description": "PatchStrategicMerge is a strategic merge patch used to modify resources. See https://kubernetes.io/docs/tasks/manage-kubernetes-objects/update-api-object-kubectl-patch/ and https://kubectl.docs.kubernetes.io/references/kustomize/patchesstrategicmerge/.",
|
||||
"x-kubernetes-preserve-unknown-fields": true
|
||||
},
|
||||
"patches": {
|
||||
"description": "Patches specifies a RFC 6902 JSON Patch to modify resources. DEPRECATED. Use PatchesJSON6902 instead. Scheduled for removal in release 1.5+.",
|
||||
"items": {
|
||||
"schema": {
|
||||
"description": "Patch is a RFC 6902 JSON Patch. See: https://tools.ietf.org/html/rfc6902",
|
||||
"properties": {
|
||||
"op": {
|
||||
"description": "Operation specifies operations supported by JSON Patch. i.e:- add, replace and delete.",
|
||||
"type": "string"
|
||||
},
|
||||
"path": {
|
||||
"description": "Path specifies path of the resource.",
|
||||
"type": "string"
|
||||
},
|
||||
"value": {
|
||||
"description": "Value specifies the value to be applied.",
|
||||
"x-kubernetes-preserve-unknown-fields": true
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"nullable": true,
|
||||
"type": "array",
|
||||
"x-kubernetes-preserve-unknown-fields": true
|
||||
},
|
||||
"patchesJson6902": {
|
||||
"description": "PatchesJSON6902 is a list of RFC 6902 JSON Patch declarations used to modify resources. See https://tools.ietf.org/html/rfc6902 and https://kubectl.docs.kubernetes.io/references/kustomize/patchesjson6902/.",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"name": {
|
||||
"description": "Name is a label to identify the rule, It must be unique within the policy.",
|
||||
"maxLength": 63,
|
||||
"type": "string"
|
||||
},
|
||||
"preconditions": {
|
||||
"description": "AnyAllConditions enable variable-based conditional rule execution. This is useful for finer control of when an rule is applied. A condition can reference object data using JMESPath notation. This too can be made to happen in a logical-manner where in some situation all the conditions need to pass and in some other situation, atleast one condition is enough to pass. For the sake of backwards compatibility, it can be populated with []kyverno.Condition.",
|
||||
"x-kubernetes-preserve-unknown-fields": true
|
||||
},
|
||||
"validate": {
|
||||
"description": "Validation is used to validate matching resources.",
|
||||
"properties": {
|
||||
"anyPattern": {
|
||||
"description": "AnyPattern specifies list of validation patterns. At least one of the patterns must be satisfied for the validation rule to succeed.",
|
||||
"x-kubernetes-preserve-unknown-fields": true
|
||||
},
|
||||
"deny": {
|
||||
"description": "Deny defines conditions to fail the validation rule.",
|
||||
"properties": {
|
||||
"conditions": {
|
||||
"description": "specifies the set of conditions to deny in a logical manner For the sake of backwards compatibility, it can be populated with []kyverno.Condition.",
|
||||
"x-kubernetes-preserve-unknown-fields": true
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"message": {
|
||||
"description": "Message specifies a custom message to be displayed on failure.",
|
||||
"type": "string"
|
||||
},
|
||||
"pattern": {
|
||||
"description": "Pattern specifies an overlay-style pattern used to check resources.",
|
||||
"x-kubernetes-preserve-unknown-fields": true
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"validationFailureAction": {
|
||||
"description": "ValidationFailureAction controls if a validation policy rule failure should disallow the admission review request (enforce), or allow (audit) the admission review request and report an error in a policy report. Optional. The default value is \"audit\".",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"status": {
|
||||
"description": "Status contains policy runtime information.",
|
||||
"properties": {
|
||||
"averageExecutionTime": {
|
||||
"description": "AvgExecutionTime is the average time taken to process the policy rules on a resource.",
|
||||
"type": "string"
|
||||
},
|
||||
"resourcesBlockedCount": {
|
||||
"description": "ResourcesBlockedCount is the total count of admission review requests that were blocked by this policy.",
|
||||
"type": "integer"
|
||||
},
|
||||
"resourcesGeneratedCount": {
|
||||
"description": "ResourcesGeneratedCount is the total count of resources that were generated by this policy.",
|
||||
"type": "integer"
|
||||
},
|
||||
"resourcesMutatedCount": {
|
||||
"description": "ResourcesMutatedCount is the total count of resources that were mutated by this policy.",
|
||||
"type": "integer"
|
||||
},
|
||||
"ruleStatus": {
|
||||
"description": "Rules provides per rule statistics",
|
||||
"items": {
|
||||
"schema": {
|
||||
"description": "RuleStats provides statistics for an individual rule within a policy.",
|
||||
"properties": {
|
||||
"appliedCount": {
|
||||
"description": "AppliedCount is the total number of times this rule was applied.",
|
||||
"type": "integer"
|
||||
},
|
||||
"averageExecutionTime": {
|
||||
"description": "ExecutionTime is the average time taken to execute this rule.",
|
||||
"type": "string"
|
||||
},
|
||||
"failedCount": {
|
||||
"description": "FailedCount is the total count of policy error results for this rule.",
|
||||
"type": "integer"
|
||||
},
|
||||
"resourcesBlockedCount": {
|
||||
"description": "ResourcesBlockedCount is the total count of admission review requests that were blocked by this rule.",
|
||||
"type": "integer"
|
||||
},
|
||||
"resourcesGeneratedCount": {
|
||||
"description": "ResourcesGeneratedCount is the total count of resources that were generated by this rule.",
|
||||
"type": "integer"
|
||||
},
|
||||
"resourcesMutatedCount": {
|
||||
"description": "ResourcesMutatedCount is the total count of resources that were mutated by this rule.",
|
||||
"type": "integer"
|
||||
},
|
||||
"ruleName": {
|
||||
"description": "Name is the rule name.",
|
||||
"type": "string"
|
||||
},
|
||||
"violationCount": {
|
||||
"description": "ViolationCount is the total count of policy failure results for this rule.",
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"ruleName"
|
||||
],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"rulesAppliedCount": {
|
||||
"description": "RulesAppliedCount is the total number of times this policy was applied.",
|
||||
"type": "integer"
|
||||
},
|
||||
"rulesFailedCount": {
|
||||
"description": "RulesFailedCount is the total count of policy execution errors for this policy.",
|
||||
"type": "integer"
|
||||
},
|
||||
"violationCount": {
|
||||
"description": "ViolationCount is the total count of policy failure results for this policy.",
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"spec"
|
||||
],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"served": true,
|
||||
"storage": true,
|
||||
"subresources": {
|
||||
"status": {}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
`
|
|
@ -1,203 +0,0 @@
|
|||
package validate
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
v1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/utils/common"
|
||||
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/utils/crds"
|
||||
sanitizederror "github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/utils/sanitizedError"
|
||||
"github.com/kyverno/kyverno/pkg/openapi"
|
||||
policy2 "github.com/kyverno/kyverno/pkg/policy"
|
||||
"github.com/kyverno/kyverno/pkg/utils"
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
|
||||
apiservervalidation "k8s.io/apiextensions-apiserver/pkg/apiserver/validation"
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
"k8s.io/apimachinery/pkg/util/validation/field"
|
||||
"sigs.k8s.io/controller-runtime/pkg/log"
|
||||
"sigs.k8s.io/yaml"
|
||||
)
|
||||
|
||||
// Command returns validate command
|
||||
func Command() *cobra.Command {
|
||||
var outputType string
|
||||
var crdPaths []string
|
||||
cmd := &cobra.Command{
|
||||
Use: "validate",
|
||||
Short: "Validates kyverno policies",
|
||||
Example: "kyverno validate /path/to/policy.yaml /path/to/folderOfPolicies",
|
||||
RunE: func(cmd *cobra.Command, policyPaths []string) (err error) {
|
||||
defer func() {
|
||||
if err != nil {
|
||||
if !sanitizederror.IsErrorSanitized(err) {
|
||||
log.Log.Error(err, "failed to sanitize")
|
||||
err = fmt.Errorf("internal error")
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
if outputType != "" {
|
||||
if outputType != "yaml" && outputType != "json" {
|
||||
return sanitizederror.NewWithError(fmt.Sprintf("%s format is not supported", outputType), errors.New("yaml and json are supported"))
|
||||
}
|
||||
}
|
||||
|
||||
if len(policyPaths) == 0 {
|
||||
return sanitizederror.NewWithError(fmt.Sprintf("policy file(s) required"), err)
|
||||
}
|
||||
|
||||
policies, err := getPolicyFromGivenPath(policyPaths)
|
||||
if err != nil {
|
||||
return sanitizederror.NewWithError("failed to parse policy", err)
|
||||
}
|
||||
|
||||
v1crd, err := getPolicyCRD()
|
||||
if err != nil {
|
||||
return sanitizederror.NewWithError("failed to decode crd: ", err)
|
||||
}
|
||||
|
||||
openAPIController, err := openapi.NewOpenAPIController()
|
||||
if err != nil {
|
||||
return sanitizederror.NewWithError("failed to initialize openAPIController", err)
|
||||
}
|
||||
|
||||
// if CRD's are passed, add these to OpenAPIController
|
||||
if len(crdPaths) > 0 {
|
||||
crds, err := common.GetCRDs(crdPaths)
|
||||
if err != nil {
|
||||
fmt.Printf("\nError: crd is invalid. \nFile: %s \nCause: %s\n", crdPaths, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
for _, crd := range crds {
|
||||
openAPIController.ParseCRD(*crd)
|
||||
}
|
||||
}
|
||||
|
||||
err = validatePolicies(policies, v1crd, openAPIController, outputType)
|
||||
if err != nil {
|
||||
return sanitizederror.NewWithError("failed to validate policies", err)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVarP(&outputType, "output", "o", "", "Prints the mutated policy in yaml or json format")
|
||||
cmd.Flags().StringArrayVarP(&crdPaths, "crd", "c", []string{}, "Path to CRD files")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func getPolicyFromGivenPath(policyPaths []string) (policies []v1.PolicyInterface, err error) {
|
||||
var errs []error
|
||||
if policyPaths[0] == "-" {
|
||||
if common.IsInputFromPipe() {
|
||||
policyStr := ""
|
||||
scanner := bufio.NewScanner(os.Stdin)
|
||||
for scanner.Scan() {
|
||||
policyStr = policyStr + scanner.Text() + "\n"
|
||||
}
|
||||
|
||||
yamlBytes := []byte(policyStr)
|
||||
policies, err = utils.GetPolicy(yamlBytes)
|
||||
if err != nil {
|
||||
return policies, sanitizederror.NewWithError("failed to parse policy", err)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
policies, errs = common.GetPolicies(policyPaths)
|
||||
if len(errs) > 0 && len(policies) == 0 {
|
||||
return policies, sanitizederror.NewWithErrors("failed to parse policies", errs)
|
||||
}
|
||||
|
||||
if len(errs) > 0 && log.Log.V(1).Enabled() {
|
||||
fmt.Printf("ignoring errors: \n")
|
||||
for _, e := range errs {
|
||||
fmt.Printf(" %v \n", e.Error())
|
||||
}
|
||||
}
|
||||
}
|
||||
return policies, nil
|
||||
}
|
||||
|
||||
func getPolicyCRD() (v1crd apiextensions.CustomResourceDefinitionSpec, err error) {
|
||||
if err = json.Unmarshal([]byte(crds.PolicyCRD), &v1crd); err != nil {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func validatePolicyAccordingToPolicyCRD(policy v1.PolicyInterface, v1crd apiextensions.CustomResourceDefinitionSpec) (err error, errList field.ErrorList) {
|
||||
policyBytes, err := json.Marshal(policy)
|
||||
if err != nil {
|
||||
return sanitizederror.NewWithError("failed to marshal policy", err), nil
|
||||
}
|
||||
|
||||
u := &unstructured.Unstructured{}
|
||||
err = u.UnmarshalJSON(policyBytes)
|
||||
if err != nil {
|
||||
return sanitizederror.NewWithError("failed to decode policy", err), nil
|
||||
}
|
||||
|
||||
versions := v1crd.Versions
|
||||
for _, version := range versions {
|
||||
validator, _, err := apiservervalidation.NewSchemaValidator(&apiextensions.CustomResourceValidation{OpenAPIV3Schema: version.Schema.OpenAPIV3Schema})
|
||||
if err != nil {
|
||||
return sanitizederror.NewWithError("failed to create schema validator", err), nil
|
||||
}
|
||||
|
||||
errList = apiservervalidation.ValidateCustomResource(nil, u.UnstructuredContent(), validator)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func validatePolicies(policies []v1.PolicyInterface, v1crd apiextensions.CustomResourceDefinitionSpec, openAPIController *openapi.Controller, outputType string) error {
|
||||
invalidPolicyFound := false
|
||||
for _, policy := range policies {
|
||||
err, errorList := validatePolicyAccordingToPolicyCRD(policy, v1crd)
|
||||
if err != nil {
|
||||
return sanitizederror.NewWithError("failed to validate policy.", err)
|
||||
}
|
||||
|
||||
if errorList == nil {
|
||||
_, err = policy2.Validate(policy, nil, true, openAPIController)
|
||||
}
|
||||
|
||||
fmt.Println("----------------------------------------------------------------------")
|
||||
if errorList != nil || err != nil {
|
||||
fmt.Printf("Policy %s is invalid.\n", policy.GetName())
|
||||
if errorList != nil {
|
||||
fmt.Printf("Error: invalid policy.\nCause: %s\n\n", errorList)
|
||||
} else {
|
||||
fmt.Printf("Error: invalid policy.\nCause: %s\n\n", err)
|
||||
}
|
||||
invalidPolicyFound = true
|
||||
} else {
|
||||
fmt.Printf("Policy %s is valid.\n\n", policy.GetName())
|
||||
if outputType != "" {
|
||||
logger := log.Log.WithName("validate")
|
||||
p, err := common.MutatePolicy(policy, logger)
|
||||
if err != nil {
|
||||
if !sanitizederror.IsErrorSanitized(err) {
|
||||
return sanitizederror.NewWithError("failed to mutate policy.", err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
if outputType == "yaml" {
|
||||
yamlPolicy, _ := yaml.Marshal(p)
|
||||
fmt.Println(string(yamlPolicy))
|
||||
} else {
|
||||
jsonPolicy, _ := json.MarshalIndent(p, "", " ")
|
||||
fmt.Println(string(jsonPolicy))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if invalidPolicyFound {
|
||||
os.Exit(1)
|
||||
}
|
||||
return nil
|
||||
}
|
|
@ -1,380 +0,0 @@
|
|||
package validate
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"gotest.tools/assert"
|
||||
)
|
||||
|
||||
func Test_validateUsingPolicyCRD(t *testing.T) {
|
||||
type TestCase struct {
|
||||
rawPolicy []byte
|
||||
errorDetail string
|
||||
detail string
|
||||
}
|
||||
|
||||
testcases := []TestCase{
|
||||
{
|
||||
rawPolicy: []byte(`
|
||||
{
|
||||
"apiVersion": "kyverno.io/v1",
|
||||
"kind": "ClusterPolicy",
|
||||
"metadata": {
|
||||
"name": "add-requests"
|
||||
},
|
||||
"spec": {
|
||||
"rules": [
|
||||
{
|
||||
"name": "Set memory and/or cpu requests for all pods in namespaces labeled 'myprivatelabel'",
|
||||
"match": {
|
||||
"resources": {
|
||||
"kinds": [
|
||||
"Pod"
|
||||
]
|
||||
}
|
||||
},
|
||||
"mutate": {
|
||||
"overlay": {
|
||||
"spec": {
|
||||
"containers": [
|
||||
{
|
||||
"(name)": "*",
|
||||
"resources": {
|
||||
"requests": {
|
||||
"cpu": "1000m"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
`),
|
||||
errorDetail: "spec.rules[0].name in body should be at most 63 chars long",
|
||||
detail: "Test: char count for rule name",
|
||||
},
|
||||
|
||||
{
|
||||
rawPolicy: []byte(`
|
||||
{
|
||||
"apiVersion": "kyverno.io/v1",
|
||||
"kind": "ClusterPolicy",
|
||||
"metadata": {
|
||||
"name": "min-replicas-clusterpolicy"
|
||||
},
|
||||
"spec": {
|
||||
"validationFailureAction": "audit",
|
||||
"rules": [
|
||||
{
|
||||
"name": "check-min-replicas",
|
||||
"match": {
|
||||
"resources": {
|
||||
"kinds": [
|
||||
"Deployment"
|
||||
]
|
||||
}
|
||||
},
|
||||
"validate": {
|
||||
"message": "should have at least 2 replicas",
|
||||
"pattern": {
|
||||
"spec": {
|
||||
"replicas": 2
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
`),
|
||||
errorDetail: "",
|
||||
detail: "Test: basic vaild policy",
|
||||
},
|
||||
|
||||
{
|
||||
rawPolicy: []byte(`
|
||||
{
|
||||
"apiVersion": "kyverno.io/v1",
|
||||
"kind": "ClusterPolicy",
|
||||
"metadata": {
|
||||
"name": "disallow-singleton"
|
||||
},
|
||||
"spec": {
|
||||
"validationFailureAction": "audit",
|
||||
"rules": [
|
||||
{
|
||||
"name": "validate-replicas",
|
||||
"match": {
|
||||
"resources": {
|
||||
"kinds": [
|
||||
"Deployment"
|
||||
],
|
||||
"annotations": {
|
||||
"singleton": "true"
|
||||
}
|
||||
}
|
||||
},
|
||||
"validate": {
|
||||
"message": "Replicasets require at least 2 replicas.",
|
||||
"pattern": {
|
||||
"spec": {
|
||||
"replicas": ">1"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
`),
|
||||
errorDetail: "",
|
||||
detail: "Test: schema validation for spec.rules.match.resources.annotations",
|
||||
},
|
||||
|
||||
{
|
||||
rawPolicy: []byte(`
|
||||
{
|
||||
"apiVersion": "kyverno.io/v1",
|
||||
"kind": "ClusterPolicy",
|
||||
"metadata": {
|
||||
"name": "disallow-singleton"
|
||||
},
|
||||
"spec": {
|
||||
"validationFailureAction": "audit",
|
||||
"rules": [
|
||||
{
|
||||
"name": "validate-replicas",
|
||||
"match": {
|
||||
"resources": {
|
||||
"kinds": [
|
||||
"Deployment"
|
||||
]
|
||||
}
|
||||
},
|
||||
"exclude": {
|
||||
"resources": {
|
||||
"annotations": {
|
||||
"singleton": "true"
|
||||
}
|
||||
}
|
||||
},
|
||||
"validate": {
|
||||
"message": "Replicasets require at least 2 replicas.",
|
||||
"pattern": {
|
||||
"spec": {
|
||||
"replicas": ">1"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
`),
|
||||
errorDetail: "",
|
||||
detail: "Test: schema validation for spec.rules.exclude.resources.annotations",
|
||||
},
|
||||
|
||||
{
|
||||
rawPolicy: []byte(`
|
||||
{
|
||||
"apiVersion": "kyverno.io/v1",
|
||||
"kind": "ClusterPolicy",
|
||||
"metadata": {
|
||||
"name": "enforce-pod-name"
|
||||
},
|
||||
"spec": {
|
||||
"validationFailureAction": "audit",
|
||||
"background": true,
|
||||
"rules": [
|
||||
{
|
||||
"name": "validate-name",
|
||||
"match": {
|
||||
"resources": {
|
||||
"kinds": [
|
||||
"Pod"
|
||||
],
|
||||
"namespaceSelector": {
|
||||
"matchLabels": {
|
||||
"app-namespace": "true"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"validate": {
|
||||
"message": "The Pod must end with -nginx",
|
||||
"pattern": {
|
||||
"metadata": {
|
||||
"name": "*-nginx"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
`),
|
||||
errorDetail: "",
|
||||
detail: "Test: schema validation for spec.rules.match.resources.namespaceSelector.matchLabels",
|
||||
},
|
||||
|
||||
{
|
||||
rawPolicy: []byte(`
|
||||
{
|
||||
"apiVersion": "kyverno.io/v1",
|
||||
"kind": "ClusterPolicy",
|
||||
"metadata": {
|
||||
"name": "enforce-pod-name"
|
||||
},
|
||||
"spec": {
|
||||
"validationFailureAction": "audit",
|
||||
"background": true,
|
||||
"rules": [
|
||||
{
|
||||
"name": "validate-name",
|
||||
"match": {
|
||||
"resources": {
|
||||
"kinds": [
|
||||
"Pod"
|
||||
]
|
||||
}
|
||||
},
|
||||
"exclude": {
|
||||
"resources": {
|
||||
"namespaceSelector": {
|
||||
"matchLabels": {
|
||||
"app-namespace": "true"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"validate": {
|
||||
"message": "The Pod must end with -nginx",
|
||||
"pattern": {
|
||||
"metadata": {
|
||||
"name": "*-nginx"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
`),
|
||||
errorDetail: "",
|
||||
detail: "Test: schema validation for spec.rules.exclude.resources.namespaceSelector.matchLabels",
|
||||
},
|
||||
|
||||
{
|
||||
rawPolicy: []byte(`
|
||||
{
|
||||
"apiVersion": "kyverno.io/v1",
|
||||
"kind": "ClusterPolicy",
|
||||
"metadata": {
|
||||
"name": "enforce-pod-name"
|
||||
},
|
||||
"spec": {
|
||||
"validationFailureAction": "audit",
|
||||
"background": true,
|
||||
"rules": [
|
||||
{
|
||||
"name": "validate-name",
|
||||
"match": {
|
||||
"resources": {
|
||||
"kinds": [
|
||||
"Pod"
|
||||
],
|
||||
"selector": {
|
||||
"matchLabels": {
|
||||
"app-namespace": "true"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"validate": {
|
||||
"message": "The Pod must end with -nginx",
|
||||
"pattern": {
|
||||
"metadata": {
|
||||
"name": "*-nginx"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
`),
|
||||
errorDetail: "",
|
||||
detail: "Test: schema validation for spec.rules.match.resources.selector.matchLabels",
|
||||
},
|
||||
|
||||
{
|
||||
rawPolicy: []byte(`
|
||||
{
|
||||
"apiVersion": "kyverno.io/v1",
|
||||
"kind": "ClusterPolicy",
|
||||
"metadata": {
|
||||
"name": "enforce-pod-name"
|
||||
},
|
||||
"spec": {
|
||||
"validationFailureAction": "audit",
|
||||
"background": true,
|
||||
"rules": [
|
||||
{
|
||||
"name": "validate-name",
|
||||
"match": {
|
||||
"resources": {
|
||||
"kinds": [
|
||||
"Pod"
|
||||
]
|
||||
}
|
||||
},
|
||||
"exclude": {
|
||||
"resources": {
|
||||
"selector": {
|
||||
"matchLabels": {
|
||||
"app-namespace": "true"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"validate": {
|
||||
"message": "The Pod must end with -nginx",
|
||||
"pattern": {
|
||||
"metadata": {
|
||||
"name": "*-nginx"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
`),
|
||||
errorDetail: "",
|
||||
detail: "Test: schema validation for spec.rules.exclude.resources.selector.matchLabels",
|
||||
},
|
||||
}
|
||||
|
||||
v1crd, err := getPolicyCRD()
|
||||
assert.NilError(t, err)
|
||||
|
||||
var policy kyverno.ClusterPolicy
|
||||
for _, tc := range testcases {
|
||||
err = json.Unmarshal(tc.rawPolicy, &policy)
|
||||
assert.NilError(t, err)
|
||||
|
||||
_, errorList := validatePolicyAccordingToPolicyCRD(&policy, v1crd)
|
||||
fmt.Println(tc.detail)
|
||||
for _, e := range errorList {
|
||||
assert.Assert(t, tc.errorDetail == e.Detail)
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Reference in a new issue