1
0
Fork 0
mirror of https://github.com/kyverno/kyverno.git synced 2025-03-06 16:06:56 +00:00
kyverno/cmd/cli/kubectl-kyverno/utils/common/fetch.go

329 lines
9.7 KiB
Go
Raw Normal View History

2020-10-15 17:29:07 -07:00
package common
import (
"context"
2020-10-15 17:29:07 -07:00
"errors"
"fmt"
"io"
"net/http"
"os"
Update Kyverno test command (#1608) * fix link (#1566) Signed-off-by: vyankatesh <vyankatesh@neualto.com> * update icon in chart.yaml Signed-off-by: Shuting Zhao <shutting06@gmail.com> Signed-off-by: vyankatesh <vyankatesh@neualto.com> * Adding default policies for restricted mode and adding notes to helm install (#1556) * Adding default policies for restricted mode, taking validationFailureAction from values.yaml and adding notes on helm install Signed-off-by: Raj Das <mail.rajdas@gmail.com> * Adding emoji Signed-off-by: Raj Das <mail.rajdas@gmail.com> * Update NOTES.txt * minor fix Signed-off-by: Raj Das <mail.rajdas@gmail.com> * adding to readme Signed-off-by: Raj Das <mail.rajdas@gmail.com> Signed-off-by: vyankatesh <vyankatesh@neualto.com> * update links and formatting in PR template (#1573) * update links and formatting in PR template Signed-off-by: Chip Zoller <chipzoller@gmail.com> * update policy submission request template Signed-off-by: Chip Zoller <chipzoller@gmail.com> Signed-off-by: vyankatesh <vyankatesh@neualto.com> * fix: restricting empty value to pass through the validation checks (#1574) Signed-off-by: Yashvardhan Kukreja <yash.kukreja.98@gmail.com> Signed-off-by: vyankatesh <vyankatesh@neualto.com> * Actually fix contributor link in PR template (#1575) * update links and formatting in PR template Signed-off-by: Chip Zoller <chipzoller@gmail.com> * update policy submission request template Signed-off-by: Chip Zoller <chipzoller@gmail.com> * actually fix contrib guidelines Signed-off-by: Chip Zoller <chipzoller@gmail.com> * actually fix contrib guidelines Signed-off-by: Chip Zoller <chipzoller@gmail.com> Signed-off-by: vyankatesh <vyankatesh@neualto.com> * code improvement (#1567) * code improvement Signed-off-by: NoSkillGirl <singhpooja240393@gmail.com> * added if conditions Signed-off-by: NoSkillGirl <singhpooja240393@gmail.com> * fixed unit test cases Signed-off-by: NoSkillGirl <singhpooja240393@gmail.com> Signed-off-by: vyankatesh <vyankatesh@neualto.com> * feat(operators): support subset checking for in and notin (#1555) * feat(operators): support subset checking for in and notin Signed-off-by: Arsh Sharma <arshsharma461@gmail.com> * feat(operators): fixed NotIn function Signed-off-by: Arsh Sharma <arshsharma461@gmail.com> Signed-off-by: vyankatesh <vyankatesh@neualto.com> * panic fix (#1601) Signed-off-by: NoSkillGirl <singhpooja240393@gmail.com> Signed-off-by: vyankatesh <vyankatesh@neualto.com> * update kyverno cli test cmd Signed-off-by: vyankatesh <vyankatesh@neualto.com> * code indentation Signed-off-by: vyankatesh <vyankatesh@neualto.com> * change help text Signed-off-by: vyankatesh <vyankatesh@neualto.com> Co-authored-by: Dekel <dekelb@users.noreply.github.com> Co-authored-by: Shuting Zhao <shutting06@gmail.com> Co-authored-by: Raj Babu Das <mail.rajdas@gmail.com> Co-authored-by: Chip Zoller <chipzoller@gmail.com> Co-authored-by: Yashvardhan Kukreja <yash.kukreja.98@gmail.com> Co-authored-by: Pooja Singh <36136335+NoSkillGirl@users.noreply.github.com> Co-authored-by: Arsh Sharma <56963264+RinkiyaKeDad@users.noreply.github.com> Co-authored-by: vyankatesh <vyankatesh@neualto.com>
2021-02-18 01:00:41 +05:30
"path/filepath"
"strings"
2020-10-15 17:29:07 -07:00
"github.com/go-git/go-billy/v5"
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
"github.com/kyverno/kyverno/pkg/autogen"
"github.com/kyverno/kyverno/pkg/clients/dclient"
2020-10-15 17:29:07 -07:00
engineutils "github.com/kyverno/kyverno/pkg/engine/utils"
yamlutils "github.com/kyverno/kyverno/pkg/utils/yaml"
"golang.org/x/text/cases"
"golang.org/x/text/language"
2020-10-15 17:29:07 -07:00
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
2020-11-04 15:56:33 -08:00
"k8s.io/client-go/kubernetes/scheme"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/yaml"
2020-10-15 17:29:07 -07:00
)
// GetResources gets matched resources by the given policies
// the resources are fetched from
// - local paths to resources, if given
// - the k8s cluster, if given
func GetResources(policies []kyvernov1.PolicyInterface, resourcePaths []string, dClient dclient.Interface, cluster bool, namespace string, policyReport bool) ([]*unstructured.Unstructured, error) {
2020-10-21 20:05:05 +05:30
resources := make([]*unstructured.Unstructured, 0)
2020-10-15 17:29:07 -07:00
var err error
resourceTypesMap := make(map[string]bool)
2020-10-21 20:05:05 +05:30
var resourceTypes []string
2020-10-21 20:05:05 +05:30
for _, policy := range policies {
for _, rule := range autogen.ComputeRules(policy) {
resourceTypesInRule := GetKindsFromRule(rule)
for resourceKind := range resourceTypesInRule {
resourceTypesMap[resourceKind] = true
}
2020-10-15 17:29:07 -07:00
}
2020-10-21 20:05:05 +05:30
}
for kind := range resourceTypesMap {
resourceTypes = append(resourceTypes, kind)
}
2020-10-15 17:29:07 -07:00
2020-10-21 20:05:05 +05:30
if cluster && dClient != nil {
resources, err = whenClusterIsTrue(resourceTypes, dClient, namespace, resourcePaths, policyReport)
2020-10-15 17:29:07 -07:00
if err != nil {
return resources, err
}
} else if len(resourcePaths) > 0 {
resources, err = whenClusterIsFalse(resourcePaths, policyReport)
if err != nil {
return resources, err
}
}
return resources, err
}
func whenClusterIsTrue(resourceTypes []string, dClient dclient.Interface, namespace string, resourcePaths []string, policyReport bool) ([]*unstructured.Unstructured, error) {
resources := make([]*unstructured.Unstructured, 0)
resourceMap, err := getResourcesOfTypeFromCluster(resourceTypes, dClient, namespace)
if err != nil {
return nil, err
}
if len(resourcePaths) == 0 {
for _, rr := range resourceMap {
resources = append(resources, rr)
}
} else {
for _, resourcePath := range resourcePaths {
lenOfResource := len(resources)
for rn, rr := range resourceMap {
s := strings.Split(rn, "-")
if s[2] == resourcePath {
resources = append(resources, rr)
}
}
if lenOfResource >= len(resources) {
if policyReport {
log.Log.V(3).Info(fmt.Sprintf("%s not found in cluster", resourcePath))
} else {
fmt.Printf("\n----------------------------------------------------------------------\nresource %s not found in cluster\n----------------------------------------------------------------------\n", resourcePath)
}
return nil, fmt.Errorf("%s not found in cluster", resourcePath)
}
2020-10-15 17:29:07 -07:00
}
}
return resources, nil
2020-10-15 17:29:07 -07:00
}
func whenClusterIsFalse(resourcePaths []string, policyReport bool) ([]*unstructured.Unstructured, error) {
resources := make([]*unstructured.Unstructured, 0)
for _, resourcePath := range resourcePaths {
resourceBytes, err := getFileBytes(resourcePath)
if err != nil {
if policyReport {
log.Log.V(3).Info(fmt.Sprintf("failed to load resources: %s.", resourcePath), "error", err)
} else {
fmt.Printf("\n----------------------------------------------------------------------\nfailed to load resources: %s. \nerror: %s\n----------------------------------------------------------------------\n", resourcePath, err)
}
continue
}
getResources, err := GetResource(resourceBytes)
if err != nil {
return nil, err
}
resources = append(resources, getResources...)
}
return resources, nil
}
// GetResourcesWithTest with gets matched resources by the given policies
func GetResourcesWithTest(fs billy.Filesystem, policies []kyvernov1.PolicyInterface, resourcePaths []string, isGit bool, policyResourcePath string) ([]*unstructured.Unstructured, error) {
resources := make([]*unstructured.Unstructured, 0)
resourceTypesMap := make(map[string]bool)
for _, policy := range policies {
for _, rule := range autogen.ComputeRules(policy) {
for _, kind := range rule.MatchResources.Kinds {
resourceTypesMap[kind] = true
}
}
}
if len(resourcePaths) > 0 {
for _, resourcePath := range resourcePaths {
var resourceBytes []byte
var err error
if isGit {
filep, err := fs.Open(filepath.Join(policyResourcePath, resourcePath))
if err != nil {
fmt.Printf("Unable to open resource file: %s. error: %s", resourcePath, err)
continue
}
resourceBytes, _ = io.ReadAll(filep)
} else {
resourceBytes, err = getFileBytes(resourcePath)
}
if err != nil {
fmt.Printf("\n----------------------------------------------------------------------\nfailed to load resources: %s. \nerror: %s\n----------------------------------------------------------------------\n", resourcePath, err)
continue
}
getResources, err := GetResource(resourceBytes)
if err != nil {
return nil, err
}
resources = append(resources, getResources...)
}
}
return resources, nil
}
2020-10-15 17:29:07 -07:00
// GetResource converts raw bytes to unstructured object
func GetResource(resourceBytes []byte) ([]*unstructured.Unstructured, error) {
resources := make([]*unstructured.Unstructured, 0)
var getErrString string
files, splitDocError := yamlutils.SplitDocuments(resourceBytes)
2020-10-15 17:29:07 -07:00
if splitDocError != nil {
return nil, splitDocError
}
for _, resourceYaml := range files {
resource, err := convertResourceToUnstructured(resourceYaml)
if err != nil {
if strings.Contains(err.Error(), "Object 'Kind' is missing") {
log.Log.V(3).Info("skipping resource as kind not found")
continue
}
2020-10-15 17:29:07 -07:00
getErrString = getErrString + err.Error() + "\n"
}
resources = append(resources, resource)
}
if getErrString != "" {
return nil, errors.New(getErrString)
}
return resources, nil
}
func getResourcesOfTypeFromCluster(resourceTypes []string, dClient dclient.Interface, namespace string) (map[string]*unstructured.Unstructured, error) {
r := make(map[string]*unstructured.Unstructured)
2020-10-16 19:56:32 +05:30
2020-10-15 17:29:07 -07:00
for _, kind := range resourceTypes {
resourceList, err := dClient.ListResource(context.TODO(), "", kind, namespace, nil)
2020-10-15 17:29:07 -07:00
if err != nil {
2020-11-18 11:08:24 +05:30
continue
2020-10-15 17:29:07 -07:00
}
2020-11-18 11:08:24 +05:30
2020-10-15 17:29:07 -07:00
version := resourceList.GetAPIVersion()
for _, resource := range resourceList.Items {
key := kind + "-" + resource.GetNamespace() + "-" + resource.GetName()
r[key] = resource.DeepCopy()
2020-10-15 17:29:07 -07:00
resource.SetGroupVersionKind(schema.GroupVersionKind{
Group: "",
Version: version,
Kind: kind,
})
}
}
2020-10-21 20:05:05 +05:30
return r, nil
2020-10-15 17:29:07 -07:00
}
func getFileBytes(path string) ([]byte, error) {
var (
file []byte
err error
)
if IsHTTPRegex.MatchString(path) {
// We accept here that a random URL might be called based on user provided input.
req, err := http.NewRequestWithContext(context.TODO(), http.MethodGet, path, nil)
if err != nil {
return nil, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, err
}
file, err = io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
} else {
path = filepath.Clean(path)
// We accept the risk of including a user provided file here.
file, err = os.ReadFile(path) // #nosec G304
if err != nil {
return nil, err
}
2020-10-15 17:29:07 -07:00
}
2020-10-15 17:29:07 -07:00
return file, err
}
func convertResourceToUnstructured(resourceYaml []byte) (*unstructured.Unstructured, error) {
decode := scheme.Codecs.UniversalDeserializer().Decode
_, metaData, decodeErr := decode(resourceYaml, nil, nil)
if decodeErr != nil {
if !strings.Contains(decodeErr.Error(), "no kind") {
return nil, decodeErr
}
2020-10-15 17:29:07 -07:00
}
resourceJSON, err := yaml.YAMLToJSON(resourceYaml)
2020-10-15 17:29:07 -07:00
if err != nil {
return nil, err
}
resource, err := engineutils.ConvertToUnstructured(resourceJSON)
if err != nil {
return nil, err
}
if decodeErr == nil {
resource.SetGroupVersionKind(*metaData)
}
2020-10-15 17:29:07 -07:00
if resource.GetNamespace() == "" {
resource.SetNamespace("default")
}
return resource, nil
}
Added Code to support the test command for mutate policy (#2279) * Added test-e2e-local in the Makefile * Added a proper Indentation * Added 3 more fields * Added getPolicyResourceFullPath function * Updating the patchedResource path to full path * Converts Namespaced policy to ClusterPolicy * Added GetPatchedResourceFromPath function * Added GetPatchedResource function * Checks for namespaced-policy from policy name provided bu user * Generalizing resultKey for both validate and mutate. Also added kind field to this key * Added Type field to PolicySpec * To handle mutate case when resource and patchedResource are equal * fetch patchResource from path provided by user and compare it with engine patchedResource * generating result by comparing patchedResource * Added kind to resultKey * Handles namespaced policy results * Skip is required * Added []*response.EngineResponse return type in ApplyPolicyOnResource function * namespaced policy only surpasses resources having same namespace as policy * apply command will print the patchedResource whereas test will not * passing engineResponse instead of validateEngineResponse because it supports results for both validate and mutate case * default namespace will printed in the output table if no namespace is being provided by the user * Added e2e test for mutate policy and also examples for both type of policies * Created a separate function to get resultKey * Changes in the resultKey for validate case * Added help description for test command in the cli * fixes code for more test cases * fixes code to support more cases and also added resources for e2e-test * some small changes like adding brackets, clubbing 2 if cond into one, changing variable name, etc. * Rearrange GetPatchedResourceFromPath function to get rid from repetion of same thing twice. * Added kind in the result section of test.yaml for all test-cases * engineResponse will handle different types of response * GetPatchedResource() uses GetResource function to fetch patched resource Signed-off-by: viveksahu26 <vivekkumarsahu650@gmail.com>
2021-10-01 14:16:33 +05:30
// GetPatchedResource converts raw bytes to unstructured object
func GetPatchedAndGeneratedResource(resourceBytes []byte) (unstructured.Unstructured, error) {
getResource, err := GetResource(resourceBytes)
if err != nil {
return unstructured.Unstructured{}, err
}
resource := *getResource[0]
return resource, nil
Added Code to support the test command for mutate policy (#2279) * Added test-e2e-local in the Makefile * Added a proper Indentation * Added 3 more fields * Added getPolicyResourceFullPath function * Updating the patchedResource path to full path * Converts Namespaced policy to ClusterPolicy * Added GetPatchedResourceFromPath function * Added GetPatchedResource function * Checks for namespaced-policy from policy name provided bu user * Generalizing resultKey for both validate and mutate. Also added kind field to this key * Added Type field to PolicySpec * To handle mutate case when resource and patchedResource are equal * fetch patchResource from path provided by user and compare it with engine patchedResource * generating result by comparing patchedResource * Added kind to resultKey * Handles namespaced policy results * Skip is required * Added []*response.EngineResponse return type in ApplyPolicyOnResource function * namespaced policy only surpasses resources having same namespace as policy * apply command will print the patchedResource whereas test will not * passing engineResponse instead of validateEngineResponse because it supports results for both validate and mutate case * default namespace will printed in the output table if no namespace is being provided by the user * Added e2e test for mutate policy and also examples for both type of policies * Created a separate function to get resultKey * Changes in the resultKey for validate case * Added help description for test command in the cli * fixes code for more test cases * fixes code to support more cases and also added resources for e2e-test * some small changes like adding brackets, clubbing 2 if cond into one, changing variable name, etc. * Rearrange GetPatchedResourceFromPath function to get rid from repetion of same thing twice. * Added kind in the result section of test.yaml for all test-cases * engineResponse will handle different types of response * GetPatchedResource() uses GetResource function to fetch patched resource Signed-off-by: viveksahu26 <vivekkumarsahu650@gmail.com>
2021-10-01 14:16:33 +05:30
}
// GetKindsFromRule will return the kinds from policy match block
func GetKindsFromRule(rule kyvernov1.Rule) map[string]bool {
resourceTypesMap := make(map[string]bool)
for _, kind := range rule.MatchResources.Kinds {
if strings.Contains(kind, "/") {
lastElement := kind[strings.LastIndex(kind, "/")+1:]
resourceTypesMap[cases.Title(language.Und, cases.NoLower).String(lastElement)] = true
}
resourceTypesMap[cases.Title(language.Und, cases.NoLower).String(kind)] = true
}
if rule.MatchResources.Any != nil {
for _, resFilter := range rule.MatchResources.Any {
for _, kind := range resFilter.ResourceDescription.Kinds {
if strings.Contains(kind, "/") {
lastElement := kind[strings.LastIndex(kind, "/")+1:]
resourceTypesMap[cases.Title(language.Und, cases.NoLower).String(lastElement)] = true
}
resourceTypesMap[kind] = true
}
}
}
if rule.MatchResources.All != nil {
for _, resFilter := range rule.MatchResources.All {
for _, kind := range resFilter.ResourceDescription.Kinds {
if strings.Contains(kind, "/") {
lastElement := kind[strings.LastIndex(kind, "/")+1:]
resourceTypesMap[cases.Title(language.Und, cases.NoLower).String(lastElement)] = true
}
resourceTypesMap[cases.Title(language.Und, cases.NoLower).String(kind)] = true
}
}
}
return resourceTypesMap
}