fix: guard against nil spec.replicas in deployment analyzer (#1683)

The Deployment analyzer dereferenced *deployment.Spec.Replicas without a
nil check. Spec.Replicas is a *int32 and, although the API server usually
defaults it to 1, a Deployment object whose replicas field is explicitly
unset (nil) panics the analyze run with a nil pointer dereference.

Guard the comparison with a nil check, mirroring the sibling StatefulSet
analyzer which already checks Spec.Replicas != nil before dereferencing.
Add a regression test that analyzes a Deployment with nil Spec.Replicas
and asserts Analyze does not panic.

Signed-off-by: Anas Khan <83116240+anxkhn@users.noreply.github.com>
Co-authored-by: Alex Jones <1235925+AlexsJones@users.noreply.github.com>
This commit is contained in:
Anas Khan
2026-07-14 13:38:49 +05:30
committed by GitHub
parent 8bda53be10
commit 58ab921e91
2 changed files with 43 additions and 1 deletions

View File

@@ -54,7 +54,7 @@ func (d DeploymentAnalyzer) Analyze(a common.Analyzer) ([]common.Result, error)
for _, deployment := range deployments.Items {
var failures []common.Failure
if *deployment.Spec.Replicas != deployment.Status.ReadyReplicas {
if deployment.Spec.Replicas != nil && *deployment.Spec.Replicas != deployment.Status.ReadyReplicas {
if deployment.Status.Replicas > *deployment.Spec.Replicas {
doc := apiDoc.GetApiDocV2("spec.replicas")

View File

@@ -74,6 +74,48 @@ func TestDeploymentAnalyzer(t *testing.T) {
assert.Equal(t, analysisResults[0].Name, "default/example")
}
func TestDeploymentAnalyzerNilReplicas(t *testing.T) {
// A Deployment with an unset spec.replicas (nil) must not panic the analyzer.
clientset := fake.NewSimpleClientset(&appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: "example",
Namespace: "default",
},
Spec: appsv1.DeploymentSpec{
Replicas: nil,
Template: v1.PodTemplateSpec{
Spec: v1.PodSpec{
Containers: []v1.Container{
{
Name: "example-container",
Image: "nginx",
},
},
},
},
},
Status: appsv1.DeploymentStatus{
Replicas: 2,
AvailableReplicas: 1,
},
})
config := common.Analyzer{
Client: &kubernetes.Client{
Client: clientset,
},
Context: context.Background(),
Namespace: "default",
}
deploymentAnalyzer := DeploymentAnalyzer{}
analysisResults, err := deploymentAnalyzer.Analyze(config)
if err != nil {
t.Error(err)
}
assert.Equal(t, len(analysisResults), 0)
}
func TestDeploymentAnalyzerNamespaceFiltering(t *testing.T) {
clientset := fake.NewSimpleClientset(
&appsv1.Deployment{