1
0
Fork 0
mirror of https://github.com/kyverno/kyverno.git synced 2025-03-31 03:45:17 +00:00

chore: enable gofmt and gofumpt linters (#3931)

Signed-off-by: Charles-Edouard Brétéché <charled.breteche@gmail.com>
This commit is contained in:
Charles-Edouard Brétéché 2022-05-17 08:19:03 +02:00 committed by GitHub
parent c12f94d6d4
commit 0099ef54ad
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
91 changed files with 329 additions and 304 deletions

View file

@ -13,6 +13,8 @@ linters:
- exportloopref
- gci
- gochecknoinits
- gofmt
- gofumpt
- goprintffuncname
- gosec
- gosimple

6
api/kyverno/v1/common_types.go Executable file → Normal file
View file

@ -40,7 +40,6 @@ type AnyAllConditions struct {
// ContextEntry adds variables and data sources to a rule Context. Either a
// ConfigMap reference or a APILookup must be provided.
type ContextEntry struct {
// Name is the variable name.
Name string `json:"name,omitempty" yaml:"name,omitempty"`
@ -92,7 +91,6 @@ type ImageRegistry struct {
// ConfigMapReference refers to a ConfigMap
type ConfigMapReference struct {
// Name is the ConfigMap name.
Name string `json:"name" yaml:"name"`
@ -105,7 +103,6 @@ type ConfigMapReference struct {
// used to perform the HTTP GET request and an optional JMESPath used to
// transform the retrieved JSON data.
type APICall struct {
// URLPath is the URL path to be used in the HTTP GET request to the
// Kubernetes API server (e.g. "/api/v1/namespaces" or "/apis/apps/v1/deployments").
// The format required is the same format used by the `kubectl get --raw` command.
@ -213,7 +210,6 @@ type ResourceFilter struct {
// Mutation defines how resource are modified.
type Mutation struct {
// Targets defines the target resources to be mutated.
// +optional
Targets []ResourceSpec `json:"targets,omitempty" yaml:"targets,omitempty"`
@ -361,7 +357,6 @@ func (d *Deny) SetAnyAllConditions(in apiextensions.JSON) {
// ForEach applies validate rules to a list of sub-elements by creating a context for each entry in the list and looping over it to apply the specified logic.
type ForEachValidation struct {
// List specifies a JMESPath expression that results in one or more elements
// to which the validation logic is applied.
List string `json:"list,omitempty" yaml:"list,omitempty"`
@ -449,7 +444,6 @@ func (g *Generation) SetData(in apiextensions.JSON) {
// CloneFrom provides the location of the source resource used to generate target resources.
// The resource kind is derived from the match criteria.
type CloneFrom struct {
// Namespace specifies source resource namespace.
// +optional
Namespace string `json:"namespace,omitempty" yaml:"namespace,omitempty"`

View file

@ -12,7 +12,6 @@ import (
// are signed with the supplied public key. Once the image is verified it is
// mutated to include the SHA digest retrieved during the registration.
type ImageVerification struct {
// Image is the image name consisting of the registry address, repository, image, and tag.
// Wildcards ('*' and '?') are allowed. See: https://kubernetes.io/docs/concepts/containers/images.
// Deprecated. Use ImageReferences instead.
@ -84,7 +83,6 @@ type ImageVerification struct {
}
type AttestorSet struct {
// Count specifies the required number of entries that must match. If the count is null, all entries must match
// (a logical AND). If the count is 1, at least one entry must match (a logical OR). If the count contains a
// value N, then N must be less than or equal to the size of entries, and at least N entries must match.
@ -99,7 +97,6 @@ type AttestorSet struct {
}
type Attestor struct {
// Keys specifies one or more public keys
// +kubebuilder:validation:Optional
Keys *StaticKeyAttestor `json:"keys,omitempty" yaml:"keys,omitempty"`
@ -128,7 +125,6 @@ type Attestor struct {
}
type StaticKeyAttestor struct {
// Keys is a set of X.509 public keys used to verify image signatures. The keys can be directly
// specified or can be a variable reference to a key specified in a ConfigMap (see
// https://kyverno.io/docs/writing-policies/variables/). When multiple keys are specified each
@ -144,7 +140,6 @@ type StaticKeyAttestor struct {
}
type CertificateAttestor struct {
// Certificate is an optional PEM encoded public certificate.
// +kubebuilder:validation:Optional
Certificate string `json:"cert,omitempty" yaml:"cert,omitempty"`
@ -161,7 +156,6 @@ type CertificateAttestor struct {
}
type KeylessAttestor struct {
// Rekor provides configuration for the Rekor transparency log service. If the value is nil,
// Rekor is not checked and a root certificate chain is expected instead. If an empty object
// is provided the public instance of Rekor (https://rekor.sigstore.dev) is used.
@ -197,7 +191,6 @@ type CTLog struct {
// See https://github.com/in-toto/attestation. Kyverno fetches signed attestations from the
// OCI registry and decodes them into a list of Statements.
type Attestation struct {
// PredicateType defines the type of Predicate contained within the Statement.
PredicateType string `json:"predicateType,omitempty" yaml:"predicateType,omitempty"`

2
api/policyreport/v1alpha2/policyreport_types.go Executable file → Normal file
View file

@ -41,7 +41,6 @@ const (
// PolicyReportSummary provides a status count summary
type PolicyReportSummary struct {
// Pass provides the count of policies whose requirements were met
// +optional
Pass int `json:"pass"`
@ -89,7 +88,6 @@ type PolicySeverity string
// PolicyReportResult provides the result for an individual policy
type PolicyReportResult struct {
// Source is an identifier for the policy engine that manages this report
// +optional
Source string `json:"source"`

View file

@ -146,7 +146,8 @@ func Command() *cobra.Command {
}
func applyCommandHelper(resourcePaths []string, userInfoPath string, cluster bool, policyReport bool, mutateLogPath string,
variablesString string, valuesFile string, namespace string, policyPaths []string, stdin bool, registryAccess bool) (rc *common.ResultCounts, resources []*unstructured.Unstructured, skipInvalidPolicies SkippedInvalidPolicies, pvInfos []policyreport.Info, err error) {
variablesString string, valuesFile string, namespace string, policyPaths []string, stdin bool, registryAccess bool,
) (rc *common.ResultCounts, resources []*unstructured.Unstructured, skipInvalidPolicies SkippedInvalidPolicies, pvInfos []policyreport.Info, err error) {
store.SetMock(true)
store.SetRegistryAccess(registryAccess)
kubernetesConfig := genericclioptions.NewConfigFlags(true)
@ -157,7 +158,6 @@ func applyCommandHelper(resourcePaths []string, userInfoPath string, cluster boo
}
variables, globalValMap, valuesMap, namespaceSelectorMap, err := common.GetVariable(variablesString, valuesFile, fs, false, "")
if err != nil {
if !sanitizederror.IsErrorSanitized(err) {
return rc, resources, skipInvalidPolicies, pvInfos, sanitizederror.NewWithError("failed to decode yaml", err)
@ -213,8 +213,7 @@ func applyCommandHelper(resourcePaths []string, userInfoPath string, cluster boo
if !mutateLogPathIsDir && mutateLogPath != "" {
mutateLogPath = filepath.Clean(mutateLogPath)
// Necessary for us to include the file via variable as it is part of the CLI.
_, err := os.OpenFile(mutateLogPath, os.O_TRUNC|os.O_WRONLY, 0600) // #nosec G304
_, err := os.OpenFile(mutateLogPath, os.O_TRUNC|os.O_WRONLY, 0o600) // #nosec G304
if err != nil {
if !sanitizederror.IsErrorSanitized(err) {
return rc, resources, skipInvalidPolicies, pvInfos, sanitizederror.NewWithError("failed to truncate the existing file at "+mutateLogPath, err)
@ -397,7 +396,6 @@ func printReportOrViolation(policyReport bool, rc *common.ResultCounts, resource
func createFileOrFolder(mutateLogPath string, mutateLogPathIsDir bool) error {
mutateLogPath = filepath.Clean(mutateLogPath)
_, err := os.Stat(mutateLogPath)
if err != nil {
if os.IsNotExist(err) {
if !mutateLogPathIsDir {
@ -409,7 +407,7 @@ func createFileOrFolder(mutateLogPath string, mutateLogPathIsDir bool) error {
folderPath = mutateLogPath[:len(mutateLogPath)-len(s[len(s)-1])-1]
_, err := os.Stat(folderPath)
if os.IsNotExist(err) {
errDir := os.MkdirAll(folderPath, 0750)
errDir := os.MkdirAll(folderPath, 0o750)
if errDir != nil {
return sanitizederror.NewWithError("failed to create directory", err)
}
@ -418,8 +416,7 @@ func createFileOrFolder(mutateLogPath string, mutateLogPathIsDir bool) error {
mutateLogPath = filepath.Clean(mutateLogPath)
// Necessary for us to create the file via variable as it is part of the CLI.
file, err := os.OpenFile(mutateLogPath, os.O_RDONLY|os.O_CREATE, 0600) // #nosec G304
file, err := os.OpenFile(mutateLogPath, os.O_RDONLY|os.O_CREATE, 0o600) // #nosec G304
if err != nil {
return sanitizederror.NewWithError("failed to create file", err)
}
@ -429,7 +426,7 @@ func createFileOrFolder(mutateLogPath string, mutateLogPathIsDir bool) error {
return sanitizederror.NewWithError("failed to close file", err)
}
} else {
errDir := os.MkdirAll(mutateLogPath, 0750)
errDir := os.MkdirAll(mutateLogPath, 0o750)
if errDir != nil {
return sanitizederror.NewWithError("failed to create directory", err)
}

View file

@ -43,6 +43,7 @@ import (
var longHelp = `
The test command provides a facility to test resources against policies by comparing expected results, declared ahead of time in a test manifest file, to actual results reported by Kyverno. Users provide the path to the folder containing a kyverno-test.yaml file where the location could be on a local filesystem or a remote git repository.
`
var exampleHelp = `
# Test a git repository containing Kyverno test cases.
kyverno test https://github.com/kyverno/policies/pod-security --git-branch main
@ -298,7 +299,7 @@ func testCommandExecute(dirPath []string, fileName string, gitBranch string, tes
fs := memfs.New()
rc = &resultCounts{}
var testYamlCount int
var tf = &testFilter{
tf := &testFilter{
enabled: true,
}
@ -772,7 +773,7 @@ func applyPoliciesFromPath(fs billy.Filesystem, policyBytes []byte, isGit bool,
os.Exit(1)
}
var filteredPolicies = []v1.PolicyInterface{}
filteredPolicies := []v1.PolicyInterface{}
for _, p := range policies {
for _, res := range values.Results {
if p.GetName() == res.Policy {
@ -783,7 +784,7 @@ func applyPoliciesFromPath(fs billy.Filesystem, policyBytes []byte, isGit bool,
}
for _, p := range filteredPolicies {
var filteredRules = []v1.Rule{}
filteredRules := []v1.Rule{}
for _, rule := range autogen.ComputeRules(p) {
for _, res := range values.Results {
@ -815,7 +816,7 @@ func applyPoliciesFromPath(fs billy.Filesystem, policyBytes []byte, isGit bool,
os.Exit(1)
}
var filteredResources = []*unstructured.Unstructured{}
filteredResources := []*unstructured.Unstructured{}
for _, r := range resources {
for _, res := range values.Results {
if r.GetName() == res.Resource {

View file

@ -570,9 +570,9 @@ func PrintMutatedOutput(mutateLogPath string, mutateLogPathIsDir bool, yaml stri
mutateLogPath = filepath.Clean(mutateLogPath)
if !mutateLogPathIsDir {
// truncation for the case when mutateLogPath is a file (not a directory) is handled under pkg/kyverno/apply/test_command.go
f, err = os.OpenFile(mutateLogPath, os.O_APPEND|os.O_WRONLY, 0600) // #nosec G304
f, err = os.OpenFile(mutateLogPath, os.O_APPEND|os.O_WRONLY, 0o600) // #nosec G304
} else {
f, err = os.OpenFile(mutateLogPath+"/"+fileName+".yaml", os.O_CREATE|os.O_WRONLY, 0600) // #nosec G304
f, err = os.OpenFile(mutateLogPath+"/"+fileName+".yaml", os.O_CREATE|os.O_WRONLY, 0o600) // #nosec G304
}
if err != nil {
@ -654,7 +654,8 @@ func GetPoliciesFromPaths(fs billy.Filesystem, dirPath []string, isGit bool, pol
// GetResourceAccordingToResourcePath - get resources according to the resource path
func GetResourceAccordingToResourcePath(fs billy.Filesystem, resourcePaths []string,
cluster bool, policies []v1.PolicyInterface, dClient client.Interface, namespace string, policyReport bool, isGit bool, policyResourcePath string) (resources []*unstructured.Unstructured, err error) {
cluster bool, policies []v1.PolicyInterface, dClient client.Interface, namespace string, policyReport bool, isGit bool, policyResourcePath string,
) (resources []*unstructured.Unstructured, err error) {
if isGit {
resources, err = GetResourcesWithTest(fs, policies, resourcePaths, isGit, policyResourcePath)
if err != nil {
@ -969,7 +970,7 @@ func CheckVariableForPolicy(valuesMap map[string]map[string]Resource, globalValM
}
func GetKindsFromPolicy(policy v1.PolicyInterface) map[string]struct{} {
var kindOnwhichPolicyIsApplied = make(map[string]struct{})
kindOnwhichPolicyIsApplied := make(map[string]struct{})
for _, rule := range autogen.ComputeRules(policy) {
for _, kind := range rule.MatchResources.ResourceDescription.Kinds {
kindOnwhichPolicyIsApplied[kind] = struct{}{}

View file

@ -29,7 +29,7 @@ import (
func GetResources(policies []v1.PolicyInterface, resourcePaths []string, dClient client.Interface, cluster bool, namespace string, policyReport bool) ([]*unstructured.Unstructured, error) {
resources := make([]*unstructured.Unstructured, 0)
var err error
var resourceTypesMap = make(map[string]bool)
resourceTypesMap := make(map[string]bool)
var resourceTypes []string
for _, policy := range policies {
@ -119,7 +119,7 @@ func whenClusterIsFalse(resourcePaths []string, policyReport bool) ([]*unstructu
// GetResourcesWithTest with gets matched resources by the given policies
func GetResourcesWithTest(fs billy.Filesystem, policies []v1.PolicyInterface, resourcePaths []string, isGit bool, policyResourcePath string) ([]*unstructured.Unstructured, error) {
resources := make([]*unstructured.Unstructured, 0)
var resourceTypesMap = make(map[string]bool)
resourceTypesMap := make(map[string]bool)
for _, policy := range policies {
for _, rule := range autogen.ComputeRules(policy) {
for _, kind := range rule.MatchResources.Kinds {
@ -289,7 +289,7 @@ func GetPatchedResource(patchResourceBytes []byte) (unstructured.Unstructured, e
// GetKindsFromRule will return the kinds from policy match block
func GetKindsFromRule(rule v1.Rule) map[string]bool {
var resourceTypesMap = make(map[string]bool)
resourceTypesMap := make(map[string]bool)
for _, kind := range rule.MatchResources.Kinds {
if strings.Contains(kind, "/") {
lastElement := kind[strings.LastIndex(kind, "/")+1:]

View file

@ -5,10 +5,12 @@ import (
rbacv1 "k8s.io/api/rbac/v1"
)
var Mock, RegistryAccess bool
var ContextVar Context
var ForeachElement int
var Subjects Subject
var (
Mock, RegistryAccess bool
ContextVar Context
ForeachElement int
Subjects Subject
)
func SetMock(mock bool) {
Mock = mock

View file

@ -445,7 +445,7 @@ func convertGR(pclient kyvernoclient.Interface) error {
}
for _, gr := range grs.Items {
var ur = &urkyverno.UpdateRequest{
ur := &urkyverno.UpdateRequest{
ObjectMeta: metav1.ObjectMeta{
GenerateName: "ur-",
Namespace: config.KyvernoNamespace(),

1
cmd/kyverno/main.go Executable file → Normal file
View file

@ -274,7 +274,6 @@ func main() {
policyControllerResyncPeriod,
promConfig,
)
if err != nil {
setupLog.Error(err, "Failed to create policy controller")
os.Exit(1)

View file

@ -11,7 +11,6 @@ var PodCPUHogTest = struct {
TestName string
TestData []testData
}{
TestName: "test-litmus-chaos-experiment",
TestData: []testData{
{

View file

@ -22,9 +22,7 @@ const (
PodControllers = "DaemonSet,Deployment,Job,StatefulSet,CronJob"
)
var (
podControllersKindsSet = sets.NewString(append(strings.Split(PodControllers, ","), "Pod")...)
)
var podControllersKindsSet = sets.NewString(append(strings.Split(PodControllers, ","), "Pod")...)
func isKindOtherthanPod(kinds []string) bool {
if len(kinds) > 1 && kubeutils.ContainsKind(kinds, "Pod") {
@ -166,7 +164,7 @@ func GetControllers(meta *metav1.ObjectMeta, spec *kyverno.Spec) ([]string, []st
// GenerateRulePatches generates rule for podControllers based on scenario A and C
func GenerateRulePatches(spec *kyverno.Spec, controllers string) (rulePatches [][]byte, errs []error) {
var ruleIndex = make(map[string]int)
ruleIndex := make(map[string]int)
for index, rule := range spec.Rules {
ruleIndex[rule.Name] = index
}

View file

@ -31,7 +31,6 @@ const (
// Controller manages life-cycle of generate-requests
type Controller struct {
// dynamic client implementation
client dclient.Interface

View file

@ -216,7 +216,7 @@ func addAnnotation(policy kyvernov1.PolicyInterface, patched *unstructured.Unstr
rulePatches = append(rulePatches, rp)
}
var annotationContent = make(map[string]string)
annotationContent := make(map[string]string)
policyName := policy.GetName()
if policy.GetNamespace() != "" {
policyName = policy.GetNamespace() + "/" + policy.GetName()

View file

@ -16,8 +16,7 @@ type Cosign interface {
VerifyImageAttestations(ctx context.Context, signedImgRef name.Reference, co *cosign.CheckOpts) (checkedAttestations []oci.Signature, bundleVerified bool, err error)
}
type driver struct {
}
type driver struct{}
func (d *driver) VerifyImageSignatures(ctx context.Context, signedImgRef name.Reference, co *cosign.CheckOpts) ([]oci.Signature, bool, error) {
return cosign.VerifyImageSignatures(ctx, signedImgRef, co)

View file

@ -356,7 +356,7 @@ func stringToJSONMap(i interface{}) (map[string]interface{}, error) {
return nil, fmt.Errorf("expected string type")
}
var data = map[string]interface{}{}
data := map[string]interface{}{}
if err := json.Unmarshal([]byte(s), &data); err != nil {
return nil, fmt.Errorf("failed to marshal JSON: %s", err.Error())
}

View file

@ -441,7 +441,7 @@ func (iv *imageVerifier) buildOptionsAndPath(attestor v1.Attestor, imageVerify v
}
func makeAddDigestPatch(imageInfo apiutils.ImageInfo, digest string) ([]byte, error) {
var patch = make(map[string]interface{})
patch := make(map[string]interface{})
patch["op"] = "replace"
patch["path"] = imageInfo.Pointer
patch["value"] = imageInfo.String() + "@" + digest

View file

@ -49,7 +49,7 @@ func parseImageMetadata(jsonData string) (*ImageVerificationMetadata, error) {
func (ivm *ImageVerificationMetadata) Patches(hasAnnotations bool, log logr.Logger) ([][]byte, error) {
var patches [][]byte
if !hasAnnotations {
var addAnnotationsPatch = make(map[string]interface{})
addAnnotationsPatch := make(map[string]interface{})
addAnnotationsPatch["op"] = "add"
addAnnotationsPatch["path"] = "/metadata/annotations"
addAnnotationsPatch["value"] = map[string]string{}
@ -67,7 +67,7 @@ func (ivm *ImageVerificationMetadata) Patches(hasAnnotations bool, log logr.Logg
return nil, errors.Wrapf(err, "failed to marshal metadata value: %v", data)
}
var addKeyPatch = make(map[string]interface{})
addKeyPatch := make(map[string]interface{})
addKeyPatch["op"] = "add"
addKeyPatch["path"] = makeAnnotationKeyForJSONPatch()
addKeyPatch["value"] = string(data)

View file

@ -67,12 +67,14 @@ var (
objectFromLists = "object_from_lists"
)
const errorPrefix = "JMESPath function '%s': "
const invalidArgumentTypeError = errorPrefix + "%d argument is expected of %s type"
const genericError = errorPrefix + "%s"
const zeroDivisionError = errorPrefix + "Zero divisor passed"
const undefinedQuoError = errorPrefix + "Undefined quotient"
const nonIntModuloError = errorPrefix + "Non-integer argument(s) passed for modulo"
const (
errorPrefix = "JMESPath function '%s': "
invalidArgumentTypeError = errorPrefix + "%d argument is expected of %s type"
genericError = errorPrefix + "%s"
zeroDivisionError = errorPrefix + "Zero divisor passed"
undefinedQuoError = errorPrefix + "Undefined quotient"
nonIntModuloError = errorPrefix + "Non-integer argument(s) passed for modulo"
)
type FunctionEntry struct {
Entry *gojmespath.FunctionEntry
@ -103,7 +105,8 @@ func (f *FunctionEntry) String() string {
func GetFunctions() []*FunctionEntry {
return []*FunctionEntry{
{
Entry: &gojmespath.FunctionEntry{Name: compare,
Entry: &gojmespath.FunctionEntry{
Name: compare,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
{Types: []JpType{JpString}},
@ -113,7 +116,8 @@ func GetFunctions() []*FunctionEntry {
ReturnType: []JpType{JpNumber},
},
{
Entry: &gojmespath.FunctionEntry{Name: equalFold,
Entry: &gojmespath.FunctionEntry{
Name: equalFold,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
{Types: []JpType{JpString}},
@ -123,7 +127,8 @@ func GetFunctions() []*FunctionEntry {
ReturnType: []JpType{JpBool},
},
{
Entry: &gojmespath.FunctionEntry{Name: replace,
Entry: &gojmespath.FunctionEntry{
Name: replace,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
{Types: []JpType{JpString}},
@ -135,7 +140,8 @@ func GetFunctions() []*FunctionEntry {
ReturnType: []JpType{JpString},
},
{
Entry: &gojmespath.FunctionEntry{Name: replaceAll,
Entry: &gojmespath.FunctionEntry{
Name: replaceAll,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
{Types: []JpType{JpString}},
@ -146,7 +152,8 @@ func GetFunctions() []*FunctionEntry {
ReturnType: []JpType{JpString},
},
{
Entry: &gojmespath.FunctionEntry{Name: toUpper,
Entry: &gojmespath.FunctionEntry{
Name: toUpper,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
},
@ -155,7 +162,8 @@ func GetFunctions() []*FunctionEntry {
ReturnType: []JpType{JpString},
},
{
Entry: &gojmespath.FunctionEntry{Name: toLower,
Entry: &gojmespath.FunctionEntry{
Name: toLower,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
},
@ -164,7 +172,8 @@ func GetFunctions() []*FunctionEntry {
ReturnType: []JpType{JpString},
},
{
Entry: &gojmespath.FunctionEntry{Name: trim,
Entry: &gojmespath.FunctionEntry{
Name: trim,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
{Types: []JpType{JpString}},
@ -174,7 +183,8 @@ func GetFunctions() []*FunctionEntry {
ReturnType: []JpType{JpString},
},
{
Entry: &gojmespath.FunctionEntry{Name: split,
Entry: &gojmespath.FunctionEntry{
Name: split,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
{Types: []JpType{JpString}},
@ -184,7 +194,8 @@ func GetFunctions() []*FunctionEntry {
ReturnType: []JpType{JpArrayString},
},
{
Entry: &gojmespath.FunctionEntry{Name: regexReplaceAll,
Entry: &gojmespath.FunctionEntry{
Name: regexReplaceAll,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
{Types: []JpType{JpString, JpNumber}},
@ -196,7 +207,8 @@ func GetFunctions() []*FunctionEntry {
Note: "converts all parameters to string",
},
{
Entry: &gojmespath.FunctionEntry{Name: regexReplaceAllLiteral,
Entry: &gojmespath.FunctionEntry{
Name: regexReplaceAllLiteral,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
{Types: []JpType{JpString, JpNumber}},
@ -208,7 +220,8 @@ func GetFunctions() []*FunctionEntry {
Note: "converts all parameters to string",
},
{
Entry: &gojmespath.FunctionEntry{Name: regexMatch,
Entry: &gojmespath.FunctionEntry{
Name: regexMatch,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
{Types: []JpType{JpString, JpNumber}},
@ -218,7 +231,8 @@ func GetFunctions() []*FunctionEntry {
ReturnType: []JpType{JpBool},
},
{
Entry: &gojmespath.FunctionEntry{Name: patternMatch,
Entry: &gojmespath.FunctionEntry{
Name: patternMatch,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
{Types: []JpType{JpString, JpNumber}},
@ -230,7 +244,8 @@ func GetFunctions() []*FunctionEntry {
},
{
// Validates if label (param1) would match pod/host/etc labels (param2)
Entry: &gojmespath.FunctionEntry{Name: labelMatch,
Entry: &gojmespath.FunctionEntry{
Name: labelMatch,
Arguments: []ArgSpec{
{Types: []JpType{JpObject}},
{Types: []JpType{JpObject}},
@ -241,7 +256,8 @@ func GetFunctions() []*FunctionEntry {
Note: "object arguments must be enclosed in backticks; ex. `{{request.object.spec.template.metadata.labels}}`",
},
{
Entry: &gojmespath.FunctionEntry{Name: add,
Entry: &gojmespath.FunctionEntry{
Name: add,
Arguments: []ArgSpec{
{Types: []JpType{JpAny}},
{Types: []JpType{JpAny}},
@ -251,7 +267,8 @@ func GetFunctions() []*FunctionEntry {
ReturnType: []JpType{JpAny},
},
{
Entry: &gojmespath.FunctionEntry{Name: subtract,
Entry: &gojmespath.FunctionEntry{
Name: subtract,
Arguments: []ArgSpec{
{Types: []JpType{JpAny}},
{Types: []JpType{JpAny}},
@ -261,7 +278,8 @@ func GetFunctions() []*FunctionEntry {
ReturnType: []JpType{JpAny},
},
{
Entry: &gojmespath.FunctionEntry{Name: multiply,
Entry: &gojmespath.FunctionEntry{
Name: multiply,
Arguments: []ArgSpec{
{Types: []JpType{JpAny}},
{Types: []JpType{JpAny}},
@ -271,7 +289,8 @@ func GetFunctions() []*FunctionEntry {
ReturnType: []JpType{JpAny},
},
{
Entry: &gojmespath.FunctionEntry{Name: divide,
Entry: &gojmespath.FunctionEntry{
Name: divide,
Arguments: []ArgSpec{
{Types: []JpType{JpAny}},
{Types: []JpType{JpAny}},
@ -282,7 +301,8 @@ func GetFunctions() []*FunctionEntry {
Note: "divisor must be non zero",
},
{
Entry: &gojmespath.FunctionEntry{Name: modulo,
Entry: &gojmespath.FunctionEntry{
Name: modulo,
Arguments: []ArgSpec{
{Types: []JpType{JpAny}},
{Types: []JpType{JpAny}},
@ -293,7 +313,8 @@ func GetFunctions() []*FunctionEntry {
Note: "divisor must be non-zero, arguments must be integers",
},
{
Entry: &gojmespath.FunctionEntry{Name: base64Decode,
Entry: &gojmespath.FunctionEntry{
Name: base64Decode,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
},
@ -302,7 +323,8 @@ func GetFunctions() []*FunctionEntry {
ReturnType: []JpType{JpString},
},
{
Entry: &gojmespath.FunctionEntry{Name: base64Encode,
Entry: &gojmespath.FunctionEntry{
Name: base64Encode,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
},
@ -311,7 +333,8 @@ func GetFunctions() []*FunctionEntry {
ReturnType: []JpType{JpString},
},
{
Entry: &gojmespath.FunctionEntry{Name: timeSince,
Entry: &gojmespath.FunctionEntry{
Name: timeSince,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
{Types: []JpType{JpString}},
@ -322,7 +345,8 @@ func GetFunctions() []*FunctionEntry {
ReturnType: []JpType{JpString},
},
{
Entry: &gojmespath.FunctionEntry{Name: pathCanonicalize,
Entry: &gojmespath.FunctionEntry{
Name: pathCanonicalize,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
},
@ -331,7 +355,8 @@ func GetFunctions() []*FunctionEntry {
ReturnType: []JpType{JpString},
},
{
Entry: &gojmespath.FunctionEntry{Name: truncate,
Entry: &gojmespath.FunctionEntry{
Name: truncate,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
{Types: []JpType{JpNumber}},
@ -342,7 +367,8 @@ func GetFunctions() []*FunctionEntry {
Note: "length argument must be enclosed in backticks; ex. \"{{request.object.metadata.name | truncate(@, `9`)}}\"",
},
{
Entry: &gojmespath.FunctionEntry{Name: semverCompare,
Entry: &gojmespath.FunctionEntry{
Name: semverCompare,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
{Types: []JpType{JpString}},
@ -352,7 +378,8 @@ func GetFunctions() []*FunctionEntry {
ReturnType: []JpType{JpBool},
},
{
Entry: &gojmespath.FunctionEntry{Name: parseJson,
Entry: &gojmespath.FunctionEntry{
Name: parseJson,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
},
@ -362,7 +389,8 @@ func GetFunctions() []*FunctionEntry {
Note: "decodes a valid JSON encoded string to the appropriate type. Opposite of `to_string` function",
},
{
Entry: &gojmespath.FunctionEntry{Name: parseYAML,
Entry: &gojmespath.FunctionEntry{
Name: parseYAML,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
},
@ -372,7 +400,8 @@ func GetFunctions() []*FunctionEntry {
Note: "decodes a valid YAML encoded string to the appropriate type provided it can be represented as JSON",
},
{
Entry: &gojmespath.FunctionEntry{Name: items,
Entry: &gojmespath.FunctionEntry{
Name: items,
Arguments: []ArgSpec{
{Types: []JpType{JpObject}},
{Types: []JpType{JpString}},
@ -384,7 +413,8 @@ func GetFunctions() []*FunctionEntry {
Note: "converts a map to an array of objects where each key:value is an item in the array",
},
{
Entry: &gojmespath.FunctionEntry{Name: objectFromLists,
Entry: &gojmespath.FunctionEntry{
Name: objectFromLists,
Arguments: []ArgSpec{
{Types: []JpType{JpArray}},
{Types: []JpType{JpArray}},

View file

@ -62,7 +62,6 @@ func (rs ResourceSpec) GetKey() string {
// PolicyStats stores statistics for the single policy application
type PolicyStats struct {
// time required to process the policy rules on a resource
ProcessingTime time.Duration `json:"processingTime"`
@ -91,7 +90,6 @@ const (
// RuleResponse details for each rule application
type RuleResponse struct {
// rule name specified in policy
Name string `json:"name"`

View file

@ -328,7 +328,7 @@ func MatchesResourceDescription(resourceRef unstructured.Unstructured, ruleRef k
}
// creating final error
var errorMessage = fmt.Sprintf("rule %s not matched:", ruleRef.Name)
errorMessage := fmt.Sprintf("rule %s not matched:", ruleRef.Name)
for i, reasonForFailure := range reasonsForFailure {
if reasonForFailure != nil {
errorMessage += "\n " + fmt.Sprint(i+1) + ". " + reasonForFailure.Error()

View file

@ -58,7 +58,7 @@ func buildResponse(ctx *PolicyContext, resp *response.EngineResponse, startTime
if reflect.DeepEqual(resp.PatchedResource, unstructured.Unstructured{}) {
// for delete requests patched resource will be oldResource since newResource is empty
var resource = ctx.NewResource
resource := ctx.NewResource
if reflect.DeepEqual(ctx.NewResource, unstructured.Unstructured{}) {
resource = ctx.OldResource
}

View file

@ -131,9 +131,11 @@ func (doh DurationOperatorHandler) validateValueWithStringPattern(key string, va
func (doh DurationOperatorHandler) validateValueWithBoolPattern(key bool, value interface{}) bool {
return false
}
func (doh DurationOperatorHandler) validateValueWithMapPattern(key map[string]interface{}, value interface{}) bool {
return false
}
func (doh DurationOperatorHandler) validateValueWithSlicePattern(key []interface{}, value interface{}) bool {
return false
}

View file

@ -210,9 +210,11 @@ func parseQuantity(key, value interface{}) (parsedKey, parsedValue resource.Quan
func (noh NumericOperatorHandler) validateValueWithBoolPattern(key bool, value interface{}) bool {
return false
}
func (noh NumericOperatorHandler) validateValueWithMapPattern(key map[string]interface{}, value interface{}) bool {
return false
}
func (noh NumericOperatorHandler) validateValueWithSlicePattern(key []interface{}, value interface{}) bool {
return false
}

View file

@ -157,7 +157,7 @@ func ConditionsToJSONObject(conditions []kyverno.AnyAllConditions) ([]map[string
return nil, err
}
var m = []map[string]interface{}{}
m := []map[string]interface{}{}
if err := json.Unmarshal(bytes, &m); err != nil {
return nil, err
}
@ -364,7 +364,6 @@ func substituteVariablesIfAny(log logr.Logger, ctx context.EvalInterface, vr Var
}
substitutedVar, err := vr(ctx, variable)
if err != nil {
switch err.(type) {
case context.InvalidVariableError, gojmespath.NotFoundError:

View file

@ -15,7 +15,6 @@ import (
)
type Interface interface {
// Run is a blocking call that runs a leader election
Run(ctx context.Context)
@ -66,7 +65,6 @@ func New(name, namespace string, kubeClient kubernetes.Interface, startWork, sto
Identity: id,
},
)
if err != nil {
return nil, errors.Wrapf(err, "error initializing resource lock: %s/%s", namespace, name)
}
@ -111,7 +109,8 @@ func New(name, namespace string, kubeClient kubernetes.Interface, startWork, sto
}
e.log.WithValues("current id", e.lock.Identity(), "leader", identity).Info("another instance has been elected as leader")
},
}}
},
}
e.leaderElector, err = leaderelection.NewLeaderElector(e.leaderElectionCfg)
if err != nil {

View file

@ -136,7 +136,7 @@ func (o *Controller) ValidateResource(patchedResource unstructured.Unstructured,
// ValidatePolicyMutation ...
func (o *Controller) ValidatePolicyMutation(policy v1.PolicyInterface) error {
var kindToRules = make(map[string][]v1.Rule)
kindToRules := make(map[string][]v1.Rule)
for _, rule := range autogen.ComputeRules(policy) {
if rule.HasMutate() {
for _, kind := range rule.MatchResources.Kinds {
@ -378,7 +378,7 @@ func getArrayValue(kindSchema *openapiv2.Schema, o *Controller) interface{} {
}
func getObjectValue(kindSchema *openapiv2.Schema, o *Controller) interface{} {
var props = make(map[string]interface{})
props := make(map[string]interface{})
properties := kindSchema.GetProperties().GetAdditionalProperties()
if len(properties) == 0 {
return props

View file

@ -16,12 +16,13 @@ func ValidatePattern(patternElement interface{}, path string, supportedAnchors [
case []interface{}:
return validateArray(typedPatternElement, path, supportedAnchors)
case string, float64, int, int64, bool, nil:
//TODO? check operator
// TODO: check operator
return "", nil
default:
return path, fmt.Errorf("error at '%s', pattern contains unknown type", path)
}
}
func validateMap(patternMap map[string]interface{}, path string, supportedAnchors []commonAnchors.IsAnchor) (string, error) {
// check if anchors are defined
for key, value := range patternMap {

View file

@ -1,8 +1,7 @@
package fake
// FakeAuth providers implementation for testing, retuning true for all operations
type FakeAuth struct {
}
type FakeAuth struct{}
// NewFakeAuth returns a new instance of Fake Auth that returns true for each operation
func NewFakeAuth() *FakeAuth {

View file

@ -240,7 +240,7 @@ func Validate(policy kyverno.PolicyInterface, client dclient.Interface, mock boo
}
}
var podOnlyMap = make(map[string]bool) //Validate that Kind is only Pod
podOnlyMap := make(map[string]bool) // Validate that Kind is only Pod
podOnlyMap["Pod"] = true
if reflect.DeepEqual(common.GetKindsFromRule(rule), podOnlyMap) && podControllerAutoGenExclusion(policy) {
msg := "Policies that match Pods apply to all Pods including those created and managed by controllers " +

8
pkg/policyreport/builder.go Executable file → Normal file
View file

@ -311,9 +311,11 @@ func toPolicyResult(status response.RuleStatus) string {
return ""
}
const categoryLabel string = "policies.kyverno.io/category"
const severityLabel string = "policies.kyverno.io/severity"
const ScoredLabel string = "policies.kyverno.io/scored"
const (
categoryLabel string = "policies.kyverno.io/category"
severityLabel string = "policies.kyverno.io/severity"
ScoredLabel string = "policies.kyverno.io/scored"
)
type annotationValues struct {
category string

View file

@ -20,8 +20,10 @@ type PolicyReportEraser interface {
EraseResultsEntries(erase EraseResultsEntries) error
}
type CleanupReportChangeRequests = func(pclient kyvernoclient.Interface, rcrLister changerequestlister.ReportChangeRequestLister, crcrLister changerequestlister.ClusterReportChangeRequestLister) error
type EraseResultsEntries = func(pclient kyvernoclient.Interface, reportLister policyreportlister.PolicyReportLister, clusterReportLister policyreportlister.ClusterPolicyReportLister) error
type (
CleanupReportChangeRequests = func(pclient kyvernoclient.Interface, rcrLister changerequestlister.ReportChangeRequestLister, crcrLister changerequestlister.ClusterReportChangeRequestLister) error
EraseResultsEntries = func(pclient kyvernoclient.Interface, reportLister policyreportlister.PolicyReportLister, clusterReportLister policyreportlister.ClusterPolicyReportLister) error
)
func (g *ReportGenerator) CleanupReportChangeRequests(cleanup CleanupReportChangeRequests) error {
return cleanup(g.pclient, g.reportChangeRequestLister, g.clusterReportChangeRequestLister)

10
pkg/policyreport/reportrequest.go Executable file → Normal file
View file

@ -22,8 +22,10 @@ import (
"k8s.io/client-go/util/workqueue"
)
const workQueueName = "report-request-controller"
const workQueueRetryLimit = 10
const (
workQueueName = "report-request-controller"
workQueueRetryLimit = 10
)
// Generator creates report request
type Generator struct {
@ -54,7 +56,8 @@ func NewReportChangeRequestGenerator(client policyreportclient.Interface,
clusterReportReqInformer requestinformer.ClusterReportChangeRequestInformer,
cpolInformer kyvernoinformer.ClusterPolicyInformer,
polInformer kyvernoinformer.PolicyInformer,
log logr.Logger) *Generator {
log logr.Logger,
) *Generator {
gen := Generator{
dclient: dclient,
clusterReportChangeRequestLister: clusterReportReqInformer.Lister(),
@ -230,7 +233,6 @@ func (gen *Generator) processNextWorkItem() bool {
gen.handleErr(err, obj)
return nil
}(obj)
if err != nil {
logger.Error(err, "failed to process item")
}

View file

@ -66,7 +66,7 @@ func Initialize(client kubernetes.Interface, ns, sa string, imagePullSecrets []s
// UpdateKeychain reinitializes the image pull secrets and default auth method for container registry API calls
func UpdateKeychain() error {
var err = Initialize(kubeClient, namespace, serviceAccount, Secrets)
err := Initialize(kubeClient, namespace, serviceAccount, Secrets)
if err != nil {
return err
}

View file

@ -5,8 +5,10 @@ import (
"os/signal"
)
var onlyOneSignalHandler = make(chan struct{})
var shutdownHandler chan os.Signal
var (
onlyOneSignalHandler = make(chan struct{})
shutdownHandler chan os.Signal
)
// SetupSignalHandler registered for SIGTERM and SIGINT. A stop channel is returned
// which is closed on one of these signals. If a second signal is caught, the program

View file

@ -90,7 +90,7 @@ func GenerateAnnotationPatches(engineResponses []*response.EngineResponse, log l
}
func annotationFromEngineResponses(engineResponses []*response.EngineResponse, log logr.Logger) []byte {
var annotationContent = make(map[string]string)
annotationContent := make(map[string]string)
for _, engineResponse := range engineResponses {
if !engineResponse.IsSuccessful() {
log.V(3).Info("skip building annotation; policy failed to apply", "policy", engineResponse.PolicyResponse.Policy.Name)

View file

@ -264,7 +264,7 @@ 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))
sliceElementsMap := make(map[string]bool, len(slice))
for _, sliceElement := range slice {
sliceElementsMap[sliceElement] = true
}

View file

@ -79,7 +79,8 @@ func NewRegister(
debug bool,
autoUpdateWebhooks bool,
stopCh <-chan struct{},
log logr.Logger) *Register {
log logr.Logger,
) *Register {
register := &Register{
clientConfig: clientConfig,
kubeClient: kubeClient,

View file

@ -316,7 +316,8 @@ func stripNonPolicyFields(obj, newRes map[string]interface{}, logger logr.Logger
}
func applyUpdateRequest(request *admissionv1.AdmissionRequest, ruleType kyvernov1beta1.RequestType, grGenerator updaterequest.Interface, userRequestInfo kyvernov1beta1.RequestInfo,
action admissionv1.Operation, engineResponses ...*response.EngineResponse) (failedUpdateRequest []updateRequestResponse) {
action admissionv1.Operation, engineResponses ...*response.EngineResponse,
) (failedUpdateRequest []updateRequestResponse) {
requestBytes, err := json.Marshal(request)
if err != nil {
logger.Error(err, "error loading request into context")

View file

@ -150,7 +150,8 @@ func (h *auditHandler) process(request *admissionv1.AdmissionRequest) error {
userRequestInfo := v1beta1.RequestInfo{
Roles: roles,
ClusterRoles: clusterRoles,
AdmissionUserInfo: request.UserInfo}
AdmissionUserInfo: request.UserInfo,
}
ctx, err := newVariablesContext(request, &userRequestInfo)
if err != nil {

View file

@ -6,10 +6,12 @@ import (
"github.com/kyverno/kyverno/test/e2e"
)
var podGVR = e2e.GetGVR("", "v1", "pods")
var deploymentGVR = e2e.GetGVR("apps", "v1", "deployments")
var configmGVR = e2e.GetGVR("", "v1", "configmaps")
var secretGVR = e2e.GetGVR("", "v1", "secrets")
var (
podGVR = e2e.GetGVR("", "v1", "pods")
deploymentGVR = e2e.GetGVR("apps", "v1", "deployments")
configmGVR = e2e.GetGVR("", "v1", "configmaps")
secretGVR = e2e.GetGVR("", "v1", "secrets")
)
func newNamespaceYaml(name string) []byte {
ns := fmt.Sprintf(`