From 3699c8c015f0da20edef7a48024e226afd179510 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 21 Oct 2026 18:10:07 -0500 Subject: [PATCH 1/2] feat(gateway): select NetworkService backends by address within VPC --- ...etworkservice_edgelistener_envtest_test.go | 7 ++- .../networkservice_protocol_envtest_test.go | 27 ++++++++++++ api/network/v1alpha1/networkservice_types.go | 31 ++++++++----- .../v1alpha1/networkservice_types_test.go | 24 ++++++++++ api/network/v1alpha1/zz_generated.deepcopy.go | 9 ++++ ...alactic.datumapis.com_networkservices.yaml | 44 ++++++++++++------- docs/api/network-gateway.md | 15 +++---- docs/gateway/architecture.md | 2 + .../controller/networkgateway_controller.go | 4 ++ internal/controller/rulebackends.go | 32 ++++++++++++-- internal/controller/rulebackends_test.go | 29 ++++++++++++ 11 files changed, 183 insertions(+), 41 deletions(-) diff --git a/api/network/v1alpha1/networkservice_edgelistener_envtest_test.go b/api/network/v1alpha1/networkservice_edgelistener_envtest_test.go index 767a42386..c7b0a1964 100644 --- a/api/network/v1alpha1/networkservice_edgelistener_envtest_test.go +++ b/api/network/v1alpha1/networkservice_edgelistener_envtest_test.go @@ -16,7 +16,7 @@ import ( ) const ( - exactlyOneBackendSourceMsg = "exactly one of backendSelector and edgeListenerRef is required" + exactlyOneBackendSourceMsg = "choose attachment backends or an edgeListenerRef" emptySelectorMsg = "backendSelector must not be empty" ) @@ -38,6 +38,11 @@ func TestNetworkServiceBackendSource(t *testing.T) { s.Spec.BackendSelector = metav1.LabelSelector{} s.Spec.EdgeListenerRef = listener }, ""}, + {"AddressesAndListener", func(s *networkv1alpha1.NetworkService) { + s.Spec.BackendSelector = metav1.LabelSelector{} + s.Spec.BackendAddresses = &[]string{"2001:db8::1"} + s.Spec.EdgeListenerRef = listener + }, exactlyOneBackendSourceMsg}, {"Both", func(s *networkv1alpha1.NetworkService) { s.Spec.EdgeListenerRef = listener }, exactlyOneBackendSourceMsg}, {"Neither", func(s *networkv1alpha1.NetworkService) { s.Spec.BackendSelector = metav1.LabelSelector{} diff --git a/api/network/v1alpha1/networkservice_protocol_envtest_test.go b/api/network/v1alpha1/networkservice_protocol_envtest_test.go index eb4d55dea..e258c77dd 100644 --- a/api/network/v1alpha1/networkservice_protocol_envtest_test.go +++ b/api/network/v1alpha1/networkservice_protocol_envtest_test.go @@ -109,6 +109,33 @@ func protocolService(name string, protocol networkv1alpha1.NetworkServiceProtoco } } +func TestNetworkServiceBackendAddressAdmission(t *testing.T) { + c, _ := startProtocolAPI(t) + ctx := context.Background() + svc := protocolService("address-only", networkv1alpha1.NetworkServiceProtocolTCP, 443, 8443) + svc.Spec.BackendSelector = metav1.LabelSelector{} + addresses := []string{"fd00:10::1"} + svc.Spec.BackendAddresses = &addresses + if err := c.Create(ctx, svc); err != nil { + t.Fatalf("address-only service must be admitted: %v", err) + } + addresses = []string{} + if err := c.Update(ctx, svc); err != nil { + t.Fatalf("explicit empty address list must permit withdrawal: %v", err) + } + svc.Spec.BackendAddresses = nil + if err := c.Update(ctx, svc); err == nil { + t.Fatal("service with no selector or address list must be refused") + } + bad := protocolService("ipv4-backend-address", networkv1alpha1.NetworkServiceProtocolTCP, 443, 8443) + bad.Spec.BackendSelector = metav1.LabelSelector{} + v4 := []string{"192.0.2.1"} + bad.Spec.BackendAddresses = &v4 + if err := c.Create(ctx, bad); err == nil { + t.Fatal("IPv4 backend address must be refused") + } +} + // requireRefusal fails unless err is a schema rejection containing every one // of want and none of unwanted. func requireRefusal(t *testing.T, err error, want, unwanted []string) { diff --git a/api/network/v1alpha1/networkservice_types.go b/api/network/v1alpha1/networkservice_types.go index ce046a1f8..1ef051a39 100644 --- a/api/network/v1alpha1/networkservice_types.go +++ b/api/network/v1alpha1/networkservice_types.go @@ -114,13 +114,11 @@ const ( // backend selection never needs a single "owning" node the way Full-NAT's // SNAT-source model did. // -// Backends are not listed. BackendSelector picks the VPCAttachments that -// serve the service, so the backend set follows attachments as they are -// created, deleted or moved to another node, and galactic-router on each -// node generates the ServiceVIPBinding its backends need from the same -// selection. A service in the gateway namespace can instead name an -// EdgeListener with EdgeListenerRef, whose listener attachments are then its -// backends. +// BackendSelector and optional BackendAddresses select VPCAttachments in the +// service's observed VPC. Address-only selection does not require a label. +// galactic-router generates ServiceVIPBindings from the same selection. +// A service in the gateway namespace can instead name an EdgeListener with +// EdgeListenerRef to use its listener attachments. // // +kubebuilder:object:root=true // +kubebuilder:subresource:status @@ -148,7 +146,8 @@ type NetworkService struct { // +kubebuilder:validation:XValidation:rule="!(self.protocol in ['esp', 'gre', 'icmp']) || !has(self.port)",message="port must not be set for esp, gre and icmp, which have no ports" // +kubebuilder:validation:XValidation:rule="!(self.protocol in ['esp', 'gre', 'icmp']) || !has(self.backendPort)",message="backendPort must not be set for esp, gre and icmp, which have no ports" // +kubebuilder:validation:XValidation:rule="self.protocol != 'udp' || !has(self.healthCheck) || has(self.healthCheck.port)",message="healthCheck.port is required for udp: a health check probes a TCP port" -// +kubebuilder:validation:XValidation:rule="has(self.backendSelector) != has(self.edgeListenerRef)",message="exactly one of backendSelector and edgeListenerRef is required" +// +kubebuilder:validation:XValidation:rule="(has(self.backendSelector) || has(self.backendAddresses)) != has(self.edgeListenerRef)",message="choose attachment backends or an edgeListenerRef" +// +kubebuilder:validation:XValidation:rule="!has(self.backendSelector) || has(self.backendAddresses) || (has(self.backendSelector) && ((has(self.backendSelector.matchLabels) && size(self.backendSelector.matchLabels) > 0) || (has(self.backendSelector.matchExpressions) && size(self.backendSelector.matchExpressions) > 0)))",message="backendSelector must not be empty without backendAddresses" type NetworkServiceSpec struct { // VPCRef is the opaque identifier of the target VPC this service applies // to, a VPC's status.vpc. In a gateway namespace, the platform API that @@ -238,13 +237,21 @@ type NetworkServiceSpec struct { // BackendPort, for both VIPs: its node translates the IPv4 VIP's flows to // and from IPv6, and its IPv4 addresses are never backends. An attachment // with no status.node, or no IPv6 address, is not a backend until it has - // both. An empty selector is rejected rather than read as "every - // attachment in the VPC". Exactly one of BackendSelector and - // EdgeListenerRef is required. + // both. An empty selector is accepted only with BackendAddresses and then + // matches all attachments in this service's observed VPC. // +optional - // +kubebuilder:validation:XValidation:rule="(has(self.matchLabels) && size(self.matchLabels) > 0) || (has(self.matchExpressions) && size(self.matchExpressions) > 0)",message="backendSelector must not be empty" BackendSelector metav1.LabelSelector `json:"backendSelector,omitzero"` + // BackendAddresses restricts selected attachments to these IPv6 backend + // addresses. When set without a selector, it matches attachments by address + // only, still requiring status.vpc to equal VPCRef. An explicit empty list + // withdraws all backends and their bindings without broadening selection. + // +optional + // +kubebuilder:validation:MaxItems=64 + // +kubebuilder:validation:XValidation:rule="self.all(a, isIP(a) && ip(a).family() == 6)",message="backendAddresses must contain IPv6 addresses" + // +listType=set + BackendAddresses *[]string `json:"backendAddresses,omitempty"` + // EdgeListenerRef names the EdgeListener, in the service's namespace, // whose listener attachments are the service's backends, in place of // BackendSelector. Core sets it on the services it writes for a diff --git a/api/network/v1alpha1/networkservice_types_test.go b/api/network/v1alpha1/networkservice_types_test.go index 6ce42a918..eae86d053 100644 --- a/api/network/v1alpha1/networkservice_types_test.go +++ b/api/network/v1alpha1/networkservice_types_test.go @@ -32,10 +32,13 @@ func newTestService() *NetworkService { // copy: mutations to slices in the copy must not affect the original. func TestNetworkServiceDeepCopy(t *testing.T) { orig := newTestService() + addresses := []string{"fd00:10::1"} + orig.Spec.BackendAddresses = &addresses dup := orig.DeepCopy() dup.Spec.VIPAddresses[0] = "2001:db8:1::20" dup.Spec.BackendSelector.MatchLabels["app"] = "api" + (*dup.Spec.BackendAddresses)[0] = "fd00:10::2" if orig.Spec.VIPAddresses[0] != "2001:db8:1::10" { t.Errorf("VIPAddresses[0] mutated: got %q", orig.Spec.VIPAddresses[0]) @@ -43,6 +46,9 @@ func TestNetworkServiceDeepCopy(t *testing.T) { if orig.Spec.BackendSelector.MatchLabels["app"] != "web" { t.Errorf("BackendSelector.MatchLabels mutated: got %v", orig.Spec.BackendSelector.MatchLabels) } + if (*orig.Spec.BackendAddresses)[0] != "fd00:10::1" { + t.Errorf("BackendAddresses mutated: got %v", *orig.Spec.BackendAddresses) + } } // TestNetworkServiceDeepCopyNil verifies DeepCopy on a nil pointer returns nil. @@ -148,6 +154,24 @@ func TestNetworkServiceBackendFieldNames(t *testing.T) { } } +func TestNetworkServiceExplicitEmptyBackendAddresses(t *testing.T) { + svc := newTestService() + svc.Spec.BackendSelector = metav1.LabelSelector{} + addresses := []string{} + svc.Spec.BackendAddresses = &addresses + data, err := json.Marshal(svc.Spec) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(data), `"backendAddresses":[]`) { + t.Fatalf("explicit empty list lost during encoding: %s", data) + } + var got NetworkServiceSpec + if err := json.Unmarshal(data, &got); err != nil || got.BackendAddresses == nil || len(*got.BackendAddresses) != 0 { + t.Fatalf("explicit empty list lost during decoding: %+v, %v", got.BackendAddresses, err) + } +} + // TestNetworkServiceProtocolValues pins the NetworkServiceProtocol values, // which are part of the published API. func TestNetworkServiceProtocolValues(t *testing.T) { diff --git a/api/network/v1alpha1/zz_generated.deepcopy.go b/api/network/v1alpha1/zz_generated.deepcopy.go index 9d8c156dd..592e82e3e 100644 --- a/api/network/v1alpha1/zz_generated.deepcopy.go +++ b/api/network/v1alpha1/zz_generated.deepcopy.go @@ -4168,6 +4168,15 @@ func (in *NetworkServiceSpec) DeepCopyInto(out *NetworkServiceSpec) { (*in).DeepCopyInto(*out) } in.BackendSelector.DeepCopyInto(&out.BackendSelector) + if in.BackendAddresses != nil { + in, out := &in.BackendAddresses, &out.BackendAddresses + *out = new([]string) + if **in != nil { + in, out := *in, *out + *out = make([]string, len(*in)) + copy(*out, *in) + } + } if in.EdgeListenerRef != nil { in, out := &in.EdgeListenerRef, &out.EdgeListenerRef *out = new(NetworkServiceEdgeListenerReference) diff --git a/config/crd/galactic.datumapis.com_networkservices.yaml b/config/crd/galactic.datumapis.com_networkservices.yaml index d35ad54f7..4cc8c16df 100644 --- a/config/crd/galactic.datumapis.com_networkservices.yaml +++ b/config/crd/galactic.datumapis.com_networkservices.yaml @@ -64,13 +64,11 @@ spec: backend selection never needs a single "owning" node the way Full-NAT's SNAT-source model did. - Backends are not listed. BackendSelector picks the VPCAttachments that - serve the service, so the backend set follows attachments as they are - created, deleted or moved to another node, and galactic-router on each - node generates the ServiceVIPBinding its backends need from the same - selection. A service in the gateway namespace can instead name an - EdgeListener with EdgeListenerRef, whose listener attachments are then its - backends. + BackendSelector and optional BackendAddresses select VPCAttachments in the + service's observed VPC. Address-only selection does not require a label. + galactic-router generates ServiceVIPBindings from the same selection. + A service in the gateway namespace can instead name an EdgeListener with + EdgeListenerRef to use its listener attachments. properties: apiVersion: description: |- @@ -184,6 +182,20 @@ spec: - message: listenerName must identify a declared listener rule: '!has(self.listenerName) || (has(self.listeners) && self.listeners.exists(l, l.name == self.listenerName))' + backendAddresses: + description: |- + BackendAddresses restricts selected attachments to these IPv6 backend + addresses. When set without a selector, it matches attachments by address + only, still requiring status.vpc to equal VPCRef. An explicit empty list + withdraws all backends and their bindings without broadening selection. + items: + type: string + maxItems: 64 + type: array + x-kubernetes-list-type: set + x-kubernetes-validations: + - message: backendAddresses must contain IPv6 addresses + rule: self.all(a, isIP(a) && ip(a).family() == 6) backendPort: description: |- BackendPort is the destination port on every selected backend, 1-65535. @@ -206,9 +218,8 @@ spec: BackendPort, for both VIPs: its node translates the IPv4 VIP's flows to and from IPv6, and its IPv4 addresses are never backends. An attachment with no status.node, or no IPv6 address, is not a backend until it has - both. An empty selector is rejected rather than read as "every - attachment in the VPC". Exactly one of BackendSelector and - EdgeListenerRef is required. + both. An empty selector is accepted only with BackendAddresses and then + matches all attachments in this service's observed VPC. properties: matchExpressions: description: matchExpressions is a list of label selector requirements. @@ -253,10 +264,6 @@ spec: type: object type: object x-kubernetes-map-type: atomic - x-kubernetes-validations: - - message: backendSelector must not be empty - rule: (has(self.matchLabels) && size(self.matchLabels) > 0) || (has(self.matchExpressions) - && size(self.matchExpressions) > 0) edgeListenerRef: description: |- EdgeListenerRef names the EdgeListener, in the service's namespace, @@ -508,8 +515,13 @@ spec: - message: 'healthCheck.port is required for udp: a health check probes a TCP port' rule: self.protocol != 'udp' || !has(self.healthCheck) || has(self.healthCheck.port) - - message: exactly one of backendSelector and edgeListenerRef is required - rule: has(self.backendSelector) != has(self.edgeListenerRef) + - message: choose attachment backends or an edgeListenerRef + rule: (has(self.backendSelector) || has(self.backendAddresses)) != has(self.edgeListenerRef) + - message: backendSelector must not be empty without backendAddresses + rule: '!has(self.backendSelector) || has(self.backendAddresses) || (has(self.backendSelector) + && ((has(self.backendSelector.matchLabels) && size(self.backendSelector.matchLabels) + > 0) || (has(self.backendSelector.matchExpressions) && size(self.backendSelector.matchExpressions) + > 0)))' status: description: NetworkServiceStatus defines the observed state of a NetworkService. properties: diff --git a/docs/api/network-gateway.md b/docs/api/network-gateway.md index bdab216ed..4d01f6ca3 100644 --- a/docs/api/network-gateway.md +++ b/docs/api/network-gateway.md @@ -426,13 +426,11 @@ flow (internal/maglev), and forwards without rewriting anything — backend selection never needs a single "owning" node the way Full-NAT's SNAT-source model did. -Backends are not listed. BackendSelector picks the VPCAttachments that -serve the service, so the backend set follows attachments as they are -created, deleted or moved to another node, and galactic-router on each -node generates the ServiceVIPBinding its backends need from the same -selection. A service in the gateway namespace can instead name an -EdgeListener with EdgeListenerRef, whose listener attachments are then its -backends. +BackendSelector and optional BackendAddresses select VPCAttachments in the +service's observed VPC. Address-only selection does not require a label. +galactic-router generates ServiceVIPBindings from the same selection. +A service in the gateway namespace can instead name an EdgeListener with +EdgeListenerRef to use its listener attachments. @@ -663,7 +661,8 @@ _Appears in:_ | `port` _integer_ | Port is the ingress port on VIPAddresses that this service load-balances,
1-65535. It is required when PortRange is absent for tcp, udp and sctp
and must be unset for one without (esp, gre and icmp). Zero means unset
and is omitted when encoding, and an explicit 0 is refused. | | Maximum: 65535
Minimum: 1
| | `portRange` _[PortRange](#portrange)_ | PortRange replaces Port for an inclusive IPv6 UDP interval. Backend ports
are preserved; BackendPort must be omitted. | | | | `addressGroup` _[NetworkServiceAddressGroup](#networkserviceaddressgroup)_ | AddressGroup binds this listener to a complete, authoritative address inventory. | | | -| `backendSelector` _[LabelSelector](https://kubernetes.io/docs/reference/generated/kubernetes-api/v/#labelselector-v1-meta)_ | BackendSelector selects the VPCAttachments (galactic.datumapis.com/v1alpha1)
that serve this service, matched against each VPCAttachment object's own
labels: in any namespace for a service in a gateway namespace, and only
in its own namespace for a service in a project namespace. Only
attachments whose status.vpc equals VPCRef are candidates, whatever their
labels, so a selector cannot reach into another tenant's VPC. Each selected attachment contributes the
IPv6 addresses in its spec.interface.addresses as backends, on
BackendPort, for both VIPs: its node translates the IPv4 VIP's flows to
and from IPv6, and its IPv4 addresses are never backends. An attachment
with no status.node, or no IPv6 address, is not a backend until it has
both. An empty selector is rejected rather than read as "every
attachment in the VPC". Exactly one of BackendSelector and
EdgeListenerRef is required. | | | +| `backendSelector` _[LabelSelector](https://kubernetes.io/docs/reference/generated/kubernetes-api/v/#labelselector-v1-meta)_ | BackendSelector selects the VPCAttachments (galactic.datumapis.com/v1alpha1)
that serve this service, matched against each VPCAttachment object's own
labels: in any namespace for a service in a gateway namespace, and only
in its own namespace for a service in a project namespace. Only
attachments whose status.vpc equals VPCRef are candidates, whatever their
labels, so a selector cannot reach into another tenant's VPC. Each selected attachment contributes the
IPv6 addresses in its spec.interface.addresses as backends, on
BackendPort, for both VIPs: its node translates the IPv4 VIP's flows to
and from IPv6, and its IPv4 addresses are never backends. An attachment
with no status.node, or no IPv6 address, is not a backend until it has
both. An empty selector is accepted only with BackendAddresses and then
matches all attachments in this service's observed VPC. | | | +| `backendAddresses` _string_ | BackendAddresses restricts selected attachments to these IPv6 backend
addresses. When set without a selector, it matches attachments by address
only, still requiring status.vpc to equal VPCRef. An explicit empty list
withdraws all backends and their bindings without broadening selection. | | MaxItems: 64
| | `edgeListenerRef` _[NetworkServiceEdgeListenerReference](#networkserviceedgelistenerreference)_ | EdgeListenerRef names the EdgeListener, in the service's namespace,
whose listener attachments are the service's backends, in place of
BackendSelector. Core sets it on the services it writes for a
listener, one per listener port. It is allowed only in the gateway
namespace. Its backends are the listener's status.backends that core
reports serving; gateways and backend nodes never select them from
VPCAttachments. | | | | `backendPort` _integer_ | BackendPort is the destination port on every selected backend, 1-65535.
Like Port, it is required for tcp, udp and sctp and must be unset for
esp, gre and icmp. Zero means unset and is omitted when encoding, and an
explicit 0 is refused. | | Maximum: 65535
Minimum: 1
| | `sessionAffinity` _[NetworkServiceSessionAffinity](#networkservicesessionaffinity)_ | SessionAffinity selects which connections from one client share a
backend: None, the default, balances each connection on its own;
ClientIP pins a client address to one backend; ClientIPAndProtocol pins
a client address and protocol to one. Two services pin a client to the
same backend only if both set the same affinity and select the same
backend addresses. A change takes effect on every gateway node without a
restart, and rehashes every connection of the service, so most open
connections reach a different backend afterwards. | None | Enum: [None ClientIP ClientIPAndProtocol]
| diff --git a/docs/gateway/architecture.md b/docs/gateway/architecture.md index dbfa589ae..c2356995b 100644 --- a/docs/gateway/architecture.md +++ b/docs/gateway/architecture.md @@ -25,6 +25,8 @@ All gateways advertise a VIP identically through `BGPAdvertisement` resources co A backend needs a valid node locator, VPC identity and attachment context. The gateway encodes the backend slot in the uSID; the backend's ingress translation row includes that slot. Gateway and router releases must agree on this map/key contract. A new gateway paired with an older router that has not written slot-aware rows drops the affected flows. +Address selection can narrow the backend set to specific IPv6 addresses in eligible VPCAttachments. The reply translation key includes VPC, backend socket, protocol and VIP family. Two services with different VIPs of the same family cannot share that backend socket. The older rule retains the claim. + The router owns each backend's `ServiceVIPBinding` and reports `Bound` after programming its rows. IPv4 VIP advertisement is additionally gated on these bindings. See [IPv4 rollout](deployment.md#rolling-out-and-rolling-back-ipv4-vips) before enabling the feature or rolling either backend component back. ## Datapath diff --git a/internal/controller/networkgateway_controller.go b/internal/controller/networkgateway_controller.go index 20d16a5ee..f02261069 100644 --- a/internal/controller/networkgateway_controller.go +++ b/internal/controller/networkgateway_controller.go @@ -1988,6 +1988,10 @@ func resolveFamilyBackends( err = fmt.Errorf("every selected backend is served by an older rule: %s", cappedList(out.unresolved)) case len(out.unresolved) > 0: err = fmt.Errorf("no selected attachment is a backend yet: %s", cappedList(out.unresolved)) + case rule.Spec.BackendAddresses != nil && len(*rule.Spec.BackendAddresses) == 0: + err = errors.New("backendAddresses is empty") + case rule.Spec.BackendAddresses != nil: + err = fmt.Errorf("backendAddresses match no selected VPCAttachment in VPC %s", rule.Spec.VPCRef) default: err = fmt.Errorf("backendSelector matches no VPCAttachment in VPC %s", rule.Spec.VPCRef) } diff --git a/internal/controller/rulebackends.go b/internal/controller/rulebackends.go index 2579e5d5c..d6eee5b01 100644 --- a/internal/controller/rulebackends.go +++ b/internal/controller/rulebackends.go @@ -263,6 +263,18 @@ func selectorCandidateBackends( return nil, nil, err } + var allowed map[netip.Addr]struct{} + if rule.Spec.BackendAddresses != nil { + allowed = make(map[netip.Addr]struct{}, len(*rule.Spec.BackendAddresses)) + for _, raw := range *rule.Spec.BackendAddresses { + addr, parseErr := netip.ParseAddr(raw) + if parseErr != nil || !addr.Is6() || addr.Is4In6() { + return nil, nil, fmt.Errorf("invalid IPv6 backend address %q", raw) + } + allowed[addr] = struct{}{} + } + } + for _, attachment := range attachments { if attachment.Status.VPC != rule.Spec.VPCRef || !selector.Matches(labels.Set(attachment.Labels)) { continue @@ -270,12 +282,21 @@ func selectorCandidateBackends( if ruleIsTenant(rule, objNS) && attachment.Namespace != rule.Namespace { continue } + addrs := attachmentIPv6Addresses(attachment) + if allowed != nil { + addrs = slices.DeleteFunc(addrs, func(addr netip.Addr) bool { + _, ok := allowed[addr] + return !ok + }) + if len(addrs) == 0 { + continue + } + } key := types.NamespacedName{Namespace: attachment.Namespace, Name: attachment.Name} if attachment.Status.Node == "" { pending = append(pending, key.String()+": status.node not set by datum-cloud/cloud") continue } - addrs := attachmentIPv6Addresses(attachment) if len(addrs) == 0 { pending = append(pending, key.String()+": no IPv6 address") continue @@ -562,12 +583,15 @@ func errTooManyVIPs(family addrFamily, n int) error { } // ruleBackendSelector converts rule's BackendSelector to a labels.Selector. -// The CRD rejects an empty selector; this rejects one anyway, since an empty -// selector would otherwise match every attachment in the VPC. +// An empty selector matches attachments by address only when an explicit +// BackendAddresses list is present; status.vpc still limits the candidate VPC. func ruleBackendSelector(rule *bgpv1alpha1.NetworkService) (labels.Selector, error) { sel := rule.Spec.BackendSelector if len(sel.MatchLabels) == 0 && len(sel.MatchExpressions) == 0 { - return nil, errors.New("backendSelector is empty") + if rule.Spec.BackendAddresses == nil { + return nil, errors.New("backendSelector is empty and backendAddresses is unset") + } + return labels.Everything(), nil } selector, err := metav1.LabelSelectorAsSelector(&sel) if err != nil { diff --git a/internal/controller/rulebackends_test.go b/internal/controller/rulebackends_test.go index 6d78bc3c2..78585ce46 100644 --- a/internal/controller/rulebackends_test.go +++ b/internal/controller/rulebackends_test.go @@ -121,6 +121,35 @@ func TestSelectRuleBackends_DropsConflictingBackends(t *testing.T) { } } +func TestRuleCandidateBackends_AddressOnlyWithinObservedVPC(t *testing.T) { + rule := newTestRule(testRuleName, testVPCRef, testVIP) + rule.Spec.BackendSelector = metav1.LabelSelector{} + addresses := []string{"fd00:10::1"} + rule.Spec.BackendAddresses = &addresses + + inVPC := newBackendAttachment(testVPCRef, "fd00:10::1") + inVPC.Labels = nil + otherVPC := newBackendAttachment("other-vpc", "fd00:10::1") + otherVPC.Name = "other-vpc" + unlisted := newBackendAttachment(testVPCRef, "fd00:10::2") + unlisted.Name = "unlisted" + unlisted.Status.Node = "" + + got, pending, err := ruleCandidateBackends(rule, []*cloudv1alpha1.VPCAttachment{otherVPC, unlisted, inVPC}, nil, testNamespace) + if err != nil || len(got) != 1 || got[0].attachment.Name != inVPC.Name || len(pending) != 0 { + t.Fatalf("address-only selection = %+v, pending %v, %v; want only the attachment in the observed VPC", got, pending, err) + } + addresses = []string{} + got, _, err = ruleCandidateBackends(rule, []*cloudv1alpha1.VPCAttachment{inVPC}, nil, testNamespace) + if err != nil || len(got) != 0 { + t.Fatalf("explicit empty list = %+v, %v; want no backends", got, err) + } + rule.Spec.BackendAddresses = nil + if _, _, err = ruleCandidateBackends(rule, []*cloudv1alpha1.VPCAttachment{inVPC}, nil, testNamespace); err == nil { + t.Fatal("empty selector without backendAddresses must fail closed") + } +} + // newSharingRule returns a rule named name with the IPv6 VIP vip, created at // second created, selecting newBackendAttachment's attachments in testVPCRef. func newSharingRule(name, vip string, created int64) *bgpv1alpha1.NetworkService { From 479d50c2b8ecbb5d548a54e878e88565e98865bf Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 21 Oct 2026 18:17:22 -0500 Subject: [PATCH 2/2] Bound backend address validation cost and fix lint --- api/network/v1alpha1/networkservice_types.go | 1 + config/crd/galactic.datumapis.com_networkservices.yaml | 1 + docs/api/network-gateway.md | 2 +- docs/gateway/configuration.md | 4 +++- internal/controller/rulebackends_test.go | 9 +++++---- 5 files changed, 11 insertions(+), 6 deletions(-) diff --git a/api/network/v1alpha1/networkservice_types.go b/api/network/v1alpha1/networkservice_types.go index 1ef051a39..0750103b5 100644 --- a/api/network/v1alpha1/networkservice_types.go +++ b/api/network/v1alpha1/networkservice_types.go @@ -248,6 +248,7 @@ type NetworkServiceSpec struct { // withdraws all backends and their bindings without broadening selection. // +optional // +kubebuilder:validation:MaxItems=64 + // +kubebuilder:validation:items:MaxLength=45 // +kubebuilder:validation:XValidation:rule="self.all(a, isIP(a) && ip(a).family() == 6)",message="backendAddresses must contain IPv6 addresses" // +listType=set BackendAddresses *[]string `json:"backendAddresses,omitempty"` diff --git a/config/crd/galactic.datumapis.com_networkservices.yaml b/config/crd/galactic.datumapis.com_networkservices.yaml index 4cc8c16df..3a4d32b44 100644 --- a/config/crd/galactic.datumapis.com_networkservices.yaml +++ b/config/crd/galactic.datumapis.com_networkservices.yaml @@ -189,6 +189,7 @@ spec: only, still requiring status.vpc to equal VPCRef. An explicit empty list withdraws all backends and their bindings without broadening selection. items: + maxLength: 45 type: string maxItems: 64 type: array diff --git a/docs/api/network-gateway.md b/docs/api/network-gateway.md index 4d01f6ca3..13896b9eb 100644 --- a/docs/api/network-gateway.md +++ b/docs/api/network-gateway.md @@ -662,7 +662,7 @@ _Appears in:_ | `portRange` _[PortRange](#portrange)_ | PortRange replaces Port for an inclusive IPv6 UDP interval. Backend ports
are preserved; BackendPort must be omitted. | | | | `addressGroup` _[NetworkServiceAddressGroup](#networkserviceaddressgroup)_ | AddressGroup binds this listener to a complete, authoritative address inventory. | | | | `backendSelector` _[LabelSelector](https://kubernetes.io/docs/reference/generated/kubernetes-api/v/#labelselector-v1-meta)_ | BackendSelector selects the VPCAttachments (galactic.datumapis.com/v1alpha1)
that serve this service, matched against each VPCAttachment object's own
labels: in any namespace for a service in a gateway namespace, and only
in its own namespace for a service in a project namespace. Only
attachments whose status.vpc equals VPCRef are candidates, whatever their
labels, so a selector cannot reach into another tenant's VPC. Each selected attachment contributes the
IPv6 addresses in its spec.interface.addresses as backends, on
BackendPort, for both VIPs: its node translates the IPv4 VIP's flows to
and from IPv6, and its IPv4 addresses are never backends. An attachment
with no status.node, or no IPv6 address, is not a backend until it has
both. An empty selector is accepted only with BackendAddresses and then
matches all attachments in this service's observed VPC. | | | -| `backendAddresses` _string_ | BackendAddresses restricts selected attachments to these IPv6 backend
addresses. When set without a selector, it matches attachments by address
only, still requiring status.vpc to equal VPCRef. An explicit empty list
withdraws all backends and their bindings without broadening selection. | | MaxItems: 64
| +| `backendAddresses` _string_ | BackendAddresses restricts selected attachments to these IPv6 backend
addresses. When set without a selector, it matches attachments by address
only, still requiring status.vpc to equal VPCRef. An explicit empty list
withdraws all backends and their bindings without broadening selection. | | MaxItems: 64
items:MaxLength: 45
| | `edgeListenerRef` _[NetworkServiceEdgeListenerReference](#networkserviceedgelistenerreference)_ | EdgeListenerRef names the EdgeListener, in the service's namespace,
whose listener attachments are the service's backends, in place of
BackendSelector. Core sets it on the services it writes for a
listener, one per listener port. It is allowed only in the gateway
namespace. Its backends are the listener's status.backends that core
reports serving; gateways and backend nodes never select them from
VPCAttachments. | | | | `backendPort` _integer_ | BackendPort is the destination port on every selected backend, 1-65535.
Like Port, it is required for tcp, udp and sctp and must be unset for
esp, gre and icmp. Zero means unset and is omitted when encoding, and an
explicit 0 is refused. | | Maximum: 65535
Minimum: 1
| | `sessionAffinity` _[NetworkServiceSessionAffinity](#networkservicesessionaffinity)_ | SessionAffinity selects which connections from one client share a
backend: None, the default, balances each connection on its own;
ClientIP pins a client address to one backend; ClientIPAndProtocol pins
a client address and protocol to one. Two services pin a client to the
same backend only if both set the same affinity and select the same
backend addresses. A change takes effect on every gateway node without a
restart, and rehashes every connection of the service, so most open
connections reach a different backend afterwards. | None | Enum: [None ClientIP ClientIPAndProtocol]
| diff --git a/docs/gateway/configuration.md b/docs/gateway/configuration.md index a13f2be2b..fc3690547 100644 --- a/docs/gateway/configuration.md +++ b/docs/gateway/configuration.md @@ -213,7 +213,9 @@ gateway node, named after that node (see the worked example above). | `spec.vipAddresses` | Yes | `[]string` (1–8) | Ingress VIP addresses this rule provisions: at most one IPv6 and at most one IPv4 address, an IPv4 address in dotted form. See below. | | `spec.protocol` | Yes | `tcp` \| `udp` | IP protocol load-balanced on `vipAddresses`. The API also accepts `sctp`, `esp`, `gre` and `icmp`, but refuses them as not served yet; see below. | | `spec.port` | tcp, udp | `int32` (1–65535) | Ingress port on `vipAddresses` this rule load-balances. Required for a protocol with ports, refused for one without. | -| `spec.backendSelector` | Yes | `metav1.LabelSelector` | Selects the `VPCAttachment`s (`galactic.datumapis.com`, any namespace) that serve the rule. Each contributes its IPv6 interface addresses as backends of both VIPs; its IPv4 addresses are never backends. Must not be empty. | +| `spec.backendSelector` | No | `metav1.LabelSelector` | Selects eligible VPCAttachments by label. A service using attachment backends needs a nonempty selector or an explicit address list. A project service selects only attachments in its namespace and VPC. | +| `spec.backendAddresses` | No | `[]string` | Selects up to 64 IPv6 addresses from eligible attachments. With a selector, both filters apply. An explicit empty list withdraws every backend. | +| `spec.edgeListenerRef` | No | object | A service in the gateway namespace can use a named EdgeListener as its backend source. This field is mutually exclusive with the attachment selector and address list. | | `spec.backendPort` | tcp, udp | `int32` (1–65535) | Destination port on every selected backend. Required for a protocol with ports, refused for one without. | | `spec.sessionAffinity` | No | `string` enum | `None` (default), `ClientIP` or `ClientIPAndProtocol`: which connections from one client share a backend. See [Session affinity](#session-affinity). | | `spec.healthCheck` | No | object | Turns on TCP health checks of the backends: `port` (default `backendPort`, required for `udp`), `intervalSeconds` (5), `timeoutSeconds` (2), `unhealthyThreshold` (3), `healthyThreshold` (3). See [Backend health checks](backend-health.md). | diff --git a/internal/controller/rulebackends_test.go b/internal/controller/rulebackends_test.go index 78585ce46..351d232ed 100644 --- a/internal/controller/rulebackends_test.go +++ b/internal/controller/rulebackends_test.go @@ -129,15 +129,16 @@ func TestRuleCandidateBackends_AddressOnlyWithinObservedVPC(t *testing.T) { inVPC := newBackendAttachment(testVPCRef, "fd00:10::1") inVPC.Labels = nil - otherVPC := newBackendAttachment("other-vpc", "fd00:10::1") - otherVPC.Name = "other-vpc" + otherVPC := newBackendAttachment(testOtherVPCRef, "fd00:10::1") + otherVPC.Name = "outside" unlisted := newBackendAttachment(testVPCRef, "fd00:10::2") unlisted.Name = "unlisted" unlisted.Status.Node = "" - got, pending, err := ruleCandidateBackends(rule, []*cloudv1alpha1.VPCAttachment{otherVPC, unlisted, inVPC}, nil, testNamespace) + attachments := []*cloudv1alpha1.VPCAttachment{otherVPC, unlisted, inVPC} + got, pending, err := ruleCandidateBackends(rule, attachments, nil, testNamespace) if err != nil || len(got) != 1 || got[0].attachment.Name != inVPC.Name || len(pending) != 0 { - t.Fatalf("address-only selection = %+v, pending %v, %v; want only the attachment in the observed VPC", got, pending, err) + t.Fatalf("address-only selection = %+v, pending %v, %v; want only the observed VPC", got, pending, err) } addresses = []string{} got, _, err = ruleCandidateBackends(rule, []*cloudv1alpha1.VPCAttachment{inVPC}, nil, testNamespace)