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

434 lines
14 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"
kubeutils "github.com/kyverno/kyverno/pkg/utils/kube"
yamlutils "github.com/kyverno/kyverno/pkg/utils/yaml"
Supporting ValidatingAdmissionPolicy in kyverno cli (apply and test command) (#6656) * feat: add policy reporter to the dev lab Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * refactor: remove obsolete structs from CLI Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * more Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * codegen Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * Supporting ValidatingAdmissionPolicy in kyverno apply Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * chore: bump k8s from v0.26.3 to v0.27.0-rc.0 Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Support validating admission policy in kyverno apply Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Support validating admission policy in kyverno test Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * refactoring Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Adding kyverno apply tests for validating admission policy Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * running codegen-all Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Adding IsVap field in TestResults Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * chore: bump k8s from v0.27.0-rc.0 to v0.27.1 Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Fix vap in engine response Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * codegen Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> --------- Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> Co-authored-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Co-authored-by: Jim Bugwadia <jim@nirmata.com>
2023-05-10 11:12:53 +03:00
"golang.org/x/text/cases"
"golang.org/x/text/language"
admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
"k8s.io/api/admissionregistration/v1alpha1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
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/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(
Supporting ValidatingAdmissionPolicy in kyverno cli (apply and test command) (#6656) * feat: add policy reporter to the dev lab Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * refactor: remove obsolete structs from CLI Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * more Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * codegen Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * Supporting ValidatingAdmissionPolicy in kyverno apply Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * chore: bump k8s from v0.26.3 to v0.27.0-rc.0 Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Support validating admission policy in kyverno apply Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Support validating admission policy in kyverno test Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * refactoring Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Adding kyverno apply tests for validating admission policy Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * running codegen-all Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Adding IsVap field in TestResults Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * chore: bump k8s from v0.27.0-rc.0 to v0.27.1 Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Fix vap in engine response Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * codegen Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> --------- Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> Co-authored-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Co-authored-by: Jim Bugwadia <jim@nirmata.com>
2023-05-10 11:12:53 +03:00
policies []kyvernov1.PolicyInterface, validatingAdmissionPolicies []v1alpha1.ValidatingAdmissionPolicy, 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
if cluster && dClient != nil {
Supporting ValidatingAdmissionPolicy in kyverno cli (apply and test command) (#6656) * feat: add policy reporter to the dev lab Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * refactor: remove obsolete structs from CLI Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * more Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * codegen Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * Supporting ValidatingAdmissionPolicy in kyverno apply Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * chore: bump k8s from v0.26.3 to v0.27.0-rc.0 Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Support validating admission policy in kyverno apply Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Support validating admission policy in kyverno test Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * refactoring Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Adding kyverno apply tests for validating admission policy Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * running codegen-all Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Adding IsVap field in TestResults Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * chore: bump k8s from v0.27.0-rc.0 to v0.27.1 Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Fix vap in engine response Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * codegen Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> --------- Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> Co-authored-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Co-authored-by: Jim Bugwadia <jim@nirmata.com>
2023-05-10 11:12:53 +03:00
if len(policies) > 0 {
matchedResources := &KyvernoResources{
policies: policies,
}
2020-10-21 20:05:05 +05:30
Supporting ValidatingAdmissionPolicy in kyverno cli (apply and test command) (#6656) * feat: add policy reporter to the dev lab Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * refactor: remove obsolete structs from CLI Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * more Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * codegen Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * Supporting ValidatingAdmissionPolicy in kyverno apply Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * chore: bump k8s from v0.26.3 to v0.27.0-rc.0 Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Support validating admission policy in kyverno apply Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Support validating admission policy in kyverno test Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * refactoring Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Adding kyverno apply tests for validating admission policy Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * running codegen-all Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Adding IsVap field in TestResults Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * chore: bump k8s from v0.27.0-rc.0 to v0.27.1 Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Fix vap in engine response Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * codegen Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> --------- Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> Co-authored-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Co-authored-by: Jim Bugwadia <jim@nirmata.com>
2023-05-10 11:12:53 +03:00
resources, err = matchedResources.FetchResourcesFromPolicy(resourcePaths, dClient, namespace, policyReport)
if err != nil {
return resources, err
}
}
2020-10-15 17:29:07 -07:00
Supporting ValidatingAdmissionPolicy in kyverno cli (apply and test command) (#6656) * feat: add policy reporter to the dev lab Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * refactor: remove obsolete structs from CLI Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * more Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * codegen Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * Supporting ValidatingAdmissionPolicy in kyverno apply Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * chore: bump k8s from v0.26.3 to v0.27.0-rc.0 Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Support validating admission policy in kyverno apply Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Support validating admission policy in kyverno test Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * refactoring Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Adding kyverno apply tests for validating admission policy Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * running codegen-all Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Adding IsVap field in TestResults Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * chore: bump k8s from v0.27.0-rc.0 to v0.27.1 Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Fix vap in engine response Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * codegen Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> --------- Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> Co-authored-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Co-authored-by: Jim Bugwadia <jim@nirmata.com>
2023-05-10 11:12:53 +03:00
if len(validatingAdmissionPolicies) > 0 {
matchedResources := &ValidatingAdmissionResources{
policies: validatingAdmissionPolicies,
}
resources, err = matchedResources.FetchResourcesFromPolicy(resourcePaths, dClient, namespace, policyReport)
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 []schema.GroupVersionKind, subresourceMap map[schema.GroupVersionKind]Subresource, dClient dclient.Interface, namespace string, resourcePaths []string, policyReport bool) ([]*unstructured.Unstructured, error) {
resources := make([]*unstructured.Unstructured, 0)
resourceMap, err := getResourcesOfTypeFromCluster(resourceTypes, subresourceMap, 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.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.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.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 []schema.GroupVersionKind, subresourceMap map[schema.GroupVersionKind]Subresource, dClient dclient.Interface, namespace string) (map[string]*unstructured.Unstructured, error) {
r := make(map[string]*unstructured.Unstructured)
2020-10-15 17:29:07 -07:00
for _, kind := range resourceTypes {
resourceList, err := dClient.ListResource(context.TODO(), kind.GroupVersion().String(), kind.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
}
gvk := resourceList.GroupVersionKind()
2020-10-15 17:29:07 -07:00
for _, resource := range resourceList.Items {
key := kind.Kind + "-" + resource.GetNamespace() + "-" + resource.GetName()
resource.SetGroupVersionKind(schema.GroupVersionKind{
Group: gvk.Group,
Version: gvk.Version,
Kind: kind.Kind,
})
r[key] = resource.DeepCopy()
}
}
for _, subresource := range subresourceMap {
parentGV := schema.GroupVersion{Group: subresource.ParentResource.Group, Version: subresource.ParentResource.Version}
resourceList, err := dClient.ListResource(context.TODO(), parentGV.String(), subresource.ParentResource.Kind, namespace, nil)
if err != nil {
continue
}
parentResourceNames := make([]string, 0)
for _, resource := range resourceList.Items {
parentResourceNames = append(parentResourceNames, resource.GetName())
}
for _, parentResourceName := range parentResourceNames {
subresourceName := strings.Split(subresource.APIResource.Name, "/")[1]
resource, err := dClient.GetResource(context.TODO(), parentGV.String(), subresource.ParentResource.Kind, namespace, parentResourceName, subresourceName)
if err != nil {
fmt.Printf("Error: %s", err.Error())
continue
}
key := subresource.APIResource.Kind + "-" + resource.GetNamespace() + "-" + resource.GetName()
2020-10-15 17:29:07 -07:00
resource.SetGroupVersionKind(schema.GroupVersionKind{
Group: subresource.APIResource.Group,
Version: subresource.APIResource.Version,
Kind: subresource.APIResource.Kind,
2020-10-15 17:29:07 -07:00
})
r[key] = resource.DeepCopy()
2020-10-15 17:29:07 -07:00
}
}
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 := kubeutils.BytesToUnstructured(resourceJSON)
2020-10-15 17:29:07 -07:00
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
}
// GetPatchedAndGeneratedResource converts raw bytes to unstructured object
func GetPatchedAndGeneratedResource(resourceBytes []byte) (unstructured.Unstructured, error) {
getResource, err := GetResource(resourceBytes)
if err != nil {
return unstructured.Unstructured{}, err
}
fix: cloneList sync behavior (#7466) * fix flaky tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * chore(deps): bump docker/login-action from 2.1.0 to 2.2.0 (#7463) Bumps [docker/login-action](https://github.com/docker/login-action) from 2.1.0 to 2.2.0. - [Release notes](https://github.com/docker/login-action/releases) - [Commits](https://github.com/docker/login-action/compare/f4ef78c080cd8ba55a85445d5b36e214a81df20a...465a07811f14bebb1938fbed4728c6a1ff8901fc) --- updated-dependencies: - dependency-name: docker/login-action dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps): bump slsa-framework/slsa-github-generator (#7462) Bumps [slsa-framework/slsa-github-generator](https://github.com/slsa-framework/slsa-github-generator) from 1.6.0 to 1.7.0. - [Release notes](https://github.com/slsa-framework/slsa-github-generator/releases) - [Changelog](https://github.com/slsa-framework/slsa-github-generator/blob/main/CHANGELOG.md) - [Commits](https://github.com/slsa-framework/slsa-github-generator/compare/v1.6.0...v1.7.0) --- updated-dependencies: - dependency-name: slsa-framework/slsa-github-generator dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * fix cloneList sync behavior Signed-off-by: ShutingZhao <shuting@nirmata.com> * skip creating duplicate URs Signed-off-by: ShutingZhao <shuting@nirmata.com> * add kuttl tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix Signed-off-by: ShutingZhao <shuting@nirmata.com> * add kuttl tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * add kuttl tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * renam Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix Signed-off-by: ShutingZhao <shuting@nirmata.com> --------- Signed-off-by: ShutingZhao <shuting@nirmata.com> Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-06-13 17:12:13 +08:00
if len(getResource) > 0 && getResource[0] != nil {
resource := *getResource[0]
return resource, nil
}
return unstructured.Unstructured{}, err
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, client dclient.Interface) (map[schema.GroupVersionKind]bool, map[schema.GroupVersionKind]Subresource) {
resourceTypesMap := make(map[schema.GroupVersionKind]bool)
subresourceMap := make(map[schema.GroupVersionKind]Subresource)
for _, kind := range rule.MatchResources.Kinds {
addGVKToResourceTypesMap(kind, resourceTypesMap, subresourceMap, client)
}
if rule.MatchResources.Any != nil {
for _, resFilter := range rule.MatchResources.Any {
for _, kind := range resFilter.ResourceDescription.Kinds {
addGVKToResourceTypesMap(kind, resourceTypesMap, subresourceMap, client)
}
}
}
if rule.MatchResources.All != nil {
for _, resFilter := range rule.MatchResources.All {
for _, kind := range resFilter.ResourceDescription.Kinds {
addGVKToResourceTypesMap(kind, resourceTypesMap, subresourceMap, client)
}
}
}
return resourceTypesMap, subresourceMap
}
Supporting ValidatingAdmissionPolicy in kyverno cli (apply and test command) (#6656) * feat: add policy reporter to the dev lab Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * refactor: remove obsolete structs from CLI Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * more Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * codegen Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * Supporting ValidatingAdmissionPolicy in kyverno apply Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * chore: bump k8s from v0.26.3 to v0.27.0-rc.0 Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Support validating admission policy in kyverno apply Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Support validating admission policy in kyverno test Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * refactoring Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Adding kyverno apply tests for validating admission policy Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * running codegen-all Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Adding IsVap field in TestResults Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * chore: bump k8s from v0.27.0-rc.0 to v0.27.1 Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Fix vap in engine response Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * codegen Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> --------- Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> Co-authored-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Co-authored-by: Jim Bugwadia <jim@nirmata.com>
2023-05-10 11:12:53 +03:00
func getKindsFromValidatingAdmissionRule(rule admissionregistrationv1.Rule, client dclient.Interface) (map[schema.GroupVersionKind]bool, map[schema.GroupVersionKind]Subresource, error) {
resourceTypesMap := make(map[schema.GroupVersionKind]bool)
subresourceMap := make(map[schema.GroupVersionKind]Subresource)
group := rule.APIGroups[0]
if group == "" {
group = "*"
}
version := rule.APIVersions[0]
for _, resource := range rule.Resources {
var kind, subresource string
isSubresource := kubeutils.IsSubresource(resource)
if isSubresource {
parts := strings.Split(resource, "/")
kind = cases.Title(language.English, cases.NoLower).String(parts[0])
kind, _ = strings.CutSuffix(kind, "s")
subresource = parts[1]
} else {
resource = cases.Title(language.English, cases.NoLower).String(resource)
resource, _ = strings.CutSuffix(resource, "s")
kind = resource
subresource = ""
}
gvrss, err := client.Discovery().FindResources(group, version, kind, subresource)
if err != nil {
log.Info("failed to find resource", "kind", kind, "error", err)
return resourceTypesMap, subresourceMap, err
}
for parent, child := range gvrss {
// The resource is not a subresource
if parent.SubResource == "" {
resourceTypesMap[parent.GroupVersionKind()] = true
} else {
gvk := schema.GroupVersionKind{
Group: child.Group, Version: child.Version, Kind: child.Kind,
}
subresourceMap[gvk] = Subresource{
APIResource: child,
ParentResource: metav1.APIResource{
Group: parent.Group,
Version: parent.Version,
Kind: parent.Kind,
Name: parent.Resource,
},
}
}
}
}
return resourceTypesMap, subresourceMap, nil
}
func addGVKToResourceTypesMap(kind string, resourceTypesMap map[schema.GroupVersionKind]bool, subresourceMap map[schema.GroupVersionKind]Subresource, client dclient.Interface) {
group, version, kind, subresource := kubeutils.ParseKindSelector(kind)
gvrss, err := client.Discovery().FindResources(group, version, kind, subresource)
if err != nil {
log.Info("failed to find resource", "kind", kind, "error", err)
return
}
for parent, child := range gvrss {
// The resource is not a subresource
if parent.SubResource == "" {
resourceTypesMap[parent.GroupVersionKind()] = true
} else {
gvk := schema.GroupVersionKind{
Group: child.Group, Version: child.Version, Kind: child.Kind,
}
subresourceMap[gvk] = Subresource{
APIResource: child,
ParentResource: metav1.APIResource{
Group: parent.Group,
Version: parent.Version,
Kind: parent.Kind,
Name: parent.Resource,
},
}
}
}
}