From d7c3949ee8a5481ace400344b2298c8f9977109d Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Sat, 28 Nov 2026 18:59:06 -0500 Subject: [PATCH 1/3] feat(edge): Drop unmatched egress from public listeners An Edge public listener may send only replies to its VIPs' clients. usid_egress admitted anything a listener attachment sent from its own address, and a packet that missed the VIP translation rows went on to the VRF's routes and the kernel, so a provider could use its listener to reach any other address. galactic-edge now marks a host link in a new edge_listener_link_table map when the attachment's EdgeService grants PublicListener, and clears the mark when the grant goes or the link is removed. usid_egress drops anything a marked link sends that matches no VIP translation row, after its link-local and Neighbor Discovery exits, and counts it as listener_unmatched_egress. The mark is its own map rather than a field in edge_link_value. Growing that value would make the loader recreate edge_link_table empty, which leaves every edge link ungated until galactic-edge writes it again. Against a datapath that predates the map, marking a link fails, so a listener attachment stays unprogrammed rather than unconfined. VIP reply translation needed no change: #1507 showed it working on edge host links for both families. Fixes: #1510 --- docs/designs/edge-public-listener.md | 9 +- docs/observability/vpc-dataplane.md | 1 + internal/edge/agent/agent.go | 40 ++++- internal/edge/agent/agent_test.go | 50 +++++++ internal/edge/agent/fixture_test.go | 17 ++- internal/edge/agent/replacement_test.go | 4 +- internal/edge/agent/setup.go | 16 +- .../ebpf/attach/schema_change_test.go | 4 +- .../ebpf/forwardgatemap/forwardgatemap.go | 71 ++++++++- .../forwardgatemap/forwardgatemap_test.go | 18 +++ internal/plumbing/ebpf/prog/dropreason.go | 6 +- internal/plumbing/ebpf/prog/usid.c | 29 ++++ .../plumbing/ebpf/prog/usid_listener_test.go | 139 ++++++++++++++++++ tests/edgeconformance/edgeprobe/main.go | 23 ++- tests/edgeconformance/listener_test.go | 100 +++++++++++-- 15 files changed, 491 insertions(+), 36 deletions(-) create mode 100644 internal/plumbing/ebpf/prog/usid_listener_test.go diff --git a/docs/designs/edge-public-listener.md b/docs/designs/edge-public-listener.md index d75940089..46d87ba02 100644 --- a/docs/designs/edge-public-listener.md +++ b/docs/designs/edge-public-listener.md @@ -1,6 +1,6 @@ # Galactic Edge public listener -Status: proposed, with its open decisions settled. The Phase 0 lab proof is done (see [Phase 0 results](#phase-0-results)), and Phase 1, the API, is implemented: `EdgeListener`, the `PublicListener` capability and `NetworkService.spec.edgeListenerRef` exist, but nothing serves a listener yet. It extends the [Galactic Edge Foundation](galactic-edge.md) and reuses the [XDP/DSR gateway](../gateway/architecture.md). The [provider contract](../edge/provider-contract.md) remains the reference for behavior that exists today. +Status: proposed, with its open decisions settled. The Phase 0 lab proof is done (see [Phase 0 results](#phase-0-results)), and Phase 1, the API, is implemented: `EdgeListener`, the `PublicListener` capability and `NetworkService.spec.edgeListenerRef` exist, but nothing serves a listener yet. Phase 3's unmatched-egress drop is implemented. It extends the [Galactic Edge Foundation](galactic-edge.md) and reuses the [XDP/DSR gateway](../gateway/architecture.md). The [provider contract](../edge/provider-contract.md) remains the reference for behavior that exists today. This design follows the [Datum enhancement template](https://github.com/datum-cloud/enhancements/blob/main/enhancements/template/README.md). @@ -212,6 +212,8 @@ Every listener service also carries a gateway health check, as a second signal b Listener attachments use the `PublicService` traffic policy path in both directions, like tenant VIP backends. The ingress VRF has no default route. A packet from a listener attachment that does not match a VIP translation row is dropped and counted under a new reason, `ListenerUnmatchedEgress`. +The node agent marks a listener attachment's host link in `edge_listener_link_table` when the attachment's `EdgeService` grants `PublicListener`, and clears the mark when the grant goes or the link is removed. `usid_egress` drops anything a marked link sends that misses the VIP translation rows, after its link-local and Neighbor Discovery exits, and counts it as `galactic_usid_drops_total{reason="listener_unmatched_egress"}`. The drop does not depend on the ingress VRF's routes. A datapath that predates the map leaves a listener attachment unprogrammed rather than unconfined. + ### Implementation phases | Phase | Work | Gate | @@ -219,7 +221,7 @@ Listener attachments use the `PublicService` traffic policy path in both directi | 0 | On the containerlab gvpc lab, hand-wire a `SocketAccess` attachment as a DSR backend: `/128` advertisement and binding, relying on the existing host link registration. Confirm the VIP reply translation on the edge host link, and qualify local and remote delivery. | Bidirectional UDP and TCP to a pod VRF socket through a gateway VIP, for both families, when the backend is not on the receiving gateway's node; local delivery's outcome recorded. Done, see [Phase 0 results](#phase-0-results). | | 1 | API: capability enums, `EdgeListener`, `NetworkService.spec.edgeListenerRef` and its rule against `backendSelector` | API review and CRD validation tests | | 2 | Core: ingress gVPC, listener admission and status, `/128` publication, `NetworkService` writer | envtest coverage of every status reason | -| 3 | Node agent and datapath: unmatched-egress drop. Phase 0 found no gap in VIP reply translation on edge host links. | Lab packet tests, including negative egress | +| 3 | Node agent and datapath: unmatched-egress drop. Phase 0 found no gap in VIP reply translation on edge host links. | Lab packet tests, including negative egress. Done in [#1510](https://github.com/datum-cloud/galactic/issues/1510). | | 4 | Gateway: backend resolution from listener backends, eligibility, local-delivery exclusion | Lab failover: drain, lease expiry, API outage, gateway loss | | 5 | MASQUE: listener attachment, sockets bound to the pod VRF, public `--authority`. Remove the Service overlay in deployment. | An independent client passes HTTP/3 and HTTP/2 through the VIP, IPv6 and IPv4 | @@ -264,7 +266,7 @@ Roll out to the staging labs first, with the existing overlay left in place on a - `EdgeListener` conditions `Accepted` and `Programmed`, and per-backend `serving`. - The gateway's existing per-rule packet, drop and advertisement metrics, labelled with the listener name. - `galactic_edge_foundation_failures_total` for listener attachment failures. -- A counter for `ListenerUnmatchedEgress`. +- `galactic_usid_drops_total{reason="listener_unmatched_egress"}` for `ListenerUnmatchedEgress`. ### Dependencies @@ -288,6 +290,7 @@ Each listener has up to 16 ports and two addresses, and each port is one `Networ - 2026-11-27: proposed, after a staging test reached MASQUE only through a hand-made `NodePort`. - 2026-11-28: open decisions settled in [#1506](https://github.com/datum-cloud/galactic/issues/1506), and listener addresses scoped to one cell. - 2026-11-28: Phase 0 proved remote delivery and the reply path, and showed local delivery failing ([#1507](https://github.com/datum-cloud/galactic/issues/1507)). +- 2026-11-28: Phase 3 added the unmatched-egress drop on listener host links ([#1510](https://github.com/datum-cloud/galactic/issues/1510)). ## Drawbacks diff --git a/docs/observability/vpc-dataplane.md b/docs/observability/vpc-dataplane.md index 49a3aa008..083e902d5 100644 --- a/docs/observability/vpc-dataplane.md +++ b/docs/observability/vpc-dataplane.md @@ -131,6 +131,7 @@ has no name for. | Egress | `egress_route_encap_failed`, `egress_route_fib_lookup_failed`, `egress_route_redirect_failed`, `public_uplink_redirect_failed` | Tenant traffic leaving the node couldn't be encapsulated or sent | | Service routes | `service_route_denied`, `service_route_redirect_failed` | A private service route refused the sender, or its redirect to the target failed | | IPv4 VIP | `vip_xlat_failed`, `vip_ipv4_fragment`, `vip_udp_no_checksum`, `vip_ipv4_backend`, `vip_ttl_exceeded` | An IPv4 VIP packet was untranslatable; `vip_ipv4_backend` means a pre-translation router | +| Edge listener | `listener_unmatched_egress` | An Edge public listener sent traffic other than a VIP reply | ```promql sum by (node, reason) (rate(galactic_usid_drops_total[5m])) > 0 diff --git a/internal/edge/agent/agent.go b/internal/edge/agent/agent.go index 2e5c40cbb..b7d332c71 100644 --- a/internal/edge/agent/agent.go +++ b/internal/edge/agent/agent.go @@ -78,8 +78,10 @@ type Datapath interface { // addr: it carries nothing else until a gate opens for it, and nothing // its traffic policy does not allow. The link is gated before any // program that forwards its traffic is attached. It is called while a - // new link is still down. - Register(vrfTable, ifindex uint32, ifname string, addr netip.Addr) error + // new link is still down. A listener link, an Edge public listener + // attachment's, sends only replies that match a VIP translation row; any + // other link has its listener mark cleared. + Register(vrfTable, ifindex uint32, ifname string, addr netip.Addr, listener bool) error // Unregister closes ifindex's gates and removes every row Register // wrote for it except the gate's link row, so the link carries nothing // beyond its own address until it is gone. @@ -153,6 +155,10 @@ type Agent struct { // held is, for the pass under way, each attachment's prefixes from // routes still accepted on this node, by attachment UID. held map[string][]netip.Prefix + // listenerServices is, for the pass under way, the UIDs of the + // EdgeServices that grant PublicListener. An attachment against one is a + // listener attachment. + listenerServices map[string]bool // local is, by VPC, each attachment's prefixes beyond its own address // that the last sync of the VPC's local routes kept, by attachment UID. local map[string]map[string]map[netip.Prefix]bool @@ -186,6 +192,11 @@ func (a *Agent) Reconcile(ctx context.Context) error { return err } a.held = held + listenerServices, err := a.listenerServiceUIDs(ctx) + if err != nil { + return err + } + a.listenerServices = listenerServices active := map[string][]*galacticv1alpha1.EdgeAttachment{} releasing := map[string][]*galacticv1alpha1.EdgeAttachment{} pods := map[string]podNS{} @@ -488,6 +499,28 @@ func (a *Agent) heldPrefixes(ctx context.Context) (map[string][]netip.Prefix, er return held, nil } +// capabilityPublicListener is the EdgeService capability that makes its +// attachments an Edge public listener's. +const capabilityPublicListener = "PublicListener" + +// listenerServiceUIDs returns the UIDs of the EdgeServices that grant +// PublicListener. A listener attachment's host link sends only replies that +// match a VIP translation row, so a failure to list fails the pass rather +// than programming a listener as an ordinary attachment. +func (a *Agent) listenerServiceUIDs(ctx context.Context) (map[string]bool, error) { + var services galacticv1alpha1.EdgeServiceList + if err := a.Client.List(ctx, &services); err != nil { + return nil, fmt.Errorf("list EdgeServices: %w", err) + } + uids := map[string]bool{} + for i := range services.Items { + if slices.Contains(services.Items[i].Spec.Capabilities, capabilityPublicListener) { + uids[string(services.Items[i].UID)] = true + } + } + return uids, nil +} + // holds reports whether rt is accepted on node and its holder has not // released it at the accepted epoch. A revoked route still holds: its // accepted holder stays until another is accepted or the route is deleted. @@ -665,7 +698,8 @@ func (a *Agent) program(att *galacticv1alpha1.EdgeAttachment, ns podNS, link hos datapathErr = a.Datapath.Unregister(uint32(res.HostIndex)) } if datapathErr == nil { - datapathErr = a.Datapath.Register(res.HostTable, uint32(res.HostIndex), spec.HostLink, spec.Address) + datapathErr = a.Datapath.Register(res.HostTable, uint32(res.HostIndex), spec.HostLink, spec.Address, + a.listenerServices[att.Spec.ServiceRef.UID]) } return datapathErr } diff --git a/internal/edge/agent/agent_test.go b/internal/edge/agent/agent_test.go index 8561b18d4..091eec423 100644 --- a/internal/edge/agent/agent_test.go +++ b/internal/edge/agent/agent_test.go @@ -18,6 +18,7 @@ import ( "github.com/vishvananda/netlink" "github.com/vishvananda/netns" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" "go.datum.net/galactic/internal/edge/diag" @@ -139,6 +140,55 @@ func TestAttachDetach(t *testing.T) { f.expectLocal(vpcB, addr+"/128") } +// TestListenerLinks: an attachment against an EdgeService that grants +// PublicListener registers its host link as a listener's, any other as not, +// and the mark follows the service's grant from one pass to the next. +func TestListenerLinks(t *testing.T) { + const socketAccess = "SocketAccess" + f := newFixture(t) + ctx := context.Background() + svc := &galacticv1alpha1.EdgeService{ + ObjectMeta: metav1.ObjectMeta{Name: "listener", Namespace: edgeNS, UID: "33333333-0000-0000-0000-000000000001"}, + Spec: galacticv1alpha1.EdgeServiceSpec{ + Capabilities: []string{socketAccess, capabilityPublicListener}, + }, + } + if err := f.client.Create(ctx, svc); err != nil { + t.Fatal(err) + } + a := f.agent() + f.pod(pod1UID) + f.attach("a", attA, pod1UID, vpcA, addr, false) + f.attach("b", attB, pod1UID, vpcB, addr, false) + att := f.get("a") + att.Spec.ServiceRef = galacticv1alpha1.EdgeServiceReference{Namespace: edgeNS, Name: svc.Name, UID: string(svc.UID)} + if err := f.client.Update(ctx, att); err != nil { + t.Fatal(err) + } + f.reconcile(a) + f.programmed("a") + f.programmed("b") + linkA, linkB := uint32(f.hostLink("a").Attrs().Index), uint32(f.hostLink("b").Attrs().Index) + if !f.dp.listener(linkA) { + t.Error("a's host link is not registered as a listener's") + } + if f.dp.listener(linkB) { + t.Error("b's host link is registered as a listener's") + } + + if err := f.client.Get(ctx, client.ObjectKeyFromObject(svc), svc); err != nil { + t.Fatal(err) + } + svc.Spec.Capabilities = []string{socketAccess} + if err := f.client.Update(ctx, svc); err != nil { + t.Fatal(err) + } + f.reconcile(a) + if f.dp.listener(linkA) { + t.Error("a's host link is still a listener's after its service stopped granting PublicListener") + } +} + // TestNewLinkClearsStaleRows: a link the agent creates is registered with no // rows left on its ifindex by a link a pod's deletion took with it, whatever // number the kernel gives it, while a link it finds already registered, as diff --git a/internal/edge/agent/fixture_test.go b/internal/edge/agent/fixture_test.go index a50590dc6..d0f8212b5 100644 --- a/internal/edge/agent/fixture_test.go +++ b/internal/edge/agent/fixture_test.go @@ -153,7 +153,9 @@ func (r *resolver) set(podUID, path string) { // gated in gates as the pinned datapath does. type datapath struct { sync.Mutex - rows map[uint32]uint32 + rows map[uint32]uint32 + // listeners is the listener flag of each link's last Register. + listeners map[uint32]bool unregistered []uint32 // failUnregister fails the next Unregister calls. failUnregister int @@ -166,7 +168,7 @@ type datapath struct { routes map[uint32][]netip.Prefix } -func (d *datapath) Register(vrfTable, ifindex uint32, _ string, addr netip.Addr) error { +func (d *datapath) Register(vrfTable, ifindex uint32, _ string, addr netip.Addr, listener bool) error { d.Lock() defer d.Unlock() if d.onRegister != nil { @@ -176,10 +178,21 @@ func (d *datapath) Register(vrfTable, ifindex uint32, _ string, addr netip.Addr) return d.failRegister } d.rows[ifindex] = vrfTable + if d.listeners == nil { + d.listeners = map[uint32]bool{} + } + d.listeners[ifindex] = listener d.gates.setLink(ifindex, addr) return nil } +// listener reports the listener flag of ifindex's last Register. +func (d *datapath) listener(ifindex uint32) bool { + d.Lock() + defer d.Unlock() + return d.listeners[ifindex] +} + func (d *datapath) Unregister(ifindex uint32) error { d.Lock() defer d.Unlock() diff --git a/internal/edge/agent/replacement_test.go b/internal/edge/agent/replacement_test.go index 7be2288e6..dfc1cecca 100644 --- a/internal/edge/agent/replacement_test.go +++ b/internal/edge/agent/replacement_test.go @@ -130,8 +130,8 @@ func inNS(path string, fn func() error) error { return fnErr } -func (d nsDatapath) Register(vrfTable, ifindex uint32, ifname string, addr netip.Addr) error { - return inNS(d.host, func() error { return d.PinnedDatapath.Register(vrfTable, ifindex, ifname, addr) }) +func (d nsDatapath) Register(vrfTable, ifindex uint32, ifname string, addr netip.Addr, listener bool) error { + return inNS(d.host, func() error { return d.PinnedDatapath.Register(vrfTable, ifindex, ifname, addr, listener) }) } func (d nsDatapath) Unregister(ifindex uint32) error { diff --git a/internal/edge/agent/setup.go b/internal/edge/agent/setup.go index fbd7ea74d..838fe34fd 100644 --- a/internal/edge/agent/setup.go +++ b/internal/edge/agent/setup.go @@ -32,11 +32,11 @@ import ( // PinDir. type PinnedDatapath struct{ PinDir string } -// Register implements Datapath: the link's gate row first, so the link -// carries only its own address from the moment usid_egress and tp_deliver -// are attached to it, then its traffic policy row and programs -// (attachreg.RegisterHostLink). -func (d PinnedDatapath) Register(vrfTable, ifindex uint32, ifname string, addr netip.Addr) error { +// Register implements Datapath: the link's gate row and listener mark first, +// so the link carries only its own address, and a listener's only VIP +// replies, from the moment usid_egress and tp_deliver are attached to it, +// then its traffic policy row and programs (attachreg.RegisterHostLink). +func (d PinnedDatapath) Register(vrfTable, ifindex uint32, ifname string, addr netip.Addr, listener bool) error { gates, err := forwardgatemap.OpenPinned(d.PinDir) if err != nil { return err @@ -45,6 +45,9 @@ func (d PinnedDatapath) Register(vrfTable, ifindex uint32, ifname string, addr n if err := gates.SetLink(ifindex, addr); err != nil { return err } + if err := gates.SetListener(ifindex, listener); err != nil { + return err + } return attachreg.RegisterHostLink(d.PinDir, vrfTable, ifindex, ifname, addr) } @@ -174,6 +177,9 @@ func (a *Agent) SetupWithManager(mgr ctrl.Manager) error { if err := ctrl.NewControllerManagedBy(mgr). Named("edge-agent"). Watches(&galacticv1alpha1.EdgeAttachment{}, toPass). + // A service gaining or losing PublicListener changes which links are + // listener links. + Watches(&galacticv1alpha1.EdgeService{}, toPass). WatchesRawSource(source.Channel(start, toPass)). WatchesRawSource(source.Channel(gated, toPass)). Complete(reconcile.Func(func(ctx context.Context, _ reconcile.Request) (reconcile.Result, error) { diff --git a/internal/plumbing/ebpf/attach/schema_change_test.go b/internal/plumbing/ebpf/attach/schema_change_test.go index 294e9d893..923300299 100644 --- a/internal/plumbing/ebpf/attach/schema_change_test.go +++ b/internal/plumbing/ebpf/attach/schema_change_test.go @@ -118,8 +118,8 @@ func TestLoad_DropReasonsGrowthKeepsVIPXlatRows(t *testing.T) { } defer objs.Close() //nolint:errcheck // test-owned objects - if got := objs.DropReasons.MaxEntries(); got != prog.DropReasonVIPTTLExceeded+1 { - t.Errorf("drop_reasons entries = %d after reload, want %d", got, prog.DropReasonVIPTTLExceeded+1) + if got := objs.DropReasons.MaxEntries(); got != prog.DropReasonListenerUnmatchedEgress+1 { + t.Errorf("drop_reasons entries = %d after reload, want %d", got, prog.DropReasonListenerUnmatchedEgress+1) } var v prog.UsidVipXlatValue if err := objs.VipXlatTable.Lookup(row, &v); err != nil { diff --git a/internal/plumbing/ebpf/forwardgatemap/forwardgatemap.go b/internal/plumbing/ebpf/forwardgatemap/forwardgatemap.go index 5a97670ef..7ebe05819 100644 --- a/internal/plumbing/ebpf/forwardgatemap/forwardgatemap.go +++ b/internal/plumbing/ebpf/forwardgatemap/forwardgatemap.go @@ -7,7 +7,9 @@ // attachment's and holds its own address, and edge_gate_table, which holds // one CLOCK_BOOTTIME deadline per prefix the link may carry. The datapath // drops every packet on an edge link whose address is neither the link's -// own nor under an unexpired gate (internal/plumbing/ebpf/prog/usid.c). +// own nor under an unexpired gate (internal/plumbing/ebpf/prog/usid.c). It +// also writes edge_listener_link_table, which marks an Edge public listener's +// host link: such a link sends only replies that match a VIP translation row. // // galactic-edge is the only writer. package forwardgatemap @@ -16,6 +18,7 @@ import ( "errors" "fmt" "net/netip" + "os" "path/filepath" "time" @@ -66,8 +69,15 @@ type Table struct { links *ebpf.Map gates *ebpf.Map stats *ebpf.Map + // listeners is edge_listener_link_table, or nil when the loaded datapath + // predates it. + listeners *ebpf.Map } +// ErrListenerUnsupported reports that the loaded datapath has no +// edge_listener_link_table, so it cannot confine a listener link's egress. +var ErrListenerUnsupported = errors.New("forwardgatemap: the loaded datapath cannot mark listener links") + // OpenPinned opens the gate maps pinned under pinDir. func OpenPinned(pinDir string) (*Table, error) { t := &Table{} @@ -86,13 +96,23 @@ func OpenPinned(pinDir string) (*Table, error) { } *m.dst = opened } + // A datapath loaded before edge_listener_link_table existed still gates + // every other link, so its absence fails only SetListener(true). + listeners, err := ebpf.LoadPinnedMap(filepath.Join(pinDir, prog.UsidMapEdgeListenerLinkTable), nil) + switch { + case err == nil: + t.listeners = listeners + case !errors.Is(err, os.ErrNotExist): + _ = t.Close() + return nil, fmt.Errorf("forwardgatemap: open pinned map %q: %w", prog.UsidMapEdgeListenerLinkTable, err) + } return t, nil } // Close releases the maps; the pins and their contents remain. func (t *Table) Close() error { var errs []error - for _, m := range []*ebpf.Map{t.links, t.gates, t.stats} { + for _, m := range []*ebpf.Map{t.links, t.gates, t.stats, t.listeners} { if m != nil { errs = append(errs, m.Close()) } @@ -138,13 +158,54 @@ func (t *Table) DeleteGates(ifindex uint32) error { return errors.Join(errs...) } -// DeleteLink removes ifindex's gates, then its link row. Call it once the -// link is deleted and before its ifindex can be reused, so no later -// interface inherits the row. Absent rows are not errors. +// SetListener marks ifindex as an Edge public listener's host link, or clears +// the mark. The datapath drops anything a marked link sends that matches no +// VIP translation row, as listener_unmatched_egress. Mark a link only after +// SetLink. Clearing an absent mark is not an error. +func (t *Table) SetListener(ifindex uint32, listener bool) error { + if t.listeners == nil { + if listener { + return ErrListenerUnsupported + } + return nil + } + if listener { + if err := t.listeners.Put(ifindex, uint8(1)); err != nil { + return fmt.Errorf("forwardgatemap: set listener %d: %w", ifindex, err) + } + return nil + } + if err := t.listeners.Delete(ifindex); err != nil && !errors.Is(err, ebpf.ErrKeyNotExist) { + return fmt.Errorf("forwardgatemap: clear listener %d: %w", ifindex, err) + } + return nil +} + +// Listener reports whether ifindex is marked as a listener's host link. +func (t *Table) Listener(ifindex uint32) (bool, error) { + if t.listeners == nil { + return false, nil + } + var v uint8 + if err := t.listeners.Lookup(ifindex, &v); err != nil { + if errors.Is(err, ebpf.ErrKeyNotExist) { + return false, nil + } + return false, fmt.Errorf("forwardgatemap: read listener %d: %w", ifindex, err) + } + return true, nil +} + +// DeleteLink removes ifindex's gates and listener mark, then its link row. +// Call it once the link is deleted and before its ifindex can be reused, so +// no later interface inherits the rows. Absent rows are not errors. func (t *Table) DeleteLink(ifindex uint32) error { if err := t.DeleteGates(ifindex); err != nil { return err } + if err := t.SetListener(ifindex, false); err != nil { + return err + } if err := t.links.Delete(ifindex); err != nil && !errors.Is(err, ebpf.ErrKeyNotExist) { return fmt.Errorf("forwardgatemap: delete link %d: %w", ifindex, err) } diff --git a/internal/plumbing/ebpf/forwardgatemap/forwardgatemap_test.go b/internal/plumbing/ebpf/forwardgatemap/forwardgatemap_test.go index 179342d51..85e31196a 100644 --- a/internal/plumbing/ebpf/forwardgatemap/forwardgatemap_test.go +++ b/internal/plumbing/ebpf/forwardgatemap/forwardgatemap_test.go @@ -6,6 +6,7 @@ package forwardgatemap import ( "encoding/binary" + "errors" "net/netip" "testing" ) @@ -29,6 +30,23 @@ func TestLayout(t *testing.T) { } } +// TestListenerWithoutMap: against a datapath that predates +// edge_listener_link_table, clearing a listener mark succeeds and no link is +// a listener's, but marking one fails rather than leave a listener's egress +// unconfined. +func TestListenerWithoutMap(t *testing.T) { + var tbl Table + if err := tbl.SetListener(7, false); err != nil { + t.Errorf("clear listener: %v", err) + } + if ok, err := tbl.Listener(7); ok || err != nil { + t.Errorf("Listener = %t, %v; want false, nil", ok, err) + } + if err := tbl.SetListener(7, true); !errors.Is(err, ErrListenerUnsupported) { + t.Errorf("set listener: %v, want ErrListenerUnsupported", err) + } +} + // TestKey checks that a gate's LPM key counts the ifindex's 32 bits ahead of // the prefix, and that only masked IPv6 prefixes have one. func TestKey(t *testing.T) { diff --git a/internal/plumbing/ebpf/prog/dropreason.go b/internal/plumbing/ebpf/prog/dropreason.go index f3ee8edd8..c2834dbf4 100644 --- a/internal/plumbing/ebpf/prog/dropreason.go +++ b/internal/plumbing/ebpf/prog/dropreason.go @@ -37,20 +37,21 @@ const ( DropReasonVIPUDPNoChecksum uint32 = 44 DropReasonVIPIPv4Backend uint32 = 45 DropReasonVIPTTLExceeded uint32 = 46 + DropReasonListenerUnmatchedEgress uint32 = 47 ) // DropReasonMetricIndices lists stable production counters. Diagnostic trace // slots between DropReasonCount and the service-route counters are deliberately // excluded from metrics. var DropReasonMetricIndices = func() []uint32 { - indices := make([]uint32, 0, DropReasonCount+7) + indices := make([]uint32, 0, DropReasonCount+8) for index := range DropReasonCount { indices = append(indices, index) } return append(indices, DropReasonServiceRouteDenied, DropReasonServiceRouteRedirectFailed, DropReasonVIPXlatFailed, DropReasonVIPIPv4Fragment, DropReasonVIPUDPNoChecksum, - DropReasonVIPIPv4Backend, DropReasonVIPTTLExceeded) + DropReasonVIPIPv4Backend, DropReasonVIPTTLExceeded, DropReasonListenerUnmatchedEgress) }() // DropReasonNames maps each index to a short, stable, metrics-friendly name, @@ -80,4 +81,5 @@ var DropReasonNames = map[uint32]string{ DropReasonVIPUDPNoChecksum: "vip_udp_no_checksum", DropReasonVIPIPv4Backend: "vip_ipv4_backend", DropReasonVIPTTLExceeded: "vip_ttl_exceeded", + DropReasonListenerUnmatchedEgress: "listener_unmatched_egress", } diff --git a/internal/plumbing/ebpf/prog/usid.c b/internal/plumbing/ebpf/prog/usid.c index 2af1c2b0c..c585e5677 100644 --- a/internal/plumbing/ebpf/prog/usid.c +++ b/internal/plumbing/ebpf/prog/usid.c @@ -1267,6 +1267,10 @@ enum drop_reason { // A packet of an IPv4 VIP's flow arrived with a TTL or hop limit that // translating it, as a router, would take to zero. DROP_REASON_VIP_TTL_EXCEEDED = 46, + // A packet from an Edge public listener attachment matched no VIP + // translation row. A listener carries only replies to its VIPs' clients, + // so anything else it sends is dropped rather than routed. + DROP_REASON_LISTENER_UNMATCHED_EGRESS = 47, __DROP_REASON_MAX, }; @@ -1459,6 +1463,21 @@ struct { __type(value, __u64); } edge_gate_stats SEC(".maps"); +// edge_listener_link_table marks an edge host link as an Edge public listener +// attachment's. usid_egress sends such a link's traffic only as a reply that +// matches a VIP translation row, and drops the rest as +// DROP_REASON_LISTENER_UNMATCHED_EGRESS. galactic-edge writes a row only for a +// link that also has an edge_link_table row, and removes it first. The flag +// is its own map so that adding it left edge_link_table's pinned layout as it +// was: recreating that map would ungate every edge link until it was written +// again. +struct { + __uint(type, BPF_MAP_TYPE_HASH); + __uint(max_entries, 4096); + __type(key, __u32); // host link ifindex + __type(value, __u8); // 1; the key's presence is the flag +} edge_listener_link_table SEC(".maps"); + // nptv6_table: one row per VRF with NPTv6 configured, keyed like vrf_table. // usid_ingress already holds that key locally, and usid_egress resolves it // through ifindex_vrf_table. @@ -6121,6 +6140,16 @@ int usid_egress(struct __sk_buff *skb) } } + // An Edge public listener sends nothing but replies to its VIPs' + // clients, which took the VIP path above. Anything else, to the + // internet or anywhere, is dropped here rather than routed, whatever + // routes its VRF holds. An edge attachment is IPv6 only, and the gate + // already dropped any IPv4 it sent, so only this branch needs it. + if (!vip_hit && bpf_map_lookup_elem(&edge_listener_link_table, &ifindex)) { + count_claimed_drop(DROP_REASON_LISTENER_UNMATCHED_EGRESS, vrf, vrf_key, VRF_DIRECTION_EGRESS); + return TC_ACT_SHOT; + } + route_family = USID_EGRESS_ROUTE_FAMILY_INET6; __builtin_memcpy(egress_scratch->dest_addr, ip6->daddr, 16); } else { diff --git a/internal/plumbing/ebpf/prog/usid_listener_test.go b/internal/plumbing/ebpf/prog/usid_listener_test.go new file mode 100644 index 000000000..3bd4b78d9 --- /dev/null +++ b/internal/plumbing/ebpf/prog/usid_listener_test.go @@ -0,0 +1,139 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package prog + +import ( + "net/netip" + "testing" +) + +// Tests for #1510: an Edge public listener's host link sends only replies +// that match a VIP translation row. usid_egress drops anything else it sends +// as listener_unmatched_egress. + +// listenerLinkIfindex is the ifindex usid_egress's test runs see, the one +// setUpEgressRouteAttachment registers. +const listenerLinkIfindex uint32 = 1 + +// setUpListenerLink registers ifindex 1 as an edge host link whose own address +// is addr, with a VIP egress row for addr:listenerPort and a configured public +// uplink, and marks it a listener link when listener is set. +func setUpListenerLink(t *testing.T, objs *UsidObjects, addr, vip netip.Addr, listener bool) { + t.Helper() + block, argument := uint64(0xFEED15), uint16(0x510) + setUpEgressRouteAttachment(t, objs, block, argument, 17) + if err := objs.PublicUplinkTable.Put(uint32(0), UsidPublicUplinkValue{LinkIfindex: 1}); err != nil { + t.Fatalf("populate public_uplink_table: %v", err) + } + if err := objs.EdgeLinkTable.Put(listenerLinkIfindex, addr.As16()); err != nil { + t.Fatalf("populate edge_link_table: %v", err) + } + if listener { + if err := objs.EdgeListenerLinkTable.Put(listenerLinkIfindex, uint8(1)); err != nil { + t.Fatalf("populate edge_listener_link_table: %v", err) + } + } + putVIPEgressRow(t, objs, block, argument, addr, vip, listenerPort) +} + +// runEgressTo sends a TCP segment from src:sport to dst through usid_egress +// and returns the verdict and the source it leaves with. +func runEgressTo(t *testing.T, objs *UsidObjects, src, dst netip.Addr, sport uint16) (uint32, netip.Addr) { + t.Helper() + ret, out, err := objs.UsidEgress.Test(buildPlainV6PacketWithL4Ports(t, src, dst, sport, 43210)) + if err != nil { + t.Fatalf("program test-run: %v", err) + } + const saddrOffset = ethHeaderLen + 8 + got, _ := netip.AddrFromSlice(out[saddrOffset : saddrOffset+16]) + return ret, got +} + +var ( + listenerAddr = netip.MustParseAddr("fd20:1510::a") + listenerVIP = netip.MustParseAddr("2001:db8:1510::1") + listenerClient = netip.MustParseAddr("2001:db8:0:13::1") +) + +const listenerPort = 8443 + +// TestUsidEgress_ListenerReplyLeavesFromVIP: a listener's reply that matches +// its VIP row leaves for the public uplink from the VIP, and nothing is +// dropped. +func TestUsidEgress_ListenerReplyLeavesFromVIP(t *testing.T) { + requireRoot(t) + objs := loadObjects(t) + setUpListenerLink(t, objs, listenerAddr, listenerVIP, true) + + ret, src := runEgressTo(t, objs, listenerAddr, listenerClient, listenerPort) + if ret != tcActRedirect || src != listenerVIP { + t.Errorf("reply: verdict=%d src=%s, want TC_ACT_REDIRECT (%d) from %s", ret, src, tcActRedirect, listenerVIP) + } + if got := sumPerCPU(t, objs.DropReasons, DropReasonListenerUnmatchedEgress); got != 0 { + t.Errorf("drop_reasons[listener_unmatched_egress] = %d, want 0", got) + } +} + +// TestUsidEgress_ListenerUnmatchedEgressDropped: anything else a listener +// sends from its own address, to an internet address from another port or to +// a NAT64 address no translation row covers, is dropped and counted. +func TestUsidEgress_ListenerUnmatchedEgressDropped(t *testing.T) { + for _, tc := range []struct { + name string + dst netip.Addr + sport uint16 + }{ + {"InternetFromOtherPort", netip.MustParseAddr("2001:db8:ffff::53"), listenerPort + 1}, + {"NAT64WithoutRow", netip.MustParseAddr("64:ff9b::c000:20a"), listenerPort + 1}, + } { + t.Run(tc.name, func(t *testing.T) { + requireRoot(t) + objs := loadObjects(t) + setUpListenerLink(t, objs, listenerAddr, listenerVIP, true) + + ret, _ := runEgressTo(t, objs, listenerAddr, tc.dst, tc.sport) + if ret != tcActShot { + t.Errorf("packet to %s: verdict=%d, want TC_ACT_SHOT (%d)", tc.dst, ret, tcActShot) + } + assertOnlyMetricDropReason(t, objs, DropReasonListenerUnmatchedEgress) + }) + } +} + +// TestUsidEgress_NonListenerEdgeLinkUnaffected: the same packet from an edge +// link that is not a listener's goes on as before, uncounted. +func TestUsidEgress_NonListenerEdgeLinkUnaffected(t *testing.T) { + requireRoot(t) + objs := loadObjects(t) + setUpListenerLink(t, objs, listenerAddr, listenerVIP, false) + + dst := netip.MustParseAddr("2001:db8:ffff::53") + ret, src := runEgressTo(t, objs, listenerAddr, dst, listenerPort+1) + if ret != tcActUnspec || src != listenerAddr { + t.Errorf("packet to %s: verdict=%d src=%s, want TC_ACT_UNSPEC (%d) from %s", + dst, ret, src, tcActUnspec, listenerAddr) + } + if got := sumPerCPU(t, objs.DropReasons, DropReasonListenerUnmatchedEgress); got != 0 { + t.Errorf("drop_reasons[listener_unmatched_egress] = %d, want 0", got) + } +} + +// TestUsidEgress_ListenerLinkLocalPasses: a listener's link-local traffic, +// such as its reply to a host-side health probe, reaches the kernel. +func TestUsidEgress_ListenerLinkLocalPasses(t *testing.T) { + requireRoot(t) + objs := loadObjects(t) + setUpListenerLink(t, objs, listenerAddr, listenerVIP, true) + + prober := netip.MustParseAddr("fe80::a060:bbff:fe37:4f09") + ret, src := runEgressTo(t, objs, listenerAddr, prober, listenerPort) + if ret != tcActUnspec || src != listenerAddr { + t.Errorf("reply to %s: verdict=%d src=%s, want TC_ACT_UNSPEC (%d) from %s", + prober, ret, src, tcActUnspec, listenerAddr) + } + if got := sumPerCPU(t, objs.DropReasons, DropReasonListenerUnmatchedEgress); got != 0 { + t.Errorf("drop_reasons[listener_unmatched_egress] = %d, want 0", got) + } +} diff --git a/tests/edgeconformance/edgeprobe/main.go b/tests/edgeconformance/edgeprobe/main.go index 9fd206b8a..3ad16f9fe 100644 --- a/tests/edgeconformance/edgeprobe/main.go +++ b/tests/edgeconformance/edgeprobe/main.go @@ -8,8 +8,9 @@ // CLOCK_BOOTTIME, the clock edge leases are timed on, so the suite can // compare packet times with a lease's renew-start. // -// edgeprobe send -to [addr]:port -interval 20ms -duration 30s -// sends numbered UDP datagrams and prints each reply: {"t","seq","from","reply"} +// edgeprobe send -to [addr]:port -interval 20ms -duration 30s [-device dev] +// sends numbered UDP datagrams, from a socket bound to dev when given, +// and prints each reply: {"t","seq","from","reply"}, then {"t","sent"} // edgeprobe sniff -iface link -port 7777 -duration 30s // prints each IPv6 UDP datagram to port on link: {"t","src","dst"}, // then {"t","end"} when the capture ends @@ -27,6 +28,7 @@ package main import ( + "context" "encoding/binary" "encoding/json" "errors" @@ -37,6 +39,7 @@ import ( "os" "strconv" "strings" + "syscall" "time" "golang.org/x/sys/unix" @@ -81,15 +84,29 @@ func send(args []string) error { to := fs.String("to", "", "destination [address]:port") interval := fs.Duration("interval", 20*time.Millisecond, "time between datagrams") duration := fs.Duration("duration", 10*time.Second, "how long to send") + device := fs.String("device", "", "bind the socket to this device, such as a pod VRF") _ = fs.Parse(args) dst, err := netip.ParseAddrPort(*to) if err != nil { return err } - conn, err := net.ListenUDP("udp6", nil) + lc := net.ListenConfig{} + if *device != "" { + lc.Control = func(_, _ string, c syscall.RawConn) error { + var serr error + if err := c.Control(func(fd uintptr) { + serr = unix.SetsockoptString(int(fd), unix.SOL_SOCKET, unix.SO_BINDTODEVICE, *device) + }); err != nil { + return err + } + return serr + } + } + pc, err := lc.ListenPacket(context.Background(), "udp6", "") if err != nil { return err } + conn := pc.(*net.UDPConn) defer func() { _ = conn.Close() }() done := make(chan struct{}) go func() { diff --git a/tests/edgeconformance/listener_test.go b/tests/edgeconformance/listener_test.go index ae5e46329..ff48effa9 100644 --- a/tests/edgeconformance/listener_test.go +++ b/tests/edgeconformance/listener_test.go @@ -6,6 +6,7 @@ package edgeconformance_test import ( "context" + "encoding/json" "fmt" "math/rand/v2" "net/netip" @@ -34,7 +35,9 @@ import ( // VIP families: // // - a dedicated ingress VPC, granted to a reference provider with -// SocketAccess only, under the lab's public-service traffic policy; +// SocketAccess and PublicListener, under the lab's public-service +// traffic policy, so the node agent marks the attachment's host link as a +// listener's (#1510); // - a stand-in VPCAttachment for the edge attachment's address, which is // how the gateway and galactic-router find backends today; // - the attachment's /128 BGPAdvertisement with its VRF ID and End.DT46, @@ -45,7 +48,9 @@ import ( // transit router to edgeNode1, so the gateway that receives each packet is // not the backend's node; it must pass. Local delivery pins the VIP to // edgeNode2, the backend's own node; it records what happens, including the -// gateway's drop counters, and does not fail the test. +// gateway's drop counters, and does not fail the test. Negative egress sends +// from the listener to an internet address, which the backend's node must +// drop and count. func TestListenerBackend(t *testing.T) { l := getLab(t) t.Cleanup(func() { l.writeSummary(t) }) @@ -98,6 +103,45 @@ func TestListenerBackend(t *testing.T) { } }) + // A listener sends nothing but replies to its VIPs' clients: anything + // else, here an echo request to the off-fabric client from the + // attachment's own address, is dropped on the backend's node and counted + // as listener_unmatched_egress (#1510). + t.Run("negative-egress", func(t *testing.T) { + const sinkPort = "7999" + before := p.l.usidDrops(t, p.node, reasonListenerUnmatchedEgress) + pid, err := sandboxPID(p.node, listenerNamespace, p.pod) + if err != nil { + t.Fatal(err) + } + // The off-fabric client listens, and must receive nothing. + dst := listenerFamilies[0].client + received := make(chan string, 1) + go func() { + // Only datagrams reach stdout; socat's exit warning goes to stderr. + out, _ := nodeExec(transitHost(), "sh", "-c", + "timeout 6 socat -u UDP6-RECV:"+sinkPort+" STDOUT 2>/dev/null") + received <- out + }() + time.Sleep(time.Second) + out, err := nodeExec(p.node, "nsenter", "-t", strconv.Itoa(pid), "-n", "/usr/local/bin/edgeprobe", "send", + "-to", "["+dst+"]:"+sinkPort, "-device", p.podVRF, "-interval", "100ms", "-duration", "1s") + if err != nil { + t.Fatal(err) + } + sent := probeSent(t, out) + p.l.record(t, "datagrams sent from the listener to "+dst, sent) + if got := <-received; got != "" { + t.Errorf("%s received %q from the listener; want nothing", dst, got) + } + var rose float64 + eventually(t, 15*time.Second, time.Second, "listener_unmatched_egress on "+p.node, func() (bool, error) { + rose = p.l.usidDrops(t, p.node, reasonListenerUnmatchedEgress) - before + return sent > 0 && rose >= float64(sent), fmt.Errorf("rose by %g for %d sent", rose, sent) + }) + p.l.record(t, p.node+" listener_unmatched_egress", rose) + }) + t.Run("local-delivery", func(t *testing.T) { for _, f := range listenerFamilies { t.Run(f.name, func(t *testing.T) { @@ -147,7 +191,11 @@ const ( protoTCP = "tcp" gatewayNamespace = "galactic-system" gatewayMetricsPort = 8081 - remoteHostNode = "remote-host" + // usidMetricsPort serves a node's uSID datapath counters. + usidMetricsPort = 9180 + capPublicListener = "PublicListener" + reasonListenerUnmatchedEgress = "listener_unmatched_egress" + remoteHostNode = "remote-host" ) // listenerFamily is one VIP family: its address, how the transit router @@ -187,10 +235,11 @@ func (f listenerFamily) clientAsSeen() string { } type listenerProof struct { - l *lab - node string - addr string - pod string + l *lab + node string + addr string + pod string + podVRF string // used holds every client source port drawn so far: a TCP port still in // TIME_WAIT towards the same VIP and port would refuse a new connect. used map[int]bool @@ -230,14 +279,16 @@ spec: l.applyOverlayOf(t, filepath.Join(l.root, "deploy", "containerlab", "resources", "tenants", "policies", "public-service"), "listener-policies", "namespace: "+listenerVPCNamespace+"\n", nil) - // The provider and its SocketAccess grant. + // The provider and its grant: SocketAccess for the attachment, and + // PublicListener, which makes the node agent mark its host link as a + // listener's. tn := tenant{vpcNamespace: listenerVPCNamespace, vpc: listenerVPC, provider: listenerProvider, namespace: listenerNamespace, service: listenerService} l.ensureNamespace(t, tn.namespace) l.register(t, tn.provider, tn.namespace, true) vpcUID := l.vpcUID(t, tn) svc := l.grantService(t, tn, tn.service, func(s *galacticv1alpha1.EdgeService) { - s.Spec.Capabilities = []string{capSocket} + s.Spec.Capabilities = []string{capSocket, capPublicListener} s.Spec.Prefixes = nil s.Spec.ClientPool = listenerPool }) @@ -255,6 +306,7 @@ services: p.pod = pod.Name att := l.waitServing(t, pod, svc) p.addr = netip.MustParseAddr(att.Status.Address).String() + p.podVRF = att.Status.PodVRF l.record(t, "attachment", fmt.Sprintf("%s address %s host link %s", att.Name, p.addr, att.Status.HostLink)) // The attachment's /128 in the ingress VRF, which is how the gateway @@ -517,6 +569,36 @@ func (l *lab) gatewayDrops(t *testing.T, node string) map[string]float64 { return m } +// usidDrops returns node's galactic_usid_drops_total for reason. +func (l *lab) usidDrops(t *testing.T, node, reason string) float64 { + t.Helper() + out, err := nodeExec(node, "curl", "-s", "--max-time", "4", + "http://localhost:"+strconv.Itoa(usidMetricsPort)+"/metrics") + if err != nil { + t.Fatal(err) + } + var sum float64 + for _, line := range strings.Split(out, "\n") { + if strings.HasPrefix(line, "galactic_usid_drops_total{") && strings.Contains(line, `reason="`+reason+`"`) { + sum += sampleValue(line) + } + } + return sum +} + +// probeSent reads the count from edgeprobe send's closing {"sent"} line. +func probeSent(t *testing.T, out string) int { + t.Helper() + lines := strings.Split(strings.TrimSpace(out), "\n") + var end struct { + Sent *int `json:"sent"` + } + if err := json.Unmarshal([]byte(lines[len(lines)-1]), &end); err != nil || end.Sent == nil { + t.Fatalf("edgeprobe send ended without a count: %q", out) + } + return *end.Sent +} + func sampleValue(line string) float64 { f := strings.Fields(line) if len(f) == 0 { From 9fa1439e32a8fce7cfd4e8a4131d9be740b54c1e Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Sat, 28 Nov 2026 19:15:39 -0500 Subject: [PATCH 2/3] fix(edge): Close listener egress gaps found in review Review of the listener egress drop found four ways a listener could still reach the kernel's routing: - Neighbor Discovery messages took usid_egress's ND exit before the listener check, whatever their destination. The check now runs before that exit. A listener's own ND is link-local, since its pod's default route is via fe80::1, and leaves at the earlier link-scope exit. - A VIP reply on a node whose public uplink is not configured fell through to routing. A listener's packet now leaves only through the VIP redirect; anything that reaches routing is dropped, in both the IPv6 branch and the translated IPv4 one. - A listener link whose ifindex_vrf_table or vrf_table row was missing, such as after a map reload, was handed to the kernel. It now fails closed until galactic-edge registers it again. - An attachment whose EdgeService the agent could not find was programmed as an ordinary attachment, unconfining a listener on a deleted or not yet cached service. It is now treated as a listener. The agent's gate sweep also removes listener marks left with no link row, so an interface that later takes the ifindex never inherits one. The provider contract records the mark, and that the uSID datapath must roll out before galactic-edge. Related to: #1510 --- docs/designs/edge-public-listener.md | 2 +- docs/edge/provider-contract.md | 2 + internal/edge/agent/agent.go | 28 +++++---- internal/edge/agent/agent_test.go | 50 +++++++++++----- internal/edge/agent/fixture_test.go | 3 + internal/edge/agent/gate.go | 5 +- internal/edge/agent/setup.go | 10 +++- .../ebpf/forwardgatemap/forwardgatemap.go | 33 +++++++++++ internal/plumbing/ebpf/prog/usid.c | 47 +++++++++++---- .../plumbing/ebpf/prog/usid_listener_test.go | 58 +++++++++++++++++++ 10 files changed, 198 insertions(+), 40 deletions(-) diff --git a/docs/designs/edge-public-listener.md b/docs/designs/edge-public-listener.md index 46d87ba02..ba9a54fab 100644 --- a/docs/designs/edge-public-listener.md +++ b/docs/designs/edge-public-listener.md @@ -212,7 +212,7 @@ Every listener service also carries a gateway health check, as a second signal b Listener attachments use the `PublicService` traffic policy path in both directions, like tenant VIP backends. The ingress VRF has no default route. A packet from a listener attachment that does not match a VIP translation row is dropped and counted under a new reason, `ListenerUnmatchedEgress`. -The node agent marks a listener attachment's host link in `edge_listener_link_table` when the attachment's `EdgeService` grants `PublicListener`, and clears the mark when the grant goes or the link is removed. `usid_egress` drops anything a marked link sends that misses the VIP translation rows, after its link-local and Neighbor Discovery exits, and counts it as `galactic_usid_drops_total{reason="listener_unmatched_egress"}`. The drop does not depend on the ingress VRF's routes. A datapath that predates the map leaves a listener attachment unprogrammed rather than unconfined. +The node agent marks a listener attachment's host link in `edge_listener_link_table` when the attachment's `EdgeService` grants `PublicListener`, or cannot be found, and clears the mark when the grant goes or the link is removed. A marked link's packet leaves only as a VIP reply through the node's public uplink, or as link-scope traffic such as the link's own Neighbor Discovery. `usid_egress` drops everything else, including Neighbor Discovery to a global address, a VIP reply on a node whose uplink is not configured, and any packet from a marked link whose datapath rows are missing, and counts it as `galactic_usid_drops_total{reason="listener_unmatched_egress"}`. The drop does not depend on the ingress VRF's routes. A datapath that predates the map leaves a listener attachment unprogrammed rather than unconfined, so the uSID datapath rolls out before `galactic-edge`. ### Implementation phases diff --git a/docs/edge/provider-contract.md b/docs/edge/provider-contract.md index 705ca1b9a..6a1780a87 100644 --- a/docs/edge/provider-contract.md +++ b/docs/edge/provider-contract.md @@ -150,6 +150,7 @@ Core sets `Published` on each `EdgeRoute` from its router's report on the route' An attachment's host link is a traffic policy subject like a workload's interface (see [Traffic policy on the node](../traffic-policy/node.md#edge-attachments)). The `EdgeService` selects its policy: `spec.trafficPolicy.ingressPolicyRef` for traffic delivered to the provider from the gVPC, and `egressPolicyRef` for traffic the provider sends into it. Each names a `TrafficPolicy` in the service's namespace. A provider controls neither: it cannot write the service, and a policy in its own namespace is never read. - `galactic-edge` writes the link's policy row, with the attachment's address, and attaches `usid_egress` and `tp_deliver` while the link is still down. On a node that enforces policy but failed the kernel preflight, it reports `DatapathFailed` and leaves the link down. +- When the attachment's `EdgeService` grants `PublicListener`, or cannot be found, `galactic-edge` marks the link as a listener's. `usid_egress` then sends only the link's replies that match a VIP translation row, out the node's public uplink, and drops everything else as `listener_unmatched_egress`. A datapath that predates the mark fails the link with `DatapathFailed`, so roll out the uSID datapath before `galactic-edge`. - `galactic-router` publishes one snapshot per direction. Until it has, the link denies everything. It publishes nothing, and unbinds what it published, while the attachment is not `Admitted` or its service is gone, being deleted, replaced or granting another provider. - An omitted reference selects the built-in `default-deny-all`. A reference to a missing policy denies everything as `policy_unavailable`. Neighbor discovery on the link is a link operation outside the rules, so it works under any policy. - `galactic-router` republishes when the service's references or a referenced policy change, so the change applies to active attachments. A change to the service re-admits its attachments under the new generation without draining them. @@ -369,6 +370,7 @@ Foundation-owned host state is what `galactic-edge` creates for an attachment, p | uSID registration of the host link (`ifindex_vrf_table`, `ifindex_egress_kind_table`) | Host link ifindex | None. | | Traffic policy interface rows (`tp_iface_table`, `tp_iface_addr_table`) for the host link | Host link ifindex | None. `galactic-router`'s traffic-policy reconciler binds snapshots to the link in `tp_binding_table`, as for a workload. | | Forwarding gate rows (`edge_link_table`, `edge_gate_table`) | Host link ifindex, and prefix | None. The link row is written before `usid_egress` and `tp_deliver` are attached to the link, and removed after its gates. | +| Listener mark (`edge_listener_link_table`) for a host link whose `EdgeService` grants `PublicListener` | Host link ifindex | None. Written with the link row on every pass and removed before it; the agent's sweep removes a mark left with no link row. | | Local pass-through entries in `egress_route_table`: each edge link's address, and each prefix of a route its attachment holds | gVPC table and prefix | None. Each entry names its owner, `egressroutemap.PassThroughEdge`, in its value, and `galactic-edge` removes only entries with that owner. `galactic-router`'s withdrawals leave them. | | Ownership records | Scope (gVPC on the node) | Every fenced writer, through `ownership.Authority`. | diff --git a/internal/edge/agent/agent.go b/internal/edge/agent/agent.go index b7d332c71..d45e19ed7 100644 --- a/internal/edge/agent/agent.go +++ b/internal/edge/agent/agent.go @@ -83,8 +83,8 @@ type Datapath interface { // other link has its listener mark cleared. Register(vrfTable, ifindex uint32, ifname string, addr netip.Addr, listener bool) error // Unregister closes ifindex's gates and removes every row Register - // wrote for it except the gate's link row, so the link carries nothing - // beyond its own address until it is gone. + // wrote for it except the gate's link row and listener mark, so the + // link carries nothing beyond its own address until it is gone. Unregister(ifindex uint32) error // Forget removes ifindex's gate link row, once the link is deleted. Forget(ifindex uint32) error @@ -155,9 +155,9 @@ type Agent struct { // held is, for the pass under way, each attachment's prefixes from // routes still accepted on this node, by attachment UID. held map[string][]netip.Prefix - // listenerServices is, for the pass under way, the UIDs of the - // EdgeServices that grant PublicListener. An attachment against one is a - // listener attachment. + // listenerServices is, for the pass under way, whether each EdgeService, + // by UID, grants PublicListener. An attachment against one that does is + // a listener attachment. listenerServices map[string]bool // local is, by VPC, each attachment's prefixes beyond its own address // that the last sync of the VPC's local routes kept, by attachment UID. @@ -503,7 +503,7 @@ func (a *Agent) heldPrefixes(ctx context.Context) (map[string][]netip.Prefix, er // attachments an Edge public listener's. const capabilityPublicListener = "PublicListener" -// listenerServiceUIDs returns the UIDs of the EdgeServices that grant +// listenerServiceUIDs returns, by UID, whether each EdgeService grants // PublicListener. A listener attachment's host link sends only replies that // match a VIP translation row, so a failure to list fails the pass rather // than programming a listener as an ordinary attachment. @@ -514,13 +514,21 @@ func (a *Agent) listenerServiceUIDs(ctx context.Context) (map[string]bool, error } uids := map[string]bool{} for i := range services.Items { - if slices.Contains(services.Items[i].Spec.Capabilities, capabilityPublicListener) { - uids[string(services.Items[i].UID)] = true - } + uids[string(services.Items[i].UID)] = slices.Contains(services.Items[i].Spec.Capabilities, + capabilityPublicListener) } return uids, nil } +// listener reports whether att's host link is a listener's. An attachment +// whose EdgeService is not found, deleted or not yet in the cache, is treated +// as one: confining a link for a pass is safe, and unconfining a listener is +// not. +func (a *Agent) listener(att *galacticv1alpha1.EdgeAttachment) bool { + granted, known := a.listenerServices[att.Spec.ServiceRef.UID] + return granted || !known +} + // holds reports whether rt is accepted on node and its holder has not // released it at the accepted epoch. A revoked route still holds: its // accepted holder stays until another is accepted or the route is deleted. @@ -699,7 +707,7 @@ func (a *Agent) program(att *galacticv1alpha1.EdgeAttachment, ns podNS, link hos } if datapathErr == nil { datapathErr = a.Datapath.Register(res.HostTable, uint32(res.HostIndex), spec.HostLink, spec.Address, - a.listenerServices[att.Spec.ServiceRef.UID]) + a.listener(att)) } return datapathErr } diff --git a/internal/edge/agent/agent_test.go b/internal/edge/agent/agent_test.go index 091eec423..2663c8f96 100644 --- a/internal/edge/agent/agent_test.go +++ b/internal/edge/agent/agent_test.go @@ -18,6 +18,7 @@ import ( "github.com/vishvananda/netlink" "github.com/vishvananda/netns" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" @@ -141,33 +142,47 @@ func TestAttachDetach(t *testing.T) { } // TestListenerLinks: an attachment against an EdgeService that grants -// PublicListener registers its host link as a listener's, any other as not, -// and the mark follows the service's grant from one pass to the next. +// PublicListener registers its host link as a listener's, one against a +// service that does not as not, and one whose service is not found as a +// listener's, failing closed. The mark follows the service's grant from one +// pass to the next. func TestListenerLinks(t *testing.T) { const socketAccess = "SocketAccess" f := newFixture(t) ctx := context.Background() - svc := &galacticv1alpha1.EdgeService{ - ObjectMeta: metav1.ObjectMeta{Name: "listener", Namespace: edgeNS, UID: "33333333-0000-0000-0000-000000000001"}, - Spec: galacticv1alpha1.EdgeServiceSpec{ - Capabilities: []string{socketAccess, capabilityPublicListener}, - }, + service := func(name, uid string, caps ...string) *galacticv1alpha1.EdgeService { + s := &galacticv1alpha1.EdgeService{ + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: edgeNS, UID: types.UID(uid)}, + Spec: galacticv1alpha1.EdgeServiceSpec{Capabilities: caps}, + } + if err := f.client.Create(ctx, s); err != nil { + t.Fatal(err) + } + return s } - if err := f.client.Create(ctx, svc); err != nil { - t.Fatal(err) + refer := func(name string, s galacticv1alpha1.EdgeServiceReference) { + att := f.get(name) + att.Spec.ServiceRef = s + if err := f.client.Update(ctx, att); err != nil { + t.Fatal(err) + } } + svc := service("listener", "33333333-0000-0000-0000-000000000001", socketAccess, capabilityPublicListener) + plain := service("plain", "33333333-0000-0000-0000-000000000002", socketAccess) a := f.agent() f.pod(pod1UID) + f.pod(pod2UID) f.attach("a", attA, pod1UID, vpcA, addr, false) f.attach("b", attB, pod1UID, vpcB, addr, false) - att := f.get("a") - att.Spec.ServiceRef = galacticv1alpha1.EdgeServiceReference{Namespace: edgeNS, Name: svc.Name, UID: string(svc.UID)} - if err := f.client.Update(ctx, att); err != nil { - t.Fatal(err) - } + f.attach("p", attP, pod2UID, vpcA, "fd00:aa::2", false) + refer("a", galacticv1alpha1.EdgeServiceReference{Namespace: edgeNS, Name: svc.Name, UID: string(svc.UID)}) + refer("b", galacticv1alpha1.EdgeServiceReference{Namespace: edgeNS, Name: plain.Name, UID: string(plain.UID)}) + refer("p", galacticv1alpha1.EdgeServiceReference{Namespace: edgeNS, Name: "gone", + UID: "33333333-0000-0000-0000-000000000009"}) f.reconcile(a) - f.programmed("a") - f.programmed("b") + for _, n := range []string{"a", "b", "p"} { + f.programmed(n) + } linkA, linkB := uint32(f.hostLink("a").Attrs().Index), uint32(f.hostLink("b").Attrs().Index) if !f.dp.listener(linkA) { t.Error("a's host link is not registered as a listener's") @@ -175,6 +190,9 @@ func TestListenerLinks(t *testing.T) { if f.dp.listener(linkB) { t.Error("b's host link is registered as a listener's") } + if !f.dp.listener(uint32(f.hostLink("p").Attrs().Index)) { + t.Error("p's host link, whose service is not found, is not registered as a listener's") + } if err := f.client.Get(ctx, client.ObjectKeyFromObject(svc), svc); err != nil { t.Fatal(err) diff --git a/internal/edge/agent/fixture_test.go b/internal/edge/agent/fixture_test.go index d0f8212b5..6820cbb85 100644 --- a/internal/edge/agent/fixture_test.go +++ b/internal/edge/agent/fixture_test.go @@ -282,6 +282,9 @@ func (g *gates) DeleteLink(ifindex uint32) error { return nil } +// PruneListeners implements GateTable: the fake keeps no listener marks. +func (g *gates) PruneListeners() error { return nil } + func (g *gates) deleteLink(ifindex uint32) { g.Lock() defer g.Unlock() diff --git a/internal/edge/agent/gate.go b/internal/edge/agent/gate.go index ae4657c7f..56edd0fab 100644 --- a/internal/edge/agent/gate.go +++ b/internal/edge/agent/gate.go @@ -39,8 +39,10 @@ type GateTable interface { Delete(ifindex uint32, prefix netip.Prefix) error // Links returns every registered edge link and its own address. Links() (map[uint32]netip.Addr, error) - // DeleteLink removes ifindex's gates and its link row. + // DeleteLink removes ifindex's gates, listener mark and link row. DeleteLink(ifindex uint32) error + // PruneListeners removes every listener mark with no link row. + PruneListeners() error } // gateLink is a registered edge link: its ifindex, VPC and gates. @@ -529,6 +531,7 @@ func (a *Agent) SweepGates(ctx context.Context) error { errs = append(errs, a.Gates.DeleteLink(ifindex)) } } + errs = append(errs, a.Gates.PruneListeners()) now := a.bootClock() for uid, l := range links { for p, g := range l.rows { diff --git a/internal/edge/agent/setup.go b/internal/edge/agent/setup.go index 838fe34fd..eab4a608d 100644 --- a/internal/edge/agent/setup.go +++ b/internal/edge/agent/setup.go @@ -52,8 +52,9 @@ func (d PinnedDatapath) Register(vrfTable, ifindex uint32, ifname string, addr n } // Unregister implements Datapath: the link's gates first, then its rows. The -// link row stays until Forget, so the link stays gated while it exists. A -// datapath whose gate maps are not pinned holds no gate. +// link row and listener mark stay until Forget, so the link stays gated, and +// a listener's confined, while it exists. A datapath whose gate maps are not +// pinned holds no gate. func (d PinnedDatapath) Unregister(ifindex uint32) error { gates, err := forwardgatemap.OpenPinned(d.PinDir) switch { @@ -151,6 +152,11 @@ func (g PinnedGates) DeleteLink(ifindex uint32) error { return g.with(func(t *forwardgatemap.Table) error { return t.DeleteLink(ifindex) }) } +// PruneListeners implements GateTable. +func (g PinnedGates) PruneListeners() error { + return g.with(func(t *forwardgatemap.Table) error { return t.PruneListeners() }) +} + // Delete implements GateTable. func (g PinnedGates) Delete(ifindex uint32, prefix netip.Prefix) error { return g.with(func(t *forwardgatemap.Table) error { return t.Delete(ifindex, prefix) }) diff --git a/internal/plumbing/ebpf/forwardgatemap/forwardgatemap.go b/internal/plumbing/ebpf/forwardgatemap/forwardgatemap.go index 7ebe05819..5ca7cad3d 100644 --- a/internal/plumbing/ebpf/forwardgatemap/forwardgatemap.go +++ b/internal/plumbing/ebpf/forwardgatemap/forwardgatemap.go @@ -196,6 +196,39 @@ func (t *Table) Listener(ifindex uint32) (bool, error) { return true, nil } +// PruneListeners removes every listener mark on an ifindex with no link row, +// such as one left when edge_link_table was recreated, so no later interface +// that takes the ifindex inherits it. +func (t *Table) PruneListeners() error { + if t.listeners == nil { + return nil + } + var ( + ifindex uint32 + v uint8 + orphans []uint32 + ) + it := t.listeners.Iterate() + for it.Next(&ifindex, &v) { + var link linkValue + err := t.links.Lookup(ifindex, &link) + switch { + case errors.Is(err, ebpf.ErrKeyNotExist): + orphans = append(orphans, ifindex) + case err != nil: + return fmt.Errorf("forwardgatemap: read link %d: %w", ifindex, err) + } + } + if err := it.Err(); err != nil { + return fmt.Errorf("forwardgatemap: list listeners: %w", err) + } + var errs []error + for _, i := range orphans { + errs = append(errs, t.SetListener(i, false)) + } + return errors.Join(errs...) +} + // DeleteLink removes ifindex's gates and listener mark, then its link row. // Call it once the link is deleted and before its ifindex can be reused, so // no later interface inherits the rows. Absent rows are not errors. diff --git a/internal/plumbing/ebpf/prog/usid.c b/internal/plumbing/ebpf/prog/usid.c index c585e5677..cbb58b9f5 100644 --- a/internal/plumbing/ebpf/prog/usid.c +++ b/internal/plumbing/ebpf/prog/usid.c @@ -1478,6 +1478,13 @@ struct { __type(value, __u8); // 1; the key's presence is the flag } edge_listener_link_table SEC(".maps"); +// listener_link reports whether ifindex is an Edge public listener's host +// link. +static USID_ALWAYS_INLINE int listener_link(__u32 ifindex) +{ + return bpf_map_lookup_elem(&edge_listener_link_table, &ifindex) != 0; +} + // nptv6_table: one row per VRF with NPTv6 configured, keyed like vrf_table. // usid_ingress already holds that key locally, and usid_egress resolves it // through ifindex_vrf_table. @@ -5905,8 +5912,15 @@ int usid_egress(struct __sk_buff *skb) __u32 ifindex = skb->ifindex; struct ifindex_vrf_value *iv = bpf_map_lookup_elem(&ifindex_vrf_table, &ifindex); + // A listener link whose rows are missing, such as after a map reload, + // fails closed until galactic-edge registers it again: handing its + // traffic to the kernel would route it. if (!iv) { count_drop(DROP_REASON_TRACE_IFINDEX_MISS); + if (listener_link(ifindex)) { + count_drop(DROP_REASON_LISTENER_UNMATCHED_EGRESS); + return TC_ACT_SHOT; + } if (tp_decide(skb->ifindex, TP_DIR_EGRESS, TP_PATH_PRIVATE)) return TC_ACT_SHOT; return TC_ACT_UNSPEC; // no attachment registered on this ifindex at all @@ -5921,6 +5935,10 @@ int usid_egress(struct __sk_buff *skb) struct vrf_value *vrf = bpf_map_lookup_elem(&vrf_table, &vrf_key); if (!vrf) { count_drop(DROP_REASON_TRACE_MISS_VRF); + if (listener_link(ifindex)) { + count_drop(DROP_REASON_LISTENER_UNMATCHED_EGRESS); + return TC_ACT_SHOT; + } if (tp_decide(skb->ifindex, TP_DIR_EGRESS, TP_PATH_PRIVATE)) return TC_ACT_SHOT; return TC_ACT_UNSPEC; @@ -6109,6 +6127,18 @@ int usid_egress(struct __sk_buff *skb) } } + // An Edge public listener sends nothing but replies to its VIPs' + // clients, and those left through the VIP redirect above. Anything + // else, including a VIP reply on a node whose uplink is not + // configured yet and Neighbor Discovery to anything but link scope, + // is dropped here rather than routed, whatever routes its VRF holds. + // A listener's own Neighbor Discovery is link-local: its pod's + // default route is via fe80::1, and the exit above passed it. + if (listener_link(ifindex)) { + count_claimed_drop(DROP_REASON_LISTENER_UNMATCHED_EGRESS, vrf, vrf_key, VRF_DIRECTION_EGRESS); + return TC_ACT_SHOT; + } + if (npt && !vip_hit) apply_nptv6(ip6->saddr, npt, 1 /* outbound: ULA -> public */); @@ -6140,16 +6170,6 @@ int usid_egress(struct __sk_buff *skb) } } - // An Edge public listener sends nothing but replies to its VIPs' - // clients, which took the VIP path above. Anything else, to the - // internet or anywhere, is dropped here rather than routed, whatever - // routes its VRF holds. An edge attachment is IPv6 only, and the gate - // already dropped any IPv4 it sent, so only this branch needs it. - if (!vip_hit && bpf_map_lookup_elem(&edge_listener_link_table, &ifindex)) { - count_claimed_drop(DROP_REASON_LISTENER_UNMATCHED_EGRESS, vrf, vrf_key, VRF_DIRECTION_EGRESS); - return TC_ACT_SHOT; - } - route_family = USID_EGRESS_ROUTE_FAMILY_INET6; __builtin_memcpy(egress_scratch->dest_addr, ip6->daddr, 16); } else { @@ -6199,6 +6219,13 @@ int usid_egress(struct __sk_buff *skb) return TC_ACT_SHOT; } + // As in the IPv6 branch: a listener's translated reply that did not + // leave through the uplink is not routed. + if (listener_link(ifindex)) { + count_claimed_drop(DROP_REASON_LISTENER_UNMATCHED_EGRESS, vrf, vrf_key, VRF_DIRECTION_EGRESS); + return TC_ACT_SHOT; + } + route_family = USID_EGRESS_ROUTE_FAMILY_INET4; __builtin_memcpy(egress_scratch->dest_addr, ip4->daddr, sizeof(ip4->daddr)); } diff --git a/internal/plumbing/ebpf/prog/usid_listener_test.go b/internal/plumbing/ebpf/prog/usid_listener_test.go index 3bd4b78d9..8f649b570 100644 --- a/internal/plumbing/ebpf/prog/usid_listener_test.go +++ b/internal/plumbing/ebpf/prog/usid_listener_test.go @@ -102,6 +102,64 @@ func TestUsidEgress_ListenerUnmatchedEgressDropped(t *testing.T) { } } +// TestUsidEgress_ListenerNeighborDiscoveryBeyondLinkDropped: Neighbor +// Discovery messages a listener addresses to a global address are not handed +// to the kernel, which would route them. Its own Neighbor Discovery is +// link-local and passes (TestUsidEgress_ListenerLinkLocalPasses). +func TestUsidEgress_ListenerNeighborDiscoveryBeyondLinkDropped(t *testing.T) { + const neighborAdvertisement = 136 + requireRoot(t) + objs := loadObjects(t) + setUpListenerLink(t, objs, listenerAddr, listenerVIP, true) + + dst := netip.MustParseAddr("2001:db8:ffff::53") + ret, _, err := objs.UsidEgress.Test(buildPlainV6PacketWithICMPv6Type(t, listenerAddr, dst, neighborAdvertisement)) + if err != nil { + t.Fatalf("program test-run: %v", err) + } + if ret != tcActShot { + t.Errorf("neighbor advertisement to %s: verdict=%d, want TC_ACT_SHOT (%d)", dst, ret, tcActShot) + } + assertOnlyMetricDropReason(t, objs, DropReasonListenerUnmatchedEgress) +} + +// TestUsidEgress_ListenerVIPReplyWithoutUplinkDropped: on a node whose public +// uplink is not configured yet, a listener's VIP reply cannot leave through +// it, and is dropped rather than routed. +func TestUsidEgress_ListenerVIPReplyWithoutUplinkDropped(t *testing.T) { + requireRoot(t) + objs := loadObjects(t) + setUpListenerLink(t, objs, listenerAddr, listenerVIP, true) + // A zero link ifindex is the map's not-configured value. + if err := objs.PublicUplinkTable.Put(uint32(0), UsidPublicUplinkValue{}); err != nil { + t.Fatalf("clear public_uplink_table: %v", err) + } + + ret, _ := runEgressTo(t, objs, listenerAddr, listenerClient, listenerPort) + if ret != tcActShot { + t.Errorf("reply without an uplink: verdict=%d, want TC_ACT_SHOT (%d)", ret, tcActShot) + } + assertOnlyMetricDropReason(t, objs, DropReasonListenerUnmatchedEgress) +} + +// TestUsidEgress_ListenerWithoutRowsDropped: a listener link with no +// ifindex_vrf_table row, as after a map reload, fails closed. +func TestUsidEgress_ListenerWithoutRowsDropped(t *testing.T) { + requireRoot(t) + objs := loadObjects(t) + if err := objs.EdgeListenerLinkTable.Put(listenerLinkIfindex, uint8(1)); err != nil { + t.Fatalf("populate edge_listener_link_table: %v", err) + } + + ret, _ := runEgressTo(t, objs, listenerAddr, netip.MustParseAddr("2001:db8:ffff::53"), listenerPort) + if ret != tcActShot { + t.Errorf("verdict=%d, want TC_ACT_SHOT (%d)", ret, tcActShot) + } + if got := sumPerCPU(t, objs.DropReasons, DropReasonListenerUnmatchedEgress); got != 1 { + t.Errorf("drop_reasons[listener_unmatched_egress] = %d, want 1", got) + } +} + // TestUsidEgress_NonListenerEdgeLinkUnaffected: the same packet from an edge // link that is not a listener's goes on as before, uncounted. func TestUsidEgress_NonListenerEdgeLinkUnaffected(t *testing.T) { From c0780e847ac38468afecae8a1d76e27c60483790 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Sat, 28 Nov 2026 21:46:05 -0500 Subject: [PATCH 3/3] fix(edge): Keep listener multicast within link scope usid_egress handed all multicast to the kernel before the listener check, so a listener could send to a site- or global-scope group. A listener link's multicast beyond link scope is now dropped and counted as listener_unmatched_egress; interface- and link-local groups still pass, which the link's own Neighbor Discovery needs. The design doc links #1519 for letting ICMPv6 errors about VIP flows through, which the listener drop discards for now. Related to: #1510 --- docs/designs/edge-public-listener.md | 4 ++- internal/plumbing/ebpf/prog/usid.c | 8 +++++ .../plumbing/ebpf/prog/usid_listener_test.go | 31 +++++++++++++++++++ 3 files changed, 42 insertions(+), 1 deletion(-) diff --git a/docs/designs/edge-public-listener.md b/docs/designs/edge-public-listener.md index ba9a54fab..6945c1824 100644 --- a/docs/designs/edge-public-listener.md +++ b/docs/designs/edge-public-listener.md @@ -212,7 +212,9 @@ Every listener service also carries a gateway health check, as a second signal b Listener attachments use the `PublicService` traffic policy path in both directions, like tenant VIP backends. The ingress VRF has no default route. A packet from a listener attachment that does not match a VIP translation row is dropped and counted under a new reason, `ListenerUnmatchedEgress`. -The node agent marks a listener attachment's host link in `edge_listener_link_table` when the attachment's `EdgeService` grants `PublicListener`, or cannot be found, and clears the mark when the grant goes or the link is removed. A marked link's packet leaves only as a VIP reply through the node's public uplink, or as link-scope traffic such as the link's own Neighbor Discovery. `usid_egress` drops everything else, including Neighbor Discovery to a global address, a VIP reply on a node whose uplink is not configured, and any packet from a marked link whose datapath rows are missing, and counts it as `galactic_usid_drops_total{reason="listener_unmatched_egress"}`. The drop does not depend on the ingress VRF's routes. A datapath that predates the map leaves a listener attachment unprogrammed rather than unconfined, so the uSID datapath rolls out before `galactic-edge`. +The node agent marks a listener attachment's host link in `edge_listener_link_table` when the attachment's `EdgeService` grants `PublicListener`, or cannot be found, and clears the mark when the grant goes or the link is removed. A marked link's packet leaves only as a VIP reply through the node's public uplink, or as link-scope traffic such as the link's own Neighbor Discovery. `usid_egress` drops everything else, including Neighbor Discovery to a global address, multicast beyond link scope, a VIP reply on a node whose uplink is not configured, and any packet from a marked link whose datapath rows are missing, and counts it as `galactic_usid_drops_total{reason="listener_unmatched_egress"}`. The drop does not depend on the ingress VRF's routes. A datapath that predates the map leaves a listener attachment unprogrammed rather than unconfined, so the uSID datapath rolls out before `galactic-edge`. + +ICMPv6 errors a listener sends about a VIP flow, such as Packet Too Big, match no translation row and are dropped for now. Translating them so they leave from the VIP is [#1519](https://github.com/datum-cloud/galactic/issues/1519). ### Implementation phases diff --git a/internal/plumbing/ebpf/prog/usid.c b/internal/plumbing/ebpf/prog/usid.c index cbb58b9f5..4605e48a8 100644 --- a/internal/plumbing/ebpf/prog/usid.c +++ b/internal/plumbing/ebpf/prog/usid.c @@ -6013,6 +6013,14 @@ int usid_egress(struct __sk_buff *skb) // never sending anything this program's drop counters could see. // The kernel's own routing handles these scopes the same way. if (ip6->daddr[0] == 0xFF || (ip6->daddr[0] == 0xFE && (ip6->daddr[1] & 0xC0) == 0x80)) { + // An Edge public listener's multicast stays within link + // scope (interface- or link-local, RFC 4291 section 2.7); + // anything wider would reach the kernel's routing. + if (ip6->daddr[0] == 0xFF && (ip6->daddr[1] & 0x0F) > 2 && listener_link(ifindex)) { + count_claimed_drop(DROP_REASON_LISTENER_UNMATCHED_EGRESS, vrf, vrf_key, + VRF_DIRECTION_EGRESS); + return TC_ACT_SHOT; + } count_drop(DROP_REASON_TRACE_MULTICAST_LL_BAIL); if (tp_decide(skb->ifindex, TP_DIR_EGRESS, TP_PATH_PRIVATE)) return TC_ACT_SHOT; diff --git a/internal/plumbing/ebpf/prog/usid_listener_test.go b/internal/plumbing/ebpf/prog/usid_listener_test.go index 8f649b570..60fc20014 100644 --- a/internal/plumbing/ebpf/prog/usid_listener_test.go +++ b/internal/plumbing/ebpf/prog/usid_listener_test.go @@ -123,6 +123,37 @@ func TestUsidEgress_ListenerNeighborDiscoveryBeyondLinkDropped(t *testing.T) { assertOnlyMetricDropReason(t, objs, DropReasonListenerUnmatchedEgress) } +// TestUsidEgress_ListenerMulticastScope: a listener's multicast to link scope +// reaches the kernel, and to any wider scope is dropped and counted. +func TestUsidEgress_ListenerMulticastScope(t *testing.T) { + for _, tc := range []struct { + dst string + want uint32 + }{ + {"ff02::1", tcActUnspec}, + {"ff05::2", tcActShot}, + {"ff0e::1:3", tcActShot}, + } { + t.Run(tc.dst, func(t *testing.T) { + requireRoot(t) + objs := loadObjects(t) + setUpListenerLink(t, objs, listenerAddr, listenerVIP, true) + + ret, _ := runEgressTo(t, objs, listenerAddr, netip.MustParseAddr(tc.dst), listenerPort) + if ret != tc.want { + t.Errorf("packet to %s: verdict=%d, want %d", tc.dst, ret, tc.want) + } + want := uint64(0) + if tc.want == tcActShot { + want = 1 + } + if got := sumPerCPU(t, objs.DropReasons, DropReasonListenerUnmatchedEgress); got != want { + t.Errorf("drop_reasons[listener_unmatched_egress] = %d, want %d", got, want) + } + }) + } +} + // TestUsidEgress_ListenerVIPReplyWithoutUplinkDropped: on a node whose public // uplink is not configured yet, a listener's VIP reply cannot leave through // it, and is dropped rather than routed.