diff --git a/docs/nat/configuration.md b/docs/nat/configuration.md index 3a591e38e..f942f78ce 100644 --- a/docs/nat/configuration.md +++ b/docs/nat/configuration.md @@ -246,12 +246,13 @@ a change strands every established flow. A shard holding the wrong identity is d The datapath needs a SID and at least one family before it translates anything: -| `Programmed` reason | Meaning | -| --------------------- | ---------------------------------------------------------------------------------------------------------------- | -| `AddressesProgrammed` | The datapath translates with the identity the spec assigns. | -| `AddressUnassigned` | The spec assigns no SID, or no masquerade address for either family. The datapath is cleared and claims nothing. | -| `ProgrammingFailed` | The datapath rejected the identity, for example a NAT64 prefix that is not a `/96`. The message says why. | -| `ShardConflict` | More than one `EgressShard` targets this node. None is programmed until only one does. | +| `Programmed` reason | Meaning | +| --------------------- | ---------------------------------------------------------------------------------------------------------------------------- | +| `AddressesProgrammed` | The datapath translates with the identity the spec assigns. | +| `AddressUnassigned` | The spec assigns no SID, or no masquerade address for either family. The datapath is cleared and claims nothing. | +| `LocatorConflict` | The SID's Block and Node-ID equal a `BGPRouter`'s. The datapath is cleared and claims nothing. The message names the router. | +| `ProgrammingFailed` | The datapath rejected the identity, for example a NAT64 prefix that is not a `/96`. The message says why. | +| `ShardConflict` | More than one `EgressShard` targets this node. None is programmed until only one does. | `EgressShardReconciler` (running inside that node's own `galactic-nat` pod) publishes one `BGPAdvertisement` per shard, built from status rather than @@ -265,11 +266,12 @@ identity, clears the datapath and withdraws the advertisement. > **Node-ID collision hazard.** The datapath's `locator_matches` check > (`internal/plumbing/ebpf/natprog/nat.c`) only compares the top 64 > bits (Block + Node-ID) of a packet's outer destination against -> `shardSID` — it does **not** check that the Node-ID is actually reserved -> for the shard. Reusing the physical node's own real `BGPRouter.Spec.NodeID` -> here means the shard's XDP program hijacks that node's own ordinary -> tenant ingress traffic before `usid_ingress` ever gets to it. Reserve a -> distinct Node-ID on the shard's locator for this purpose alone — see +> `shardSID`. A shard reusing a `BGPRouter`'s `srv6Locator` and `nodeID` +> would capture that router's tenant ingress before `usid_ingress` ever +> gets to it, so `EgressShardReconciler` checks the SID against every +> `BGPRouter` in the cluster and refuses one that matches, with +> `Programmed=False` reason `LocatorConflict`. Reserve a distinct Node-ID +> on the shard's locator for this purpose alone — see > `deploy/containerlab/resources/galactic-nat/dfw/egressshard.yaml` for > the exact encoding the lab uses. @@ -621,9 +623,10 @@ knowing before you rely on this component in production: until it refills. `icmp_rate_limited` counts each refusal; a per-peer or global limiter is the follow-up if that counter shows either problem. - **A shard's identity is entirely operator-chosen.** Nothing in this repo - allocates `spec.shardSID` or the masquerade addresses, and nothing checks - that a chosen SID's Node-ID doesn't collide with a real node's own — see - the "Node-ID collision hazard" callout above. + allocates `spec.shardSID` or the masquerade addresses. A SID colliding + with a `BGPRouter`'s Block and Node-ID is refused (see the "Node-ID + collision hazard" callout above), but a collision with any other uSID + identity, one no `BGPRouter` carries, is not detected. - **One NIC receive queue on a `bnxt_en` uplink can stall.** The queue drops a steady share of its packets while the CPU sits idle, and every flow hashed to it fails on each retry: tenant egress times out per flow, diff --git a/internal/controller/egressshard_controller.go b/internal/controller/egressshard_controller.go index 0bdecd540..2e7449e78 100644 --- a/internal/controller/egressshard_controller.go +++ b/internal/controller/egressshard_controller.go @@ -26,6 +26,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/source" "go.datum.net/galactic/internal/plumbing/ebpf/uformat" + "go.datum.net/galactic/internal/plumbing/srv6" bgpv1alpha1 "go.datum.net/network/api/v1alpha1" ) @@ -94,6 +95,12 @@ const ( // holds one identity, so none of them is programmed until the conflict is // resolved. reasonEgressShardConflict = "ShardConflict" + + // reasonEgressShardLocatorConflict is the Programmed condition reason on + // an EgressShard whose SID shares its Block and Node-ID with a BGPRouter. + // The datapath claims every packet matching those 64 bits, so programming + // the shard would capture that router's tenant ingress. + reasonEgressShardLocatorConflict = "LocatorConflict" ) // EgressShardReconciler programs this node's egress translation datapath from @@ -234,7 +241,7 @@ func (r *EgressShardReconciler) syncNode(ctx context.Context) error { return nil case len(mine) == 1: var err error - if programmed, err = r.program(mine[0]); err != nil { + if programmed, err = r.program(ctx, mine[0]); err != nil { // Publish why before returning the error for a retry. if pubErr := r.publish(ctx, mine[0], programmed); pubErr != nil { return errors.Join(err, pubErr) @@ -263,8 +270,9 @@ func (r *EgressShardReconciler) syncNode(ctx context.Context) error { // program writes shard's spec into the datapath and returns the resulting // Programmed condition. A spec that assigns no usable identity yet clears the // datapath rather than leaving a previous one in place, which is not an error: -// the assignment arrives later as a spec update. -func (r *EgressShardReconciler) program(shard *bgpv1alpha1.EgressShard) (metav1.Condition, error) { +// the assignment arrives later as a spec update. A SID that shares its Block +// and Node-ID with a BGPRouter is refused too; see routerLocatorConflict. +func (r *EgressShardReconciler) program(ctx context.Context, shard *bgpv1alpha1.EgressShard) (metav1.Condition, error) { cond := metav1.Condition{Type: bgpv1alpha1.ConditionTypeProgrammed, Status: metav1.ConditionFalse} identity, missing, err := identityFromSpec(shard.Spec) @@ -281,6 +289,22 @@ func (r *EgressShardReconciler) program(shard *bgpv1alpha1.EgressShard) (metav1. cond.Message = missing return cond, nil } + conflict, err := r.routerLocatorConflict(ctx, identity.ShardSID) + if err != nil { + cond.Reason = bgpv1alpha1.ProgrammedReasonProgrammingFailed + cond.Message = err.Error() + return cond, err + } + if conflict != "" { + if err := r.Datapath.Clear(); err != nil { + cond.Reason = bgpv1alpha1.ProgrammedReasonProgrammingFailed + cond.Message = err.Error() + return cond, fmt.Errorf("clear egress translation datapath: %w", err) + } + cond.Reason = reasonEgressShardLocatorConflict + cond.Message = conflict + return cond, nil + } if err := r.Datapath.Program(identity); err != nil { cond.Reason = bgpv1alpha1.ProgrammedReasonProgrammingFailed cond.Message = err.Error() @@ -294,6 +318,46 @@ func (r *EgressShardReconciler) program(shard *bgpv1alpha1.EgressShard) (metav1. return cond, nil } +// routerLocatorConflict reports, as a condition message, the first BGPRouter +// whose Block and Node-ID equal sid's top 64 bits, or "" if none does. +// +// locator_matches in internal/plumbing/ebpf/natprog/nat.c claims every +// encapsulated packet matching those 64 bits, so a shard reusing a router's +// Block and Node-ID captures the tenant ingress addressed to it and drops what +// it cannot translate. Every BGPRouter in the cluster is checked, not only this +// node's: the shard's SID is advertised across the fabric, so a clash with any +// router misroutes that router's traffic. A router whose locator or Node-ID is +// unset or invalid owns no uSID identity and is skipped. +func (r *EgressShardReconciler) routerLocatorConflict(ctx context.Context, sid netip.Addr) (string, error) { + if !sid.Is6() { + return "", nil + } + routers := &bgpv1alpha1.BGPRouterList{} + if err := r.List(ctx, routers); err != nil { + return "", fmt.Errorf("list BGPRouters: %w", err) + } + shardLocator := netip.PrefixFrom(sid, uformat.LocatorBits).Masked() + for i := range routers.Items { + router := &routers.Items[i] + if router.Spec.SRv6Locator == "" || router.Spec.NodeID == 0 { + continue + } + base, err := srv6.NodeSIDBase(router.Spec.SRv6Locator, router.Spec.NodeID) + if err != nil { + log.FromContext(ctx).V(1).Info("skip BGPRouter with no valid uSID identity", + "bgpRouter", client.ObjectKeyFromObject(router), "error", err.Error()) + continue + } + if netip.PrefixFrom(base, uformat.LocatorBits).Masked() == shardLocator { + return fmt.Sprintf( + "Shard SID %s shares Block and Node-ID %s with BGPRouter %s/%s (srv6Locator %s, nodeID %d); "+ + "a shard needs a Node-ID no BGPRouter uses", + sid, shardLocator, router.Namespace, router.Name, router.Spec.SRv6Locator, router.Spec.NodeID), nil + } + } + return "", nil +} + // identityFromSpec parses spec's identity fields. missing is non-empty, with // the error nil, when the spec does not yet assign enough to translate with: a // SID and at least one family. err is a value that does not parse, which the @@ -412,7 +476,8 @@ func shardAdvertisementName(shardName string) string { // advertised and carries no meaning; installEgressRoutes overwrites it per // tenant. Reserving the Block and Node-ID for this shard alone is what the /64 // requires, which was already true -- locator_matches' doc comment spells out -// what reusing a co-located BGPRouter's Node-ID silently breaks. +// what reusing a co-located BGPRouter's Node-ID silently breaks, and program +// refuses a shard that does. // // The shard address stays a /128. It is an ordinary masquerade source address, // not a uSID, and nothing varies below it. @@ -566,7 +631,10 @@ func (r *EgressShardReconciler) readyCondition() metav1.Condition { // The BGPRouter watch closes a startup race: without it, a EgressShard whose // node's BGPRouter does not exist yet at first reconcile fails its router // lookup once and gets no second chance until an unrelated event triggers a -// fresh reconcile. +// fresh reconcile. It also re-checks this node's shard against every +// BGPRouter's uSID identity whenever any of them changes, in any namespace, +// so a router created over the shard's Block and Node-ID unprograms it and +// one moved off them programs it again. // // The startup runnable closes another. The datapath's maps are pinned, so a // restarted process inherits whatever identity its predecessor programmed. If @@ -590,8 +658,8 @@ func (r *EgressShardReconciler) SetupWithManager(mgr ctrl.Manager) error { b := ctrl.NewControllerManagedBy(mgr). For(&bgpv1alpha1.EgressShard{}). Watches(&bgpv1alpha1.BGPRouter{}, handler.EnqueueRequestsFromMapFunc( - func(ctx context.Context, obj client.Object) []ctrlreconcile.Request { - return broadcastToShardRequests(ctx, r.Client, obj.GetNamespace()) + func(ctx context.Context, _ client.Object) []ctrlreconcile.Request { + return r.nodeShardRequests(ctx) }), ) if r.CoverageEvents != nil { @@ -623,22 +691,3 @@ func (r *EgressShardReconciler) nodeShardRequests(ctx context.Context) []ctrlrec } return reqs } - -// broadcastToShardRequests enqueues every EgressShard in namespace. A BGPRouter -// change may be the one this node's shard was waiting on, and there is normally -// at most one shard per node, so listing the namespace is cheap. -func broadcastToShardRequests(ctx context.Context, c client.Client, namespace string) []ctrlreconcile.Request { - logger := log.FromContext(ctx) - shardList := &bgpv1alpha1.EgressShardList{} - if err := c.List(ctx, shardList, client.InNamespace(namespace)); err != nil { - logger.Error(err, "list EgressShards for BGPRouter change", "namespace", namespace) - return nil - } - reqs := make([]ctrlreconcile.Request, 0, len(shardList.Items)) - for _, s := range shardList.Items { - reqs = append(reqs, ctrlreconcile.Request{ - NamespacedName: types.NamespacedName{Namespace: s.Namespace, Name: s.Name}, - }) - } - return reqs -} diff --git a/internal/controller/egressshard_controller_test.go b/internal/controller/egressshard_controller_test.go index 40a1ca652..9c7e801fb 100644 --- a/internal/controller/egressshard_controller_test.go +++ b/internal/controller/egressshard_controller_test.go @@ -791,3 +791,136 @@ func TestEgressShardReconciler_DisabledWithdrawsAndProgramsNothing(t *testing.T) t.Errorf("advertisement still present while disabled: err = %v", err) } } + +// testNAT66RouterLocator is the Block of testNAT66ShardSIDVal, so a BGPRouter +// with this locator and Node-ID 9 owns the shard SID's whole /64. +const testNAT66RouterLocator = "fc00:1:2::/48" + +// withUSIDIdentity gives router locator testNAT66RouterLocator and nodeID. +func withUSIDIdentity(router *bgpv1alpha1.BGPRouter, nodeID int32) *bgpv1alpha1.BGPRouter { + router.Spec.SRv6Locator = testNAT66RouterLocator + router.Spec.NodeID = nodeID + return router +} + +// TestEgressShardReconciler_RefusesSIDOverlappingItsNodesRouter is #711: a +// shard SID sharing its Block and Node-ID with this node's own BGPRouter would +// capture that router's tenant ingress, so the shard is never programmed and +// never advertised. +func TestEgressShardReconciler_RefusesSIDOverlappingItsNodesRouter(t *testing.T) { + scheme := nat66TestScheme(t) + shard := newEgressShard(testNAT66NodeA) + router := withUSIDIdentity(newTestNAT66Router(), 9) + c := newIndexedClientBuilder(scheme).WithObjects(shard, router).WithStatusSubresource(shard).Build() + datapath := &fakeEgressDatapath{attached: true} + r := newNAT66Reconciler(c, scheme, datapath) + + got, err := reconcileShard(t, r, c) + if err != nil { + t.Fatalf("Reconcile() error = %v", err) + } + if datapath.programs != 0 { + t.Errorf("datapath programmed %d times, want 0", datapath.programs) + } + if _, ok := datapath.Programmed(); ok { + t.Errorf("datapath holds an identity for a refused shard") + } + assertCondition(t, got, bgpv1alpha1.ConditionTypeProgrammed, metav1.ConditionFalse, reasonEgressShardLocatorConflict) + cond := meta.FindStatusCondition(got.Status.Conditions, bgpv1alpha1.ConditionTypeProgrammed) + if !strings.Contains(cond.Message, testNAT66RouterName) { + t.Errorf("Programmed message %q does not name BGPRouter %s", cond.Message, testNAT66RouterName) + } + if got.Status.ShardSID != "" { + t.Errorf("Status.ShardSID = %q, want empty", got.Status.ShardSID) + } + advKey := client.ObjectKey{Namespace: testNAT66Namespace, Name: shardAdvertisementName(testNAT66ShardName)} + if err := c.Get(context.Background(), advKey, &bgpv1alpha1.BGPAdvertisement{}); !apierrors.IsNotFound(err) { + t.Errorf("advertisement exists for a refused shard: err = %v", err) + } +} + +// TestEgressShardReconciler_RefusesSIDOverlappingAnotherNodesRouter covers a +// clash with a BGPRouter on another node, in another namespace: the shard SID +// is advertised fabric-wide, so it misroutes that router's traffic too. +func TestEgressShardReconciler_RefusesSIDOverlappingAnotherNodesRouter(t *testing.T) { + scheme := nat66TestScheme(t) + shard := newEgressShard(testNAT66NodeA) + other := withUSIDIdentity(&bgpv1alpha1.BGPRouter{ + ObjectMeta: metav1.ObjectMeta{Namespace: "other", Name: "node-b-router"}, + Spec: bgpv1alpha1.BGPRouterSpec{ + TargetRef: bgpv1alpha1.TargetRef{Kind: testTargetRefKind, Name: testNAT66NodeB}, + }, + }, 9) + c := newIndexedClientBuilder(scheme).WithObjects(shard, other, newTestNAT66Router()). + WithStatusSubresource(shard).Build() + datapath := &fakeEgressDatapath{attached: true} + r := newNAT66Reconciler(c, scheme, datapath) + + got, err := reconcileShard(t, r, c) + if err != nil { + t.Fatalf("Reconcile() error = %v", err) + } + if _, ok := datapath.Programmed(); ok { + t.Errorf("datapath holds an identity for a refused shard") + } + assertCondition(t, got, bgpv1alpha1.ConditionTypeProgrammed, metav1.ConditionFalse, reasonEgressShardLocatorConflict) +} + +// TestEgressShardReconciler_ProgramsSIDBesideItsRoutersNodeID is the address +// plan the lab uses: shard and router share a Block, but the shard's Node-ID +// is its own. +func TestEgressShardReconciler_ProgramsSIDBesideItsRoutersNodeID(t *testing.T) { + scheme := nat66TestScheme(t) + shard := newEgressShard(testNAT66NodeA) + router := withUSIDIdentity(newTestNAT66Router(), 8) + c := newIndexedClientBuilder(scheme).WithObjects(shard, router).WithStatusSubresource(shard).Build() + datapath := &fakeEgressDatapath{attached: true} + r := newNAT66Reconciler(c, scheme, datapath) + + got, err := reconcileShard(t, r, c) + if err != nil { + t.Fatalf("Reconcile() error = %v", err) + } + if _, ok := datapath.Programmed(); !ok { + t.Errorf("datapath not programmed for a shard with its own Node-ID") + } + assertCondition(t, got, bgpv1alpha1.ConditionTypeProgrammed, metav1.ConditionTrue, + bgpv1alpha1.ProgrammedReasonAddressesProgrammed) +} + +// TestEgressShardReconciler_ProgramsOnceTheLocatorConflictIsResolved checks a +// refusal is not sticky: moving the router to another Node-ID programs the +// shard on the next reconcile, which the BGPRouter watch delivers. +func TestEgressShardReconciler_ProgramsOnceTheLocatorConflictIsResolved(t *testing.T) { + scheme := nat66TestScheme(t) + shard := newEgressShard(testNAT66NodeA) + router := withUSIDIdentity(newTestNAT66Router(), 9) + c := newIndexedClientBuilder(scheme).WithObjects(shard, router).WithStatusSubresource(shard).Build() + datapath := &fakeEgressDatapath{attached: true} + r := newNAT66Reconciler(c, scheme, datapath) + + got, err := reconcileShard(t, r, c) + if err != nil { + t.Fatalf("conflicting Reconcile() error = %v", err) + } + assertCondition(t, got, bgpv1alpha1.ConditionTypeProgrammed, metav1.ConditionFalse, reasonEgressShardLocatorConflict) + + stored := &bgpv1alpha1.BGPRouter{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(router), stored); err != nil { + t.Fatalf("get BGPRouter: %v", err) + } + stored.Spec.NodeID = 8 + if err := c.Update(context.Background(), stored); err != nil { + t.Fatalf("update BGPRouter: %v", err) + } + + got, err = reconcileShard(t, r, c) + if err != nil { + t.Fatalf("resolved Reconcile() error = %v", err) + } + if _, ok := datapath.Programmed(); !ok { + t.Errorf("datapath not programmed after the conflict was resolved") + } + assertCondition(t, got, bgpv1alpha1.ConditionTypeProgrammed, metav1.ConditionTrue, + bgpv1alpha1.ProgrammedReasonAddressesProgrammed) +} diff --git a/internal/plumbing/ebpf/natprog/nat.c b/internal/plumbing/ebpf/natprog/nat.c index b0bbf430e..eaac79c29 100644 --- a/internal/plumbing/ebpf/natprog/nat.c +++ b/internal/plumbing/ebpf/natprog/nat.c @@ -675,7 +675,10 @@ static NAT_ALWAYS_INLINE int addr6_eq(const __u8 a[16], const __u8 b[16]) // silently hijacked here before reaching the ingress hook. // // That is an address-allocation conflict this function cannot detect, not a -// flaw in the 64-bit match. Widening to a full 128-bit compare breaks the +// flaw in the 64-bit match. The EgressShard controller refuses a shard whose +// SID shares a BGPRouter's Block and Node-ID (routerLocatorConflict in +// internal/controller/egressshard_controller.go), so such a shard_sid never +// reaches this map. Widening to a full 128-bit compare breaks the // intended case of two tenants' egress packets sharing this shard_sid with // different Argument values. static NAT_ALWAYS_INLINE int locator_matches(const __u8 daddr[16], const __u8 shard_sid[16])