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

Add New Template and Objectkind #813

Closed
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
20 changes: 20 additions & 0 deletions docs/generated/templates.md
Original file line number Diff line number Diff line change
Expand Up @@ -759,6 +759,26 @@ KubeLinter supports the following templates:
**Supported Objects**: DeploymentLike


## StatefulSet VolumeClaimTemplate Annotation

**Key**: `statefulset-volumeclaimtemplate-annotation`

**Description**: Check if StatefulSet's VolumeClaimTemplate contains a specific annotation

**Supported Objects**: DeploymentLike


**Parameters**:

```yaml
- description: Annotation specifies the required annotation to match.
name: annotation
negationAllowed: true
regexAllowed: true
required: true
type: string
```

## Target Port

**Key**: `target-port`
Expand Down
32 changes: 32 additions & 0 deletions pkg/extract/sts_spec.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package extract

import (
"reflect"

"golang.stackrox.io/kube-linter/pkg/k8sutil"
appsV1 "k8s.io/api/apps/v1"
)

func StatefulSetSpec(obj k8sutil.Object) (appsV1.StatefulSetSpec, bool) {
switch obj := obj.(type) {
case *appsV1.StatefulSet:
return obj.Spec, true
default:

kind := obj.GetObjectKind().GroupVersionKind().Kind
if kind != "StatefulSet" {
return appsV1.StatefulSetSpec{}, false
}

objValue := reflect.Indirect(reflect.ValueOf(obj))
spec := objValue.FieldByName("Spec")
if !spec.IsValid() {
return appsV1.StatefulSetSpec{}, false
}
statefulSetSpec, ok := spec.Interface().(appsV1.StatefulSetSpec)
if ok {
return statefulSetSpec, true
}
return appsV1.StatefulSetSpec{}, false
}
}
5 changes: 5 additions & 0 deletions pkg/lintcontext/mocks/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,8 @@ func (l *MockLintContext) InvalidObjects() []lintcontext.InvalidObject {
func NewMockContext() *MockLintContext {
return &MockLintContext{objects: make(map[string]k8sutil.Object)}
}

// AddObject adds an object to the MockLintContext
func (l *MockLintContext) AddObject(key string, obj k8sutil.Object) {
l.objects[key] = obj
}
24 changes: 24 additions & 0 deletions pkg/objectkinds/pvc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package objectkinds

import (
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
)

const (
PersistentVolumeClaim = "PersistentVolumeClaim"
)

var (
persistentvolumeclaimGVK = v1.SchemeGroupVersion.WithKind("PersistentVolumeClaim")
)

func init() {
RegisterObjectKind(PersistentVolumeClaim, MatcherFunc(func(gvk schema.GroupVersionKind) bool {
return gvk == persistentvolumeclaimGVK
}))
}

func GetPersistentVolumeClaimAPIVersion() string {
return persistentvolumeclaimGVK.GroupVersion().String()
}
1 change: 1 addition & 0 deletions pkg/templates/all/all.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ import (
_ "golang.stackrox.io/kube-linter/pkg/templates/targetport"
_ "golang.stackrox.io/kube-linter/pkg/templates/unsafeprocmount"
_ "golang.stackrox.io/kube-linter/pkg/templates/updateconfig"
_ "golang.stackrox.io/kube-linter/pkg/templates/volumeclaimtemplates"
_ "golang.stackrox.io/kube-linter/pkg/templates/wildcardinrules"
_ "golang.stackrox.io/kube-linter/pkg/templates/writablehostmount"
)

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package params

// Params represents the params accepted by this template.
type Params struct {
// Annotation specifies the required annotation to match.
// +required
Annotation string
}
52 changes: 52 additions & 0 deletions pkg/templates/volumeclaimtemplates/template.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package volumeclaimtemplates

import (
"fmt"

"golang.stackrox.io/kube-linter/pkg/check"
"golang.stackrox.io/kube-linter/pkg/config"
"golang.stackrox.io/kube-linter/pkg/diagnostic"
"golang.stackrox.io/kube-linter/pkg/extract"
"golang.stackrox.io/kube-linter/pkg/lintcontext"
"golang.stackrox.io/kube-linter/pkg/objectkinds"
"golang.stackrox.io/kube-linter/pkg/templates"
"golang.stackrox.io/kube-linter/pkg/templates/volumeclaimtemplates/internal/params"
)

const (
templateKey = "statefulset-volumeclaimtemplate-annotation"
)

func init() {
templates.Register(check.Template{
HumanName: "StatefulSet VolumeClaimTemplate Annotation",
Key: templateKey,
Description: "Check if StatefulSet's VolumeClaimTemplate contains a specific annotation",
SupportedObjectKinds: config.ObjectKindsDesc{
ObjectKinds: []string{objectkinds.DeploymentLike},
},
Parameters: params.ParamDescs,
ParseAndValidateParams: params.ParseAndValidate,
Instantiate: params.WrapInstantiateFunc(func(p params.Params) (check.Func, error) {
return func(_ lintcontext.LintContext, object lintcontext.Object) []diagnostic.Diagnostic {
sts, ok := extract.StatefulSetSpec(object.K8sObject)
if !ok {
fmt.Println("failed to extract StatefulSet spec")
return nil
}

var diagnostics []diagnostic.Diagnostic

for _, vct := range sts.VolumeClaimTemplates {
if vct.Annotations == nil || vct.Annotations[p.Annotation] == "" {
diagnostics = append(diagnostics, diagnostic.Diagnostic{
Message: fmt.Sprintf("StatefulSet's VolumeClaimTemplate is missing required annotation: %s", p.Annotation),
})
}
}

return diagnostics
}, nil
}),
})
}
66 changes: 66 additions & 0 deletions pkg/templates/volumeclaimtemplates/template_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package volumeclaimtemplates

import (
"testing"

"golang.stackrox.io/kube-linter/pkg/lintcontext/mocks"
"golang.stackrox.io/kube-linter/pkg/templates"
"golang.stackrox.io/kube-linter/pkg/templates/volumeclaimtemplates/internal/params"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

func TestStatefulSetVolumeClaimTemplateAnnotation(t *testing.T) {
tests := []struct {
name string
annotation string // Adjusted to match the parameter name in Params
wantDiags int
}{
{"WithAnnotation", "value", 0},
{"WithoutAnnotation", "", 1}, // Empty string or any value for negative case
}



for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
sts := &appsv1.StatefulSet{
ObjectMeta: metav1.ObjectMeta{Name: "statefulset"},
Spec: appsv1.StatefulSetSpec{
VolumeClaimTemplates: []corev1.PersistentVolumeClaim{
{ObjectMeta: metav1.ObjectMeta{Annotations: tt.annotations}},

Check failure on line 32 in pkg/templates/volumeclaimtemplates/template_test.go

View workflow job for this annotation

GitHub Actions / build-and-test

tt.annotations undefined (type struct{name string; annotation string; wantDiags int} has no field or method annotations) (typecheck)
},
},
}

// Creating mock lint context
mockLintCtx := mocks.NewMockContext()
mockLintCtx.AddObject("statefulset", sts)

// Fetching template
template, found := templates.Get("statefulset-volumeclaimtemplate-annotation")
if !found {
t.Fatalf("failed to get template")
}

// Parsing and validating parameters
params, err := params.ParseAndValidate(map[string]interface{}{})
if err != nil {
t.Fatalf("failed to parse and validate params: %v", err)
}

// Instantiating check function
checkFunc, err := template.Instantiate(params)
if err != nil {
t.Fatalf("failed to instantiate check function: %v", err)
}

// Running the check function
diags := checkFunc(mockLintCtx, mockLintCtx.Objects()[0])
if len(diags) != tt.wantDiags {
t.Errorf("got %d diagnostics, want %d", len(diags), tt.wantDiags)
}
})
}
}
Loading