Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: add revive linter, fix linting errors, remove unused code #63

Merged
merged 5 commits into from
Jul 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ linters:
- misspell
- nakedret
- prealloc
- revive
- staticcheck
- typecheck
- unconvert
Expand Down
12 changes: 6 additions & 6 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@

# -include will silently skip missing files, which allows us
# to load those files with a target in the Makefile. If only
# "include" was used, the make command would fail and refuse
# to run a target until the include commands succeeded.
-include build/makelib/common.mk
include build/makelib/common.mk
include build/makelib/plugin.mk

# Image URL to use all building/pushing image targets
IMG ?= quay.io/validator-labs/validator-plugin-kubescape:latest

# Helm vars
CHART_NAME=validator-plugin-kubescape

.PHONY: dev
dev:
devspace dev -n validator
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ pre-commit install --hook-type pre-commit
```

## License
Copyright 2023.
Copyright 2024.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

Expand Down
2 changes: 1 addition & 1 deletion api/v1alpha1/groupversion_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

// Package v1 contains API Schema definitions for the validation v1 API group
// Package v1alpha1 contains API Schema definitions for the validation v1alpha1 API group
// +kubebuilder:object:generate=true
// +groupName=validation.spectrocloud.labs
package v1alpha1
Expand Down
10 changes: 6 additions & 4 deletions api/v1alpha1/kubescapevalidator_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,30 +31,31 @@ type KubescapeValidatorSpec struct {
Namespace string `json:"namespace,omitempty" yaml:"namespace,omitempty"`
// Global Severity Limit Rule
SeverityLimitRule SeverityLimitRule `json:"severityLimitRule,omitempty" yaml:"severityLimitRule,omitempty"`
// Global Ignore CVEs
IgnoredCVERule []string `json:"ignoredCVERule,omitempty" yaml:"ignoredCVERule,omitempty"`
// Rule for Flagged CVEs
FlaggedCVERule []FlaggedCVE `json:"flaggedCVERule,omitempty" yaml:"flaggedCVERule,omitempty"`
}

// FlaggedCVE is a flagged CVE rule.
type FlaggedCVE string

// Name returns the formatted name of the flagged CVE.
func (r FlaggedCVE) Name() string {
return fmt.Sprintf("FLAG-%s", string(r))
}

// Increase for every rule
// ResultCount returns the number of validation results expected for an KubescapeValidatorSpec.
func (s KubescapeValidatorSpec) ResultCount() int {
count := 0
if s.SeverityLimitRule != (SeverityLimitRule{}) {
count++
}
count += len(s.IgnoredCVERule)
count += len(s.FlaggedCVERule)

return count
}

// SeverityLimitRule verifies that the number of vulnerabilities of each severity level does not
// exceed the specified limit.
type SeverityLimitRule struct {
Critical *int `json:"critical,omitempty"`
High *int `json:"high,omitempty"`
Expand All @@ -64,6 +65,7 @@ type SeverityLimitRule struct {
Unknown *int `json:"unknown,omitempty"`
}

// Name is the name of all severity limit rules.
func (r SeverityLimitRule) Name() string {
return "SeverityLimitRule"
}
Expand Down
5 changes: 0 additions & 5 deletions api/v1alpha1/zz_generated.deepcopy.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion build
Submodule build updated 2 files
+68 −102 makelib/common.mk
+87 −0 makelib/plugin.mk
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
annotations:
controller-gen.kubebuilder.io/version: v0.12.0
controller-gen.kubebuilder.io/version: v0.15.0
name: kubescapevalidators.validation.spectrocloud.labs
spec:
group: validation.spectrocloud.labs
Expand All @@ -21,14 +21,19 @@ spec:
API
properties:
apiVersion:
description: 'APIVersion defines the versioned schema of this representation
of an object. Servers should convert recognized schemas to the latest
internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources'
description: |-
APIVersion defines the versioned schema of this representation of an object.
Servers should convert recognized schemas to the latest internal value, and
may reject unrecognized values.
More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
type: string
kind:
description: 'Kind is a string value representing the REST resource this
object represents. Servers may infer this from the endpoint the client
submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds'
description: |-
Kind is a string value representing the REST resource this object represents.
Servers may infer this from the endpoint the client submits requests to.
Cannot be updated.
In CamelCase.
More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
type: string
metadata:
type: object
Expand All @@ -38,11 +43,7 @@ spec:
flaggedCVERule:
description: Rule for Flagged CVEs
items:
type: string
type: array
ignoredCVERule:
description: Global Ignore CVEs
items:
description: FlaggedCVE is a flagged CVE rule.
type: string
type: array
namespace:
Expand Down
1 change: 1 addition & 0 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

// Package main initializes a KubescapeValidator controller.
package main

import (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,7 @@ spec:
flaggedCVERule:
description: Rule for Flagged CVEs
items:
type: string
type: array
ignoredCVERule:
description: Global Ignore CVEs
items:
description: FlaggedCVE is a flagged CVE rule.
type: string
type: array
namespace:
Expand Down
2 changes: 1 addition & 1 deletion config/manager/kustomization.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@ apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
images:
- name: controller
newName: controller
newName: quay.io/validator-labs/validator-plugin-kubescape
newTag: latest
4 changes: 0 additions & 4 deletions config/samples/validation_v1_kubescapevalidator.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,3 @@ spec:
# Rule to flag CVEs
flaggedCVERule:
- "CVE-2022-21698"

# Global rule to ignore specified CVEs
ignoredCVERule:
- "CVE-xxxx-xxxx"
6 changes: 5 additions & 1 deletion internal/constants/constants.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
// Package constants contains Kubescape plugin constants.
package constants

const (
PluginCode = "KUBESCAPE"
// PluginCode is the code for the plugin.
PluginCode = "KUBESCAPE"

// ValidationTypeSeverity is the validation type for severity limit rules.
ValidationTypeSeverity = "kubescape-severity"
)
7 changes: 5 additions & 2 deletions internal/controller/kubescapevalidator_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
limitations under the License.
*/

// Package controller defines a controller for reconciling KubescapeValidator objects.
package controller

import (
Expand Down Expand Up @@ -63,6 +64,8 @@
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.15.0/pkg/reconcile

// Reconcile reconciles each rule found in each KubescapeValidator in the cluster and creates
// ValidationResults accordingly.
func (r *KubescapeValidatorReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
l := r.Log.V(0).WithValues("name", req.Name, "namespace", req.Namespace)
l.Info("Reconciling Kubescape Validator")
Expand Down Expand Up @@ -120,7 +123,7 @@
}

// Reconcile Severity Rule
vrr, err := kubescapeService.ReconcileSeverityRule(nn, validator.Spec.SeverityLimitRule, validator.Spec.IgnoredCVERule, manifests)
vrr, err := kubescapeService.ReconcileSeverityRule(validator.Spec.SeverityLimitRule, manifests)

Check warning on line 126 in internal/controller/kubescapevalidator_controller.go

View check run for this annotation

Codecov / codecov/patch

internal/controller/kubescapevalidator_controller.go#L126

Added line #L126 was not covered by tests
if err != nil {
l.Error(err, "failed to reconcile Severity rule")
}
Expand All @@ -129,7 +132,7 @@
// Reconcile Flagged CVE Rule
for _, rule := range validator.Spec.FlaggedCVERule {
fmt.Println("ahash")
vrr, err := kubescapeService.ReconcileFlaggedCVERule(nn, rule, manifests)
vrr, err := kubescapeService.ReconcileFlaggedCVERule(rule, manifests)

Check warning on line 135 in internal/controller/kubescapevalidator_controller.go

View check run for this annotation

Codecov / codecov/patch

internal/controller/kubescapevalidator_controller.go#L135

Added line #L135 was not covered by tests
if err != nil {
l.Error(err, "failed to reconcile Severity rule")
}
Expand Down
17 changes: 11 additions & 6 deletions internal/validators/kubescape.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// Package validators handles Kubescape validation rule reconciliation.
package validators

import (
Expand All @@ -13,25 +14,27 @@
"github.com/validator-labs/validator/pkg/types"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
ktypes "k8s.io/apimachinery/pkg/types"
)

type kubescapeRule interface {
Name() string
}

// KubescapeService retrieves vulnerability data and uses it to reconcile Kubescape rules.
type KubescapeService struct {
Log logr.Logger
API *kubevuln.APIServerStore
}

func NewKubescapeService(log logr.Logger, kvApi *kubevuln.APIServerStore) *KubescapeService {
// NewKubescapeService creates a KubescapeService.
func NewKubescapeService(log logr.Logger, kvAPI *kubevuln.APIServerStore) *KubescapeService {

Check warning on line 30 in internal/validators/kubescape.go

View check run for this annotation

Codecov / codecov/patch

internal/validators/kubescape.go#L30

Added line #L30 was not covered by tests
return &KubescapeService{
Log: log,
API: kvApi,
API: kvAPI,

Check warning on line 33 in internal/validators/kubescape.go

View check run for this annotation

Codecov / codecov/patch

internal/validators/kubescape.go#L33

Added line #L33 was not covered by tests
}
}

// Manifests retrieves vulnerability data.
func (n *KubescapeService) Manifests() ([]kubescapev1.VulnerabilityManifest, error) {
manifestList, err := n.API.StorageClient.VulnerabilityManifests("kubescape").List(context.Background(), metav1.ListOptions{})
if err != nil {
Expand All @@ -51,7 +54,8 @@
return manifests, nil
}

func (n *KubescapeService) ReconcileSeverityRule(nn ktypes.NamespacedName, rule validationv1.SeverityLimitRule, ignoredCVEs []string, manifests []kubescapev1.VulnerabilityManifest) (*types.ValidationRuleResult, error) {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Param ignoredCVEs was unused. The refactor went all the way up to spec. I figured it's best to reintroduce it to the spec after we implement it instead of keeping it in the spec but unused til then.

// ReconcileSeverityRule reconciles a severity limit rule.
func (n *KubescapeService) ReconcileSeverityRule(rule validationv1.SeverityLimitRule, manifests []kubescapev1.VulnerabilityManifest) (*types.ValidationRuleResult, error) {

Check warning on line 58 in internal/validators/kubescape.go

View check run for this annotation

Codecov / codecov/patch

internal/validators/kubescape.go#L58

Added line #L58 was not covered by tests
vr := buildValidationResult(rule, constants.ValidationTypeSeverity)

critical := 0
Expand Down Expand Up @@ -145,7 +149,8 @@
return vr, nil
}

func (n *KubescapeService) ReconcileFlaggedCVERule(nn ktypes.NamespacedName, cve validationv1.FlaggedCVE, manifests []kubescapev1.VulnerabilityManifest) (*types.ValidationRuleResult, error) {
// ReconcileFlaggedCVERule reconciles a flagged CVE rule.
func (n *KubescapeService) ReconcileFlaggedCVERule(cve validationv1.FlaggedCVE, manifests []kubescapev1.VulnerabilityManifest) (*types.ValidationRuleResult, error) {

Check warning on line 153 in internal/validators/kubescape.go

View check run for this annotation

Codecov / codecov/patch

internal/validators/kubescape.go#L153

Added line #L153 was not covered by tests
vr := buildValidationResult(cve, constants.ValidationTypeSeverity)

count := 0
Expand All @@ -163,7 +168,7 @@
}

checkedImages[imageTag] = true
count += 1
count++

Check warning on line 171 in internal/validators/kubescape.go

View check run for this annotation

Codecov / codecov/patch

internal/validators/kubescape.go#L171

Added line #L171 was not covered by tests

vr.Condition.Details = append(vr.Condition.Details, fmt.Sprintf("%s found in %s", match.Vulnerability.ID, imageTag))
vr.Condition.Failures = append(vr.Condition.Failures, imageTag)
Expand Down
9 changes: 3 additions & 6 deletions internal/validators/kubescape_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
kubescapev1 "github.com/kubescape/storage/pkg/apis/softwarecomposition/v1beta1"
validationv1 "github.com/validator-labs/validator-plugin-kubescape/api/v1alpha1"
"github.com/validator-labs/validator/pkg/types"
ktypes "k8s.io/apimachinery/pkg/types"
)

func TestKubescapeService_ReconcileSeverityRule(t *testing.T) {
Expand All @@ -18,10 +17,8 @@ func TestKubescapeService_ReconcileSeverityRule(t *testing.T) {
API *kubevuln.APIServerStore
}
type args struct {
nn ktypes.NamespacedName
rule validationv1.SeverityLimitRule
ignoredCVEs []string
manifests []kubescapev1.VulnerabilityManifest
rule validationv1.SeverityLimitRule
manifests []kubescapev1.VulnerabilityManifest
}
tests := []struct {
name string
Expand All @@ -38,7 +35,7 @@ func TestKubescapeService_ReconcileSeverityRule(t *testing.T) {
Log: tt.fields.Log,
API: tt.fields.API,
}
got, err := n.ReconcileSeverityRule(tt.args.nn, tt.args.rule, tt.args.ignoredCVEs, tt.args.manifests)
got, err := n.ReconcileSeverityRule(tt.args.rule, tt.args.manifests)
if (err != nil) != tt.wantErr {
t.Errorf("KubescapeService.ReconcileSeverityRule() error = %v, wantErr %v", err, tt.wantErr)
return
Expand Down