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

618 lines
26 KiB
Go
Raw Normal View History

2020-03-06 03:00:18 +05:30
package apply
import (
"context"
2020-03-06 03:00:18 +05:30
"fmt"
"io"
"net/url"
"os"
"path/filepath"
"strings"
2020-04-03 10:30:52 +05:30
"time"
"github.com/go-git/go-billy/v5/memfs"
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
kyvernov2 "github.com/kyverno/kyverno/api/kyverno/v2"
kyvernov2alpha1 "github.com/kyverno/kyverno/api/kyverno/v2alpha1"
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/command"
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/deprecations"
Support PolicyExceptions with CLI (#9525) * loding policyExecptions from func Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * adding PolicyExceptions in crds Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * adding PolicyExceptions in GetPolicy function Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * adding policyexceptions in Load function Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * resolve error becuase of now Getpolicy return policyexceptions Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * added -exception flag loaded policyexception Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * added policyexceptions in processor and NewEngine Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * Revert "added -exception flag loaded policyexception" This reverts commit f53b205c089e780033b14c9a6343a141c20875b6. * Revert "Added support for PolicyExceptions for apply command " This reverts commit 82689ea0c1b914c566ac8ef30ab863f33d9b5460. * Update cmd/cli/kubectl-kyverno/commands/test/test.go loading exceptions with policies Co-authored-by: Mariam Fahmy <mariamfahmy66@gmail.com> Signed-off-by: Sanskar Gurdasani <92817635+Sanskarzz@users.noreply.github.com> * updated GetFullPaths function and remove unnecessary code Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * added tests for loading exceptions in GetPolicy function Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * added tests for loading policy exceptions Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * Used selector in List function Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * generated cli crd Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * updated loadpolicy_test tests and corrected kind Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * resolved unit test error in path_test.go file Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * limiting the usage of exceptions to ValidatingAdmissionPolicies Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * remove changes in common code Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes 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> --------- Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> Signed-off-by: Sanskar Gurdasani <92817635+Sanskarzz@users.noreply.github.com> Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Co-authored-by: Mariam Fahmy <mariamfahmy66@gmail.com> Co-authored-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com>
2024-02-01 03:58:14 +05:30
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/exception"
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/log"
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/output/color"
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/policy"
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/processor"
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/source"
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/store"
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/userinfo"
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/utils/common"
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/variables"
"github.com/kyverno/kyverno/pkg/autogen"
"github.com/kyverno/kyverno/pkg/cel/engine"
celpolicy "github.com/kyverno/kyverno/pkg/cel/policy"
"github.com/kyverno/kyverno/pkg/clients/dclient"
"github.com/kyverno/kyverno/pkg/config"
engineapi "github.com/kyverno/kyverno/pkg/engine/api"
gitutils "github.com/kyverno/kyverno/pkg/utils/git"
policyvalidation "github.com/kyverno/kyverno/pkg/validation/policy"
2020-03-06 03:00:18 +05:30
"github.com/spf13/cobra"
admissionregistrationv1beta1 "k8s.io/api/admissionregistration/v1beta1"
corev1 "k8s.io/api/core/v1"
2020-10-15 17:29:07 -07:00
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
Mutate existing CLI support (#11453) * feat: Add flags for target resources and add fake client initialization Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add fake discovery client and cluster bool in the policy processor Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use the full mutation engine policy response in the engine response Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Extract mutated targets from the policy responses and print them out Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add TargetResources field in the cli test schema Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Generate CLI crds Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: modify checkResult to take an arbitrary actual resource and resource name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: change getAndCompareResource to take a resource name and cascade it to GetResourceFromPath Signed-off-by: aerosouund <aerosound161@gmail.com> * test: Create a simple test to test mutate existing in the CLI Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Allow GetResourceFromPath to select a resource with a name from a multi resource yaml Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Modify the runTest command to return the TestResponse type - Create a fake client, load the target resources in it and use it in the PolicyProcessor. - Create the TestResponse which contains Trigger and Target fields, each is a map of gvk/name to the responses corresponding to that resource. Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Rewrite output.go to use the TestResponse type - Check for both target and trigger - Create logic for appending the resource array in case no resources are passed - Move row creation logic into a separate method to avoid code duplication - Extract the proper target resource based on rule type - Create a function to extract mutated target from the engine response Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Move tests to the correct folder Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use apiVersion/Kind/Name as the key in the test responses Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use the apiVersion/Kind/name key schema in checking results and fix invalid resource name checking for generate policies Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use better variable names for rows Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Account for Generate resources being an array Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use generated resource name in checking the results and printing output Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Uncomment checks printing Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Remove bug in engine response creation Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Move the generate logic into an else block Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix namespace fetching bug in cel validator Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use pointer to int in the test counter Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Remove redundant method Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Skip resources not being found in the manifests Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Create another field in the engine to denote if this is a cluster engine or an offline engine Simply checking for the client being nil is no longer enough because for cli operations the client will be a fake client A pointer to bool is chosen because callers who don't necessarily know what to pass should be able to pass nil Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Add extra argument in fake client initiation Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: add extra argument in fuzz test Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Add extra arg Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Handle resources specified as ns/name as this schema will be deprecated in favor of apiVersion/Kind/Name Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Fix linter complaints Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Use comma separation as array separators as kubernetes names don't support commas To avoid undefined array length on splitting on / using commas will result in a fixed length since all resources will have an apiVersion, kind, namespace and name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Change resource array type to an array of any instead of array of string To support the use of a string or a TestResourceSpec Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Expect the resource array to be an array of string or array of TestResourceSpec Assert that an array element is either of these types and match the resources in both cases according to the element type Expect that the key in responses is now separated by commas instead of slashes Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Expect that the resource array is now of type array of any and modify tests that use it Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Skip response check if the policy name isnt whats in the result Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Match the name if its specified as ns/name Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Create CLI CRDs Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix linter complaints Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Cleanup invalid code used in FixTest to adapt it to the schema changes Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Check if resource is nil before extracting Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: use the loadResources method to open targets in a directory Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Account for target resources with the same name but different namespaces Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Add CLI test for mutate existing with the same name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Infer resource name and namespace from the actual resource and account for resources with the same name and namespace but different kinds Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: remove extra line Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add printing mutate existing resources to the output or to a file Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Minor fixes Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Revert result back to error Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use io discard to not print resources in the test command Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Update vague comments and remove outdated ones Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Integrate mutate existing changes with diff generation Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Move resource key generation into a function Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Add a mutate existing test that fails Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Remove redundant comment Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Fix array of any assignment in cli test Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Dont check duplicate strings for field that is an array of any Signed-off-by: aerosouund <aerosound161@gmail.com> * bug: Fix appending to the wrong array Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: run fix tests Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run fix tests Signed-off-by: aerosouund <aerosound161@gmail.com> --------- Signed-off-by: aerosouund <aerosound161@gmail.com> Signed-off-by: ammar <ammar.yasser@vodafone.com> Signed-off-by: Ammar Yasser <aerosound161@gmail.com> Co-authored-by: ammar <ammar.yasser@vodafone.com> Co-authored-by: shuting <shuting@nirmata.com>
2024-12-19 09:42:54 +02:00
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
2020-03-06 03:00:18 +05:30
)
type SkippedInvalidPolicies struct {
skipped []string
invalid []string
}
type ApplyCommandConfig struct {
KubeConfig string
Context string
Namespace string
MutateLogPath string
Variables []string
ValuesFile string
UserInfoPath string
Cluster bool
PolicyReport bool
OutputFormat string
Stdin bool
RegistryAccess bool
AuditWarn bool
ResourcePaths []string
PolicyPaths []string
Mutate existing CLI support (#11453) * feat: Add flags for target resources and add fake client initialization Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add fake discovery client and cluster bool in the policy processor Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use the full mutation engine policy response in the engine response Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Extract mutated targets from the policy responses and print them out Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add TargetResources field in the cli test schema Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Generate CLI crds Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: modify checkResult to take an arbitrary actual resource and resource name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: change getAndCompareResource to take a resource name and cascade it to GetResourceFromPath Signed-off-by: aerosouund <aerosound161@gmail.com> * test: Create a simple test to test mutate existing in the CLI Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Allow GetResourceFromPath to select a resource with a name from a multi resource yaml Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Modify the runTest command to return the TestResponse type - Create a fake client, load the target resources in it and use it in the PolicyProcessor. - Create the TestResponse which contains Trigger and Target fields, each is a map of gvk/name to the responses corresponding to that resource. Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Rewrite output.go to use the TestResponse type - Check for both target and trigger - Create logic for appending the resource array in case no resources are passed - Move row creation logic into a separate method to avoid code duplication - Extract the proper target resource based on rule type - Create a function to extract mutated target from the engine response Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Move tests to the correct folder Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use apiVersion/Kind/Name as the key in the test responses Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use the apiVersion/Kind/name key schema in checking results and fix invalid resource name checking for generate policies Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use better variable names for rows Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Account for Generate resources being an array Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use generated resource name in checking the results and printing output Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Uncomment checks printing Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Remove bug in engine response creation Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Move the generate logic into an else block Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix namespace fetching bug in cel validator Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use pointer to int in the test counter Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Remove redundant method Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Skip resources not being found in the manifests Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Create another field in the engine to denote if this is a cluster engine or an offline engine Simply checking for the client being nil is no longer enough because for cli operations the client will be a fake client A pointer to bool is chosen because callers who don't necessarily know what to pass should be able to pass nil Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Add extra argument in fake client initiation Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: add extra argument in fuzz test Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Add extra arg Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Handle resources specified as ns/name as this schema will be deprecated in favor of apiVersion/Kind/Name Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Fix linter complaints Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Use comma separation as array separators as kubernetes names don't support commas To avoid undefined array length on splitting on / using commas will result in a fixed length since all resources will have an apiVersion, kind, namespace and name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Change resource array type to an array of any instead of array of string To support the use of a string or a TestResourceSpec Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Expect the resource array to be an array of string or array of TestResourceSpec Assert that an array element is either of these types and match the resources in both cases according to the element type Expect that the key in responses is now separated by commas instead of slashes Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Expect that the resource array is now of type array of any and modify tests that use it Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Skip response check if the policy name isnt whats in the result Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Match the name if its specified as ns/name Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Create CLI CRDs Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix linter complaints Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Cleanup invalid code used in FixTest to adapt it to the schema changes Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Check if resource is nil before extracting Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: use the loadResources method to open targets in a directory Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Account for target resources with the same name but different namespaces Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Add CLI test for mutate existing with the same name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Infer resource name and namespace from the actual resource and account for resources with the same name and namespace but different kinds Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: remove extra line Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add printing mutate existing resources to the output or to a file Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Minor fixes Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Revert result back to error Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use io discard to not print resources in the test command Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Update vague comments and remove outdated ones Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Integrate mutate existing changes with diff generation Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Move resource key generation into a function Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Add a mutate existing test that fails Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Remove redundant comment Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Fix array of any assignment in cli test Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Dont check duplicate strings for field that is an array of any Signed-off-by: aerosouund <aerosound161@gmail.com> * bug: Fix appending to the wrong array Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: run fix tests Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run fix tests Signed-off-by: aerosouund <aerosound161@gmail.com> --------- Signed-off-by: aerosouund <aerosound161@gmail.com> Signed-off-by: ammar <ammar.yasser@vodafone.com> Signed-off-by: Ammar Yasser <aerosound161@gmail.com> Co-authored-by: ammar <ammar.yasser@vodafone.com> Co-authored-by: shuting <shuting@nirmata.com>
2024-12-19 09:42:54 +02:00
TargetResourcePaths []string
GitBranch string
warnExitCode int
warnNoPassed bool
Exception []string
ContinueOnFail bool
inlineExceptions bool
GenerateExceptions bool
GeneratedExceptionTTL time.Duration
}
func Command() *cobra.Command {
var removeColor, detailedResults, table bool
applyCommandConfig := &ApplyCommandConfig{}
cmd := &cobra.Command{
Use: "apply",
Short: command.FormatDescription(true, websiteUrl, false, description...),
Long: command.FormatDescription(false, websiteUrl, false, description...),
Example: command.FormatExamples(examples...),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) (err error) {
out := cmd.OutOrStdout()
color.Init(removeColor)
applyCommandConfig.PolicyPaths = args
rc, _, skipInvalidPolicies, responses, err := applyCommandConfig.applyCommandHelper(out)
if err != nil {
return err
}
cmd.SilenceErrors = true
printSkippedAndInvalidPolicies(out, skipInvalidPolicies)
if applyCommandConfig.PolicyReport {
printReports(out, responses, applyCommandConfig.AuditWarn, applyCommandConfig.OutputFormat)
} else if applyCommandConfig.GenerateExceptions {
printExceptions(out, responses, applyCommandConfig.AuditWarn, applyCommandConfig.OutputFormat, applyCommandConfig.GeneratedExceptionTTL)
} else if table {
printTable(out, detailedResults, applyCommandConfig.AuditWarn, responses...)
} else {
for _, response := range responses {
var failedRules []engineapi.RuleResponse
resPath := fmt.Sprintf("%s/%s/%s", response.Resource.GetNamespace(), response.Resource.GetKind(), response.Resource.GetName())
for _, rule := range response.PolicyResponse.Rules {
if rule.Status() == engineapi.RuleStatusFail {
failedRules = append(failedRules, rule)
}
if rule.RuleType() == engineapi.Mutation {
if rule.Status() == engineapi.RuleStatusSkip {
fmt.Fprintln(out, "\nskipped mutate policy", response.Policy().GetName(), "->", "resource", resPath)
} else if rule.Status() == engineapi.RuleStatusError {
fmt.Fprintln(out, "\nerror while applying mutate policy", response.Policy().GetName(), "->", "resource", resPath, "\nerror: ", rule.Message())
}
}
}
if len(failedRules) > 0 {
auditWarn := false
if applyCommandConfig.AuditWarn && response.GetValidationFailureAction().Audit() {
auditWarn = true
}
if auditWarn {
fmt.Fprintln(out, "policy", response.Policy().GetName(), "->", "resource", resPath, "failed as audit warning:")
} else {
fmt.Fprintln(out, "policy", response.Policy().GetName(), "->", "resource", resPath, "failed:")
}
for i, rule := range failedRules {
fmt.Fprintln(out, i+1, "-", rule.Name(), rule.Message())
}
fmt.Fprintln(out, "")
}
}
printViolations(out, rc)
}
return exit(out, rc, applyCommandConfig.warnExitCode, applyCommandConfig.warnNoPassed)
2020-12-20 01:21:31 +05:30
},
}
cmd.Flags().StringSliceVarP(&applyCommandConfig.ResourcePaths, "resource", "r", []string{}, "Path to resource files")
cmd.Flags().StringSliceVarP(&applyCommandConfig.ResourcePaths, "resources", "", []string{}, "Path to resource files")
Mutate existing CLI support (#11453) * feat: Add flags for target resources and add fake client initialization Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add fake discovery client and cluster bool in the policy processor Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use the full mutation engine policy response in the engine response Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Extract mutated targets from the policy responses and print them out Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add TargetResources field in the cli test schema Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Generate CLI crds Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: modify checkResult to take an arbitrary actual resource and resource name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: change getAndCompareResource to take a resource name and cascade it to GetResourceFromPath Signed-off-by: aerosouund <aerosound161@gmail.com> * test: Create a simple test to test mutate existing in the CLI Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Allow GetResourceFromPath to select a resource with a name from a multi resource yaml Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Modify the runTest command to return the TestResponse type - Create a fake client, load the target resources in it and use it in the PolicyProcessor. - Create the TestResponse which contains Trigger and Target fields, each is a map of gvk/name to the responses corresponding to that resource. Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Rewrite output.go to use the TestResponse type - Check for both target and trigger - Create logic for appending the resource array in case no resources are passed - Move row creation logic into a separate method to avoid code duplication - Extract the proper target resource based on rule type - Create a function to extract mutated target from the engine response Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Move tests to the correct folder Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use apiVersion/Kind/Name as the key in the test responses Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use the apiVersion/Kind/name key schema in checking results and fix invalid resource name checking for generate policies Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use better variable names for rows Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Account for Generate resources being an array Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use generated resource name in checking the results and printing output Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Uncomment checks printing Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Remove bug in engine response creation Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Move the generate logic into an else block Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix namespace fetching bug in cel validator Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use pointer to int in the test counter Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Remove redundant method Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Skip resources not being found in the manifests Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Create another field in the engine to denote if this is a cluster engine or an offline engine Simply checking for the client being nil is no longer enough because for cli operations the client will be a fake client A pointer to bool is chosen because callers who don't necessarily know what to pass should be able to pass nil Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Add extra argument in fake client initiation Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: add extra argument in fuzz test Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Add extra arg Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Handle resources specified as ns/name as this schema will be deprecated in favor of apiVersion/Kind/Name Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Fix linter complaints Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Use comma separation as array separators as kubernetes names don't support commas To avoid undefined array length on splitting on / using commas will result in a fixed length since all resources will have an apiVersion, kind, namespace and name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Change resource array type to an array of any instead of array of string To support the use of a string or a TestResourceSpec Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Expect the resource array to be an array of string or array of TestResourceSpec Assert that an array element is either of these types and match the resources in both cases according to the element type Expect that the key in responses is now separated by commas instead of slashes Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Expect that the resource array is now of type array of any and modify tests that use it Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Skip response check if the policy name isnt whats in the result Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Match the name if its specified as ns/name Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Create CLI CRDs Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix linter complaints Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Cleanup invalid code used in FixTest to adapt it to the schema changes Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Check if resource is nil before extracting Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: use the loadResources method to open targets in a directory Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Account for target resources with the same name but different namespaces Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Add CLI test for mutate existing with the same name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Infer resource name and namespace from the actual resource and account for resources with the same name and namespace but different kinds Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: remove extra line Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add printing mutate existing resources to the output or to a file Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Minor fixes Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Revert result back to error Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use io discard to not print resources in the test command Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Update vague comments and remove outdated ones Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Integrate mutate existing changes with diff generation Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Move resource key generation into a function Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Add a mutate existing test that fails Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Remove redundant comment Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Fix array of any assignment in cli test Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Dont check duplicate strings for field that is an array of any Signed-off-by: aerosouund <aerosound161@gmail.com> * bug: Fix appending to the wrong array Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: run fix tests Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run fix tests Signed-off-by: aerosouund <aerosound161@gmail.com> --------- Signed-off-by: aerosouund <aerosound161@gmail.com> Signed-off-by: ammar <ammar.yasser@vodafone.com> Signed-off-by: Ammar Yasser <aerosound161@gmail.com> Co-authored-by: ammar <ammar.yasser@vodafone.com> Co-authored-by: shuting <shuting@nirmata.com>
2024-12-19 09:42:54 +02:00
cmd.Flags().StringSliceVarP(&applyCommandConfig.TargetResourcePaths, "target-resource", "", []string{}, "Path to individual files containing target resources files for policies that have mutate existing")
cmd.Flags().StringSliceVarP(&applyCommandConfig.TargetResourcePaths, "target-resources", "", []string{}, "Path to a directory containing target resources files for policies that have mutate existing")
cmd.Flags().BoolVarP(&applyCommandConfig.Cluster, "cluster", "c", false, "Checks if policies should be applied to cluster in the current context")
cmd.Flags().StringVarP(&applyCommandConfig.MutateLogPath, "output", "o", "", "Prints the mutated/generated resources in provided file/directory")
// currently `set` flag supports variable for single policy applied on single resource
cmd.Flags().StringVarP(&applyCommandConfig.UserInfoPath, "userinfo", "u", "", "Admission Info including Roles, Cluster Roles and Subjects")
cmd.Flags().StringSliceVarP(&applyCommandConfig.Variables, "set", "s", nil, "Variables that are required")
cmd.Flags().StringVarP(&applyCommandConfig.ValuesFile, "values-file", "f", "", "File containing values for policy variables")
cmd.Flags().BoolVarP(&applyCommandConfig.PolicyReport, "policy-report", "p", false, "Generates policy report when passed (default policyviolation)")
cmd.Flags().StringVarP(&applyCommandConfig.OutputFormat, "output-format", "", "yaml", "Specifies the policy report format (json or yaml). Default: yaml.")
cmd.Flags().StringVarP(&applyCommandConfig.Namespace, "namespace", "n", "", "Optional Policy parameter passed with cluster flag")
cmd.Flags().BoolVarP(&applyCommandConfig.Stdin, "stdin", "i", false, "Optional mutate policy parameter to pipe directly through to kubectl")
cmd.Flags().BoolVar(&applyCommandConfig.RegistryAccess, "registry", false, "If set to true, access the image registry using local docker credentials to populate external data")
cmd.Flags().StringVar(&applyCommandConfig.KubeConfig, "kubeconfig", "", "path to kubeconfig file with authorization and master location information")
cmd.Flags().StringVar(&applyCommandConfig.Context, "context", "", "The name of the kubeconfig context to use")
cmd.Flags().StringVarP(&applyCommandConfig.GitBranch, "git-branch", "b", "", "test git repository branch")
cmd.Flags().BoolVar(&applyCommandConfig.AuditWarn, "audit-warn", false, "If set to true, will flag audit policies as warnings instead of failures")
cmd.Flags().IntVar(&applyCommandConfig.warnExitCode, "warn-exit-code", 0, "Set the exit code for warnings; if failures or errors are found, will exit 1")
cmd.Flags().BoolVar(&applyCommandConfig.warnNoPassed, "warn-no-pass", false, "Specify if warning exit code should be raised if no objects satisfied a policy; can be used together with --warn-exit-code flag")
cmd.Flags().BoolVar(&removeColor, "remove-color", false, "Remove any color from output")
cmd.Flags().BoolVar(&detailedResults, "detailed-results", false, "If set to true, display detailed results")
cmd.Flags().BoolVarP(&table, "table", "t", false, "Show results in table format")
cmd.Flags().StringSliceVarP(&applyCommandConfig.Exception, "exception", "e", nil, "Policy exception to be considered when evaluating policies against resources")
cmd.Flags().StringSliceVarP(&applyCommandConfig.Exception, "exceptions", "", nil, "Policy exception to be considered when evaluating policies against resources")
cmd.Flags().BoolVar(&applyCommandConfig.ContinueOnFail, "continue-on-fail", false, "If set to true, will continue to apply policies on the next resource upon failure to apply to the current resource instead of exiting out")
cmd.Flags().BoolVarP(&applyCommandConfig.inlineExceptions, "exceptions-with-resources", "", false, "Evaluate policy exceptions from the resources path")
cmd.Flags().BoolVarP(&applyCommandConfig.GenerateExceptions, "generate-exceptions", "", false, "Generate policy exceptions for each violation")
cmd.Flags().DurationVarP(&applyCommandConfig.GeneratedExceptionTTL, "generated-exception-ttl", "", time.Hour*24*30, "Default TTL for generated exceptions")
2020-12-20 01:21:31 +05:30
return cmd
}
2020-08-05 23:53:27 +05:30
func (c *ApplyCommandConfig) applyCommandHelper(out io.Writer) (*processor.ResultCounts, []*unstructured.Unstructured, SkippedInvalidPolicies, []engineapi.EngineResponse, error) {
var skippedInvalidPolicies SkippedInvalidPolicies
err := c.checkArguments()
if err != nil {
return nil, nil, skippedInvalidPolicies, nil, err
}
mutateLogPathIsDir, err := c.getMutateLogPathIsDir()
if err != nil {
return nil, nil, skippedInvalidPolicies, nil, err
}
if err := c.cleanPreviousContent(mutateLogPathIsDir); err != nil {
return nil, nil, skippedInvalidPolicies, nil, err
}
var userInfo *kyvernov2.RequestInfo
if c.UserInfoPath != "" {
info, err := userinfo.Load(nil, c.UserInfoPath, "")
if err != nil {
return nil, nil, skippedInvalidPolicies, nil, fmt.Errorf("failed to load request info (%w)", err)
}
deprecations.CheckUserInfo(out, c.UserInfoPath, info)
userInfo = &info.RequestInfo
}
variables, err := variables.New(out, nil, "", c.ValuesFile, nil, c.Variables...)
2020-12-20 01:21:31 +05:30
if err != nil {
return nil, nil, skippedInvalidPolicies, nil, fmt.Errorf("failed to decode yaml (%w)", err)
2020-12-20 01:21:31 +05:30
}
var store store.Store
policies, vaps, vapBindings, vps, err := c.loadPolicies()
if err != nil {
return nil, nil, skippedInvalidPolicies, nil, err
}
Mutate existing CLI support (#11453) * feat: Add flags for target resources and add fake client initialization Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add fake discovery client and cluster bool in the policy processor Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use the full mutation engine policy response in the engine response Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Extract mutated targets from the policy responses and print them out Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add TargetResources field in the cli test schema Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Generate CLI crds Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: modify checkResult to take an arbitrary actual resource and resource name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: change getAndCompareResource to take a resource name and cascade it to GetResourceFromPath Signed-off-by: aerosouund <aerosound161@gmail.com> * test: Create a simple test to test mutate existing in the CLI Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Allow GetResourceFromPath to select a resource with a name from a multi resource yaml Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Modify the runTest command to return the TestResponse type - Create a fake client, load the target resources in it and use it in the PolicyProcessor. - Create the TestResponse which contains Trigger and Target fields, each is a map of gvk/name to the responses corresponding to that resource. Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Rewrite output.go to use the TestResponse type - Check for both target and trigger - Create logic for appending the resource array in case no resources are passed - Move row creation logic into a separate method to avoid code duplication - Extract the proper target resource based on rule type - Create a function to extract mutated target from the engine response Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Move tests to the correct folder Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use apiVersion/Kind/Name as the key in the test responses Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use the apiVersion/Kind/name key schema in checking results and fix invalid resource name checking for generate policies Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use better variable names for rows Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Account for Generate resources being an array Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use generated resource name in checking the results and printing output Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Uncomment checks printing Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Remove bug in engine response creation Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Move the generate logic into an else block Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix namespace fetching bug in cel validator Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use pointer to int in the test counter Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Remove redundant method Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Skip resources not being found in the manifests Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Create another field in the engine to denote if this is a cluster engine or an offline engine Simply checking for the client being nil is no longer enough because for cli operations the client will be a fake client A pointer to bool is chosen because callers who don't necessarily know what to pass should be able to pass nil Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Add extra argument in fake client initiation Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: add extra argument in fuzz test Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Add extra arg Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Handle resources specified as ns/name as this schema will be deprecated in favor of apiVersion/Kind/Name Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Fix linter complaints Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Use comma separation as array separators as kubernetes names don't support commas To avoid undefined array length on splitting on / using commas will result in a fixed length since all resources will have an apiVersion, kind, namespace and name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Change resource array type to an array of any instead of array of string To support the use of a string or a TestResourceSpec Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Expect the resource array to be an array of string or array of TestResourceSpec Assert that an array element is either of these types and match the resources in both cases according to the element type Expect that the key in responses is now separated by commas instead of slashes Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Expect that the resource array is now of type array of any and modify tests that use it Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Skip response check if the policy name isnt whats in the result Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Match the name if its specified as ns/name Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Create CLI CRDs Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix linter complaints Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Cleanup invalid code used in FixTest to adapt it to the schema changes Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Check if resource is nil before extracting Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: use the loadResources method to open targets in a directory Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Account for target resources with the same name but different namespaces Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Add CLI test for mutate existing with the same name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Infer resource name and namespace from the actual resource and account for resources with the same name and namespace but different kinds Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: remove extra line Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add printing mutate existing resources to the output or to a file Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Minor fixes Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Revert result back to error Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use io discard to not print resources in the test command Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Update vague comments and remove outdated ones Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Integrate mutate existing changes with diff generation Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Move resource key generation into a function Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Add a mutate existing test that fails Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Remove redundant comment Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Fix array of any assignment in cli test Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Dont check duplicate strings for field that is an array of any Signed-off-by: aerosouund <aerosound161@gmail.com> * bug: Fix appending to the wrong array Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: run fix tests Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run fix tests Signed-off-by: aerosouund <aerosound161@gmail.com> --------- Signed-off-by: aerosouund <aerosound161@gmail.com> Signed-off-by: ammar <ammar.yasser@vodafone.com> Signed-off-by: Ammar Yasser <aerosound161@gmail.com> Co-authored-by: ammar <ammar.yasser@vodafone.com> Co-authored-by: shuting <shuting@nirmata.com>
2024-12-19 09:42:54 +02:00
var targetResources []*unstructured.Unstructured
if len(c.TargetResourcePaths) > 0 {
targetResources, err = c.loadResources(out, c.TargetResourcePaths, policies, vaps, nil)
if err != nil {
return nil, nil, skippedInvalidPolicies, nil, err
Mutate existing CLI support (#11453) * feat: Add flags for target resources and add fake client initialization Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add fake discovery client and cluster bool in the policy processor Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use the full mutation engine policy response in the engine response Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Extract mutated targets from the policy responses and print them out Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add TargetResources field in the cli test schema Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Generate CLI crds Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: modify checkResult to take an arbitrary actual resource and resource name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: change getAndCompareResource to take a resource name and cascade it to GetResourceFromPath Signed-off-by: aerosouund <aerosound161@gmail.com> * test: Create a simple test to test mutate existing in the CLI Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Allow GetResourceFromPath to select a resource with a name from a multi resource yaml Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Modify the runTest command to return the TestResponse type - Create a fake client, load the target resources in it and use it in the PolicyProcessor. - Create the TestResponse which contains Trigger and Target fields, each is a map of gvk/name to the responses corresponding to that resource. Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Rewrite output.go to use the TestResponse type - Check for both target and trigger - Create logic for appending the resource array in case no resources are passed - Move row creation logic into a separate method to avoid code duplication - Extract the proper target resource based on rule type - Create a function to extract mutated target from the engine response Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Move tests to the correct folder Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use apiVersion/Kind/Name as the key in the test responses Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use the apiVersion/Kind/name key schema in checking results and fix invalid resource name checking for generate policies Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use better variable names for rows Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Account for Generate resources being an array Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use generated resource name in checking the results and printing output Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Uncomment checks printing Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Remove bug in engine response creation Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Move the generate logic into an else block Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix namespace fetching bug in cel validator Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use pointer to int in the test counter Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Remove redundant method Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Skip resources not being found in the manifests Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Create another field in the engine to denote if this is a cluster engine or an offline engine Simply checking for the client being nil is no longer enough because for cli operations the client will be a fake client A pointer to bool is chosen because callers who don't necessarily know what to pass should be able to pass nil Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Add extra argument in fake client initiation Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: add extra argument in fuzz test Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Add extra arg Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Handle resources specified as ns/name as this schema will be deprecated in favor of apiVersion/Kind/Name Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Fix linter complaints Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Use comma separation as array separators as kubernetes names don't support commas To avoid undefined array length on splitting on / using commas will result in a fixed length since all resources will have an apiVersion, kind, namespace and name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Change resource array type to an array of any instead of array of string To support the use of a string or a TestResourceSpec Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Expect the resource array to be an array of string or array of TestResourceSpec Assert that an array element is either of these types and match the resources in both cases according to the element type Expect that the key in responses is now separated by commas instead of slashes Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Expect that the resource array is now of type array of any and modify tests that use it Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Skip response check if the policy name isnt whats in the result Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Match the name if its specified as ns/name Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Create CLI CRDs Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix linter complaints Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Cleanup invalid code used in FixTest to adapt it to the schema changes Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Check if resource is nil before extracting Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: use the loadResources method to open targets in a directory Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Account for target resources with the same name but different namespaces Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Add CLI test for mutate existing with the same name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Infer resource name and namespace from the actual resource and account for resources with the same name and namespace but different kinds Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: remove extra line Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add printing mutate existing resources to the output or to a file Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Minor fixes Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Revert result back to error Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use io discard to not print resources in the test command Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Update vague comments and remove outdated ones Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Integrate mutate existing changes with diff generation Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Move resource key generation into a function Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Add a mutate existing test that fails Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Remove redundant comment Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Fix array of any assignment in cli test Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Dont check duplicate strings for field that is an array of any Signed-off-by: aerosouund <aerosound161@gmail.com> * bug: Fix appending to the wrong array Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: run fix tests Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run fix tests Signed-off-by: aerosouund <aerosound161@gmail.com> --------- Signed-off-by: aerosouund <aerosound161@gmail.com> Signed-off-by: ammar <ammar.yasser@vodafone.com> Signed-off-by: Ammar Yasser <aerosound161@gmail.com> Co-authored-by: ammar <ammar.yasser@vodafone.com> Co-authored-by: shuting <shuting@nirmata.com>
2024-12-19 09:42:54 +02:00
}
}
dClient, err := c.initStoreAndClusterClient(&store, targetResources...)
if err != nil {
return nil, nil, skippedInvalidPolicies, nil, err
}
Mutate existing CLI support (#11453) * feat: Add flags for target resources and add fake client initialization Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add fake discovery client and cluster bool in the policy processor Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use the full mutation engine policy response in the engine response Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Extract mutated targets from the policy responses and print them out Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add TargetResources field in the cli test schema Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Generate CLI crds Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: modify checkResult to take an arbitrary actual resource and resource name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: change getAndCompareResource to take a resource name and cascade it to GetResourceFromPath Signed-off-by: aerosouund <aerosound161@gmail.com> * test: Create a simple test to test mutate existing in the CLI Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Allow GetResourceFromPath to select a resource with a name from a multi resource yaml Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Modify the runTest command to return the TestResponse type - Create a fake client, load the target resources in it and use it in the PolicyProcessor. - Create the TestResponse which contains Trigger and Target fields, each is a map of gvk/name to the responses corresponding to that resource. Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Rewrite output.go to use the TestResponse type - Check for both target and trigger - Create logic for appending the resource array in case no resources are passed - Move row creation logic into a separate method to avoid code duplication - Extract the proper target resource based on rule type - Create a function to extract mutated target from the engine response Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Move tests to the correct folder Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use apiVersion/Kind/Name as the key in the test responses Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use the apiVersion/Kind/name key schema in checking results and fix invalid resource name checking for generate policies Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use better variable names for rows Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Account for Generate resources being an array Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use generated resource name in checking the results and printing output Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Uncomment checks printing Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Remove bug in engine response creation Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Move the generate logic into an else block Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix namespace fetching bug in cel validator Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use pointer to int in the test counter Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Remove redundant method Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Skip resources not being found in the manifests Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Create another field in the engine to denote if this is a cluster engine or an offline engine Simply checking for the client being nil is no longer enough because for cli operations the client will be a fake client A pointer to bool is chosen because callers who don't necessarily know what to pass should be able to pass nil Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Add extra argument in fake client initiation Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: add extra argument in fuzz test Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Add extra arg Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Handle resources specified as ns/name as this schema will be deprecated in favor of apiVersion/Kind/Name Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Fix linter complaints Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Use comma separation as array separators as kubernetes names don't support commas To avoid undefined array length on splitting on / using commas will result in a fixed length since all resources will have an apiVersion, kind, namespace and name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Change resource array type to an array of any instead of array of string To support the use of a string or a TestResourceSpec Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Expect the resource array to be an array of string or array of TestResourceSpec Assert that an array element is either of these types and match the resources in both cases according to the element type Expect that the key in responses is now separated by commas instead of slashes Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Expect that the resource array is now of type array of any and modify tests that use it Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Skip response check if the policy name isnt whats in the result Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Match the name if its specified as ns/name Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Create CLI CRDs Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix linter complaints Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Cleanup invalid code used in FixTest to adapt it to the schema changes Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Check if resource is nil before extracting Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: use the loadResources method to open targets in a directory Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Account for target resources with the same name but different namespaces Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Add CLI test for mutate existing with the same name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Infer resource name and namespace from the actual resource and account for resources with the same name and namespace but different kinds Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: remove extra line Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add printing mutate existing resources to the output or to a file Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Minor fixes Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Revert result back to error Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use io discard to not print resources in the test command Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Update vague comments and remove outdated ones Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Integrate mutate existing changes with diff generation Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Move resource key generation into a function Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Add a mutate existing test that fails Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Remove redundant comment Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Fix array of any assignment in cli test Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Dont check duplicate strings for field that is an array of any Signed-off-by: aerosouund <aerosound161@gmail.com> * bug: Fix appending to the wrong array Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: run fix tests Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run fix tests Signed-off-by: aerosouund <aerosound161@gmail.com> --------- Signed-off-by: aerosouund <aerosound161@gmail.com> Signed-off-by: ammar <ammar.yasser@vodafone.com> Signed-off-by: Ammar Yasser <aerosound161@gmail.com> Co-authored-by: ammar <ammar.yasser@vodafone.com> Co-authored-by: shuting <shuting@nirmata.com>
2024-12-19 09:42:54 +02:00
resources, err := c.loadResources(out, c.ResourcePaths, policies, vaps, dClient)
if err != nil {
return nil, nil, skippedInvalidPolicies, nil, err
}
var exceptions []*kyvernov2.PolicyException
if c.inlineExceptions {
exceptions = exception.SelectFrom(resources)
} else {
exceptions, err = exception.Load(c.Exception...)
if err != nil {
return nil, nil, skippedInvalidPolicies, nil, fmt.Errorf("Error: failed to load exceptions (%s)", err)
}
Support PolicyExceptions with CLI (#9525) * loding policyExecptions from func Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * adding PolicyExceptions in crds Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * adding PolicyExceptions in GetPolicy function Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * adding policyexceptions in Load function Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * resolve error becuase of now Getpolicy return policyexceptions Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * added -exception flag loaded policyexception Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * added policyexceptions in processor and NewEngine Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * Revert "added -exception flag loaded policyexception" This reverts commit f53b205c089e780033b14c9a6343a141c20875b6. * Revert "Added support for PolicyExceptions for apply command " This reverts commit 82689ea0c1b914c566ac8ef30ab863f33d9b5460. * Update cmd/cli/kubectl-kyverno/commands/test/test.go loading exceptions with policies Co-authored-by: Mariam Fahmy <mariamfahmy66@gmail.com> Signed-off-by: Sanskar Gurdasani <92817635+Sanskarzz@users.noreply.github.com> * updated GetFullPaths function and remove unnecessary code Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * added tests for loading exceptions in GetPolicy function Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * added tests for loading policy exceptions Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * Used selector in List function Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * generated cli crd Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * updated loadpolicy_test tests and corrected kind Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * resolved unit test error in path_test.go file Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * limiting the usage of exceptions to ValidatingAdmissionPolicies Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * remove changes in common code Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes 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> --------- Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> Signed-off-by: Sanskar Gurdasani <92817635+Sanskarzz@users.noreply.github.com> Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Co-authored-by: Mariam Fahmy <mariamfahmy66@gmail.com> Co-authored-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com>
2024-02-01 03:58:14 +05:30
}
if !c.Stdin && !c.PolicyReport && !c.GenerateExceptions {
var policyRulesCount int
for _, policy := range policies {
policyRulesCount += len(autogen.Default.ComputeRules(policy, ""))
}
// account for vaps
policyRulesCount += len(vaps)
// account for vps
policyRulesCount += len(vps)
Support PolicyExceptions with CLI (#9525) * loding policyExecptions from func Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * adding PolicyExceptions in crds Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * adding PolicyExceptions in GetPolicy function Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * adding policyexceptions in Load function Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * resolve error becuase of now Getpolicy return policyexceptions Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * added -exception flag loaded policyexception Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * added policyexceptions in processor and NewEngine Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * Revert "added -exception flag loaded policyexception" This reverts commit f53b205c089e780033b14c9a6343a141c20875b6. * Revert "Added support for PolicyExceptions for apply command " This reverts commit 82689ea0c1b914c566ac8ef30ab863f33d9b5460. * Update cmd/cli/kubectl-kyverno/commands/test/test.go loading exceptions with policies Co-authored-by: Mariam Fahmy <mariamfahmy66@gmail.com> Signed-off-by: Sanskar Gurdasani <92817635+Sanskarzz@users.noreply.github.com> * updated GetFullPaths function and remove unnecessary code Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * added tests for loading exceptions in GetPolicy function Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * added tests for loading policy exceptions Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * Used selector in List function Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * generated cli crd Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * updated loadpolicy_test tests and corrected kind Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * resolved unit test error in path_test.go file Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * limiting the usage of exceptions to ValidatingAdmissionPolicies Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * remove changes in common code Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes 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> --------- Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> Signed-off-by: Sanskar Gurdasani <92817635+Sanskarzz@users.noreply.github.com> Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Co-authored-by: Mariam Fahmy <mariamfahmy66@gmail.com> Co-authored-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com>
2024-02-01 03:58:14 +05:30
if len(exceptions) > 0 {
fmt.Fprintf(out, "\nApplying %d policy rule(s) to %d resource(s) with %d exception(s)...\n", policyRulesCount, len(resources), len(exceptions))
} else {
fmt.Fprintf(out, "\nApplying %d policy rule(s) to %d resource(s)...\n", policyRulesCount, len(resources))
}
}
rc, resources1, responses1, err := c.applyPolicies(
out,
&store,
variables,
policies,
resources,
Support PolicyExceptions with CLI (#9525) * loding policyExecptions from func Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * adding PolicyExceptions in crds Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * adding PolicyExceptions in GetPolicy function Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * adding policyexceptions in Load function Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * resolve error becuase of now Getpolicy return policyexceptions Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * added -exception flag loaded policyexception Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * added policyexceptions in processor and NewEngine Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * Revert "added -exception flag loaded policyexception" This reverts commit f53b205c089e780033b14c9a6343a141c20875b6. * Revert "Added support for PolicyExceptions for apply command " This reverts commit 82689ea0c1b914c566ac8ef30ab863f33d9b5460. * Update cmd/cli/kubectl-kyverno/commands/test/test.go loading exceptions with policies Co-authored-by: Mariam Fahmy <mariamfahmy66@gmail.com> Signed-off-by: Sanskar Gurdasani <92817635+Sanskarzz@users.noreply.github.com> * updated GetFullPaths function and remove unnecessary code Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * added tests for loading exceptions in GetPolicy function Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * added tests for loading policy exceptions Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * Used selector in List function Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * generated cli crd Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * updated loadpolicy_test tests and corrected kind Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * resolved unit test error in path_test.go file Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * limiting the usage of exceptions to ValidatingAdmissionPolicies Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * remove changes in common code Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes 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> --------- Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> Signed-off-by: Sanskar Gurdasani <92817635+Sanskarzz@users.noreply.github.com> Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Co-authored-by: Mariam Fahmy <mariamfahmy66@gmail.com> Co-authored-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com>
2024-02-01 03:58:14 +05:30
exceptions,
&skippedInvalidPolicies,
dClient,
userInfo,
mutateLogPathIsDir,
)
if err != nil {
return rc, resources1, skippedInvalidPolicies, responses1, err
}
responses2, err := c.applyValidatingAdmissionPolicies(vaps, vapBindings, resources1, variables.NamespaceSelectors(), rc, dClient)
if err != nil {
return rc, resources1, skippedInvalidPolicies, responses1, err
}
responses3, err := c.applyValidatingPolicies(vps, resources1, variables.Namespace, rc, dClient)
if err != nil {
return rc, resources1, skippedInvalidPolicies, responses1, err
}
var responses []engineapi.EngineResponse
responses = append(responses, responses1...)
responses = append(responses, responses2...)
responses = append(responses, responses3...)
return rc, resources1, skippedInvalidPolicies, responses, nil
}
func (c *ApplyCommandConfig) getMutateLogPathIsDir() (bool, error) {
mutateLogPathIsDir, err := checkMutateLogPath(c.MutateLogPath)
if err != nil {
return false, fmt.Errorf("failed to create file/folder (%w)", err)
}
return mutateLogPathIsDir, nil
}
func (c *ApplyCommandConfig) applyValidatingAdmissionPolicies(
vaps []admissionregistrationv1beta1.ValidatingAdmissionPolicy,
vapBindings []admissionregistrationv1beta1.ValidatingAdmissionPolicyBinding,
resources []*unstructured.Unstructured,
namespaceSelectorMap map[string]map[string]string,
rc *processor.ResultCounts,
dClient dclient.Interface,
) ([]engineapi.EngineResponse, error) {
var responses []engineapi.EngineResponse
for _, resource := range resources {
processor := processor.ValidatingAdmissionPolicyProcessor{
Policies: vaps,
Bindings: vapBindings,
Resource: resource,
NamespaceSelectorMap: namespaceSelectorMap,
PolicyReport: c.PolicyReport,
Rc: rc,
Client: dClient,
}
ers, err := processor.ApplyPolicyOnResource()
if err != nil {
if c.ContinueOnFail {
fmt.Printf("failed to apply policies on resource %s (%v)\n", resource.GetName(), err)
continue
}
return responses, fmt.Errorf("failed to apply policies on resource %s (%w)", resource.GetName(), err)
}
responses = append(responses, ers...)
}
return responses, nil
}
func (c *ApplyCommandConfig) applyValidatingPolicies(
vps []kyvernov2alpha1.ValidatingPolicy,
resources []*unstructured.Unstructured,
namespaceProvider func(string) *corev1.Namespace,
_ *processor.ResultCounts,
dclient dclient.Interface,
) ([]engineapi.EngineResponse, error) {
ctx := context.TODO()
compiler := celpolicy.NewCompiler()
provider, err := engine.NewProvider(compiler, vps...)
if err != nil {
return nil, err
}
eng := engine.NewEngine(provider, namespaceProvider, nil)
// TODO: mock when no cluster provided
var contextProvider celpolicy.Context
if dclient != nil {
contextProvider = celpolicy.NewContextProvider(dclient.GetKubeClient())
}
responses := make([]engineapi.EngineResponse, 0)
for _, resource := range resources {
request := engine.EngineRequest{
Context: contextProvider,
Resource: resource,
}
response, err := eng.Handle(ctx, request)
if err != nil {
if c.ContinueOnFail {
fmt.Printf("failed to apply validating policies on resource %s (%v)\n", resource.GetName(), err)
continue
}
return responses, fmt.Errorf("failed to apply validating policies on resource %s (%w)", resource.GetName(), err)
}
// transform response into legacy engine responses
for _, r := range response.Policies {
engineResponse := engineapi.EngineResponse{
Resource: *response.Resource,
PolicyResponse: engineapi.PolicyResponse{
Rules: r.Rules,
},
}
engineResponse = engineResponse.WithPolicy(engineapi.NewValidatingPolicy(&r.Policy))
responses = append(responses, engineResponse)
}
}
return responses, nil
}
func (c *ApplyCommandConfig) applyPolicies(
out io.Writer,
store *store.Store,
vars *variables.Variables,
policies []kyvernov1.PolicyInterface,
resources []*unstructured.Unstructured,
exceptions []*kyvernov2.PolicyException,
skipInvalidPolicies *SkippedInvalidPolicies,
dClient dclient.Interface,
userInfo *kyvernov2.RequestInfo,
mutateLogPathIsDir bool,
) (*processor.ResultCounts, []*unstructured.Unstructured, []engineapi.EngineResponse, error) {
if vars != nil {
vars.SetInStore(store)
}
var rc processor.ResultCounts
// validate policies
validPolicies := make([]kyvernov1.PolicyInterface, 0, len(policies))
for _, pol := range policies {
// TODO we should return this info to the caller
remove wildcard permissions (#10785) * remove wildcard permissions Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update codegen Signed-off-by: Jim Bugwadia <jim@nirmata.com> * codegen Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix background controller perms Signed-off-by: Jim Bugwadia <jim@nirmata.com> * remove secrets perm Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix reports-controller role Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add wildcard check and limit generate policy checks based on `synchronize` Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update manifest Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix permissions Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix wildcard check Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update default QPS and burst for better performance and to prevent test failure Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix test permissions Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix test permissions Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix test permissions Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix test permissions Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix test permissions Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix test permissions Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix test permissions Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix perms Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix perms Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix test permissions Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix test permissions Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix merge issues Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix merge issues Signed-off-by: Jim Bugwadia <jim@nirmata.com> --------- Signed-off-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Mariam Fahmy <mariam.fahmy@nirmata.com>
2024-08-20 01:55:32 -07:00
sa := config.KyvernoUserName(config.KyvernoServiceAccountName())
_, err := policyvalidation.Validate(pol, nil, nil, nil, true, sa, sa)
if err != nil {
log.Log.Error(err, "policy validation error")
rc.IncrementError(1)
if strings.HasPrefix(err.Error(), "variable 'element.name'") {
skipInvalidPolicies.invalid = append(skipInvalidPolicies.invalid, pol.GetName())
} else {
skipInvalidPolicies.skipped = append(skipInvalidPolicies.skipped, pol.GetName())
}
continue
}
validPolicies = append(validPolicies, pol)
}
var responses []engineapi.EngineResponse
for _, resource := range resources {
processor := processor.PolicyProcessor{
Store: store,
Policies: validPolicies,
Resource: *resource,
Support PolicyExceptions with CLI (#9525) * loding policyExecptions from func Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * adding PolicyExceptions in crds Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * adding PolicyExceptions in GetPolicy function Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * adding policyexceptions in Load function Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * resolve error becuase of now Getpolicy return policyexceptions Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * added -exception flag loaded policyexception Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * added policyexceptions in processor and NewEngine Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * Revert "added -exception flag loaded policyexception" This reverts commit f53b205c089e780033b14c9a6343a141c20875b6. * Revert "Added support for PolicyExceptions for apply command " This reverts commit 82689ea0c1b914c566ac8ef30ab863f33d9b5460. * Update cmd/cli/kubectl-kyverno/commands/test/test.go loading exceptions with policies Co-authored-by: Mariam Fahmy <mariamfahmy66@gmail.com> Signed-off-by: Sanskar Gurdasani <92817635+Sanskarzz@users.noreply.github.com> * updated GetFullPaths function and remove unnecessary code Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * added tests for loading exceptions in GetPolicy function Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * added tests for loading policy exceptions Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * Used selector in List function Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * generated cli crd Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * updated loadpolicy_test tests and corrected kind Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * resolved unit test error in path_test.go file Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * limiting the usage of exceptions to ValidatingAdmissionPolicies Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> * remove changes in common code Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes 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> --------- Signed-off-by: Sanskarzz <sanskar.gur@gmail.com> Signed-off-by: Sanskar Gurdasani <92817635+Sanskarzz@users.noreply.github.com> Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Co-authored-by: Mariam Fahmy <mariamfahmy66@gmail.com> Co-authored-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com>
2024-02-01 03:58:14 +05:30
PolicyExceptions: exceptions,
MutateLogPath: c.MutateLogPath,
MutateLogPathIsDir: mutateLogPathIsDir,
Variables: vars,
UserInfo: userInfo,
PolicyReport: c.PolicyReport,
NamespaceSelectorMap: vars.NamespaceSelectors(),
Stdin: c.Stdin,
Rc: &rc,
PrintPatchResource: true,
Mutate existing CLI support (#11453) * feat: Add flags for target resources and add fake client initialization Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add fake discovery client and cluster bool in the policy processor Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use the full mutation engine policy response in the engine response Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Extract mutated targets from the policy responses and print them out Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add TargetResources field in the cli test schema Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Generate CLI crds Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: modify checkResult to take an arbitrary actual resource and resource name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: change getAndCompareResource to take a resource name and cascade it to GetResourceFromPath Signed-off-by: aerosouund <aerosound161@gmail.com> * test: Create a simple test to test mutate existing in the CLI Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Allow GetResourceFromPath to select a resource with a name from a multi resource yaml Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Modify the runTest command to return the TestResponse type - Create a fake client, load the target resources in it and use it in the PolicyProcessor. - Create the TestResponse which contains Trigger and Target fields, each is a map of gvk/name to the responses corresponding to that resource. Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Rewrite output.go to use the TestResponse type - Check for both target and trigger - Create logic for appending the resource array in case no resources are passed - Move row creation logic into a separate method to avoid code duplication - Extract the proper target resource based on rule type - Create a function to extract mutated target from the engine response Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Move tests to the correct folder Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use apiVersion/Kind/Name as the key in the test responses Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use the apiVersion/Kind/name key schema in checking results and fix invalid resource name checking for generate policies Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use better variable names for rows Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Account for Generate resources being an array Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use generated resource name in checking the results and printing output Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Uncomment checks printing Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Remove bug in engine response creation Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Move the generate logic into an else block Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix namespace fetching bug in cel validator Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use pointer to int in the test counter Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Remove redundant method Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Skip resources not being found in the manifests Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Create another field in the engine to denote if this is a cluster engine or an offline engine Simply checking for the client being nil is no longer enough because for cli operations the client will be a fake client A pointer to bool is chosen because callers who don't necessarily know what to pass should be able to pass nil Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Add extra argument in fake client initiation Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: add extra argument in fuzz test Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Add extra arg Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Handle resources specified as ns/name as this schema will be deprecated in favor of apiVersion/Kind/Name Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Fix linter complaints Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Use comma separation as array separators as kubernetes names don't support commas To avoid undefined array length on splitting on / using commas will result in a fixed length since all resources will have an apiVersion, kind, namespace and name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Change resource array type to an array of any instead of array of string To support the use of a string or a TestResourceSpec Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Expect the resource array to be an array of string or array of TestResourceSpec Assert that an array element is either of these types and match the resources in both cases according to the element type Expect that the key in responses is now separated by commas instead of slashes Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Expect that the resource array is now of type array of any and modify tests that use it Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Skip response check if the policy name isnt whats in the result Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Match the name if its specified as ns/name Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Create CLI CRDs Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix linter complaints Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Cleanup invalid code used in FixTest to adapt it to the schema changes Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Check if resource is nil before extracting Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: use the loadResources method to open targets in a directory Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Account for target resources with the same name but different namespaces Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Add CLI test for mutate existing with the same name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Infer resource name and namespace from the actual resource and account for resources with the same name and namespace but different kinds Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: remove extra line Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add printing mutate existing resources to the output or to a file Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Minor fixes Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Revert result back to error Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use io discard to not print resources in the test command Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Update vague comments and remove outdated ones Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Integrate mutate existing changes with diff generation Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Move resource key generation into a function Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Add a mutate existing test that fails Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Remove redundant comment Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Fix array of any assignment in cli test Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Dont check duplicate strings for field that is an array of any Signed-off-by: aerosouund <aerosound161@gmail.com> * bug: Fix appending to the wrong array Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: run fix tests Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run fix tests Signed-off-by: aerosouund <aerosound161@gmail.com> --------- Signed-off-by: aerosouund <aerosound161@gmail.com> Signed-off-by: ammar <ammar.yasser@vodafone.com> Signed-off-by: Ammar Yasser <aerosound161@gmail.com> Co-authored-by: ammar <ammar.yasser@vodafone.com> Co-authored-by: shuting <shuting@nirmata.com>
2024-12-19 09:42:54 +02:00
Cluster: c.Cluster,
Client: dClient,
AuditWarn: c.AuditWarn,
Subresources: vars.Subresources(),
Out: out,
}
ers, err := processor.ApplyPoliciesOnResource()
if err != nil {
if c.ContinueOnFail {
log.Log.Info(fmt.Sprintf("failed to apply policies on resource %s (%s)\n", resource.GetName(), err.Error()))
continue
}
return &rc, resources, responses, fmt.Errorf("failed to apply policies on resource %s (%w)", resource.GetName(), err)
}
responses = append(responses, ers...)
2020-12-20 01:21:31 +05:30
}
for _, policy := range validPolicies {
if policy.GetNamespace() == "" && policy.GetKind() == "Policy" {
log.Log.Info(fmt.Sprintf("Policy %s has no namespace detected. Ensure that namespaced policies are correctly loaded.", policy.GetNamespace()))
}
}
return &rc, resources, responses, nil
}
Mutate existing CLI support (#11453) * feat: Add flags for target resources and add fake client initialization Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add fake discovery client and cluster bool in the policy processor Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use the full mutation engine policy response in the engine response Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Extract mutated targets from the policy responses and print them out Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add TargetResources field in the cli test schema Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Generate CLI crds Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: modify checkResult to take an arbitrary actual resource and resource name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: change getAndCompareResource to take a resource name and cascade it to GetResourceFromPath Signed-off-by: aerosouund <aerosound161@gmail.com> * test: Create a simple test to test mutate existing in the CLI Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Allow GetResourceFromPath to select a resource with a name from a multi resource yaml Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Modify the runTest command to return the TestResponse type - Create a fake client, load the target resources in it and use it in the PolicyProcessor. - Create the TestResponse which contains Trigger and Target fields, each is a map of gvk/name to the responses corresponding to that resource. Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Rewrite output.go to use the TestResponse type - Check for both target and trigger - Create logic for appending the resource array in case no resources are passed - Move row creation logic into a separate method to avoid code duplication - Extract the proper target resource based on rule type - Create a function to extract mutated target from the engine response Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Move tests to the correct folder Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use apiVersion/Kind/Name as the key in the test responses Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use the apiVersion/Kind/name key schema in checking results and fix invalid resource name checking for generate policies Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use better variable names for rows Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Account for Generate resources being an array Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use generated resource name in checking the results and printing output Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Uncomment checks printing Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Remove bug in engine response creation Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Move the generate logic into an else block Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix namespace fetching bug in cel validator Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use pointer to int in the test counter Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Remove redundant method Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Skip resources not being found in the manifests Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Create another field in the engine to denote if this is a cluster engine or an offline engine Simply checking for the client being nil is no longer enough because for cli operations the client will be a fake client A pointer to bool is chosen because callers who don't necessarily know what to pass should be able to pass nil Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Add extra argument in fake client initiation Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: add extra argument in fuzz test Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Add extra arg Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Handle resources specified as ns/name as this schema will be deprecated in favor of apiVersion/Kind/Name Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Fix linter complaints Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Use comma separation as array separators as kubernetes names don't support commas To avoid undefined array length on splitting on / using commas will result in a fixed length since all resources will have an apiVersion, kind, namespace and name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Change resource array type to an array of any instead of array of string To support the use of a string or a TestResourceSpec Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Expect the resource array to be an array of string or array of TestResourceSpec Assert that an array element is either of these types and match the resources in both cases according to the element type Expect that the key in responses is now separated by commas instead of slashes Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Expect that the resource array is now of type array of any and modify tests that use it Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Skip response check if the policy name isnt whats in the result Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Match the name if its specified as ns/name Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Create CLI CRDs Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix linter complaints Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Cleanup invalid code used in FixTest to adapt it to the schema changes Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Check if resource is nil before extracting Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: use the loadResources method to open targets in a directory Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Account for target resources with the same name but different namespaces Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Add CLI test for mutate existing with the same name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Infer resource name and namespace from the actual resource and account for resources with the same name and namespace but different kinds Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: remove extra line Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add printing mutate existing resources to the output or to a file Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Minor fixes Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Revert result back to error Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use io discard to not print resources in the test command Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Update vague comments and remove outdated ones Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Integrate mutate existing changes with diff generation Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Move resource key generation into a function Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Add a mutate existing test that fails Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Remove redundant comment Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Fix array of any assignment in cli test Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Dont check duplicate strings for field that is an array of any Signed-off-by: aerosouund <aerosound161@gmail.com> * bug: Fix appending to the wrong array Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: run fix tests Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run fix tests Signed-off-by: aerosouund <aerosound161@gmail.com> --------- Signed-off-by: aerosouund <aerosound161@gmail.com> Signed-off-by: ammar <ammar.yasser@vodafone.com> Signed-off-by: Ammar Yasser <aerosound161@gmail.com> Co-authored-by: ammar <ammar.yasser@vodafone.com> Co-authored-by: shuting <shuting@nirmata.com>
2024-12-19 09:42:54 +02:00
func (c *ApplyCommandConfig) loadResources(out io.Writer, paths []string, policies []kyvernov1.PolicyInterface, vap []admissionregistrationv1beta1.ValidatingAdmissionPolicy, dClient dclient.Interface) ([]*unstructured.Unstructured, error) {
resources, err := common.GetResourceAccordingToResourcePath(out, nil, paths, c.Cluster, policies, vap, dClient, c.Namespace, c.PolicyReport, "")
if err != nil {
return resources, fmt.Errorf("failed to load resources (%w)", err)
}
return resources, nil
}
func (c *ApplyCommandConfig) loadPolicies() (
[]kyvernov1.PolicyInterface,
[]admissionregistrationv1beta1.ValidatingAdmissionPolicy,
[]admissionregistrationv1beta1.ValidatingAdmissionPolicyBinding,
[]kyvernov2alpha1.ValidatingPolicy,
error,
) {
// load policies
var policies []kyvernov1.PolicyInterface
var vaps []admissionregistrationv1beta1.ValidatingAdmissionPolicy
var vapBindings []admissionregistrationv1beta1.ValidatingAdmissionPolicyBinding
var vps []kyvernov2alpha1.ValidatingPolicy
for _, path := range c.PolicyPaths {
isGit := source.IsGit(path)
if isGit {
gitSourceURL, err := url.Parse(path)
if err != nil {
return nil, nil, nil, nil, fmt.Errorf("failed to load policies (%w)", err)
}
pathElems := strings.Split(gitSourceURL.Path[1:], "/")
if len(pathElems) <= 1 {
err := fmt.Errorf("invalid URL path %s - expected https://<any_git_source_domain>/:owner/:repository/:branch (without --git-branch flag) OR https://<any_git_source_domain>/:owner/:repository/:directory (with --git-branch flag)", gitSourceURL.Path)
return nil, nil, nil, nil, fmt.Errorf("failed to parse URL (%w)", err)
}
gitSourceURL.Path = strings.Join([]string{pathElems[0], pathElems[1]}, "/")
repoURL := gitSourceURL.String()
var gitPathToYamls string
c.GitBranch, gitPathToYamls = common.GetGitBranchOrPolicyPaths(c.GitBranch, repoURL, path)
fs := memfs.New()
if _, err := gitutils.Clone(repoURL, fs, c.GitBranch); err != nil {
log.Log.V(3).Info(fmt.Sprintf("failed to clone repository %v as it is not valid", repoURL), "error", err)
return nil, nil, nil, nil, fmt.Errorf("failed to clone repository (%w)", err)
}
policyYamls, err := gitutils.ListYamls(fs, gitPathToYamls)
if err != nil {
return nil, nil, nil, nil, fmt.Errorf("failed to list YAMLs in repository (%w)", err)
}
for _, policyYaml := range policyYamls {
loaderResults, err := policy.Load(fs, "", policyYaml)
if loaderResults != nil && loaderResults.NonFatalErrors != nil {
for _, err := range loaderResults.NonFatalErrors {
log.Log.Error(err.Error, "Non-fatal parsing error for single document")
}
}
if err != nil {
continue
}
policies = append(policies, loaderResults.Policies...)
vaps = append(vaps, loaderResults.VAPs...)
vapBindings = append(vapBindings, loaderResults.VAPBindings...)
vps = append(vps, loaderResults.ValidatingPolicies...)
}
} else {
loaderResults, err := policy.Load(nil, "", path)
if loaderResults != nil && loaderResults.NonFatalErrors != nil {
for _, err := range loaderResults.NonFatalErrors {
log.Log.Error(err.Error, "Non-fatal parsing error for single document")
}
}
if err != nil {
log.Log.V(3).Info("skipping invalid YAML file", "path", path, "error", err)
} else {
policies = append(policies, loaderResults.Policies...)
vaps = append(vaps, loaderResults.VAPs...)
vapBindings = append(vapBindings, loaderResults.VAPBindings...)
vps = append(vps, loaderResults.ValidatingPolicies...)
}
}
for _, policy := range policies {
if policy.GetNamespace() == "" && policy.GetKind() == "Policy" {
log.Log.V(3).Info(fmt.Sprintf("Namespace is empty for a namespaced Policy %s. This might cause incorrect report generation.", policy.GetNamespace()))
}
}
2020-12-20 01:21:31 +05:30
}
return policies, vaps, vapBindings, vps, nil
}
func (c *ApplyCommandConfig) initStoreAndClusterClient(store *store.Store, targetResources ...*unstructured.Unstructured) (dclient.Interface, error) {
store.SetLocal(true)
store.SetRegistryAccess(c.RegistryAccess)
if c.Cluster {
store.AllowApiCall(true)
2020-12-20 01:21:31 +05:30
}
var err error
var dClient dclient.Interface
if c.Cluster {
restConfig, err := config.CreateClientConfigWithContext(c.KubeConfig, c.Context)
2020-12-20 01:21:31 +05:30
if err != nil {
return nil, err
2020-12-20 01:21:31 +05:30
}
kubeClient, err := kubernetes.NewForConfig(restConfig)
if err != nil {
return nil, err
2020-12-20 01:21:31 +05:30
}
dynamicClient, err := dynamic.NewForConfig(restConfig)
if err != nil {
return nil, err
}
dClient, err = dclient.NewClient(context.Background(), dynamicClient, kubeClient, 15*time.Minute)
if err != nil {
return nil, err
2020-12-20 01:21:31 +05:30
}
2020-03-06 03:00:18 +05:30
}
Mutate existing CLI support (#11453) * feat: Add flags for target resources and add fake client initialization Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add fake discovery client and cluster bool in the policy processor Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use the full mutation engine policy response in the engine response Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Extract mutated targets from the policy responses and print them out Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add TargetResources field in the cli test schema Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Generate CLI crds Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: modify checkResult to take an arbitrary actual resource and resource name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: change getAndCompareResource to take a resource name and cascade it to GetResourceFromPath Signed-off-by: aerosouund <aerosound161@gmail.com> * test: Create a simple test to test mutate existing in the CLI Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Allow GetResourceFromPath to select a resource with a name from a multi resource yaml Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Modify the runTest command to return the TestResponse type - Create a fake client, load the target resources in it and use it in the PolicyProcessor. - Create the TestResponse which contains Trigger and Target fields, each is a map of gvk/name to the responses corresponding to that resource. Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Rewrite output.go to use the TestResponse type - Check for both target and trigger - Create logic for appending the resource array in case no resources are passed - Move row creation logic into a separate method to avoid code duplication - Extract the proper target resource based on rule type - Create a function to extract mutated target from the engine response Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Move tests to the correct folder Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use apiVersion/Kind/Name as the key in the test responses Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use the apiVersion/Kind/name key schema in checking results and fix invalid resource name checking for generate policies Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use better variable names for rows Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Account for Generate resources being an array Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use generated resource name in checking the results and printing output Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Uncomment checks printing Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Remove bug in engine response creation Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Move the generate logic into an else block Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix namespace fetching bug in cel validator Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use pointer to int in the test counter Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Remove redundant method Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Skip resources not being found in the manifests Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Create another field in the engine to denote if this is a cluster engine or an offline engine Simply checking for the client being nil is no longer enough because for cli operations the client will be a fake client A pointer to bool is chosen because callers who don't necessarily know what to pass should be able to pass nil Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Add extra argument in fake client initiation Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: add extra argument in fuzz test Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Add extra arg Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Handle resources specified as ns/name as this schema will be deprecated in favor of apiVersion/Kind/Name Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Fix linter complaints Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Use comma separation as array separators as kubernetes names don't support commas To avoid undefined array length on splitting on / using commas will result in a fixed length since all resources will have an apiVersion, kind, namespace and name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Change resource array type to an array of any instead of array of string To support the use of a string or a TestResourceSpec Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Expect the resource array to be an array of string or array of TestResourceSpec Assert that an array element is either of these types and match the resources in both cases according to the element type Expect that the key in responses is now separated by commas instead of slashes Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Expect that the resource array is now of type array of any and modify tests that use it Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Skip response check if the policy name isnt whats in the result Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Match the name if its specified as ns/name Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Create CLI CRDs Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix linter complaints Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Cleanup invalid code used in FixTest to adapt it to the schema changes Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Check if resource is nil before extracting Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: use the loadResources method to open targets in a directory Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Account for target resources with the same name but different namespaces Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Add CLI test for mutate existing with the same name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Infer resource name and namespace from the actual resource and account for resources with the same name and namespace but different kinds Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: remove extra line Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add printing mutate existing resources to the output or to a file Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Minor fixes Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Revert result back to error Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use io discard to not print resources in the test command Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Update vague comments and remove outdated ones Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Integrate mutate existing changes with diff generation Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Move resource key generation into a function Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Add a mutate existing test that fails Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Remove redundant comment Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Fix array of any assignment in cli test Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Dont check duplicate strings for field that is an array of any Signed-off-by: aerosouund <aerosound161@gmail.com> * bug: Fix appending to the wrong array Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: run fix tests Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run fix tests Signed-off-by: aerosouund <aerosound161@gmail.com> --------- Signed-off-by: aerosouund <aerosound161@gmail.com> Signed-off-by: ammar <ammar.yasser@vodafone.com> Signed-off-by: Ammar Yasser <aerosound161@gmail.com> Co-authored-by: ammar <ammar.yasser@vodafone.com> Co-authored-by: shuting <shuting@nirmata.com>
2024-12-19 09:42:54 +02:00
if len(targetResources) > 0 && !c.Cluster {
var targets []runtime.Object
for _, t := range targetResources {
targets = append(targets, t)
}
dClient, err = dclient.NewFakeClient(runtime.NewScheme(), map[schema.GroupVersionResource]string{}, targets...)
dClient.SetDiscovery(dclient.NewFakeDiscoveryClient(nil))
if err != nil {
return nil, err
Mutate existing CLI support (#11453) * feat: Add flags for target resources and add fake client initialization Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add fake discovery client and cluster bool in the policy processor Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use the full mutation engine policy response in the engine response Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Extract mutated targets from the policy responses and print them out Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add TargetResources field in the cli test schema Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Generate CLI crds Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: modify checkResult to take an arbitrary actual resource and resource name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: change getAndCompareResource to take a resource name and cascade it to GetResourceFromPath Signed-off-by: aerosouund <aerosound161@gmail.com> * test: Create a simple test to test mutate existing in the CLI Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Allow GetResourceFromPath to select a resource with a name from a multi resource yaml Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Modify the runTest command to return the TestResponse type - Create a fake client, load the target resources in it and use it in the PolicyProcessor. - Create the TestResponse which contains Trigger and Target fields, each is a map of gvk/name to the responses corresponding to that resource. Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Rewrite output.go to use the TestResponse type - Check for both target and trigger - Create logic for appending the resource array in case no resources are passed - Move row creation logic into a separate method to avoid code duplication - Extract the proper target resource based on rule type - Create a function to extract mutated target from the engine response Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Move tests to the correct folder Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use apiVersion/Kind/Name as the key in the test responses Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use the apiVersion/Kind/name key schema in checking results and fix invalid resource name checking for generate policies Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use better variable names for rows Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Account for Generate resources being an array Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use generated resource name in checking the results and printing output Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Uncomment checks printing Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Remove bug in engine response creation Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Move the generate logic into an else block Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix namespace fetching bug in cel validator Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use pointer to int in the test counter Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Remove redundant method Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Skip resources not being found in the manifests Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Create another field in the engine to denote if this is a cluster engine or an offline engine Simply checking for the client being nil is no longer enough because for cli operations the client will be a fake client A pointer to bool is chosen because callers who don't necessarily know what to pass should be able to pass nil Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Add extra argument in fake client initiation Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: add extra argument in fuzz test Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Add extra arg Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Handle resources specified as ns/name as this schema will be deprecated in favor of apiVersion/Kind/Name Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Fix linter complaints Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Use comma separation as array separators as kubernetes names don't support commas To avoid undefined array length on splitting on / using commas will result in a fixed length since all resources will have an apiVersion, kind, namespace and name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Change resource array type to an array of any instead of array of string To support the use of a string or a TestResourceSpec Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Expect the resource array to be an array of string or array of TestResourceSpec Assert that an array element is either of these types and match the resources in both cases according to the element type Expect that the key in responses is now separated by commas instead of slashes Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Expect that the resource array is now of type array of any and modify tests that use it Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Skip response check if the policy name isnt whats in the result Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Match the name if its specified as ns/name Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Create CLI CRDs Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix linter complaints Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Cleanup invalid code used in FixTest to adapt it to the schema changes Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Check if resource is nil before extracting Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: use the loadResources method to open targets in a directory Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Account for target resources with the same name but different namespaces Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Add CLI test for mutate existing with the same name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Infer resource name and namespace from the actual resource and account for resources with the same name and namespace but different kinds Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: remove extra line Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add printing mutate existing resources to the output or to a file Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Minor fixes Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Revert result back to error Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use io discard to not print resources in the test command Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Update vague comments and remove outdated ones Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Integrate mutate existing changes with diff generation Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Move resource key generation into a function Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Add a mutate existing test that fails Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Remove redundant comment Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Fix array of any assignment in cli test Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Dont check duplicate strings for field that is an array of any Signed-off-by: aerosouund <aerosound161@gmail.com> * bug: Fix appending to the wrong array Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: run fix tests Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run fix tests Signed-off-by: aerosouund <aerosound161@gmail.com> --------- Signed-off-by: aerosouund <aerosound161@gmail.com> Signed-off-by: ammar <ammar.yasser@vodafone.com> Signed-off-by: Ammar Yasser <aerosound161@gmail.com> Co-authored-by: ammar <ammar.yasser@vodafone.com> Co-authored-by: shuting <shuting@nirmata.com>
2024-12-19 09:42:54 +02:00
}
}
return dClient, err
}
2020-03-06 03:00:18 +05:30
func (c *ApplyCommandConfig) cleanPreviousContent(mutateLogPathIsDir bool) error {
// empty the previous contents of the file just in case if the file already existed before with some content(so as to perform overwrites)
// the truncation of files for the case when mutateLogPath is dir, is handled under pkg/kyverno/apply/common.go
if !mutateLogPathIsDir && c.MutateLogPath != "" {
c.MutateLogPath = filepath.Clean(c.MutateLogPath)
// Necessary for us to include the file via variable as it is part of the CLI.
_, err := os.OpenFile(c.MutateLogPath, os.O_TRUNC|os.O_WRONLY, 0o600) // #nosec G304
if err != nil {
return fmt.Errorf("failed to truncate the existing file at %s (%w)", c.MutateLogPath, err)
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
}
}
return 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
func (c *ApplyCommandConfig) checkArguments() error {
if c.ValuesFile != "" && c.Variables != nil {
return fmt.Errorf("pass the values either using set flag or values_file flag")
}
if len(c.PolicyPaths) == 0 {
return fmt.Errorf("require policy")
}
if (len(c.PolicyPaths) > 0 && c.PolicyPaths[0] == "-") && len(c.ResourcePaths) > 0 && c.ResourcePaths[0] == "-" {
return fmt.Errorf("a stdin pipe can be used for either policies or resources, not both")
}
if len(c.ResourcePaths) == 0 && !c.Cluster {
return fmt.Errorf("resource file(s) or cluster required")
}
return nil
2020-03-06 03:00:18 +05:30
}
type WarnExitCodeError struct {
ExitCode int
}
func (w WarnExitCodeError) Error() string {
return fmt.Sprintf("exit as warnExitCode is %d", w.ExitCode)
}
func exit(out io.Writer, rc *processor.ResultCounts, warnExitCode int, warnNoPassed bool) error {
if rc.Fail > 0 {
return fmt.Errorf("exit as there are policy violations")
} else if rc.Error > 0 {
return fmt.Errorf("exit as there are policy errors")
} else if rc.Warn > 0 && warnExitCode != 0 {
fmt.Printf("exit as warnExitCode is %d", warnExitCode)
return WarnExitCodeError{
ExitCode: warnExitCode,
}
} else if rc.Pass == 0 && warnNoPassed {
fmt.Println(out, "exit as no objects satisfied policy")
return WarnExitCodeError{
ExitCode: warnExitCode,
}
}
return nil
}