mirror of
https://github.com/kyverno/kyverno.git
synced 2024-12-14 11:57:48 +00:00
chore: enable whitespace linter (#3864)
Signed-off-by: Charles-Edouard Brétéché <charled.breteche@gmail.com> Co-authored-by: Sambhav Kothari <sambhavs.email@gmail.com>
This commit is contained in:
parent
5532203091
commit
97e5e64fd4
52 changed files with 36 additions and 101 deletions
|
@ -12,6 +12,7 @@ linters:
|
|||
- typecheck
|
||||
- unused
|
||||
- varcheck
|
||||
- whitespace
|
||||
|
||||
run:
|
||||
timeout: 5m
|
||||
|
|
|
@ -317,7 +317,6 @@ func applyCommandHelper(resourcePaths []string, userInfoPath string, cluster boo
|
|||
return rc, resources, skipInvalidPolicies, pvInfos, sanitizederror.NewWithError(fmt.Errorf("failed to apply policy %v on resource %v", policy.GetName(), resource.GetName()).Error(), err)
|
||||
}
|
||||
pvInfos = append(pvInfos, info)
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -427,14 +426,12 @@ func createFileOrFolder(mutateLogPath string, mutateLogPathIsDir bool) error {
|
|||
if err != nil {
|
||||
return sanitizederror.NewWithError("failed to close file", err)
|
||||
}
|
||||
|
||||
} else {
|
||||
errDir := os.MkdirAll(mutateLogPath, 0750)
|
||||
if errDir != nil {
|
||||
return sanitizederror.NewWithError("failed to create directory", err)
|
||||
}
|
||||
}
|
||||
|
||||
} else {
|
||||
return sanitizederror.NewWithError("failed to describe file", err)
|
||||
}
|
||||
|
|
|
@ -422,7 +422,6 @@ func testCommandExecute(dirPath []string, fileName string, gitBranch string, tes
|
|||
if testYamlCount == 0 {
|
||||
fmt.Printf("\n No test yamls available \n")
|
||||
}
|
||||
|
||||
} else {
|
||||
var testFiles int
|
||||
path := filepath.Clean(dirPath[0])
|
||||
|
@ -528,7 +527,6 @@ func buildPolicyResults(engineResponses []*response.EngineResponse, testResults
|
|||
var resultsKey string
|
||||
resultsKey = GetResultKeyAccordingToTestResults(userDefinedPolicyNamespace, test.Policy, test.Rule, test.Namespace, test.Kind, test.Resource)
|
||||
if !util.ContainsString(rules, test.Rule) {
|
||||
|
||||
if !util.ContainsString(rules, "autogen-"+test.Rule) {
|
||||
if !util.ContainsString(rules, "autogen-cronjob-"+test.Rule) {
|
||||
result.Result = report.StatusSkip
|
||||
|
@ -554,7 +552,6 @@ func buildPolicyResults(engineResponses []*response.EngineResponse, testResults
|
|||
results[resultsKey] = result
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
for _, rule := range resp.PolicyResponse.Rules {
|
||||
|
@ -576,10 +573,8 @@ func buildPolicyResults(engineResponses []*response.EngineResponse, testResults
|
|||
|
||||
if rule.Status == response.RuleStatusSkip {
|
||||
result.Result = report.StatusSkip
|
||||
|
||||
} else if rule.Status == response.RuleStatusError {
|
||||
result.Result = report.StatusError
|
||||
|
||||
} else {
|
||||
var x string
|
||||
for _, path := range patchedResourcePath {
|
||||
|
@ -711,7 +706,6 @@ func getFullPath(paths []string, policyResourcePath string, isGit bool) []string
|
|||
}
|
||||
|
||||
func applyPoliciesFromPath(fs billy.Filesystem, policyBytes []byte, isGit bool, policyResourcePath string, rc *resultCounts, openAPIController *openapi.Controller, tf *testFilter) (err error) {
|
||||
|
||||
engineResponses := make([]*response.EngineResponse, 0)
|
||||
var dClient client.Interface
|
||||
values := &Test{}
|
||||
|
|
|
@ -120,7 +120,6 @@ func GetPolicies(paths []string) (policies []v1.PolicyInterface, errors []error)
|
|||
policiesFromDir, errorsFromDir := GetPolicies(listOfFiles)
|
||||
errors = append(errors, errorsFromDir...)
|
||||
policies = append(policies, policiesFromDir...)
|
||||
|
||||
} else {
|
||||
var fileBytes []byte
|
||||
if isHTTPPath {
|
||||
|
@ -378,8 +377,8 @@ func MutatePolicies(policies []v1.PolicyInterface) ([]v1.PolicyInterface, error)
|
|||
func ApplyPolicyOnResource(policy v1.PolicyInterface, resource *unstructured.Unstructured,
|
||||
mutateLogPath string, mutateLogPathIsDir bool, variables map[string]interface{}, userInfo v1beta1.RequestInfo, policyReport bool,
|
||||
namespaceSelectorMap map[string]map[string]string, stdin bool, rc *ResultCounts,
|
||||
printPatchResource bool) ([]*response.EngineResponse, policyreport.Info, error) {
|
||||
|
||||
printPatchResource bool,
|
||||
) ([]*response.EngineResponse, policyreport.Info, error) {
|
||||
var engineResponses []*response.EngineResponse
|
||||
namespaceLabels := make(map[string]string)
|
||||
operationIsDelete := false
|
||||
|
@ -676,7 +675,6 @@ func GetResourceAccordingToResourcePath(fs billy.Filesystem, resourcePaths []str
|
|||
return nil, err
|
||||
}
|
||||
if fileDesc.IsDir() {
|
||||
|
||||
files, err := ioutil.ReadDir(resourcePaths[0])
|
||||
if err != nil {
|
||||
return nil, sanitizederror.NewWithError(fmt.Sprintf("failed to parse %v", resourcePaths[0]), err)
|
||||
|
@ -773,7 +771,6 @@ func ProcessValidateEngineResponse(policy v1.PolicyInterface, validateResponse *
|
|||
}
|
||||
violatedRules = append(violatedRules, vruleSkip)
|
||||
}
|
||||
|
||||
}
|
||||
return buildPVInfo(validateResponse, violatedRules)
|
||||
}
|
||||
|
|
|
@ -151,7 +151,6 @@ func GetResourcesWithTest(fs billy.Filesystem, policies []v1.PolicyInterface, re
|
|||
}
|
||||
|
||||
resources = append(resources, getResources...)
|
||||
|
||||
}
|
||||
}
|
||||
return resources, nil
|
||||
|
@ -210,7 +209,6 @@ func getResourcesOfTypeFromCluster(resourceTypes []string, dClient client.Interf
|
|||
}
|
||||
|
||||
func getFileBytes(path string) ([]byte, error) {
|
||||
|
||||
var (
|
||||
file []byte
|
||||
err error
|
||||
|
|
|
@ -19,9 +19,12 @@ import (
|
|||
)
|
||||
|
||||
func NewBackgroundContext(dclient dclient.Interface, ur *urkyverno.UpdateRequest,
|
||||
policy kyverno.PolicyInterface, trigger *unstructured.Unstructured,
|
||||
cfg config.Configuration, namespaceLabels map[string]string, logger logr.Logger) (*engine.PolicyContext, bool, error) {
|
||||
|
||||
policy kyverno.PolicyInterface,
|
||||
trigger *unstructured.Unstructured,
|
||||
cfg config.Configuration,
|
||||
namespaceLabels map[string]string,
|
||||
logger logr.Logger,
|
||||
) (*engine.PolicyContext, bool, error) {
|
||||
ctx := context.NewContext()
|
||||
requestString := ur.Spec.Context.AdmissionRequestInfo.AdmissionRequest
|
||||
var request admissionv1.AdmissionRequest
|
||||
|
|
|
@ -277,7 +277,6 @@ func (c *Controller) syncUpdateRequest(key string) error {
|
|||
|
||||
if pNamespace == "" {
|
||||
_, err = c.pLister.Get(pName)
|
||||
|
||||
} else {
|
||||
_, err = c.npLister.Policies(pNamespace).Get(pName)
|
||||
}
|
||||
|
|
|
@ -78,7 +78,6 @@ func NewGenerateController(
|
|||
log logr.Logger,
|
||||
dynamicConfig config.Configuration,
|
||||
) (*GenerateController, error) {
|
||||
|
||||
c := GenerateController{
|
||||
client: client,
|
||||
kyvernoClient: kyvernoClient,
|
||||
|
@ -133,7 +132,6 @@ func (c *GenerateController) ProcessUR(ur *urkyverno.UpdateRequest) error {
|
|||
incrementedCountString := strconv.Itoa(sleepCountInt)
|
||||
urAnnotations["generate.kyverno.io/retry-count"] = incrementedCountString
|
||||
}
|
||||
|
||||
} else {
|
||||
time.Sleep(time.Second * 1)
|
||||
urAnnotations["generate.kyverno.io/retry-count"] = "1"
|
||||
|
@ -484,9 +482,7 @@ func applyRule(log logr.Logger, client dclient.Interface, rule kyverno.Rule, res
|
|||
}
|
||||
|
||||
logger.V(2).Info("created generate target resource")
|
||||
|
||||
} else if mode == Update {
|
||||
|
||||
generatedObj, err := client.GetResource(genAPIVersion, genKind, genNamespace, genName)
|
||||
if err != nil {
|
||||
logger.Error(err, fmt.Sprintf("generated resource not found name:%v namespace:%v kind:%v", genName, genNamespace, genKind))
|
||||
|
@ -607,7 +603,6 @@ func manageClone(log logr.Logger, apiVersion, kind, namespace, name, policy stri
|
|||
|
||||
// create the resource based on the reference clone
|
||||
return obj.UnstructuredContent(), Create, nil
|
||||
|
||||
}
|
||||
|
||||
// ResourceMode defines the mode for generated resource
|
||||
|
|
|
@ -62,7 +62,6 @@ func NewMutateExistingController(
|
|||
log logr.Logger,
|
||||
dynamicConfig config.Configuration,
|
||||
) (*MutateExistingController, error) {
|
||||
|
||||
c := MutateExistingController{
|
||||
client: client,
|
||||
kyvernoClient: kyvernoClient,
|
||||
|
|
|
@ -82,7 +82,6 @@ func NewController(
|
|||
log logr.Logger,
|
||||
dynamicConfig config.Configuration,
|
||||
) (*Controller, error) {
|
||||
|
||||
c := Controller{
|
||||
client: client,
|
||||
kyvernoClient: kyvernoClient,
|
||||
|
|
|
@ -161,7 +161,6 @@ func (c *client) DeleteResource(apiVersion string, kind string, namespace string
|
|||
options = metav1.DeleteOptions{DryRun: []string{metav1.DryRunAll}}
|
||||
}
|
||||
return c.getResourceInterface(apiVersion, kind, namespace).Delete(context.TODO(), name, options)
|
||||
|
||||
}
|
||||
|
||||
// CreateResource creates object for the specified resource/namespace
|
||||
|
|
|
@ -58,7 +58,6 @@ func (nh NegationHandler) Handle(handler resourceElementHandler, resourceMap map
|
|||
// no need to process elements in value as key cannot be present in resource
|
||||
ac.AnchorError = NewNegationAnchorError(fmt.Sprintf("%s is not allowed", currentPath))
|
||||
return currentPath, ac.AnchorError.Error()
|
||||
|
||||
}
|
||||
// key is not defined in the resource
|
||||
return "", nil
|
||||
|
@ -157,7 +156,6 @@ func (ch ConditionAnchorHandler) Handle(handler resourceElementHandler, resource
|
|||
return returnPath, ac.AnchorError.Error()
|
||||
}
|
||||
return "", nil
|
||||
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
|
|
@ -33,7 +33,6 @@ func NewAPIPath(path string) (*APIPath, error) {
|
|||
}
|
||||
|
||||
if paths[0] == "api" {
|
||||
|
||||
// /api/v1/namespaces
|
||||
if len(paths) == 3 {
|
||||
return &APIPath{
|
||||
|
|
|
@ -82,7 +82,6 @@ func filterRule(rule kyverno.Rule, policyContext *PolicyContext) *response.RuleR
|
|||
"kind", newResource.GetKind(), "namespace", newResource.GetNamespace(), "name", newResource.GetName())
|
||||
|
||||
if err = MatchesResourceDescription(newResource, rule, admissionInfo, excludeGroupRole, namespaceLabels, ""); err != nil {
|
||||
|
||||
if ruleType == response.Generation {
|
||||
// if the oldResource matched, return "false" to delete GR for it
|
||||
if err = MatchesResourceDescription(oldResource, rule, admissionInfo, excludeGroupRole, namespaceLabels, ""); err == nil {
|
||||
|
|
|
@ -115,7 +115,6 @@ func appendError(resp *response.EngineResponse, rule *v1.Rule, msg string, statu
|
|||
}
|
||||
|
||||
func substituteVariables(rule *v1.Rule, ctx context.EvalInterface, logger logr.Logger) (*v1.Rule, error) {
|
||||
|
||||
// remove attestations as variables are not substituted in them
|
||||
ruleCopy := *rule.DeepCopy()
|
||||
for i := range ruleCopy.VerifyImages {
|
||||
|
@ -412,7 +411,6 @@ func (iv *imageVerifier) buildOptionsAndPath(attestor v1.Attestor, imageVerify v
|
|||
if attestor.Keys.Rekor != nil {
|
||||
opts.RekorURL = attestor.Keys.Rekor.URL
|
||||
}
|
||||
|
||||
} else if attestor.Certificates != nil {
|
||||
path = path + ".certificates"
|
||||
opts.Cert = attestor.Certificates.Certificate
|
||||
|
@ -420,7 +418,6 @@ func (iv *imageVerifier) buildOptionsAndPath(attestor v1.Attestor, imageVerify v
|
|||
if attestor.Certificates.Rekor != nil {
|
||||
opts.RekorURL = attestor.Certificates.Rekor.URL
|
||||
}
|
||||
|
||||
} else if attestor.Keyless != nil {
|
||||
path = path + ".keyless"
|
||||
if attestor.Keyless.Rekor != nil {
|
||||
|
|
|
@ -395,7 +395,6 @@ func GetFunctions() []*FunctionEntry {
|
|||
Note: "converts a pair of lists containing keys and values to an object",
|
||||
},
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func jpfCompare(arguments []interface{}) (interface{}, error) {
|
||||
|
|
|
@ -317,7 +317,6 @@ func fetchAPIData(log logr.Logger, entry kyverno.ContextEntry, ctx *PolicyContex
|
|||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to add resource with urlPath: %s: %v", p, err)
|
||||
}
|
||||
|
||||
} else {
|
||||
jsonData, err = loadResourceList(ctx, p)
|
||||
if err != nil {
|
||||
|
|
|
@ -66,7 +66,6 @@ func getIndexToBeReversed(patches []jsonpatch.JsonPatchOperation) [][]int {
|
|||
}
|
||||
}
|
||||
return getRemoveInterval(removePaths)
|
||||
|
||||
}
|
||||
|
||||
func getRemoveInterval(removePaths []string) [][]int {
|
||||
|
|
|
@ -321,7 +321,6 @@ func hasAnchors(pattern *yaml.RNode, isAnchor func(key string) bool) bool {
|
|||
} else if kind == yaml.ScalarNode {
|
||||
v := ynode.Value
|
||||
return anchor.ContainsCondition(v)
|
||||
|
||||
} else if kind == yaml.SequenceNode {
|
||||
elements, _ := pattern.Elements()
|
||||
for _, e := range elements {
|
||||
|
|
|
@ -271,7 +271,6 @@ func matchSubjects(ruleSubjects []rbacv1.Subject, userInfo authenticationv1.User
|
|||
|
||||
//MatchesResourceDescription checks if the resource matches resource description of the rule or not
|
||||
func MatchesResourceDescription(resourceRef unstructured.Unstructured, ruleRef kyverno.Rule, admissionInfoRef urkyverno.RequestInfo, dynamicConfig []string, namespaceLabels map[string]string, policyNamespace string) error {
|
||||
|
||||
rule := ruleRef.DeepCopy()
|
||||
resource := *resourceRef.DeepCopy()
|
||||
admissionInfo := *admissionInfoRef.DeepCopy()
|
||||
|
|
|
@ -48,7 +48,6 @@ func ApplyPatchNew(resource, patch []byte) ([]byte, error) {
|
|||
}
|
||||
|
||||
return patchedResource, err
|
||||
|
||||
}
|
||||
|
||||
//ConvertToUnstructured converts the resource to unstructured format
|
||||
|
|
|
@ -124,7 +124,6 @@ func validateMap(log logr.Logger, resourceMap, patternMap map[string]interface{}
|
|||
|
||||
// Evaluate anchors
|
||||
for key, patternElement := range anchors {
|
||||
|
||||
// get handler for each pattern in the pattern
|
||||
// - Conditional
|
||||
// - Existence
|
||||
|
|
|
@ -55,7 +55,6 @@ func (allin AllInHandler) validateValueWithStringPattern(key string, value inter
|
|||
|
||||
func allKeyExistsInArray(key string, value interface{}, log logr.Logger) (invalidType bool, keyExists bool) {
|
||||
switch valuesAvailable := value.(type) {
|
||||
|
||||
case []interface{}:
|
||||
for _, val := range valuesAvailable {
|
||||
if wildcard.Match(key, fmt.Sprint(val)) {
|
||||
|
@ -112,7 +111,6 @@ func (allin AllInHandler) validateValueWithStringSetPattern(key []string, value
|
|||
// allnotIn argument if set to true will check for allNotIn
|
||||
func allSetExistsInArray(key []string, value interface{}, log logr.Logger, allNotIn bool) (invalidType bool, keyExists bool) {
|
||||
switch valuesAvailable := value.(type) {
|
||||
|
||||
case []interface{}:
|
||||
var valueSlice []string
|
||||
for _, val := range valuesAvailable {
|
||||
|
@ -202,7 +200,6 @@ func isAllNotIn(key []string, value []string) bool {
|
|||
}
|
||||
}
|
||||
return found != len(key)
|
||||
|
||||
}
|
||||
|
||||
func (allin AllInHandler) validateValueWithBoolPattern(_ bool, _ interface{}) bool {
|
||||
|
|
|
@ -60,7 +60,6 @@ func (anyin AnyInHandler) validateValueWithStringPattern(key string, value inter
|
|||
// array of strings (e.g. ["val1", "val2", "val3"].
|
||||
func anyKeyExistsInArray(key string, value interface{}, log logr.Logger) (invalidType bool, keyExists bool) {
|
||||
switch valuesAvailable := value.(type) {
|
||||
|
||||
case []interface{}:
|
||||
for _, val := range valuesAvailable {
|
||||
if wildcard.Match(fmt.Sprint(val), key) || wildcard.Match(key, fmt.Sprint(val)) {
|
||||
|
@ -125,7 +124,6 @@ func (anyin AnyInHandler) validateValueWithStringSetPattern(key []string, value
|
|||
// notIn argument if set to true will check for NotIn
|
||||
func anySetExistsInArray(key []string, value interface{}, log logr.Logger, anyNotIn bool) (invalidType bool, keyExists bool) {
|
||||
switch valuesAvailable := value.(type) {
|
||||
|
||||
case []interface{}:
|
||||
var valueSlice []string
|
||||
for _, val := range valuesAvailable {
|
||||
|
|
|
@ -60,7 +60,6 @@ func (in InHandler) validateValueWithStringPattern(key string, value interface{}
|
|||
// array of strings (e.g. ["val1", "val2", "val3"].
|
||||
func keyExistsInArray(key string, value interface{}, log logr.Logger) (invalidType bool, keyExists bool) {
|
||||
switch valuesAvailable := value.(type) {
|
||||
|
||||
case []interface{}:
|
||||
for _, val := range valuesAvailable {
|
||||
if wildcard.Match(fmt.Sprint(val), key) || wildcard.Match(key, fmt.Sprint(val)) {
|
||||
|
@ -109,7 +108,6 @@ func (in InHandler) validateValueWithStringSetPattern(key []string, value interf
|
|||
// notIn argument if set to true will check for NotIn
|
||||
func setExistsInArray(key []string, value interface{}, log logr.Logger, notIn bool) (invalidType bool, keyExists bool) {
|
||||
switch valuesAvailable := value.(type) {
|
||||
|
||||
case []interface{}:
|
||||
var valueSlice []string
|
||||
for _, val := range valuesAvailable {
|
||||
|
|
|
@ -28,7 +28,6 @@ type VariableSubstitutionHandler = func(log logr.Logger, ctx context.EvalInterfa
|
|||
func CreateOperatorHandler(log logr.Logger, ctx context.EvalInterface, op kyverno.ConditionOperator) OperatorHandler {
|
||||
str := strings.ToLower(string(op))
|
||||
switch str {
|
||||
|
||||
case strings.ToLower(string(kyverno.ConditionOperators["Equal"])),
|
||||
strings.ToLower(string(kyverno.ConditionOperators["Equals"])):
|
||||
return NewEqualHandler(log, ctx)
|
||||
|
|
|
@ -492,7 +492,6 @@ func resolveReference(log logr.Logger, fullDocument interface{}, reference, abso
|
|||
|
||||
//Parse value to string
|
||||
func valFromReferenceToString(value interface{}, operator string) (string, error) {
|
||||
|
||||
switch typed := value.(type) {
|
||||
case string:
|
||||
return typed, nil
|
||||
|
|
|
@ -64,7 +64,6 @@ func replaceWildCardChars(s string) string {
|
|||
// here, as they are evaluated separately while processing the validation pattern. Anchors
|
||||
// on the tags (e.g. "=(kubernetes.io/*)" will be preserved when the values are expanded.
|
||||
func ExpandInMetadata(patternMap, resourceMap map[string]interface{}) map[string]interface{} {
|
||||
|
||||
_, patternMetadata := getPatternValue("metadata", patternMap)
|
||||
if patternMetadata == nil {
|
||||
return patternMap
|
||||
|
|
|
@ -300,7 +300,6 @@ func (c *Controller) updateKindToAPIVersions(apiResourceLists, preferredAPIResou
|
|||
for key, value := range tempKindToAPIVersions {
|
||||
c.kindToAPIVersions.Set(key, value)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func getSchemaDocument() (*openapiv2.Document, error) {
|
||||
|
@ -336,7 +335,6 @@ func (o *Controller) getCRDSchema(kind string) (proto.Schema, error) {
|
|||
}
|
||||
|
||||
func (o *Controller) generateEmptyResource(kindSchema *openapiv2.Schema) interface{} {
|
||||
|
||||
types := kindSchema.GetType().GetValue()
|
||||
|
||||
if kindSchema.GetXRef() != "" {
|
||||
|
|
|
@ -20,8 +20,8 @@ import (
|
|||
// applyPolicy applies policy on a resource
|
||||
func applyPolicy(policy kyverno.PolicyInterface, resource unstructured.Unstructured,
|
||||
logger logr.Logger, excludeGroupRole []string,
|
||||
client client.Interface, namespaceLabels map[string]string) (responses []*response.EngineResponse) {
|
||||
|
||||
client client.Interface, namespaceLabels map[string]string,
|
||||
) (responses []*response.EngineResponse) {
|
||||
startTime := time.Now()
|
||||
defer func() {
|
||||
name := resource.GetKind() + "/" + resource.GetName()
|
||||
|
@ -73,7 +73,6 @@ func applyPolicy(policy kyverno.PolicyInterface, resource unstructured.Unstructu
|
|||
}
|
||||
|
||||
func mutation(policy kyverno.PolicyInterface, resource unstructured.Unstructured, log logr.Logger, jsonContext context.Interface, namespaceLabels map[string]string) (*response.EngineResponse, error) {
|
||||
|
||||
policyContext := &engine.PolicyContext{
|
||||
Policy: policy,
|
||||
NewResource: resource,
|
||||
|
|
|
@ -202,7 +202,6 @@ func buildKey(policy, pv, kind, ns, name, rv string) string {
|
|||
}
|
||||
|
||||
func (pc *PolicyController) processExistingKinds(kinds []string, policy kyverno.PolicyInterface, rule kyverno.Rule, logger logr.Logger) {
|
||||
|
||||
for _, kind := range kinds {
|
||||
logger = logger.WithValues("rule", rule.Name, "kind", kind)
|
||||
_, err := pc.rm.GetScope(kind)
|
||||
|
|
|
@ -139,7 +139,6 @@ func (g *Generate) canIGenerate(kind, namespace string) error {
|
|||
if !ok {
|
||||
return fmt.Errorf("kyverno does not have permissions to 'delete' resource %s/%s. Update permissions in ClusterRole 'kyverno:generate'", kind, namespace)
|
||||
}
|
||||
|
||||
} else {
|
||||
g.log.V(4).Info("name & namespace uses variables, so cannot be resolved. Skipping Auth Checks.")
|
||||
}
|
||||
|
|
|
@ -111,7 +111,6 @@ func NewPolicyController(
|
|||
reconcilePeriod time.Duration,
|
||||
promConfig *metrics.PromConfig,
|
||||
) (*PolicyController, error) {
|
||||
|
||||
// Event broad caster
|
||||
eventBroadcaster := record.NewBroadcaster()
|
||||
eventBroadcaster.StartLogging(log.V(5).Info)
|
||||
|
|
|
@ -223,7 +223,6 @@ func mergePvInfos(infos []policyreport.Info) []policyreport.Info {
|
|||
tmpInfo.Results = append(tmpInfo.Results, info.Results...)
|
||||
aggregatedInfoPerNamespace[info.Namespace] = tmpInfo
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
for _, i := range aggregatedInfoPerNamespace {
|
||||
|
|
|
@ -201,7 +201,6 @@ func createMutateLabels(policyKey string, trigger *unstructured.Unstructured) la
|
|||
|
||||
if trigger.GetAPIVersion() != "" {
|
||||
selector[urkyverno.URMutatetriggerAPIVersionLabel] = trigger.GetAPIVersion()
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -72,7 +72,6 @@ func validateJSONPatchPathForForwardSlash(patch string) error {
|
|||
if !val {
|
||||
return fmt.Errorf("%s", path)
|
||||
}
|
||||
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
@ -195,13 +194,11 @@ func Validate(policy kyverno.PolicyInterface, client dclient.Interface, mock boo
|
|||
}
|
||||
|
||||
if utils.ContainsString(rule.MatchResources.Kinds, "*") || utils.ContainsString(rule.ExcludeResources.Kinds, "*") {
|
||||
|
||||
if rule.HasGenerate() || rule.HasVerifyImages() || rule.Validation.ForEachValidation != nil {
|
||||
return nil, fmt.Errorf("wildcard policy does not support rule type")
|
||||
}
|
||||
|
||||
if rule.HasValidate() {
|
||||
|
||||
if rule.Validation.GetPattern() != nil || rule.Validation.GetAnyPattern() != nil {
|
||||
if !ruleOnlyDealsWithResourceMetaData(rule) {
|
||||
return nil, fmt.Errorf("policy can only deal with the metadata field of the resource if" +
|
||||
|
@ -992,7 +989,6 @@ func checkClusterResourceInMatchAndExclude(rule kyverno.Rule, clusterResources s
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
|
@ -144,7 +144,6 @@ func getResultsFromHash(resHash *hashmap.HashMap) []interface{} {
|
|||
}
|
||||
|
||||
results = append(results, result.Value.(map[string]interface{}))
|
||||
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
@ -166,7 +165,6 @@ func generateHashKey(result map[string]interface{}, dr deletedResource) (string,
|
|||
return "", false
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return fmt.Sprintf(
|
||||
|
|
|
@ -82,8 +82,8 @@ func NewReportGenerator(
|
|||
reportReqInformer requestinformer.ReportChangeRequestInformer,
|
||||
clusterReportReqInformer requestinformer.ClusterReportChangeRequestInformer,
|
||||
namespace informers.NamespaceInformer,
|
||||
log logr.Logger) (*ReportGenerator, error) {
|
||||
|
||||
log logr.Logger,
|
||||
) (*ReportGenerator, error) {
|
||||
gen := &ReportGenerator{
|
||||
pclient: pclient,
|
||||
dclient: dclient,
|
||||
|
@ -508,8 +508,10 @@ func (g *ReportGenerator) removeFromPolicyReport(policyName, ruleName string) er
|
|||
|
||||
// aggregateReports aggregates cluster / report change requests to a policy report
|
||||
func (g *ReportGenerator) aggregateReports(namespace string) (
|
||||
report *unstructured.Unstructured, aggregatedRequests interface{}, err error) {
|
||||
|
||||
report *unstructured.Unstructured,
|
||||
aggregatedRequests interface{},
|
||||
err error,
|
||||
) {
|
||||
kyvernoNamespace, err := g.nsLister.Get(config.KyvernoNamespace)
|
||||
if err != nil {
|
||||
g.log.Error(err, "failed to get Kyverno namespace, policy reports will not be garbage collected upon termination")
|
||||
|
@ -704,7 +706,6 @@ func (g *ReportGenerator) updateReport(old interface{}, new *unstructured.Unstru
|
|||
if _, err := g.pclient.Wgpolicyk8sV1alpha2().ClusterPolicyReports().Update(context.TODO(), cpolr, metav1.UpdateOptions{}); err != nil {
|
||||
return fmt.Errorf("failed to update ClusterPolicyReport: %v", err)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
g.log.V(3).Info("successfully updated policy report", "kind", new.GetKind(), "namespace", new.GetNamespace(), "name", new.GetName())
|
||||
|
|
|
@ -426,7 +426,6 @@ func loadObjects(t *testing.T, path string) []k8sRuntime.Object {
|
|||
resources = append(resources, obj)
|
||||
}
|
||||
return resources
|
||||
|
||||
}
|
||||
|
||||
func loadPolicy(t *testing.T, path string) *kyverno.ClusterPolicy {
|
||||
|
@ -464,7 +463,6 @@ func loadPolicy(t *testing.T, path string) *kyverno.ClusterPolicy {
|
|||
}
|
||||
|
||||
func testScenario(t *testing.T, path string) {
|
||||
|
||||
// flag.Set("logtostderr", "true")
|
||||
// flag.Set("v", "8")
|
||||
|
||||
|
|
|
@ -77,10 +77,8 @@ func getRoleRefByClusterRoleBindings(clusterroleBindings []*rbacv1.ClusterRoleBi
|
|||
// return true directly if found a match
|
||||
// subject.kind can only be ServiceAccount, User and Group
|
||||
func matchSubjectsMap(subject rbacv1.Subject, userInfo authenticationv1.UserInfo, namespace string) bool {
|
||||
|
||||
if strings.Contains(userInfo.Username, saPrefix) {
|
||||
return matchServiceAccount(subject, userInfo, namespace)
|
||||
|
||||
}
|
||||
return matchUserOrGroup(subject, userInfo)
|
||||
}
|
||||
|
|
|
@ -265,7 +265,6 @@ func isVersionHigher(version string, major int, minor int, patch int) (bool, err
|
|||
|
||||
// SliceContains checks whether values are contained in slice
|
||||
func SliceContains(slice []string, values ...string) bool {
|
||||
|
||||
var sliceElementsMap = make(map[string]bool, len(slice))
|
||||
for _, sliceElement := range slice {
|
||||
sliceElementsMap[sliceElement] = true
|
||||
|
|
|
@ -88,8 +88,8 @@ func newWebhookConfigManager(
|
|||
autoUpdateWebhooks bool,
|
||||
createDefaultWebhook chan<- string,
|
||||
stopCh <-chan struct{},
|
||||
log logr.Logger) manage {
|
||||
|
||||
log logr.Logger,
|
||||
) manage {
|
||||
m := &webhookConfigManager{
|
||||
discoveryClient: discoveryClient,
|
||||
kyvernoClient: kyvernoClient,
|
||||
|
|
|
@ -202,7 +202,6 @@ func registerWebhookIfNotPresent(register *Register, logger logr.Logger) error {
|
|||
}
|
||||
|
||||
func lastRequestTimeFromAnnotation(leaseClient coordinationv1.LeaseInterface, logger logr.Logger) *time.Time {
|
||||
|
||||
lease, err := leaseClient.Get(context.TODO(), "kyverno", metav1.GetOptions{})
|
||||
if err != nil {
|
||||
logger.Info("Lease 'kyverno' not found. Starting clean-up...")
|
||||
|
|
|
@ -96,7 +96,6 @@ func createStatusUpdateEvent(status string, eventGen event.Interface) {
|
|||
}
|
||||
|
||||
func (vc statusControl) UpdateLastRequestTimestmap(new time.Time) error {
|
||||
|
||||
lease, err := vc.leaseClient.Get(context.TODO(), leaseName, metav1.GetOptions{})
|
||||
if err != nil {
|
||||
vc.log.WithName("UpdateLastRequestTimestmap").Error(err, "Lease 'kyverno' not found. Starting clean-up...")
|
||||
|
|
|
@ -41,7 +41,6 @@ func (ws *WebhookServer) handleGenerate(
|
|||
generateEngineResponsesSenderForAdmissionReviewDurationMetric *chan []*response.EngineResponse,
|
||||
generateEngineResponsesSenderForAdmissionRequestsCountMetric *chan []*response.EngineResponse,
|
||||
) {
|
||||
|
||||
logger := ws.log.WithValues("action", "generation", "uid", request.UID, "kind", request.Kind, "namespace", request.Namespace, "name", request.Name, "operation", request.Operation, "gvk", request.Kind.String())
|
||||
logger.V(6).Info("update request")
|
||||
|
||||
|
@ -122,7 +121,6 @@ func (ws *WebhookServer) handleUpdatesForGenerateRules(request *admissionv1.Admi
|
|||
func (ws *WebhookServer) handleUpdateGenerateSourceResource(resLabels map[string]string, logger logr.Logger) {
|
||||
policyNames := strings.Split(resLabels["generate.kyverno.io/clone-policy-name"], ",")
|
||||
for _, policyName := range policyNames {
|
||||
|
||||
// check if the policy exists
|
||||
_, err := ws.kyvernoClient.KyvernoV1().ClusterPolicies().Get(contextdefault.TODO(), policyName, metav1.GetOptions{})
|
||||
if err != nil {
|
||||
|
@ -146,7 +144,6 @@ func (ws *WebhookServer) handleUpdateGenerateSourceResource(resLabels map[string
|
|||
ws.updateAnnotationInUR(ur, logger)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -275,7 +272,6 @@ func getGeneratedByResource(newRes *unstructured.Unstructured, resLabels map[str
|
|||
|
||||
//stripNonPolicyFields - remove feilds which get updated with each request by kyverno and are non policy fields
|
||||
func stripNonPolicyFields(obj, newRes map[string]interface{}, logger logr.Logger) (map[string]interface{}, map[string]interface{}) {
|
||||
|
||||
if metadata, found := obj["metadata"]; found {
|
||||
requiredMetadataInObj := make(map[string]interface{})
|
||||
if annotations, found := metadata.(map[string]interface{})["annotations"]; found {
|
||||
|
@ -384,7 +380,6 @@ func (ws *WebhookServer) deleteGR(logger logr.Logger, engineResponse *response.E
|
|||
|
||||
func applyUpdateRequest(request *admissionv1.AdmissionRequest, ruleType urkyverno.RequestType, grGenerator updaterequest.Interface, userRequestInfo urkyverno.RequestInfo,
|
||||
action admissionv1.Operation, engineResponses ...*response.EngineResponse) (failedUpdateRequest []updateRequestResponse) {
|
||||
|
||||
requestBytes, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
logger.Error(err, "error loading request into context")
|
||||
|
|
|
@ -37,8 +37,8 @@ func (ws *WebhookServer) applyMutatePolicies(request *admissionv1.AdmissionReque
|
|||
func (ws *WebhookServer) handleMutation(
|
||||
request *admissionv1.AdmissionRequest,
|
||||
policyContext *engine.PolicyContext,
|
||||
policies []kyverno.PolicyInterface) ([]byte, []*response.EngineResponse) {
|
||||
|
||||
policies []kyverno.PolicyInterface,
|
||||
) ([]byte, []*response.EngineResponse) {
|
||||
if len(policies) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
|
|
@ -28,7 +28,6 @@ func (ws *WebhookServer) createUpdateRequests(request *admissionv1.AdmissionRequ
|
|||
}
|
||||
|
||||
func (ws *WebhookServer) handleMutateExisting(request *admissionv1.AdmissionRequest, policies []kyverno.PolicyInterface, policyContext *engine.PolicyContext, admissionRequestTimestamp int64) {
|
||||
|
||||
logger := ws.log.WithValues("action", "mutateExisting", "uid", request.UID, "kind", request.Kind, "namespace", request.Namespace, "name", request.Name, "operation", request.Operation, "gvk", request.Kind.String())
|
||||
logger.V(4).Info("update request")
|
||||
|
||||
|
|
|
@ -89,9 +89,13 @@ func (g *Generator) generate(i info) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func retryApplyResource(client kyvernoclient.Interface, urSpec urkyverno.UpdateRequestSpec,
|
||||
log logr.Logger, action admissionv1.Operation, urLister urkyvernolister.UpdateRequestNamespaceLister) error {
|
||||
|
||||
func retryApplyResource(
|
||||
client kyvernoclient.Interface,
|
||||
urSpec urkyverno.UpdateRequestSpec,
|
||||
log logr.Logger,
|
||||
action admissionv1.Operation,
|
||||
urLister urkyvernolister.UpdateRequestNamespaceLister,
|
||||
) error {
|
||||
if action == admissionv1.Delete && urSpec.Type == urkyverno.Generate {
|
||||
return nil
|
||||
}
|
||||
|
|
|
@ -67,8 +67,8 @@ func NewValidateAuditHandler(pCache policycache.Interface,
|
|||
log logr.Logger,
|
||||
dynamicConfig config.Configuration,
|
||||
client client.Interface,
|
||||
promConfig *metrics.PromConfig) AuditHandler {
|
||||
|
||||
promConfig *metrics.PromConfig,
|
||||
) AuditHandler {
|
||||
return &auditHandler{
|
||||
pCache: pCache,
|
||||
queue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), workQueueName),
|
||||
|
|
|
@ -32,8 +32,8 @@ func (v *validationHandler) handleValidation(
|
|||
policies []v1.PolicyInterface,
|
||||
policyContext *engine.PolicyContext,
|
||||
namespaceLabels map[string]string,
|
||||
admissionRequestTimestamp int64) (bool, string) {
|
||||
|
||||
admissionRequestTimestamp int64,
|
||||
) (bool, string) {
|
||||
if len(policies) == 0 {
|
||||
return true, ""
|
||||
}
|
||||
|
|
|
@ -23,10 +23,11 @@ func (ws *WebhookServer) applyImageVerifyPolicies(request *admissionv1.Admission
|
|||
return imagePatches, nil
|
||||
}
|
||||
|
||||
func (ws *WebhookServer) handleVerifyImages(request *admissionv1.AdmissionRequest,
|
||||
func (ws *WebhookServer) handleVerifyImages(
|
||||
request *admissionv1.AdmissionRequest,
|
||||
policyContext *engine.PolicyContext,
|
||||
policies []v1.PolicyInterface) (bool, string, []byte) {
|
||||
|
||||
policies []v1.PolicyInterface,
|
||||
) (bool, string, []byte) {
|
||||
if len(policies) == 0 {
|
||||
return true, "", nil
|
||||
}
|
||||
|
|
|
@ -71,7 +71,6 @@ func ProcessMetrics(newStr, e2ePolicyName string) error {
|
|||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in a new issue