Skip to content
Open
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
15 changes: 15 additions & 0 deletions docs/generated/checks.md
Original file line number Diff line number Diff line change
Expand Up @@ -613,6 +613,21 @@ dirs:
- ^/sys$
- ^/usr$
```
## sorted-keys

**Enabled by default**: No

**Description**: Check that YAML keys are sorted in alphabetical order wherever possible.

**Remediation**: Ensure that keys in your YAML manifest are sorted in alphabetical order to improve consistency and readability.

**Template**: [sorted-keys](templates.md#sorted-keys)

**Parameters**:

```yaml
recursive: true
```
## ssh-port

**Enabled by default**: Yes
Expand Down
19 changes: 19 additions & 0 deletions docs/generated/templates.md
Original file line number Diff line number Diff line change
Expand Up @@ -820,6 +820,25 @@ KubeLinter supports the following templates:
type: string
```

## Sorted Keys

**Key**: `sorted-keys`

**Description**: Flag YAML keys that are not sorted in alphabetical order

**Supported Objects**: Any


**Parameters**:

```yaml
- description: Recursive determines whether to check keys recursively at all nesting
levels. Default is true.
name: recursive
required: false
type: boolean
```

## Startup Port Exposed

**Key**: `startup-port`
Expand Down
19 changes: 19 additions & 0 deletions e2etests/bats-tests.sh
Original file line number Diff line number Diff line change
Expand Up @@ -926,6 +926,25 @@ get_value_from() {
[[ "${count}" == "2" ]]
}

@test "sorted-keys" {
tmp="tests/checks/sorted-keys.yaml"
cmd="${KUBE_LINTER_BIN} lint --include sorted-keys --do-not-auto-add-defaults --format json ${tmp}"
run ${cmd}

print_info "${status}" "${output}" "${cmd}" "${tmp}"
[ "$status" -eq 1 ]

message1=$(get_value_from "${lines[0]}" '.Reports[0].Object.K8sObject.GroupVersionKind.Kind + ": " + .Reports[0].Diagnostic.Message')
message2=$(get_value_from "${lines[0]}" '.Reports[1].Object.K8sObject.GroupVersionKind.Kind + ": " + .Reports[1].Diagnostic.Message')
message3=$(get_value_from "${lines[0]}" '.Reports[2].Object.K8sObject.GroupVersionKind.Kind + ": " + .Reports[2].Diagnostic.Message')
count=$(get_value_from "${lines[0]}" '.Reports | length')

[[ "${message1}" == "Deployment: Keys are not sorted at spec.template.spec.containers[0]. Expected order: [image, name, ports], got: [name, image, ports]" ]]
[[ "${message2}" == "Deployment: Keys are not sorted at root. Expected order: [apiVersion, kind, metadata, spec], got: [apiVersion, metadata, spec, kind]" ]]
[[ "${message3}" == "Deployment: Keys are not sorted at spec.template. Expected order: [metadata, spec], got: [spec, metadata]" ]]
[[ "${count}" == "27" ]]
}

