diff --git a/internal/catalog/internal/types/service.go b/internal/catalog/internal/types/service.go index 3ff89be38d..1ee9a2a5d8 100644 --- a/internal/catalog/internal/types/service.go +++ b/internal/catalog/internal/types/service.go @@ -33,9 +33,34 @@ func RegisterService(r resource.Registry) { Proto: &pbcatalog.Service{}, Scope: resource.ScopeNamespace, Validate: ValidateService, + Mutate: MutateService, }) } +func MutateService(res *pbresource.Resource) error { + var service pbcatalog.Service + + if err := res.Data.UnmarshalTo(&service); err != nil { + return err + } + + changed := false + + // Default service port protocols. + for _, port := range service.Ports { + if port.Protocol == pbcatalog.Protocol_PROTOCOL_UNSPECIFIED { + port.Protocol = pbcatalog.Protocol_PROTOCOL_TCP + changed = true + } + } + + if !changed { + return nil + } + + return res.Data.MarshalFrom(&service) +} + func ValidateService(res *pbresource.Resource) error { var service pbcatalog.Service diff --git a/internal/catalog/internal/types/service_test.go b/internal/catalog/internal/types/service_test.go index 4f53a5c0a6..f97135a8ca 100644 --- a/internal/catalog/internal/types/service_test.go +++ b/internal/catalog/internal/types/service_test.go @@ -11,6 +11,7 @@ import ( "google.golang.org/protobuf/types/known/anypb" "github.com/hashicorp/consul/internal/resource" + "github.com/hashicorp/consul/internal/resource/resourcetest" pbcatalog "github.com/hashicorp/consul/proto-public/pbcatalog/v1alpha1" "github.com/hashicorp/consul/proto-public/pbresource" ) @@ -34,6 +35,38 @@ func createServiceResource(t *testing.T, data protoreflect.ProtoMessage) *pbreso return res } +func TestMutateServicePorts(t *testing.T) { + data := &pbcatalog.Service{ + Workloads: &pbcatalog.WorkloadSelector{ + Names: []string{"foo", "bar"}, + }, + Ports: []*pbcatalog.ServicePort{ + { + TargetPort: "tcp", + Protocol: pbcatalog.Protocol_PROTOCOL_UNSPECIFIED, + }, + { + TargetPort: "http", + Protocol: pbcatalog.Protocol_PROTOCOL_HTTP, + }, + }, + VirtualIps: []string{"198.18.0.1"}, + } + + res := createServiceResource(t, data) + + err := MutateService(res) + require.NoError(t, err) + + got := resourcetest.MustDecode[*pbcatalog.Service](t, res) + + require.Len(t, got.Data.Ports, 2) + require.Equal(t, pbcatalog.Protocol_PROTOCOL_TCP, got.Data.Ports[0].Protocol) + + // Check that specified protocol is not mutated. + require.Equal(t, data.Ports[1].Protocol, got.Data.Ports[1].Protocol) +} + func TestValidateService_Ok(t *testing.T) { data := &pbcatalog.Service{ Workloads: &pbcatalog.WorkloadSelector{