diff --git a/deploy/containerlab/Taskfile.yaml b/deploy/containerlab/Taskfile.yaml index d597c37e3..928660157 100644 --- a/deploy/containerlab/Taskfile.yaml +++ b/deploy/containerlab/Taskfile.yaml @@ -1333,6 +1333,19 @@ tasks: cmds: - EDGE_CONFORMANCE_KUBECONFIG={{.ROOT_DIR}}/dfw.kubeconfig go test -count=1 -v -timeout 40m -run '^TestNoLocalWorkload$' ./tests/edgeconformance/ + # Not part of verify: Phase 0 of docs/designs/edge-public-listener.md + # (#1507). It hand-wires a reference provider's SocketAccess attachment on + # dfw-worker3 as the backend of a dfw VIP, pins the VIP on tr1 to each dfw + # gateway in turn, sends UDP and TCP over both families from remote-host, + # and removes everything it created. Remote delivery must pass; local + # delivery is recorded. Needs the edge-provider image from + # build:edge-provider. Results land in bin/edge-conformance/. + "verify:edge-listener": + desc: Prove an edge SocketAccess attachment as a gateway VIP backend, remote and local delivery + dir: ../.. + cmds: + - EDGE_CONFORMANCE_KUBECONFIG={{.ROOT_DIR}}/dfw.kubeconfig LAB={{.LAB}} go test -count=1 -v -timeout 30m -run '^TestListenerBackend$' ./tests/edgeconformance/ + # Not part of verify: it takes about 20 minutes, deploys the shipped MASQUE # service from config/masque through resources/masque-service (images from # build:masque-service and build:masque-authority, loaded by diff --git a/docs/designs/edge-public-listener.md b/docs/designs/edge-public-listener.md index 7f228398d..91ec3bb1e 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. Nothing in this design 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. +Status: proposed, with its open decisions settled. The Phase 0 lab proof is done (see [Phase 0 results](#phase-0-results)); nothing else in this design 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). @@ -89,8 +89,8 @@ The Kubernetes Service and any `LoadBalancer`, `NodePort` or `hostPort` overlay | Risk | Mitigation | | --- | --- | | Maglev is stateless. A change in the backend set moves about 1/N of flows, which breaks QUIC and TLS connections on the moved flows. | Default affinity is `ClientIPAndProtocol`. Drain removes an instance from new selection only after `drainSeconds`, so providers can send HTTP/3 GOAWAY or HTTP/2 GOAWAY first. Connection-ID routing is a follow-up, not part of v1. | -| An edge node that also runs the gateway can select a backend on itself. The gateway has no qualified local-delivery branch: a node's own locator can match a discard route. | Phase 0 qualifies local delivery on the containerlab gvpc lab. Until it passes, the listener controller excludes backends on nodes that advertise the listener's VIPs, and reports `LocalBackendsExcluded`. | -| The return rewrite needs the listener attachment's host veth in `ifindex_vrf_table` with `usid_egress` attached. | The node agent already does this for every edge attachment. Phase 0 confirms that `usid_egress` applies the VIP reverse translation on an edge host link. See [Decisions](#decisions). | +| An edge node that also runs the gateway can select a backend on itself. The gateway has no local-delivery branch: its FIB lookup of a backend uSID on its own node meets the discard route for the node's locator. | Phase 0 showed every such flow dropped as `fib_unreachable`. The listener controller excludes backends on nodes that advertise the listener's VIPs, and reports `LocalBackendsExcluded`, until the gateway gains a local-delivery branch. | +| The return rewrite needs the listener attachment's host veth in `ifindex_vrf_table` with `usid_egress` attached. | The node agent already does this for every edge attachment, and Phase 0 showed `usid_egress` applying the VIP reverse translation on an edge host link for both families. See [Decisions](#decisions). | | A client reaches a cell that does not hold its grant. | A listener's addresses belong to one cell. Each cell's gateway VIP prefixes are disjoint from every other cell's, and core refuses an address outside its own prefixes. | | A compromised provider could try to originate internet traffic through the listener. | The ingress VRF has no default route and no egress shard. Only replies that match a VIP translation row leave through the node's uplink. Anything else is dropped and counted. | | One provider's listener reaches another provider or a tenant. | One ingress gVPC per provider, no route leaking, and the `PublicService` traffic policy path on the listener attachment. | @@ -105,8 +105,8 @@ These were open when the design was proposed and were settled in [#1506](https:/ | --- | --- | --- | | Who supplies listener addresses | The platform authority, from the cell's gateway VIP prefixes. Core refuses any other address with `AddressOutsidePool`. | This is how gateway-namespace services get addresses today. An allocator can follow later without an API change. | | How many ingress gVPCs exist | One per provider type, not one per listener | It isolates providers from each other at the cost of one VPC identifier each. A provider has one listener, so a gVPC per listener adds no isolation. | -| Who registers a listener attachment's host veth in `ifindex_vrf_table` | No new component. The node agent (`galactic-edge`) already registers every edge host link through `attachreg.RegisterHostLink`, which writes the `ifindex_vrf_table` row, sets the veth egress kind and attaches `usid_egress`. | The registration a listener needs exists today. What remains unproven is that the gateway's VIP reverse translation applies on an edge host link, which Phase 0 tests. | -| What happens to a backend on a node that also advertises the VIP | It is excluded, and the listener reports `LocalBackendsExcluded`, until Phase 0 qualifies gateway local delivery. The exclusion is removed once it passes. | Local delivery is unqualified today, and excluding those backends keeps the rest of the work unblocked. | +| Who registers a listener attachment's host veth in `ifindex_vrf_table` | No new component. The node agent (`galactic-edge`) already registers every edge host link through `attachreg.RegisterHostLink`, which writes the `ifindex_vrf_table` row, sets the veth egress kind and attaches `usid_egress`. | The registration a listener needs exists today, and Phase 0 showed the VIP reverse translation working on an edge host link. | +| What happens to a backend on a node that also advertises the VIP | It is excluded, and the listener reports `LocalBackendsExcluded`. Phase 0 showed local delivery failing, so the exclusion stays until the gateway can deliver to its own node. | Excluding those backends keeps the rest of the work unblocked. | A listener's addresses belong to one cell. Grants are scoped to one cell, so an address announced from two cells would send some clients to a cell that cannot authorize them. Core in one cell cannot see other cells' addresses, so address planning enforces the rule: each cell's gateway VIP prefixes are disjoint from every other cell's. @@ -216,13 +216,39 @@ Listener attachments use the `PublicService` traffic policy path in both directi | Phase | Work | Gate | | --- | --- | --- | -| 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, with a backend on a gateway node and on a node that is not a gateway | +| 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: VIP reply translation on edge host links if Phase 0 shows a gap, unmatched-egress drop | 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 | | 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 | +### Phase 0 results + +Run on 2026-11-28 on the containerlab gvpc lab by `task verify:edge-listener` (`TestListenerBackend` in `tests/edgeconformance`), for [#1507](https://github.com/datum-cloud/galactic/issues/1507). The test wires one backend by hand, with no controller change: + +1. A dedicated ingress VPC under the lab's `public-service` traffic policy, granted to the reference provider with `SocketAccess` only. The provider serves UDP and TCP echo from a socket bound to its pod VRF. +2. A stand-in `VPCAttachment` naming the edge attachment's address and node, because the gateway and `galactic-router` select backends from `VPCAttachment`s. +3. The attachment's `/128` `BGPAdvertisement` in the ingress VRF, with `VRFID` and `End.DT46`. +4. One gateway-namespace `NetworkService` per protocol, each with an IPv6 and an IPv4 VIP and no health check. + +`galactic-router` on the backend's node bound all four VIP and protocol pairs. The off-fabric client then sent eight flows per protocol and family, with the VIP pinned on the transit router to one gateway at a time. + +| Case | Result | +| --- | --- | +| Remote delivery: the VIP pinned to the gateway that does not hold the backend | Every UDP and TCP flow answered, over IPv6 and IPv4. Replies came from the VIP. The backend saw the IPv6 client's own address, and the IPv4 client under `64:ff9b::/96`. | +| Local delivery: the VIP pinned to the backend's own node | No flow answered. The gateway matched every packet and dropped each one as `fib_unreachable`. | + +What this settles: + +- `RegisterHostLink` and `usid_egress` already carry listener replies, including the IPv4 translation. Phase 3 needs no reply-translation work. +- The gateway cannot deliver to a backend on its own node, so the `LocalBackendsExcluded` exclusion is required, not precautionary. + +Limits of the proof: + +- Every edge node in the lab also runs a gateway. The proof's "node that is not a gateway" is therefore a node that is not the gateway the packet arrives on. The receiving gateway's datapath is the same either way. +- The stand-in attachment has no `hostInterface`, so the gateway health check was not exercised. Phase 4 covers it. + ## Production Readiness Review Questionnaire ### Feature Enablement and Rollback @@ -261,6 +287,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)). ## Drawbacks diff --git a/examples/edge-provider/README.md b/examples/edge-provider/README.md index 0aace754b..f55b3cce3 100644 --- a/examples/edge-provider/README.md +++ b/examples/edge-provider/README.md @@ -13,19 +13,18 @@ For each `EdgeService` it is configured with, it: 1. creates its pod's `EdgeInstance` and holds the instance's lease, renewing it every 5 s; 2. requests an `EdgeAttachment` and, once `galactic-edge` reports it - `Programmed`, answers UDP on the attachment's address (`SocketAccess`) and - sets `Ready`; + `Programmed`, answers UDP and TCP on the attachment's address + (`SocketAccess`) and sets `Ready`; 3. for `PacketAccess`, opens the attachment's TUN device and answers ICMPv6 echo and UDP for every address in the prefixes it claims; 4. claims an `EdgeRoute` for each configured prefix while its lease is held. -Every UDP reply starts with `//`, so a client can tell -which instance answered. On SIGTERM it stops forwarding, then releases its -routes, deletes its attachments and releases its lease. SIGUSR1 freezes it: it -stops renewing and writing to the API while its data planes keep answering, -past its lease's deadline too. -The conformance suite uses that to show that `galactic-edge` stops forwarding -on its own. +Every UDP and TCP reply starts with `//`, so a client +can tell which instance answered. On SIGTERM it stops forwarding, then releases +its routes, deletes its attachments and releases its lease. SIGUSR1 freezes it: +it stops renewing and writing to the API while its data planes keep answering, +past its lease's deadline too. The conformance suite uses that to show that +`galactic-edge` stops forwarding on its own. ## Build @@ -79,7 +78,7 @@ and its VPC's UID from the grant: ```yaml provider: example-echo # the EdgeProvider this pod runs as -port: 7777 # UDP port of the attachment-address echo +port: 7777 # UDP and TCP port of the attachment-address echo services: - namespace: tenant-a # the EdgeService's namespace name: echo diff --git a/examples/edge-provider/internal/config/config.go b/examples/edge-provider/internal/config/config.go index 556e15eea..340b80da2 100644 --- a/examples/edge-provider/internal/config/config.go +++ b/examples/edge-provider/internal/config/config.go @@ -29,7 +29,7 @@ const ( type Config struct { // Provider is the EdgeProvider this process runs as. Provider string `json:"provider"` - // Port is the UDP port the SocketAccess echo listens on. + // Port is the UDP and TCP port the SocketAccess echo listens on. Port uint16 `json:"port"` // Services are the grants to attach to. Services []Service `json:"services"` diff --git a/examples/edge-provider/internal/dataplane/dataplane.go b/examples/edge-provider/internal/dataplane/dataplane.go index eb6a90661..27d7976fe 100644 --- a/examples/edge-provider/internal/dataplane/dataplane.go +++ b/examples/edge-provider/internal/dataplane/dataplane.go @@ -20,6 +20,7 @@ import ( "strconv" "sync" "syscall" + "time" "github.com/datum-cloud/galactic/examples/edge-provider/internal/packet" "golang.org/x/sys/unix" @@ -30,8 +31,9 @@ type Server interface { Close() error } -// Echo serves UDP on address and port, bound to the VRF vrf, replying with -// identity, a space and the request's payload. Binding a socket to a device +// Echo serves UDP and TCP on address and port, bound to the VRF vrf. Each +// UDP datagram, and each read on a TCP connection, is answered with +// identity, a space and the bytes received. Binding a socket to a device // needs no capability as long as the socket is not already bound to one. func Echo(ctx context.Context, log *slog.Logger, vrf string, address netip.Addr, port uint16, identity string, ) (Server, error) { @@ -44,11 +46,55 @@ func Echo(ctx context.Context, log *slog.Logger, vrf string, address netip.Addr, } return serr }} - pc, err := lc.ListenPacket(ctx, "udp6", net.JoinHostPort(address.String(), strconv.Itoa(int(port)))) + hostPort := net.JoinHostPort(address.String(), strconv.Itoa(int(port))) + pc, err := lc.ListenPacket(ctx, "udp6", hostPort) if err != nil { - return nil, fmt.Errorf("listen on [%s]:%d in VRF %s: %w", address, port, vrf, err) + return nil, fmt.Errorf("listen on UDP [%s]:%d in VRF %s: %w", address, port, vrf, err) } - s := &loop{closer: pc} + ln, err := lc.Listen(ctx, "tcp6", hostPort) + if err != nil { + _ = pc.Close() + return nil, fmt.Errorf("listen on TCP [%s]:%d in VRF %s: %w", address, port, vrf, err) + } + conns := &connSet{conns: map[net.Conn]struct{}{}} + s := &loop{closer: multiCloser{pc, ln, conns}} + s.wg.Go(func() { + var backoff time.Duration + for { + c, err := ln.Accept() + if err != nil { + if errors.Is(err, net.ErrClosed) { + return + } + // A transient failure such as running out of descriptors + // must not end TCP service while UDP keeps answering. + backoff = min(max(2*backoff, 5*time.Millisecond), time.Second) + log.Error("echo listener accept failed", "vrf", vrf, "error", err, "retryIn", backoff) + time.Sleep(backoff) + continue + } + backoff = 0 + if !conns.add(c) { + _ = c.Close() + return + } + s.wg.Go(func() { + defer conns.remove(c) + buf := make([]byte, 4096) + for { + _ = c.SetReadDeadline(time.Now().Add(tcpIdle)) + n, err := c.Read(buf) + if err != nil { + return + } + if _, err := c.Write(append([]byte(identity+" "), buf[:n]...)); err != nil { + log.Warn("echo reply failed", "to", c.RemoteAddr(), "error", err) + return + } + } + }) + } + }) s.wg.Go(func() { buf := make([]byte, 65535) for { @@ -115,8 +161,60 @@ func TUN(log *slog.Logger, name, identity string, allow func() bool) (Server, er return s, nil } +// tcpIdle is how long a TCP echo connection may stay silent before the +// server closes it. +const tcpIdle = time.Minute + type closer interface{ Close() error } +// multiCloser closes each of its members and returns the first error. +type multiCloser []closer + +func (m multiCloser) Close() error { + var first error + for _, c := range m { + if err := c.Close(); err != nil && first == nil { + first = err + } + } + return first +} + +// connSet holds the open TCP echo connections, so closing the server ends +// them and its wait returns. Once closed it refuses new connections. +type connSet struct { + mu sync.Mutex + conns map[net.Conn]struct{} + closed bool +} + +func (s *connSet) add(c net.Conn) bool { + s.mu.Lock() + defer s.mu.Unlock() + if s.closed { + return false + } + s.conns[c] = struct{}{} + return true +} + +func (s *connSet) remove(c net.Conn) { + s.mu.Lock() + delete(s.conns, c) + s.mu.Unlock() + _ = c.Close() +} + +func (s *connSet) Close() error { + s.mu.Lock() + defer s.mu.Unlock() + s.closed = true + for c := range s.conns { + _ = c.Close() + } + return nil +} + type loop struct { closer closer wg sync.WaitGroup diff --git a/examples/edge-provider/internal/dataplane/dataplane_test.go b/examples/edge-provider/internal/dataplane/dataplane_test.go new file mode 100644 index 000000000..b49e0e208 --- /dev/null +++ b/examples/edge-provider/internal/dataplane/dataplane_test.go @@ -0,0 +1,87 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package dataplane + +import ( + "context" + "io" + "log/slog" + "net" + "net/netip" + "strconv" + "testing" + "time" +) + +// TestEchoUDPAndTCP binds the echo to the loopback device, which needs no +// capability, and checks that both protocols answer with the identity +// prefix and that Close ends an open TCP connection. +func TestEchoUDPAndTCP(t *testing.T) { + ctx := context.Background() + var lc net.ListenConfig + ln, err := lc.Listen(ctx, "tcp6", "[::1]:0") + if err != nil { + t.Skipf("no IPv6 loopback: %v", err) + } + port := ln.Addr().(*net.TCPAddr).Port + _ = ln.Close() + addr := net.JoinHostPort("::1", strconv.Itoa(port)) + + d := net.Dialer{Timeout: 2 * time.Second} + s, err := Echo(ctx, slog.New(slog.NewTextHandler(io.Discard, nil)), "lo", + netip.MustParseAddr("::1"), uint16(port), "id-1") + if err != nil { + t.Skipf("cannot bind to lo: %v", err) + } + t.Cleanup(func() { _ = s.Close() }) + + for _, network := range []string{"udp6", "tcp6"} { + t.Run(network, func(t *testing.T) { + c, err := d.DialContext(ctx, network, addr) + if err != nil { + t.Fatal(err) + } + defer func() { _ = c.Close() }() + _ = c.SetDeadline(time.Now().Add(2 * time.Second)) + if _, err := c.Write([]byte("ping")); err != nil { + t.Fatal(err) + } + buf := make([]byte, 64) + n, err := c.Read(buf) + if err != nil { + t.Fatal(err) + } + if got := string(buf[:n]); got != "id-1 ping" { + t.Fatalf("reply %q, want %q", got, "id-1 ping") + } + }) + } + + // An answered exchange proves the server accepted the connection, so + // Close must end it rather than racing its accept. + c, err := d.DialContext(ctx, "tcp6", addr) + if err != nil { + t.Fatal(err) + } + defer func() { _ = c.Close() }() + _ = c.SetDeadline(time.Now().Add(5 * time.Second)) + if _, err := c.Write([]byte("hold")); err != nil { + t.Fatal(err) + } + buf := make([]byte, 64) + if _, err := c.Read(buf); err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + go func() { done <- s.Close() }() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("Close did not return with a TCP connection open") + } + if _, err := c.Read(buf); err == nil { + t.Fatal("the connection stayed open after Close") + } +} diff --git a/tests/edgeconformance/listener_test.go b/tests/edgeconformance/listener_test.go new file mode 100644 index 000000000..ae5e46329 --- /dev/null +++ b/tests/edgeconformance/listener_test.go @@ -0,0 +1,575 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package edgeconformance_test + +import ( + "context" + "fmt" + "math/rand/v2" + "net/netip" + "os" + "path/filepath" + "regexp" + "strconv" + "strings" + "testing" + "time" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + + networkv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" + galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" + "go.datum.net/galactic/internal/crdnames" +) + +// TestListenerBackend is Phase 0 of the Edge public listener design +// (docs/designs/edge-public-listener.md, #1507). It wires one SocketAccess +// attachment by hand as the backend of a gateway VIP, with no controller +// change, and sends UDP and TCP to it from the off-fabric host over both +// VIP families: +// +// - a dedicated ingress VPC, granted to a reference provider with +// SocketAccess only, under the lab's public-service traffic policy; +// - 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, +// the shape edge route publication writes; +// - one gateway-namespace NetworkService per protocol. +// +// The provider runs on edgeNode2. Remote delivery pins the VIP on the +// 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. +func TestListenerBackend(t *testing.T) { + l := getLab(t) + t.Cleanup(func() { l.writeSummary(t) }) + + p := &listenerProof{l: l, node: edgeNode2, used: map[int]bool{}} + // EDGE_CONFORMANCE_KEEP keeps the fixtures and the VIP's pins on tr1, + // for probing by hand. Delete the pins when done. + if os.Getenv("EDGE_CONFORMANCE_KEEP") == "" { + t.Cleanup(func() { p.teardown(t) }) + t.Cleanup(p.unpin) + } + + if !t.Run("setup", p.setup) { + t.FailNow() + } + + t.Run("remote-delivery", func(t *testing.T) { + for _, f := range listenerFamilies { + t.Run(f.name, func(t *testing.T) { + p.pin(t, f, edgeNode1) + before := p.l.rulePackets(t, edgeNode1, f.vip) + for _, proto := range listenerProtocols { + // The first flow waits for the gateway to program the + // rule; every later one must answer at once. + eventually(t, 2*time.Minute, 2*time.Second, proto+" through "+edgeNode1, func() (bool, error) { + err := p.request(f, proto) + return err == nil, err + }) + answered := 0 + for range listenerFlows { + if err := p.request(f, proto); err != nil { + t.Errorf("%s %s: %v", f.name, proto, err) + continue + } + answered++ + } + p.l.record(t, proto+" flows answered", fmt.Sprintf("%d/%d", answered, listenerFlows)) + } + peer := p.tcpPeer(t, f) + p.l.record(t, "backend saw client as", peer) + if want := f.clientAsSeen(); peer != want { + t.Errorf("backend saw the client as %q, want %q", peer, want) + } + after := p.l.rulePackets(t, edgeNode1, f.vip) + p.l.record(t, edgeNode1+" rule packets", after-before) + if after <= before { + t.Errorf("%s counted no packets for %s: another node served the VIP", edgeNode1, f.vip) + } + }) + } + }) + + t.Run("local-delivery", func(t *testing.T) { + for _, f := range listenerFamilies { + t.Run(f.name, func(t *testing.T) { + p.pin(t, f, p.node) + drops := p.l.gatewayDrops(t, p.node) + rule := p.l.rulePackets(t, p.node, f.vip) + for _, proto := range listenerProtocols { + answered := 0 + var last error + for range listenerFlows { + if err := p.request(f, proto); err != nil { + last = err + continue + } + answered++ + } + p.l.record(t, proto+" flows answered", fmt.Sprintf("%d/%d", answered, listenerFlows)) + if last != nil { + p.l.record(t, proto+" last failure", last) + } + } + p.l.record(t, p.node+" rule packets", + p.l.rulePackets(t, p.node, f.vip)-rule) + p.l.record(t, p.node+" drops by reason", diffDrops(drops, p.l.gatewayDrops(t, p.node))) + }) + } + }) +} + +// The proof's fixed values. The VIPs fall in dfw's gateway VIP prefixes, +// which dfw's edge nodes originate to the transit; the ingress VPC's +// identifier and prefix are used by no other lab tenant. +const ( + listenerVPCNamespace = "edge-ingress" + listenerVPC = "95" + listenerVPCNetwork = "fd00:ed95::/32" + listenerPool = "fd00:ed95:0:1::/64" + listenerProvider = "listener-proof" + listenerNamespace = "edge-listener" + listenerService = "listener" + listenerDeploy = "lp1" + listenerAdvert = "edge-listener-proof" + listenerLabel = "edge-listener-proof" + listenerPort = 443 + listenerFlows = 8 + protoUDP = "udp" + protoTCP = "tcp" + gatewayNamespace = "galactic-system" + gatewayMetricsPort = 8081 + remoteHostNode = "remote-host" +) + +// listenerFamily is one VIP family: its address, how the transit router +// pins it to a gateway, and the client's address on the off-fabric host. +type listenerFamily struct { + name string + vip string + client string + // uplinks maps each dfw gateway to its address on its tr1 link and + // tr1's bond to it; keep in step with scripts/verify-gateway-ingress*.sh. + uplinks map[string][2]string +} + +var listenerFamilies = []listenerFamily{ + {name: "ipv6", vip: "2001:db8:6060:1::95", client: "2001:db8:1:40::2", uplinks: map[string][2]string{ + edgeNode1: {"2001:db8:1:11::2", "bond1"}, edgeNode2: {"2001:db8:1:12::2", "bond2"}}}, + {name: "ipv4", vip: "198.51.100.30", client: "11.1.40.2", uplinks: map[string][2]string{ + edgeNode1: {"10.1.11.2", "bond1"}, edgeNode2: {"10.1.12.2", "bond2"}}}, +} + +// listenerProtocols are the protocols the proof serves, one NetworkService +// each. +var listenerProtocols = []string{protoUDP, protoTCP} + +func (f listenerFamily) v4() bool { return strings.Contains(f.vip, ".") } + +// clientAsSeen is the client's address as the IPv6-only backend sees it: +// itself for IPv6, and embedded under 64:ff9b::/96 for IPv4 (RFC 6052). +func (f listenerFamily) clientAsSeen() string { + if !f.v4() { + return f.client + } + a := netip.MustParseAddr(f.client).As4() + b := [16]byte{0, 0x64, 0xff, 0x9b} + copy(b[12:], a[:]) + return netip.AddrFrom16(b).String() +} + +type listenerProof struct { + l *lab + node string + addr string + pod 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 +} + +// sourcePort draws a client source port in 20000-59999 that no earlier +// flow of this run used. +func (p *listenerProof) sourcePort() int { + for { + port := 20000 + rand.IntN(40000) + if !p.used[port] { + p.used[port] = true + return port + } + } +} + +func (p *listenerProof) setup(t *testing.T) { + l := p.l + ctx := context.Background() + + // The ingress VPC and its traffic policy. The lab writes a VPC's + // identifier by hand, as deploy:galactic-edge does for ns10 and ns20. + l.ensureNamespace(t, listenerVPCNamespace) + p.applyYAML(t, "listener-vpc.yaml", fmt.Sprintf(`apiVersion: galactic.datumapis.com/v1alpha1 +kind: VPC +metadata: + name: %q + namespace: %s +spec: + networks: [%s] +`, listenerVPC, listenerVPCNamespace, listenerVPCNetwork)) + if _, err := l.kubectl("-n", listenerVPCNamespace, "patch", "vpc", listenerVPC, "--subresource=status", + "--type=merge", "-p", fmt.Sprintf(`{"status":{"vpc":%q}}`, listenerVPC)); err != nil { + t.Fatal(err) + } + 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. + 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.Prefixes = nil + s.Spec.ClientPool = listenerPool + }) + l.waitServiceAdmitted(t, svc, true) + l.deployProvider(t, tn.namespace, listenerDeploy, p.node, fmt.Sprintf(`provider: %s +port: %d +services: + - namespace: %s + name: %s + uid: %s + vpcUID: %s + capabilities: [SocketAccess] +`, tn.provider, echoPort, svc.Namespace, svc.Name, svc.UID, vpcUID)) + pod := l.waitProviderPod(t, tn.namespace, listenerDeploy, p.node) + p.pod = pod.Name + att := l.waitServing(t, pod, svc) + p.addr = netip.MustParseAddr(att.Status.Address).String() + 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 + // resolves a backend's uSID and galactic-router binds a VIP to it. It + // carries no edge-route label, so no forwarding gate withholds it. + var vrf networkv1alpha1.BGPVRFInstance + key := client.ObjectKey{Namespace: gatewayNamespace, Name: crdnames.BGPVRFInstanceName(listenerVPC, p.node)} + eventually(t, time.Minute, time.Second, "BGPVRFInstance "+key.Name, func() (bool, error) { + err := l.c.Get(ctx, key, &vrf) + return err == nil && vrf.Spec.RouterRef != nil && len(vrf.Spec.ExportRouteTargets) > 0, err + }) + vrfID := vrf.Spec.VRFID + fn := networkv1alpha1.SRv6FunctionEndDT46 + adv := &networkv1alpha1.BGPAdvertisement{ + ObjectMeta: metav1.ObjectMeta{Name: listenerAdvert, Namespace: gatewayNamespace}, + Spec: networkv1alpha1.BGPAdvertisementSpec{ + RouterRef: networkv1alpha1.RouterRef{Name: vrf.Spec.RouterRef.Name}, + AddressFamily: networkv1alpha1.AddressFamily{AFI: networkv1alpha1.AFIL2VPN, SAFI: networkv1alpha1.SAFIEVPN}, + Prefixes: []networkv1alpha1.Prefix{networkv1alpha1.Prefix(p.addr + "/128")}, + Communities: []networkv1alpha1.Community{networkv1alpha1.Community(vrf.Spec.ExportRouteTargets[0].Value)}, + VRFID: &vrfID, + Function: &fn, + }, + } + l.deleteAndWait(t, &networkv1alpha1.BGPAdvertisement{ObjectMeta: adv.ObjectMeta}) + if err := l.c.Create(ctx, adv); err != nil { + t.Fatal(err) + } + l.record(t, "advertisement", fmt.Sprintf("%s/128 vrfID %d router %s", p.addr, vrfID, vrf.Spec.RouterRef.Name)) + + // The stand-in backend: the gateway and galactic-router select + // VPCAttachments, so one names the edge attachment's address and node. + // It has no hostInterface, so neither traffic policy nor the health + // prober binds to it, and the services carry no health check. + p.applyYAML(t, "listener-backend.yaml", fmt.Sprintf(`apiVersion: galactic.datumapis.com/v1alpha1 +kind: VPCAttachment +metadata: + name: listener-backend + namespace: %s + labels: {app: %s} +spec: + vpc: {name: %q} + interface: + name: %s + mode: Netns + addresses: [%s/128] +`, listenerVPCNamespace, listenerLabel, listenerVPC, att.Status.HostLink, p.addr)) + if _, err := l.kubectl("-n", listenerVPCNamespace, "patch", "vpcattachment", "listener-backend", + "--subresource=status", "--type=merge", "-p", + fmt.Sprintf(`{"status":{"vpc":%q,"node":%q}}`, listenerVPC, p.node)); err != nil { + t.Fatal(err) + } + + var b strings.Builder + for _, proto := range listenerProtocols { + fmt.Fprintf(&b, `--- +apiVersion: galactic.datumapis.com/v1alpha1 +kind: NetworkService +metadata: + name: listener-proof-%s + namespace: %s +spec: + vpcRef: %q + vipAddresses: [%s, %s] + protocol: %s + port: %d + backendSelector: + matchLabels: {app: %s} + backendPort: %d +`, proto, gatewayNamespace, listenerVPC, listenerFamilies[0].vip, listenerFamilies[1].vip, proto, + listenerPort, listenerLabel, echoPort) + } + p.applyYAML(t, "listener-services.yaml", b.String()) + + // One binding per protocol per VIP on the backend's node, each Bound. + eventually(t, 3*time.Minute, 2*time.Second, "four Bound bindings for "+p.addr, func() (bool, error) { + var list networkv1alpha1.ServiceVIPBindingList + if err := l.c.List(ctx, &list, client.InNamespace(gatewayNamespace)); err != nil { + return false, err + } + bound := 0 + for _, sb := range list.Items { + a, err := netip.ParsePrefix(sb.Spec.BackendAddress) + if err != nil { + addr, aerr := netip.ParseAddr(sb.Spec.BackendAddress) + if aerr != nil { + continue + } + a = netip.PrefixFrom(addr, 128) + } + if a.Addr().String() == p.addr && + meta.IsStatusConditionTrue(sb.Status.Conditions, networkv1alpha1.ConditionTypeBound) { + bound++ + } + } + return bound == 4, fmt.Errorf("%d of 4 bound", bound) + }) +} + +// applyYAML writes body to the run's artifacts and applies it. +func (p *listenerProof) applyYAML(t *testing.T, name, body string) { + t.Helper() + path := filepath.Join(p.l.artifacts, name) + if err := os.WriteFile(path, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + if _, err := p.l.kubectl("apply", "-f", path); err != nil { + t.Fatal(err) + } +} + +// clab is the container name of a containerlab node of the lab. +func clab(node string) string { + lab := os.Getenv("LAB") + if lab == "" { + lab = "gvpc" + } + return "clab-" + lab + "-" + node +} + +func transitRouter() string { return clab("tr1") } + +// pin routes f's VIP from tr1 to gateway only, more specific than the +// prefix both dfw edge nodes originate. +func (p *listenerProof) pin(t *testing.T, f listenerFamily, gateway string) { + t.Helper() + up := f.uplinks[gateway] + fam, plen := "-6", "/128" + if f.v4() { + fam, plen = "-4", "/32" + } + if _, err := nodeExec(transitRouter(), "ip", fam, "route", "replace", f.vip+plen, "via", up[0], "dev", + up[1]); err != nil { + t.Fatal(err) + } +} + +// unpin removes both families' pins, whatever is pinned. +func (p *listenerProof) unpin() { + for _, f := range listenerFamilies { + fam, plen := "-6", "/128" + if f.v4() { + fam, plen = "-4", "/32" + } + _, _ = nodeExec(transitRouter(), "ip", fam, "route", "del", f.vip+plen) + } +} + +// request sends one flow from a fresh source port on the off-fabric host +// and checks the reply. The echo answers with its identity and the +// payload; a connected socat accepts a reply only from the VIP, so any +// answer also proves the reply's source. Only the first line counts: over +// UDP, socat ends its input with an empty datagram, which draws a second, +// identity-only echo. +func (p *listenerProof) request(f listenerFamily, proto string) error { + addr := p.socatAddress(f, proto, 0) + out, err := nodeExec(transitHost(), "sh", "-c", + "echo probe | timeout 5 socat -t2 -T3 - "+addr) + if err != nil { + return fmt.Errorf("%s: %w", addr, err) + } + reply, _, _ := strings.Cut(strings.TrimSpace(out), "\n") + if !strings.HasPrefix(reply, listenerProvider+"/") || !strings.HasSuffix(reply, " probe") { + return fmt.Errorf("%s: reply %q is not the provider's echo", addr, reply) + } + return nil +} + +func transitHost() string { return clab(remoteHostNode) } + +// socatAddress is a socat address for f and proto from sport, or from a +// random unprivileged port when sport is 0. +func (p *listenerProof) socatAddress(f listenerFamily, proto string, sport int) string { + if sport == 0 { + sport = p.sourcePort() + } + kind := strings.ToUpper(proto) + "6" + host := "[" + f.vip + "]" + if f.v4() { + kind, host = strings.ToUpper(proto)+"4", f.vip + } + return fmt.Sprintf("%s:%s:%d,sourceport=%d,reuseaddr", kind, host, listenerPort, sport) +} + +var ssPeer = regexp.MustCompile(`\[?([0-9a-fA-F:.]+)\]?:(\d+)\s*$`) + +// tcpPeer holds one TCP connection open through f's VIP and reads, from +// the provider pod's own network namespace, the address the backend sees +// as its peer. +func (p *listenerProof) tcpPeer(t *testing.T, f listenerFamily) string { + t.Helper() + sport := p.sourcePort() + done := make(chan error, 1) + go func() { + _, err := nodeExec(transitHost(), "sh", "-c", + "(echo probe; sleep 5) | timeout 8 socat -t6 - "+p.socatAddress(f, protoTCP, sport)) + done <- err + }() + defer func() { <-done }() + pid, err := sandboxPID(p.node, listenerNamespace, p.pod) + if err != nil { + t.Fatal(err) + } + var peer string + eventually(t, 5*time.Second, 200*time.Millisecond, "the backend's TCP connection", func() (bool, error) { + out, err := nodeExec(p.node, "nsenter", "-t", strconv.Itoa(pid), "-n", "ss", "-Htn", "state", + "established", "( sport = :"+strconv.Itoa(echoPort)+" )") + if err != nil { + return false, err + } + for _, line := range strings.Split(out, "\n") { + m := ssPeer.FindStringSubmatch(strings.TrimSpace(line)) + if m != nil && m[2] == strconv.Itoa(sport) { + a, err := netip.ParseAddr(m[1]) + if err != nil { + return false, err + } + peer = a.Unmap().String() + return true, nil + } + } + return false, fmt.Errorf("no connection from port %d in %q", sport, out) + }) + return peer +} + +// gatewayMetrics scrapes a gateway's metrics endpoint. +func (l *lab) gatewayMetrics(t *testing.T, node string) string { + t.Helper() + out, err := nodeExec(node, "curl", "-s", "--max-time", "4", + "http://localhost:"+strconv.Itoa(gatewayMetricsPort)+"/metrics") + if err != nil { + t.Fatal(err) + } + return out +} + +// rulePackets sums node's galactic_edge_rule_packets_total samples for vip. +func (l *lab) rulePackets(t *testing.T, node, vip string) float64 { + t.Helper() + var sum float64 + for _, line := range strings.Split(l.gatewayMetrics(t, node), "\n") { + if strings.HasPrefix(line, "galactic_edge_rule_packets_total{") && strings.Contains(line, `vip="`+vip+`"`) { + sum += sampleValue(line) + } + } + return sum +} + +// gatewayDrops returns node's galactic_edge_drops_total samples by labels. +func (l *lab) gatewayDrops(t *testing.T, node string) map[string]float64 { + t.Helper() + m := map[string]float64{} + for _, line := range strings.Split(l.gatewayMetrics(t, node), "\n") { + if strings.HasPrefix(line, "galactic_edge_drops_total") { + i := strings.LastIndexByte(line, ' ') + m[line[:i]] += sampleValue(line) + } + } + return m +} + +func sampleValue(line string) float64 { + f := strings.Fields(line) + if len(f) == 0 { + return 0 + } + v, _ := strconv.ParseFloat(f[len(f)-1], 64) + return v +} + +// diffDrops lists the drop series that rose between two scrapes. +func diffDrops(before, after map[string]float64) string { + var rose []string + for k, v := range after { + if d := v - before[k]; d > 0 { + rose = append(rose, fmt.Sprintf("%s +%g", k, d)) + } + } + if len(rose) == 0 { + return "none" + } + return strings.Join(rose, "; ") +} + +// teardown removes everything setup created, services first so the VIP's +// bindings go before their backend. +func (p *listenerProof) teardown(t *testing.T) { + l := p.l + for _, proto := range listenerProtocols { + _, _ = l.kubectl("-n", gatewayNamespace, "delete", "networkservice", "listener-proof-"+proto, + "--ignore-not-found", "--wait=true", "--timeout=120s") + } + _, _ = l.kubectl("-n", gatewayNamespace, "delete", "bgpadvertisement", listenerAdvert, "--ignore-not-found") + if _, err := l.kubectl("delete", "namespace", listenerNamespace, "--ignore-not-found", "--wait=true", + "--timeout=180s"); err != nil { + t.Error(err) + } + l.unapprove(listenerProvider) + _ = l.c.Delete(context.Background(), &galacticv1alpha1.EdgeProvider{ObjectMeta: metav1.ObjectMeta{ + Name: listenerProvider}}) + if _, err := l.kubectl("delete", "namespace", listenerVPCNamespace, "--ignore-not-found", "--wait=true", + "--timeout=180s"); err != nil { + t.Error(err) + } + + // galactic-router GC removes the ingress VPC's BGPVRFInstance, and with + // it the VPC's routes, on its next pass once nothing on the node uses the + // VPC. Wait for that, so the lab is handed back as it was found. + start := time.Now() + key := client.ObjectKey{Namespace: gatewayNamespace, Name: crdnames.BGPVRFInstanceName(listenerVPC, p.node)} + eventually(t, l.gcInterval(t)+2*time.Minute, 5*time.Second, "release of "+key.Name, func() (bool, error) { + var inst networkv1alpha1.BGPVRFInstance + err := l.c.Get(context.Background(), key, &inst) + return apierrors.IsNotFound(err), client.IgnoreNotFound(err) + }) + l.record(t, "ingress VPC state released after", time.Since(start).Round(time.Second)) +}