@test "ssh-port" {
tmp="tests/checks/ssh-port.yml"
cmd="${KUBE_LINTER_BIN} lint --include ssh-port --do-not-auto-add-defaults --format json ${tmp}"
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ require (
github.com/spf13/pflag v1.0.10
github.com/spf13/viper v1.21.0
github.com/stretchr/testify v1.11.1
gopkg.in/yaml.v3 v3.0.1
helm.sh/helm/v3 v3.19.0
k8s.io/api v0.34.1
k8s.io/apimachinery v0.34.1
Expand Down Expand Up @@ -122,7 +123,6 @@ require (
google.golang.org/protobuf v1.36.9 // indirect
gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
k8s.io/apiextensions-apiserver v0.34.1 // indirect
k8s.io/cli-runtime v0.34.0 // indirect
k8s.io/component-base v0.34.1 // indirect
Expand Down
9 changes: 9 additions & 0 deletions pkg/builtinchecks/yamls/sorted-keys.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
name: "sorted-keys"
description: "Check that YAML keys are sorted in alphabetical order wherever possible."
remediation: "Ensure that keys in your YAML manifest are sorted in alphabetical order to improve consistency and readability."
scope:
objectKinds:
- Any
template: "sorted-keys"
params:
recursive: true
22 changes: 18 additions & 4 deletions pkg/lintcontext/mocks/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,19 @@ import (

// MockLintContext is mock implementation of the LintContext used in unit tests
type MockLintContext struct {
objects map[string]k8sutil.Object
objects map[string]k8sutil.Object
rawObjects map[string][]byte
}

// Objects returns all the objects under this MockLintContext
func (l *MockLintContext) Objects() []lintcontext.Object {
result := make([]lintcontext.Object, 0, len(l.objects))
for _, p := range l.objects {
result = append(result, lintcontext.Object{Metadata: lintcontext.ObjectMetadata{}, K8sObject: p})
for key, p := range l.objects {
metadata := lintcontext.ObjectMetadata{}
if raw, ok := l.rawObjects[key]; ok {
metadata.Raw = raw
}
result = append(result, lintcontext.Object{Metadata: metadata, K8sObject: p})
}
return result
}
Expand All @@ -26,10 +31,19 @@ func (l *MockLintContext) InvalidObjects() []lintcontext.InvalidObject {

// NewMockContext returns an empty mockLintContext
func NewMockContext() *MockLintContext {
return &MockLintContext{objects: make(map[string]k8sutil.Object)}
return &MockLintContext{
objects: make(map[string]k8sutil.Object),
rawObjects: make(map[string][]byte),
}
}

// AddObject adds an object to the MockLintContext
func (l *MockLintContext) AddObject(key string, obj k8sutil.Object) {
l.objects[key] = obj
}

// AddObjectWithRaw adds an object to the MockLintContext with raw YAML data
func (l *MockLintContext) AddObjectWithRaw(key string, obj k8sutil.Object, raw []byte) {
l.objects[key] = obj
l.rawObjects[key] = raw
}
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/sccdenypriv"
_ "golang.stackrox.io/kube-linter/pkg/templates/serviceaccount"
_ "golang.stackrox.io/kube-linter/pkg/templates/servicetype"
_ "golang.stackrox.io/kube-linter/pkg/templates/sortedkeys"
_ "golang.stackrox.io/kube-linter/pkg/templates/startupport"
_ "golang.stackrox.io/kube-linter/pkg/templates/sysctl"
_ "golang.stackrox.io/kube-linter/pkg/templates/targetport"
Expand Down
68 changes: 68 additions & 0 deletions pkg/templates/sortedkeys/internal/params/gen-params.go

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

8 changes: 8 additions & 0 deletions pkg/templates/sortedkeys/internal/params/params.go
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 {
// Recursive determines whether to check keys recursively at all nesting levels.
// Default is true.
Recursive bool
}
135 changes: 135 additions & 0 deletions pkg/templates/sortedkeys/template.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
package sortedkeys

import (
"fmt"
"sort"
"strings"

"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/lintcontext"
"golang.stackrox.io/kube-linter/pkg/objectkinds"
"golang.stackrox.io/kube-linter/pkg/templates"
"golang.stackrox.io/kube-linter/pkg/templates/sortedkeys/internal/params"
"gopkg.in/yaml.v3"
)

const templateKey = "sorted-keys"

func init() {
templates.Register(check.Template{
HumanName: "Sorted Keys",
Key: templateKey,
Description: "Flag YAML keys that are not sorted in alphabetical order",
SupportedObjectKinds: config.ObjectKindsDesc{
ObjectKinds: []string{objectkinds.Any},
},
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 {
// Parse the raw YAML to preserve key order
var node yaml.Node
if err := yaml.Unmarshal(object.Metadata.Raw, &node); err != nil {
// Skip objects that can't be parsed
return nil
}

var diagnostics []diagnostic.Diagnostic

// The root node is a document node, we need to check its content
if node.Kind == yaml.DocumentNode && len(node.Content) > 0 {
diagnostics = checkNode(node.Content[0], "", p.Recursive)
} else if node.Kind == yaml.MappingNode {
diagnostics = checkNode(&node, "", p.Recursive)
}

return diagnostics
}, nil
}),
})
}

// checkNode recursively checks if keys in a YAML node are sorted
func checkNode(node *yaml.Node, path string, recursive bool) []diagnostic.Diagnostic {
if node == nil {
return nil
}

var diagnostics []diagnostic.Diagnostic

switch node.Kind {
case yaml.MappingNode:
// Extract keys from the mapping node
// In yaml.v3, mapping nodes store key-value pairs as alternating elements in Content
var keys []string
keyPositions := make(map[string]int) // Track original positions

for i := 0; i < len(node.Content); i += 2 {
if node.Content[i].Kind == yaml.ScalarNode {
key := node.Content[i].Value
keys = append(keys, key)
keyPositions[key] = i / 2
}
}

// Check if keys are sorted
if len(keys) > 1 {
sortedKeys := make([]string, len(keys))
copy(sortedKeys, keys)
sort.Strings(sortedKeys)

// Find the first key that is out of order
for i := 0; i < len(keys); i++ {
if keys[i] != sortedKeys[i] {
location := path
if location == "" {
location = "root"
}

diagnostics = append(diagnostics, diagnostic.Diagnostic{
Message: fmt.Sprintf(
"Keys are not sorted at %s. Expected order: [%s], got: [%s]",
location,
strings.Join(sortedKeys, ", "),
strings.Join(keys, ", "),
),
})
// Only report once per level
break
}
}
}

// Recursively check child nodes if recursive is enabled
if recursive {
for i := 0; i < len(node.Content); i += 2 {
keyNode := node.Content[i]
valueNode := node.Content[i+1]

childPath := path
if childPath == "" {
childPath = keyNode.Value
} else {
childPath = path + "." + keyNode.Value
}

childDiagnostics := checkNode(valueNode, childPath, recursive)
diagnostics = append(diagnostics, childDiagnostics...)
}
}

case yaml.SequenceNode:
// For sequences, check each element if it's a mapping
if recursive {
for idx, item := range node.Content {
childPath := fmt.Sprintf("%s[%d]", path, idx)
childDiagnostics := checkNode(item, childPath, recursive)
diagnostics = append(diagnostics, childDiagnostics...)
}
}
}

return diagnostics
}
Loading
Loading