diff --git a/pkg/restore/actions/service_action.go b/pkg/restore/actions/service_action.go index 56697902a..9a9f3ef92 100644 --- a/pkg/restore/actions/service_action.go +++ b/pkg/restore/actions/service_action.go @@ -193,8 +193,11 @@ func deleteNodePorts(service *corev1api.Service) error { if !ok { // unnamed port unnamedPortInts.Insert(nodePortInt) - } else { - explicitNodePorts.Insert(fmt.Sprint(portName)) + } else if name, ok := portName.(string); ok { + // spec.ports[].name must be a string in a valid Service, so + // silently skip any non-string value rather than coercing it, + // which could otherwise create a false match with a real port name. + explicitNodePorts.Insert(name) } } } diff --git a/pkg/restore/actions/service_action_test.go b/pkg/restore/actions/service_action_test.go index 89f3b0e69..c4623f448 100644 --- a/pkg/restore/actions/service_action_test.go +++ b/pkg/restore/actions/service_action_test.go @@ -712,6 +712,44 @@ func TestServiceActionExecute(t *testing.T) { }, }, }, + { + name: "If a port name in last-applied-configuration is a non-string value that stringifies to match a real port name, it should not falsely preserve that port's NodePort.", + obj: corev1api.Service{ + ObjectMeta: metav1.ObjectMeta{ + Name: "svc-1", + Annotations: map[string]string{ + "kubectl.kubernetes.io/last-applied-configuration": `{"spec":{"ports":[{"nodePort":30001,"name":true}]}}`, + }, + }, + Spec: corev1api.ServiceSpec{ + Type: corev1api.ServiceTypeNodePort, + Ports: []corev1api.ServicePort{ + { + Name: "true", + NodePort: 30001, + }, + }, + }, + }, + restore: builder.ForRestore(api.DefaultNamespace, "").PreserveNodePorts(false).Result(), + expectedRes: corev1api.Service{ + ObjectMeta: metav1.ObjectMeta{ + Name: "svc-1", + Annotations: map[string]string{ + "kubectl.kubernetes.io/last-applied-configuration": `{"spec":{"ports":[{"nodePort":30001,"name":true}]}}`, + }, + }, + Spec: corev1api.ServiceSpec{ + Type: corev1api.ServiceTypeNodePort, + Ports: []corev1api.ServicePort{ + { + Name: "true", + NodePort: 0, + }, + }, + }, + }, + }, } for _, test := range tests {