diff --git a/docs/designs/edge-public-listener.md b/docs/designs/edge-public-listener.md index d75940089..6945c1824 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,10 @@ 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, 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 | Phase | Work | Gate | @@ -219,7 +223,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 +268,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 +292,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/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/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..d45e19ed7 100644 --- a/internal/edge/agent/agent.go +++ b/internal/edge/agent/agent.go @@ -78,11 +78,13 @@ 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. + // 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 @@ -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, 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. 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,36 @@ 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, 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. +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 { + 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. @@ -665,7 +706,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.listener(att)) } return datapathErr } diff --git a/internal/edge/agent/agent_test.go b/internal/edge/agent/agent_test.go index 8561b18d4..2663c8f96 100644 --- a/internal/edge/agent/agent_test.go +++ b/internal/edge/agent/agent_test.go @@ -18,6 +18,8 @@ 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" "go.datum.net/galactic/internal/edge/diag" @@ -139,6 +141,72 @@ 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, 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() + 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 + } + 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) + 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) + 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") + } + 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) + } + 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..6820cbb85 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() @@ -269,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/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..eab4a608d 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,12 +45,16 @@ 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) } // 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 { @@ -148,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) }) @@ -174,6 +183,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..5ca7cad3d 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,87 @@ 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 +} + +// 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. 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..4605e48a8 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,28 @@ 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"); + +// 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. @@ -5886,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 @@ -5902,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; @@ -5976,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; @@ -6090,6 +6135,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 */); @@ -6170,6 +6227,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 new file mode 100644 index 000000000..60fc20014 --- /dev/null +++ b/internal/plumbing/ebpf/prog/usid_listener_test.go @@ -0,0 +1,228 @@ +// 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_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_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. +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) { + 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 {