1
0
Fork 0
mirror of https://github.com/kyverno/kyverno.git synced 2025-03-28 02:18:15 +00:00

Fix various go lint issues (#2639)

* Fix various go lint issues

Signed-off-by: Marcus Noble <github@marcusnoble.co.uk>

* Fix if mistake

Signed-off-by: Marcus Noble <github@marcusnoble.co.uk>

* Simplified returns

Signed-off-by: Marcus Noble <github@marcusnoble.co.uk>
This commit is contained in:
Marcus Noble 2021-10-29 16:06:03 +01:00 committed by GitHub
parent 40b579ccd7
commit 1966c82c6d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
32 changed files with 142 additions and 137 deletions

View file

@ -1,8 +1,6 @@
package main
import (
"github.com/kyverno/kyverno/pkg/kyverno"
)
import "github.com/kyverno/kyverno/pkg/kyverno"
func main() {
kyverno.CLI()

View file

@ -50,6 +50,7 @@ type GenerateRequestContext struct {
AdmissionRequestInfo AdmissionRequestInfoObject `json:"admissionRequestInfo,omitempty" yaml:"admissionRequestInfo,omitempty"`
}
// AdmissionRequestInfoObject stores the admission request and operation details
type AdmissionRequestInfoObject struct {
// +optional
AdmissionRequest string `json:"admissionRequest,omitempty" yaml:"admissionRequest,omitempty"`

View file

@ -136,7 +136,7 @@ const (
Fail FailurePolicyType = "Fail"
)
// AnyAllCondition consists of conditions wrapped denoting a logical criteria to be fulfilled.
// AnyAllConditions consists of conditions wrapped denoting a logical criteria to be fulfilled.
// AnyConditions get fulfilled when at least one of its sub-conditions passes.
// AllConditions get fulfilled only when all of its sub-conditions pass.
type AnyAllConditions struct {
@ -311,9 +311,10 @@ type ExcludeResources struct {
ResourceDescription `json:"resources,omitempty" yaml:"resources,omitempty"`
}
// ResourceFilters is a slice of ResourceFilter
type ResourceFilters []ResourceFilter
// ResourceFilters allow users to "AND" or "OR" between resources
// ResourceFilter allow users to "AND" or "OR" between resources
type ResourceFilter struct {
// UserInfo contains information about the user performing the operation.
// +optional
@ -411,12 +412,12 @@ type Mutation struct {
// +optional
PatchesJSON6902 string `json:"patchesJson6902,omitempty" yaml:"patchesJson6902,omitempty"`
// ForEach applies policy rule changes to nested elements.
// ForEachMutation applies policy rule changes to nested elements.
// +optional
ForEachMutation []*ForEachMutation `json:"foreach,omitempty" yaml:"foreach,omitempty"`
}
// ForEach applies policy rule changes to nested elements.
// ForEachMutation applies policy rule changes to nested elements.
type ForEachMutation struct {
// List specifies a JMESPath expression that results in one or more elements
@ -427,7 +428,7 @@ type ForEachMutation struct {
// +optional
Context []ContextEntry `json:"context,omitempty" yaml:"context,omitempty"`
// Preconditions are used to determine if a policy rule should be applied by evaluating a
// AnyAllConditions are used to determine if a policy rule should be applied by evaluating a
// set of conditions. The declaration can contain nested `any` or `all` statements.
// See: https://kyverno.io/docs/writing-policies/preconditions/
// +kubebuilder:validation:XPreserveUnknownFields
@ -498,7 +499,7 @@ type Deny struct {
AnyAllConditions apiextensions.JSON `json:"conditions,omitempty" yaml:"conditions,omitempty"`
}
// ForEach applies policy rule checks to nested elements.
// ForEachValidation applies policy rule checks to nested elements.
type ForEachValidation struct {
// List specifies a JMESPath expression that results in one or more elements
@ -509,7 +510,7 @@ type ForEachValidation struct {
// +optional
Context []ContextEntry `json:"context,omitempty" yaml:"context,omitempty"`
// Preconditions are used to determine if a policy rule should be applied by evaluating a
// AnyAllConditions are used to determine if a policy rule should be applied by evaluating a
// set of conditions. The declaration can contain nested `any` or `all` statements.
// See: https://kyverno.io/docs/writing-policies/preconditions/
// +kubebuilder:validation:XPreserveUnknownFields

View file

@ -19,7 +19,7 @@ func (p *ClusterPolicy) HasAutoGenAnnotation() bool {
return false
}
//HasMutateOrValidateOrGenerate checks for rule types
// HasMutateOrValidateOrGenerate checks for rule types
func (p *ClusterPolicy) HasMutateOrValidateOrGenerate() bool {
for _, rule := range p.Spec.Rules {
if rule.HasMutate() || rule.HasValidate() || rule.HasGenerate() {
@ -29,7 +29,7 @@ func (p *ClusterPolicy) HasMutateOrValidateOrGenerate() bool {
return false
}
//HasMutate checks for mutate rule types
// HasMutate checks for mutate rule types
func (p *ClusterPolicy) HasMutate() bool {
for _, rule := range p.Spec.Rules {
if rule.HasMutate() {
@ -62,7 +62,7 @@ func (p *ClusterPolicy) HasGenerate() bool {
return false
}
//HasVerifyImages checks for image verification rule types
// HasVerifyImages checks for image verification rule types
func (p *ClusterPolicy) HasVerifyImages() bool {
for _, rule := range p.Spec.Rules {
if rule.HasVerifyImages() {
@ -102,6 +102,7 @@ func (r Rule) HasGenerate() bool {
return !reflect.DeepEqual(r.Generation, Generation{})
}
// MatchKinds returns a slice of all kinds to match
func (r Rule) MatchKinds() []string {
matchKinds := r.MatchResources.ResourceDescription.Kinds
for _, value := range r.MatchResources.All {
@ -114,6 +115,7 @@ func (r Rule) MatchKinds() []string {
return matchKinds
}
// ExcludeKinds returns a slice of all kinds to exclude
func (r Rule) ExcludeKinds() []string {
excludeKinds := r.ExcludeResources.ResourceDescription.Kinds
for _, value := range r.ExcludeResources.All {
@ -243,20 +245,20 @@ func (in *Rule) DeepCopyInto(out *Rule) {
// }
}
//ToKey generates the key string used for adding label to polivy violation
// ToKey generates the key string used for adding label to polivy violation
func (rs ResourceSpec) ToKey() string {
return rs.Kind + "." + rs.Name
}
// ViolatedRule stores the information regarding the rule.
type ViolatedRule struct {
// Specifies violated rule name.
// Name specifies violated rule name.
Name string `json:"name" yaml:"name"`
// Specifies violated rule type.
// Type specifies violated rule type.
Type string `json:"type" yaml:"type"`
// Specifies violation message.
// Message specifies violation message.
// +optional
Message string `json:"message" yaml:"message"`

View file

@ -22,8 +22,10 @@ import (
// Policy Reporting Modes
const (
Enforce = "enforce" // blocks the request on failure
Audit = "audit" // dont block the request on failure, but report failiures as policy violations
// Enforce blocks the request on failure
Enforce = "enforce"
// Audit indicates not to block the request on failure, but report failiures as policy violations
Audit = "audit"
)
// Policy Reporting Types
@ -118,6 +120,7 @@ func VariableToJSON(key, value string) []byte {
return jsonData
}
// RetryFunc allows retrying a function on error within a given timeout
func RetryFunc(retryInterval, timeout time.Duration, run func() error, logger logr.Logger) func() error {
return func() error {
registerTimeout := time.After(timeout)

View file

@ -104,12 +104,14 @@ func (cd *ConfigData) FilterNamespaces(namespaces []string) []string {
return results
}
// GetWebhooks returns the webhook configs
func (cd *ConfigData) GetWebhooks() []WebhookConfig {
cd.mux.RLock()
defer cd.mux.RUnlock()
return cd.webhooks
}
// GetInitConfigMapName returns the init configmap name
func (cd *ConfigData) GetInitConfigMapName() string {
return cd.cmName
}
@ -170,7 +172,7 @@ func NewConfigData(rclient kubernetes.Interface, cmInformer informers.ConfigMapI
return &cd
}
//Run checks syncing
// Run checks syncing
func (cd *ConfigData) Run(stopCh <-chan struct{}) {
logger := cd.log
// wait for cache to populate first time

View file

@ -24,6 +24,7 @@ type MetricsConfigData struct {
log logr.Logger
}
// MetricsConfig stores the config for metrics
type MetricsConfig struct {
namespaces namespacesConfig
metricsRefreshInterval time.Duration
@ -44,10 +45,12 @@ func (mcd *MetricsConfigData) GetIncludeNamespaces() []string {
return mcd.metricsConfig.namespaces.IncludeNamespaces
}
// GetMetricsRefreshInterval returns the refresh interval for the metrics
func (mcd *MetricsConfigData) GetMetricsRefreshInterval() time.Duration {
return mcd.metricsConfig.metricsRefreshInterval
}
// GetMetricsConfigMapName returns the configmap name for the metric
func (mcd *MetricsConfigData) GetMetricsConfigMapName() string {
return mcd.cmName
}

View file

@ -49,6 +49,7 @@ func Initialize(client kubernetes.Interface, namespace, serviceAccount string, i
return nil
}
// VerifySignature verifies that the image has the expected key
func VerifySignature(imageRef string, key []byte, repository string, log logr.Logger) (digest string, err error) {
pubKey, err := decodePEM(key)
if err != nil {

View file

@ -10,14 +10,14 @@ import (
"sigs.k8s.io/controller-runtime/pkg/log"
)
//ValidationHandler for element processes
// ValidationHandler for element processes
type ValidationHandler interface {
Handle(handler resourceElementHandler, resourceMap map[string]interface{}, originPattern interface{}, ac *common.AnchorKey) (string, error)
}
type resourceElementHandler = func(log logr.Logger, resourceElement, patternElement, originPattern interface{}, path string, ac *common.AnchorKey) (string, error)
//CreateElementHandler factory to process elements
// CreateElementHandler factory to process elements
func CreateElementHandler(element string, pattern interface{}, path string) ValidationHandler {
switch {
case commonAnchors.IsConditionAnchor(element):
@ -35,7 +35,7 @@ func CreateElementHandler(element string, pattern interface{}, path string) Vali
}
}
//NewNegationHandler returns instance of negation handler
// NewNegationHandler returns instance of negation handler
func NewNegationHandler(anchor string, pattern interface{}, path string) ValidationHandler {
return NegationHandler{
anchor: anchor,
@ -44,14 +44,14 @@ func NewNegationHandler(anchor string, pattern interface{}, path string) Validat
}
}
//NegationHandler provides handler for check if the tag in anchor is not defined
// NegationHandler provides handler for check if the tag in anchor is not defined
type NegationHandler struct {
anchor string
pattern interface{}
path string
}
//Handle process negation handler
// Handle process negation handler
func (nh NegationHandler) Handle(handler resourceElementHandler, resourceMap map[string]interface{}, originPattern interface{}, ac *common.AnchorKey) (string, error) {
anchorKey, _ := commonAnchors.RemoveAnchor(nh.anchor)
currentPath := nh.path + anchorKey + "/"
@ -64,7 +64,7 @@ func (nh NegationHandler) Handle(handler resourceElementHandler, resourceMap map
return "", nil
}
//NewEqualityHandler returens instance of equality handler
// NewEqualityHandler returens instance of equality handler
func NewEqualityHandler(anchor string, pattern interface{}, path string) ValidationHandler {
return EqualityHandler{
anchor: anchor,
@ -73,14 +73,14 @@ func NewEqualityHandler(anchor string, pattern interface{}, path string) Validat
}
}
//EqualityHandler provides handler for non anchor element
// EqualityHandler provides handler for non anchor element
type EqualityHandler struct {
anchor string
pattern interface{}
path string
}
//Handle processed condition anchor
// Handle processed condition anchor
func (eh EqualityHandler) Handle(handler resourceElementHandler, resourceMap map[string]interface{}, originPattern interface{}, ac *common.AnchorKey) (string, error) {
anchorKey, _ := commonAnchors.RemoveAnchor(eh.anchor)
currentPath := eh.path + anchorKey + "/"
@ -96,7 +96,7 @@ func (eh EqualityHandler) Handle(handler resourceElementHandler, resourceMap map
return "", nil
}
//NewDefaultHandler returns handler for non anchor elements
// NewDefaultHandler returns handler for non anchor elements
func NewDefaultHandler(element string, pattern interface{}, path string) ValidationHandler {
return DefaultHandler{
element: element,
@ -105,14 +105,14 @@ func NewDefaultHandler(element string, pattern interface{}, path string) Validat
}
}
//DefaultHandler provides handler for non anchor element
// DefaultHandler provides handler for non anchor element
type DefaultHandler struct {
element string
pattern interface{}
path string
}
//Handle process non anchor element
// Handle process non anchor element
func (dh DefaultHandler) Handle(handler resourceElementHandler, resourceMap map[string]interface{}, originPattern interface{}, ac *common.AnchorKey) (string, error) {
currentPath := dh.path + dh.element + "/"
if dh.pattern == "*" && resourceMap[dh.element] != nil {
@ -128,7 +128,7 @@ func (dh DefaultHandler) Handle(handler resourceElementHandler, resourceMap map[
return "", nil
}
//NewConditionAnchorHandler returns an instance of condition acnhor handler
// NewConditionAnchorHandler returns an instance of condition acnhor handler
func NewConditionAnchorHandler(anchor string, pattern interface{}, path string) ValidationHandler {
return ConditionAnchorHandler{
anchor: anchor,
@ -137,14 +137,14 @@ func NewConditionAnchorHandler(anchor string, pattern interface{}, path string)
}
}
//ConditionAnchorHandler provides handler for condition anchor
// ConditionAnchorHandler provides handler for condition anchor
type ConditionAnchorHandler struct {
anchor string
pattern interface{}
path string
}
//Handle processed condition anchor
// Handle processed condition anchor
func (ch ConditionAnchorHandler) Handle(handler resourceElementHandler, resourceMap map[string]interface{}, originPattern interface{}, ac *common.AnchorKey) (string, error) {
anchorKey, _ := commonAnchors.RemoveAnchor(ch.anchor)
currentPath := ch.path + anchorKey + "/"
@ -162,7 +162,7 @@ func (ch ConditionAnchorHandler) Handle(handler resourceElementHandler, resource
return "", nil
}
//NewGlobalAnchorHandler returns an instance of condition acnhor handler
// NewGlobalAnchorHandler returns an instance of condition acnhor handler
func NewGlobalAnchorHandler(anchor string, pattern interface{}, path string) ValidationHandler {
return GlobalAnchorHandler{
anchor: anchor,
@ -171,14 +171,14 @@ func NewGlobalAnchorHandler(anchor string, pattern interface{}, path string) Val
}
}
//GlobalAnchorHandler provides handler for global condition anchor
// GlobalAnchorHandler provides handler for global condition anchor
type GlobalAnchorHandler struct {
anchor string
pattern interface{}
path string
}
//Handle processed global condition anchor
// Handle processed global condition anchor
func (gh GlobalAnchorHandler) Handle(handler resourceElementHandler, resourceMap map[string]interface{}, originPattern interface{}, ac *common.AnchorKey) (string, error) {
anchorKey, _ := commonAnchors.RemoveAnchor(gh.anchor)
currentPath := gh.path + anchorKey + "/"
@ -195,7 +195,7 @@ func (gh GlobalAnchorHandler) Handle(handler resourceElementHandler, resourceMap
return "", nil
}
//NewExistenceHandler returns existence handler
// NewExistenceHandler returns existence handler
func NewExistenceHandler(anchor string, pattern interface{}, path string) ValidationHandler {
return ExistenceHandler{
anchor: anchor,
@ -204,14 +204,14 @@ func NewExistenceHandler(anchor string, pattern interface{}, path string) Valida
}
}
//ExistenceHandler provides handlers to process exitence anchor handler
// ExistenceHandler provides handlers to process exitence anchor handler
type ExistenceHandler struct {
anchor string
pattern interface{}
path string
}
//Handle processes the existence anchor handler
// Handle processes the existence anchor handler
func (eh ExistenceHandler) Handle(handler resourceElementHandler, resourceMap map[string]interface{}, originPattern interface{}, ac *common.AnchorKey) (string, error) {
// skip is used by existence anchor to not process further if condition is not satisfied
anchorKey, _ := commonAnchors.RemoveAnchor(eh.anchor)
@ -261,7 +261,7 @@ func validateExistenceListResource(handler resourceElementHandler, resourceList
return path, fmt.Errorf("existence anchor validation failed at path %s", path)
}
//GetAnchorsResourcesFromMap returns map of anchors
// GetAnchorsResourcesFromMap returns map of anchors
func GetAnchorsResourcesFromMap(patternMap map[string]interface{}) (map[string]interface{}, map[string]interface{}) {
anchors := map[string]interface{}{}
resources := map[string]interface{}{}

View file

@ -26,7 +26,7 @@ func NewConditionalAnchorError(msg string) ValidateAnchorError {
}
}
// IsConditionAnchorError ...
// IsConditionAnchorError checks if the error is a conditional anchor error
func (e ValidateAnchorError) IsConditionAnchorError() bool {
return e.Err == ConditionalAnchorErr
}
@ -39,16 +39,17 @@ func NewGlobalAnchorError(msg string) ValidateAnchorError {
}
}
// IsConditionAnchorError ...
// IsGlobalAnchorError checks if the error is a global anchor error
func (e ValidateAnchorError) IsGlobalAnchorError() bool {
return e.Err == GlobalAnchorErr
}
// IsNil ...
// IsNil checks if the error isn't populated
func (e ValidateAnchorError) IsNil() bool {
return e == ValidateAnchorError{}
}
// Error returns an error instance of the anchor error
func (e ValidateAnchorError) Error() error {
return errors.New(e.Message)
}

View file

@ -99,7 +99,7 @@ func (ctx *Context) AddJSON(dataRaw []byte) error {
return nil
}
// AddJSON merges json data
// AddJSONObject merges json data
func (ctx *Context) AddJSONObject(jsonData interface{}) error {
jsonBytes, err := json.Marshal(jsonData)
if err != nil {

View file

@ -1,4 +1,4 @@
package json_utils
package jsonutils
import (
"fmt"

View file

@ -1,4 +1,4 @@
package json_utils
package jsonutils
import (
"encoding/json"

View file

@ -99,7 +99,7 @@ func Mutate(policyContext *PolicyContext) (resp *response.EngineResponse) {
if rule.Mutation.ForEachMutation != nil {
ruleResp, patchedResource = mutateForEachResource(ruleCopy, policyContext, patchedResource, logger)
} else {
err, mutateResp := mutateResource(ruleCopy, policyContext.JSONContext, patchedResource, logger, 0)
mutateResp, err := mutateResource(ruleCopy, policyContext.JSONContext, patchedResource, logger, 0)
if err != nil {
if mutateResp.skip {
ruleResp = ruleResponse(&policy.Spec.Rules[i], utils.Mutation, err.Error(), response.RuleStatusSkip)
@ -174,7 +174,7 @@ func mutateForEachResource(rule *kyverno.Rule, ctx *PolicyContext, resource unst
}
var skip = false
err, mutateResp := mutateResource(rule, ctx.JSONContext, patchedResource, logger, foreachIndex)
mutateResp, err := mutateResource(rule, ctx.JSONContext, patchedResource, logger, foreachIndex)
if err != nil && !skip {
return ruleResponse(rule, utils.Mutation, err.Error(), response.RuleStatusError), resource
}
@ -204,7 +204,7 @@ type mutateResponse struct {
message string
}
func mutateResource(rule *kyverno.Rule, ctx *context.Context, resource unstructured.Unstructured, logger logr.Logger, foreachIndex int) (error, *mutateResponse) {
func mutateResource(rule *kyverno.Rule, ctx *context.Context, resource unstructured.Unstructured, logger logr.Logger, foreachIndex int) (*mutateResponse, error) {
mutateResp := &mutateResponse{false, unstructured.Unstructured{}, nil, ""}
// Pre-conditions checks for the list of foreach rules should ideally be performed once.
@ -212,22 +212,22 @@ func mutateResource(rule *kyverno.Rule, ctx *context.Context, resource unstructu
// Also, the foreach index parameter should be removed and a set of patches should be passed in.
anyAllConditions, err := variables.SubstituteAllInPreconditions(logger, ctx, rule.AnyAllConditions)
if err != nil {
return errors.Wrapf(err, "failed to substitute vars in preconditions"), mutateResp
return mutateResp, errors.Wrapf(err, "failed to substitute vars in preconditions")
}
copyConditions, err := transformConditions(anyAllConditions)
if err != nil {
return errors.Wrapf(err, "failed to load context"), mutateResp
return mutateResp, errors.Wrapf(err, "failed to load context")
}
if !variables.EvaluateConditions(logger, ctx, copyConditions) {
mutateResp.skip = true
return fmt.Errorf("preconditions mismatch"), mutateResp
return mutateResp, fmt.Errorf("preconditions mismatch")
}
updatedRule, err := variables.SubstituteAllInRule(logger, ctx, *rule)
if err != nil {
return errors.Wrapf(err, "variable substitution failed"), mutateResp
return mutateResp, errors.Wrapf(err, "variable substitution failed")
}
mutation := updatedRule.Mutation.DeepCopy()
@ -238,7 +238,7 @@ func mutateResource(rule *kyverno.Rule, ctx *context.Context, resource unstructu
// - overlay pattern does not match the resource conditions
if resp.Patches == nil {
mutateResp.skip = true
return fmt.Errorf("resource does not match pattern"), mutateResp
return mutateResp, fmt.Errorf("resource does not match pattern")
}
mutateResp.skip = false
@ -252,7 +252,7 @@ func mutateResource(rule *kyverno.Rule, ctx *context.Context, resource unstructu
logger.Error(err, "failed to update resource in the JSON context")
}
return nil, mutateResp
return mutateResp, nil
}
func startMutateResultResponse(resp *response.EngineResponse, policy kyverno.ClusterPolicy, resource unstructured.Unstructured) {

View file

@ -81,17 +81,17 @@ func getRuleStatus(s string) (*RuleStatus, error) {
return nil, fmt.Errorf("invalid status: %s", s)
}
func (v *RuleStatus) UnmarshalYAML(unmarshal func(interface{}) error) error {
var s string
if err := unmarshal(&s); err != nil {
func (s *RuleStatus) UnmarshalYAML(unmarshal func(interface{}) error) error {
var str string
if err := unmarshal(&str); err != nil {
return err
}
statusVal, err := getRuleStatus(s)
statusVal, err := getRuleStatus(str)
if err != nil {
return err
}
*v = *statusVal
*s = *statusVal
return nil
}

View file

@ -425,7 +425,8 @@ func isSameRuleResponse(r1 *response.RuleResponse, r2 *response.RuleResponse) bo
func (v *validator) validatePatterns(resource unstructured.Unstructured) *response.RuleResponse {
if v.pattern != nil {
if err := validate.MatchPattern(v.log, resource.Object, v.pattern); err != nil {
if pe, ok := err.(*validate.PatternError); ok {
pe, ok := err.(*validate.PatternError)
if ok {
v.log.V(3).Info("validation error", "path", pe.Path, "error", err.Error())
if pe.Skip {
@ -437,9 +438,9 @@ func (v *validator) validatePatterns(resource unstructured.Unstructured) *respon
}
return ruleResponse(v.rule, utils.Validation, v.buildErrorMessage(err, pe.Path), response.RuleStatusFail)
} else {
return ruleResponse(v.rule, utils.Validation, v.buildErrorMessage(err, pe.Path), response.RuleStatusError)
}
return ruleResponse(v.rule, utils.Validation, v.buildErrorMessage(err, pe.Path), response.RuleStatusError)
}
v.log.V(4).Info("successfully processed rule")

View file

@ -110,12 +110,7 @@ func isAllIn(key []string, value []string) bool {
}
}
}
if found == len(key) {
return true
} else {
return false
}
return found == len(key)
}
// isAllNotIn checks if all the values in S1 are not in S2

View file

@ -124,11 +124,7 @@ func isAnyNotIn(key []string, value []string) bool {
}
}
}
if found < len(key) {
return true
} else {
return false
}
return found < len(key)
}
func (anyin AnyInHandler) validateValueWithBoolPattern(_ bool, _ interface{}) bool {

View file

@ -10,8 +10,9 @@ import (
"github.com/kyverno/kyverno/pkg/engine/context"
)
// deprecated
//NewInHandler returns handler to manage In operations
// NewInHandler returns handler to manage In operations
//
// Deprecated: Use `NewAllInHandler` or `NewAnyInHandler` instead
func NewInHandler(log logr.Logger, ctx context.EvalInterface) OperatorHandler {
return InHandler{
ctx: ctx,
@ -19,13 +20,13 @@ func NewInHandler(log logr.Logger, ctx context.EvalInterface) OperatorHandler {
}
}
//InHandler provides implementation to handle In Operator
// InHandler provides implementation to handle In Operator
type InHandler struct {
ctx context.EvalInterface
log logr.Logger
}
//Evaluate evaluates expression with In Operator
// Evaluate evaluates expression with In Operator
func (in InHandler) Evaluate(key, value interface{}) bool {
switch typedKey := key.(type) {
case string:

View file

@ -7,8 +7,9 @@ import (
"github.com/kyverno/kyverno/pkg/engine/context"
)
// deprecated
//NewNotInHandler returns handler to manage NotIn operations
//
// Deprecated: Use `NewAllNotInHandler` or `NewAnyNotInHandler` instead
func NewNotInHandler(log logr.Logger, ctx context.EvalInterface) OperatorHandler {
return NotInHandler{
ctx: ctx,
@ -16,13 +17,13 @@ func NewNotInHandler(log logr.Logger, ctx context.EvalInterface) OperatorHandler
}
}
//NotInHandler provides implementation to handle NotIn Operator
// NotInHandler provides implementation to handle NotIn Operator
type NotInHandler struct {
ctx context.EvalInterface
log logr.Logger
}
//Evaluate evaluates expression with NotIn Operator
// Evaluate evaluates expression with NotIn Operator
func (nin NotInHandler) Evaluate(key, value interface{}) bool {
switch typedKey := key.(type) {
case string:

View file

@ -13,7 +13,7 @@ import (
kyverno "github.com/kyverno/kyverno/pkg/api/kyverno/v1"
"github.com/kyverno/kyverno/pkg/engine/anchor/common"
"github.com/kyverno/kyverno/pkg/engine/context"
jsonUtils "github.com/kyverno/kyverno/pkg/engine/json-utils"
jsonUtils "github.com/kyverno/kyverno/pkg/engine/jsonutils"
"github.com/kyverno/kyverno/pkg/engine/operator"
)
@ -21,10 +21,10 @@ var RegexVariables = regexp.MustCompile(`^\{\{[^{}]*\}\}|[^\\]\{\{[^{}]*\}\}`)
var RegexEscpVariables = regexp.MustCompile(`\\\{\{[^{}]*\}\}`)
// Regex for '$(...)' at the beginning of the string, and 'x$(...)' where 'x' is not '\'
// RegexReferences is the Regex for '$(...)' at the beginning of the string, and 'x$(...)' where 'x' is not '\'
var RegexReferences = regexp.MustCompile(`^\$\(.[^\ ]*\)|[^\\]\$\(.[^\ ]*\)`)
// Regex for '\$(...)'
// RegexEscpReferences is the Regex for '\$(...)'
var RegexEscpReferences = regexp.MustCompile(`\\\$\(.[^\ ]*\)`)
var regexVariableInit = regexp.MustCompile(`^\{\{[^{}]*\}\}`)
@ -298,7 +298,7 @@ func substituteReferencesIfAny(log logr.Logger) jsonUtils.Action {
for _, v := range RegexReferences.FindAllString(value, -1) {
initial := v[:2] == `$(`
v_old := v
old := v
if !initial {
v = v[1:]
@ -321,15 +321,15 @@ func substituteReferencesIfAny(log logr.Logger) jsonUtils.Action {
log.V(3).Info("reference resolved", "reference", v, "value", resolvedReference, "path", data.Path)
if val, ok := resolvedReference.(string); ok {
replace_with := ""
replacement := ""
if !initial {
replace_with = string(v_old[0])
replacement = string(old[0])
}
replace_with += val
replacement += val
value = strings.Replace(value, v_old, replace_with, 1)
value = strings.Replace(value, old, replacement, 1)
continue
}
@ -370,7 +370,7 @@ func substituteVariablesIfAny(log logr.Logger, ctx context.EvalInterface, vr Var
for _, v := range vars {
initial := len(regexVariableInit.FindAllString(v, -1)) > 0
v_old := v
old := v
if !initial {
v = v[1:]
@ -406,7 +406,7 @@ func substituteVariablesIfAny(log logr.Logger, ctx context.EvalInterface, vr Var
prefix := ""
if !initial {
prefix = string(v_old[0])
prefix = string(old[0])
}
if value, err = substituteVarInPattern(prefix, originalPattern, v, substitutedVar); err != nil {
@ -524,7 +524,7 @@ func valFromReferenceToString(value interface{}, operator string) (string, error
func FindAndShiftReferences(log logr.Logger, value, shift, pivot string) string {
for _, reference := range RegexReferences.FindAllString(value, -1) {
initial := reference[:2] == `$(`
reference_old := reference
oldReference := reference
if !initial {
reference = reference[1:]
@ -542,15 +542,15 @@ func FindAndShiftReferences(log logr.Logger, value, shift, pivot string) string
}
shiftedReference := strings.Replace(reference, pivot, pivot+"/"+shift, -1)
replace_with := ""
replacement := ""
if !initial {
replace_with = string(reference_old[0])
replacement = string(oldReference[0])
}
replace_with += shiftedReference
replacement += shiftedReference
value = strings.Replace(value, reference_old, replace_with, 1)
value = strings.Replace(value, oldReference, replacement, 1)
}
return value

View file

@ -9,7 +9,7 @@ import (
v1 "github.com/kyverno/kyverno/pkg/api/kyverno/v1"
"github.com/kyverno/kyverno/pkg/engine/context"
ju "github.com/kyverno/kyverno/pkg/engine/json-utils"
ju "github.com/kyverno/kyverno/pkg/engine/jsonutils"
"gotest.tools/assert"
"sigs.k8s.io/controller-runtime/pkg/log"
)

View file

@ -81,10 +81,10 @@ func GetPolicies(paths []string) (policies []*v1.ClusterPolicy, errors []error)
err error
)
isHttpPath := IsHttpRegex.MatchString(path)
isHTTPPath := IsHTTPRegex.MatchString(path)
// path clean and retrieving file info can be possible if it's not an HTTP URL
if !isHttpPath {
if !isHTTPPath {
path = filepath.Clean(path)
fileDesc, err = os.Stat(path)
if err != nil {
@ -95,7 +95,7 @@ func GetPolicies(paths []string) (policies []*v1.ClusterPolicy, errors []error)
}
// apply file from a directory is possible only if the path is not HTTP URL
if !isHttpPath && fileDesc.IsDir() {
if !isHTTPPath && fileDesc.IsDir() {
files, err := ioutil.ReadDir(path)
if err != nil {
err := fmt.Errorf("failed to process %v: %v", path, err.Error())
@ -117,7 +117,7 @@ func GetPolicies(paths []string) (policies []*v1.ClusterPolicy, errors []error)
} else {
var fileBytes []byte
if isHttpPath {
if isHTTPPath {
// We accept here that a random URL might be called based on user provided input.
resp, err := http.Get(path) // #nosec
if err != nil {

View file

@ -220,7 +220,7 @@ func getFileBytes(path string) ([]byte, error) {
err error
)
if IsHttpRegex.MatchString(path) {
if IsHTTPRegex.MatchString(path) {
// We accept here that a random URL might be called based on user provided input.
resp, err := http.Get(path) // #nosec
if err != nil {

View file

@ -10,8 +10,8 @@ var RegexVariables = regexp.MustCompile(`\{\{[^{}]*\}\}`)
// AllowedVariables represents regex for {{request.}}, {{serviceAccountName}}, {{serviceAccountNamespace}}, {{@}}, {{element.}}, {{images.}}
var AllowedVariables = regexp.MustCompile(`\{\{\s*(request\.|serviceAccountName|serviceAccountNamespace|element\.|@|images\.|([a-z_0-9]+\())[^{}]*\}\}`)
// AllowedVariables represents regex for {{request.}}, {{serviceAccountName}}, {{serviceAccountNamespace}}
// WildCardAllowedVariables represents regex for the allowed fields in wildcards
var WildCardAllowedVariables = regexp.MustCompile(`\{\{\s*(request\.|serviceAccountName|serviceAccountNamespace)[^{}]*\}\}`)
// IsHttpRegex represents regex for starts with http:// or https://
var IsHttpRegex = regexp.MustCompile("^(http|https)://")
// IsHTTPRegex represents regex for starts with http:// or https://
var IsHTTPRegex = regexp.MustCompile("^(http|https)://")

View file

@ -81,7 +81,7 @@ For validate policies
rule: <name>
resource: <name>
namespace: <name> (OPTIONAL)
kind: <name>
kind: <name>
result: <pass|fail|skip>
@ -101,7 +101,7 @@ Policy (Namespaced)
rule: <name>
resource: <name>
namespace: <name> (OPTIONAL)
kind: <name>
kind: <name>
patchedResource: <path>
result: <pass|fail|skip>
@ -126,7 +126,7 @@ ClusterPolicy (Cluster-wide)
Result descriptions:
pass --> The patched resource generated by Kyverno equals the patched resource provided by the user.
fail --> The patched resource generated by Kyverno is not equal to the patched resource provided by the user.
fail --> The patched resource generated by Kyverno is not equal to the patched resource provided by the user.
skip --> The rule is not applied.
For more information visit https://kyverno.io/docs/kyverno-cli/#test
@ -521,9 +521,9 @@ func isNamespacedPolicy(policyNames string) (bool, error) {
func getUserDefinedPolicyNameAndNamespace(policyName string) (string, string) {
if strings.Contains(policyName, "/") {
policy_n_ns := strings.Split(policyName, "/")
namespace := policy_n_ns[0]
policy := policy_n_ns[1]
parts := strings.Split(policyName, "/")
namespace := parts[0]
policy := parts[1]
return namespace, policy
}
return "", policyName

View file

@ -197,11 +197,11 @@ func addCacheHelper(rmr kyverno.ResourceFilter, m *pMap, rule kyverno.Rule, muta
}
}
func (pc *pMap) get(key PolicyType, gvk, namespace string) (names []string) {
pc.RLock()
defer pc.RUnlock()
func (m *pMap) get(key PolicyType, gvk, namespace string) (names []string) {
m.RLock()
defer m.RUnlock()
_, kind := common.GetKindFromGVK(gvk)
for _, policyName := range pc.kindDataMap[kind][key] {
for _, policyName := range m.kindDataMap[kind][key] {
ns, key, isNamespacedPolicy := policy2.ParseNamespacedPolicy(policyName)
if !isNamespacedPolicy && namespace == "" {
names = append(names, key)
@ -262,19 +262,19 @@ func removeCacheHelper(rmr kyverno.ResourceFilter, m *pMap, pName string) {
}
}
func (m *policyCache) getPolicyObject(key PolicyType, gvk string, nspace string) (policyObject []*kyverno.ClusterPolicy) {
func (pc *policyCache) getPolicyObject(key PolicyType, gvk string, nspace string) (policyObject []*kyverno.ClusterPolicy) {
_, kind := common.GetKindFromGVK(gvk)
policyNames := m.pMap.get(key, kind, nspace)
wildcardPolicies := m.pMap.get(key, "*", nspace)
policyNames := pc.pMap.get(key, kind, nspace)
wildcardPolicies := pc.pMap.get(key, "*", nspace)
policyNames = append(policyNames, wildcardPolicies...)
for _, policyName := range policyNames {
var policy *kyverno.ClusterPolicy
ns, key, isNamespacedPolicy := policy2.ParseNamespacedPolicy(policyName)
if !isNamespacedPolicy {
policy, _ = m.pLister.Get(key)
policy, _ = pc.pLister.Get(key)
} else {
if ns == nspace {
nspolicy, _ := m.npLister.Policies(ns).Get(key)
nspolicy, _ := pc.npLister.Policies(ns).Get(key)
policy = policy2.ConvertPolicyToClusterPolicy(nspolicy)
}
}

View file

@ -35,7 +35,7 @@ const (
deletedAnnotationResourceName string = "kyverno.io/delete.resource.name"
deletedAnnotationResourceKind string = "kyverno.io/delete.resource.kind"
// static value for PolicyReportResult.Source
// SourceValue is the static value for PolicyReportResult.Source
SourceValue = "Kyverno"
)

View file

@ -32,13 +32,13 @@ type Scenario struct {
TestCases []TestCase
}
//CaseT defines input and output for a case
// TestCase defines input and output for a case
type TestCase struct {
Input Input `yaml:"input"`
Expected Expected `yaml:"expected"`
}
//Input defines input for a test scenario
// Input defines input for a test scenario
type Input struct {
Policy string `yaml:"policy"`
Resource string `yaml:"resource"`

View file

@ -24,7 +24,7 @@ import (
var regexVersion = regexp.MustCompile(`v(\d+).(\d+).(\d+)\.*`)
//Contains Check if strint is contained in a list of string
// Contains checks if a string is contained in a list of string
func contains(list []string, element string, fn func(string, string) bool) bool {
for _, e := range list {
if fn(e, element) {
@ -44,12 +44,12 @@ func ContainsPod(list []string, element string) bool {
return false
}
//ContainsNamepace check if namespace satisfies any list of pattern(regex)
// ContainsNamepace check if namespace satisfies any list of pattern(regex)
func ContainsNamepace(patterns []string, ns string) bool {
return contains(patterns, ns, compareNamespaces)
}
//ContainsString check if the string is contains in a list
// ContainsString checks if the string is contained in the list
func ContainsString(list []string, element string) bool {
return contains(list, element, compareString)
}
@ -62,7 +62,7 @@ func compareString(str, name string) bool {
return str == name
}
//NewKubeClient returns a new kubernetes client
// NewKubeClient returns a new kubernetes client
func NewKubeClient(config *rest.Config) (kubernetes.Interface, error) {
kclient, err := kubernetes.NewForConfig(config)
if err != nil {
@ -214,7 +214,7 @@ func SliceContains(slice []string, values ...string) bool {
return false
}
// ApiextensionsJsonTOKyvernoConditions takes in user-provided conditions in abstract apiextensions.JSON form
// ApiextensionsJsonToKyvernoConditions takes in user-provided conditions in abstract apiextensions.JSON form
// and converts it into []kyverno.Condition or kyverno.AnyAllConditions according to its content.
// it also helps in validating the condtions as it returns an error when the conditions are provided wrongfully by the user.
func ApiextensionsJsonToKyvernoConditions(original apiextensions.JSON) (interface{}, error) {

View file

@ -175,11 +175,11 @@ func (wrc *Register) Remove(cleanUp chan<- struct{}) {
}
// +deprecated
// UpdateWebhookConfigurations updates resource webhook configurations dynamically
// base on the UPDATEs of Kyverno init-config ConfigMap
//
// it currently updates namespaceSelector only, can be extend to update other fields
// +deprecated
func (wrc *Register) UpdateWebhookConfigurations(configHandler config.Interface) {
logger := wrc.log.WithName("UpdateWebhookConfigurations")
for {
@ -622,12 +622,12 @@ func (wrc *Register) checkEndpoint() error {
}
kyverno := pods.Items[0]
podIp, _, err := unstructured.NestedString(kyverno.UnstructuredContent(), "status", "podIP")
podIP, _, err := unstructured.NestedString(kyverno.UnstructuredContent(), "status", "podIP")
if err != nil {
return fmt.Errorf("failed to extract pod IP: %v", err)
}
if podIp == "" {
if podIP == "" {
return fmt.Errorf("pod is not assigned to any node yet")
}
@ -637,7 +637,7 @@ func (wrc *Register) checkEndpoint() error {
}
for _, addr := range subset.Addresses {
if addr.IP == podIp {
if addr.IP == podIP {
wrc.log.Info("Endpoint ready", "ns", config.KyvernoNamespace, "name", config.KyvernoServiceName)
return nil
}

View file

@ -346,11 +346,10 @@ func (ws *WebhookServer) buildPolicyContext(request *v1beta1.AdmissionRequest, a
}
if addRoles {
if roles, clusterRoles, err := userinfo.GetRoleRef(ws.rbLister, ws.crbLister, request, ws.configHandler); err != nil {
var err error
userRequestInfo.Roles, userRequestInfo.ClusterRoles, err = userinfo.GetRoleRef(ws.rbLister, ws.crbLister, request, ws.configHandler)
if err != nil {
return nil, errors.Wrap(err, "failed to fetch RBAC information for request")
} else {
userRequestInfo.Roles = roles
userRequestInfo.ClusterRoles = clusterRoles
}
}