From 6fbb1025b2872c7749f09f5c48cc1974e265ea0a Mon Sep 17 00:00:00 2001 From: Brad Fitzpatrick Date: Fri, 5 Jun 2026 16:59:02 +0000 Subject: [PATCH] tstest/natlab/vmtest: add asymmetric subnet route UDP test Updates #19612 Change-Id: I19836da9fea3feece8bcf2b49397a244c989f93b Signed-off-by: Brad Fitzpatrick --- cmd/tta/tta.go | 194 ++++++++++++++++++++++++++++ tstest/natlab/vmtest/vmtest.go | 26 ++++ tstest/natlab/vmtest/vmtest_test.go | 101 +++++++++++++++ 3 files changed, 321 insertions(+) diff --git a/cmd/tta/tta.go b/cmd/tta/tta.go index bbc6dbcda..9255027bf 100644 --- a/cmd/tta/tta.go +++ b/cmd/tta/tta.go @@ -13,6 +13,7 @@ package main import ( "bytes" "context" + "encoding/json" "errors" "flag" "fmt" @@ -30,6 +31,7 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "time" "tailscale.com/atomicfile" @@ -81,6 +83,195 @@ func serveCmd(w http.ResponseWriter, cmd string, args ...string) { w.Write(out) } +var asymUDP asymUDPState + +type asymUDPState struct { + mu sync.Mutex + started bool + a atomic.Int64 + b atomic.Int64 + lastASource string + lastBSource string + lastPong string +} + +type asymUDPStatus struct { + A int64 `json:"a"` + B int64 `json:"b"` + LastASource string `json:"lastASource,omitempty"` + LastBSource string `json:"lastBSource,omitempty"` + LastPong string `json:"lastPong,omitempty"` +} + +func asymUDPClientHandler(w http.ResponseWriter, r *http.Request) { + port, err := strconv.Atoi(r.URL.Query().Get("port")) + if err != nil || port <= 0 || port > 65535 { + http.Error(w, "bad port", http.StatusBadRequest) + return + } + token := r.URL.Query().Get("token") + if token == "" { + http.Error(w, "missing token", http.StatusBadRequest) + return + } + + asymUDP.mu.Lock() + if asymUDP.started { + asymUDP.mu.Unlock() + io.WriteString(w, "already running\n") + return + } + asymUDP.started = true + asymUDP.mu.Unlock() + + uc, err := net.ListenUDP("udp4", &net.UDPAddr{Port: port}) + if err != nil { + asymUDP.mu.Lock() + asymUDP.started = false + asymUDP.mu.Unlock() + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + dst := &net.UDPAddr{IP: net.ParseIP("10.0.0.1"), Port: port} + go func() { + var buf [2048]byte + for { + n, addr, err := uc.ReadFromUDP(buf[:]) + if err != nil { + log.Printf("asym-udp-client read: %v", err) + return + } + msg := string(buf[:n]) + switch { + case strings.HasPrefix(msg, "A-"): + asymUDP.a.Add(1) + asymUDP.mu.Lock() + asymUDP.lastASource = addr.IP.String() + asymUDP.mu.Unlock() + case strings.HasPrefix(msg, "B-"): + asymUDP.b.Add(1) + asymUDP.mu.Lock() + asymUDP.lastBSource = addr.IP.String() + asymUDP.mu.Unlock() + case strings.HasPrefix(msg, "PONG-"): + asymUDP.mu.Lock() + asymUDP.lastPong = msg + asymUDP.mu.Unlock() + } + log.Printf("asym-udp-client RX %q from %v", msg, addr) + } + }() + go func() { + ticker := time.NewTicker(time.Second) + defer ticker.Stop() + payload := []byte("PING-" + token) + for range ticker.C { + if _, err := uc.WriteToUDP(payload, dst); err != nil { + log.Printf("asym-udp-client write: %v", err) + return + } + log.Printf("asym-udp-client TX %q to %v", payload, dst) + } + }() + io.WriteString(w, "OK\n") +} + +func asymUDPRouterHandler(w http.ResponseWriter, r *http.Request) { + label := r.URL.Query().Get("label") + if label != "A" && label != "B" { + http.Error(w, "bad label", http.StatusBadRequest) + return + } + client := net.ParseIP(r.URL.Query().Get("client")) + if client == nil || client.To4() == nil { + http.Error(w, "bad client", http.StatusBadRequest) + return + } + port, err := strconv.Atoi(r.URL.Query().Get("port")) + if err != nil || port <= 0 || port > 65535 { + http.Error(w, "bad port", http.StatusBadRequest) + return + } + if runtime.GOOS != "linux" { + http.Error(w, "asym-udp-router only supports linux", http.StatusNotImplemented) + return + } + for _, args := range [][]string{ + {"addr", "add", "10.0.0.1/32", "dev", "lo"}, + } { + if out, err := exec.Command("ip", args...).CombinedOutput(); err != nil && !bytes.Contains(out, []byte("File exists")) { + http.Error(w, fmt.Sprintf("ip %v: %v\n%s", args, err, out), http.StatusInternalServerError) + return + } + } + for _, args := range [][]string{ + {"-w", "net.ipv4.conf.all.rp_filter=0"}, + {"-w", "net.ipv4.conf.default.rp_filter=0"}, + } { + if out, err := exec.Command("sysctl", args...).CombinedOutput(); err != nil { + http.Error(w, fmt.Sprintf("sysctl %v: %v\n%s", args, err, out), http.StatusInternalServerError) + return + } + } + + uc, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.ParseIP("10.0.0.1"), Port: port}) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + go func() { + var buf [2048]byte + for { + n, addr, err := uc.ReadFromUDP(buf[:]) + if err != nil { + log.Printf("asym-udp-router-%s read: %v", label, err) + return + } + msg := string(buf[:n]) + log.Printf("asym-udp-router-%s RX %q from %v", label, msg, addr) + if strings.HasPrefix(msg, "PING-") { + pong := []byte("PONG-" + label + "-" + strings.TrimPrefix(msg, "PING-")) + if _, err := uc.WriteToUDP(pong, addr); err != nil { + log.Printf("asym-udp-router-%s pong: %v", label, err) + return + } + log.Printf("asym-udp-router-%s TX %q to %v", label, pong, addr) + } + } + }() + go func() { + ticker := time.NewTicker(200 * time.Millisecond) + defer ticker.Stop() + dst := &net.UDPAddr{IP: client, Port: port} + var seq int64 + for range ticker.C { + payload := []byte(fmt.Sprintf("%s-%d", label, seq)) + if _, err := uc.WriteToUDP(payload, dst); err != nil { + log.Printf("asym-udp-router-%s write: %v", label, err) + return + } + seq++ + } + }() + io.WriteString(w, "OK\n") +} + +func asymUDPStatusHandler(w http.ResponseWriter, r *http.Request) { + asymUDP.mu.Lock() + st := asymUDPStatus{ + A: asymUDP.a.Load(), + B: asymUDP.b.Load(), + LastASource: asymUDP.lastASource, + LastBSource: asymUDP.lastBSource, + LastPong: asymUDP.lastPong, + } + asymUDP.mu.Unlock() + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(st); err != nil { + log.Printf("asym-udp-status encode: %v", err) + } +} + type localClientRoundTripper struct { lc local.Client } @@ -401,6 +592,9 @@ func main() { w.WriteHeader(resp.StatusCode) io.Copy(w, resp.Body) }) + ttaMux.HandleFunc("/asym-udp-client", asymUDPClientHandler) + ttaMux.HandleFunc("/asym-udp-router", asymUDPRouterHandler) + ttaMux.HandleFunc("/asym-udp-status", asymUDPStatusHandler) ttaMux.HandleFunc("/fw", addFirewallHandler) ttaMux.HandleFunc("/wg-server-up", func(w http.ResponseWriter, r *http.Request) { if wgServerUp == nil { diff --git a/tstest/natlab/vmtest/vmtest.go b/tstest/natlab/vmtest/vmtest.go index 6f5abdc97..95745ebeb 100644 --- a/tstest/natlab/vmtest/vmtest.go +++ b/tstest/natlab/vmtest/vmtest.go @@ -1237,6 +1237,32 @@ func (e *Env) AddRoute(n *Node, prefix, via string) { } } +// AgentGet makes an HTTP GET request to the TTA agent running on n. The path +// must begin with "/". It returns the response body, or fatals the test on +// non-200 responses. +func (e *Env) AgentGet(n *Node, path string) string { + e.t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if !strings.HasPrefix(path, "/") { + e.t.Fatalf("AgentGet(%s): path %q does not start with /", n.name, path) + } + req, err := http.NewRequestWithContext(ctx, "GET", "http://unused"+path, nil) + if err != nil { + e.t.Fatalf("AgentGet(%s, %q): %v", n.name, path, err) + } + resp, err := n.agent.HTTPClient.Do(req) + if err != nil { + e.t.Fatalf("AgentGet(%s, %q): %v", n.name, path, err) + } + defer resp.Body.Close() + body, _ := io.ReadAll(resp.Body) + if resp.StatusCode != 200 { + e.t.Fatalf("AgentGet(%s, %q): %s: %s", n.name, path, resp.Status, body) + } + return string(body) +} + // SSHExec runs a command on a cloud VM via its debug SSH NIC. // Only works for cloud VMs that have the debug NIC and SSH key configured. // Returns stdout and any error. diff --git a/tstest/natlab/vmtest/vmtest_test.go b/tstest/natlab/vmtest/vmtest_test.go index ec6bfd86b..746bfe614 100644 --- a/tstest/natlab/vmtest/vmtest_test.go +++ b/tstest/natlab/vmtest/vmtest_test.go @@ -6,6 +6,9 @@ package vmtest_test import ( "bytes" "context" + "crypto/rand" + "encoding/hex" + "encoding/json" "fmt" "net/netip" "runtime" @@ -213,6 +216,76 @@ func testSiteToSite(t *testing.T, srOS vmtest.OSImage) { httpStep.End(nil) } +// TestAsymmetricSubnetRouteUDP demonstrates two subnet routers advertising the +// same route and sourcing traffic from the same non-Tailscale IP. The client +// should receive UDP from both routers as 10.0.0.1, and a client-originated +// UDP ping to 10.0.0.1 should route through one router and get a labeled pong. +func TestAsymmetricSubnetRouteUDP(t *testing.T) { + env := vmtest.New(t, vmtest.AllOnline()) + + clientNet := env.AddNetwork("2.1.1.1", "192.168.1.1/24", vnet.EasyNAT) + routerANet := env.AddNetwork("3.1.1.1", "192.168.2.1/24", vnet.EasyNAT) + routerBNet := env.AddNetwork("4.1.1.1", "192.168.3.1/24", vnet.EasyNAT) + + client := env.AddNode("client", clientNet, + vmtest.OS(vmtest.Ubuntu2404)) + routerA := env.AddNode("subnet-router-a", routerANet, + vmtest.OS(vmtest.Ubuntu2404), + vmtest.AdvertiseRoutes("10.0.0.0/8"), + vmtest.SNATSubnetRoutes(false)) + routerB := env.AddNode("subnet-router-b", routerBNet, + vmtest.OS(vmtest.Ubuntu2404), + vmtest.AdvertiseRoutes("10.0.0.0/8"), + vmtest.SNATSubnetRoutes(false)) + + approveStep := env.AddStep("Approve duplicate subnet routes") + configStep := env.AddStep("Configure UDP workers") + udpStep := env.AddStep("Verify asymmetric UDP") + + env.Start() + + approveStep.Begin() + env.ApproveRoutes(routerA, "10.0.0.0/8") + env.ApproveRoutes(routerB, "10.0.0.0/8") + approveStep.End(nil) + + configStep.Begin() + clientIP := mustStatusTailscaleIPv4(t, env, client) + token := randomHex(t, 8) + const port = 31987 + env.AgentGet(client, fmt.Sprintf("/asym-udp-client?port=%d&token=%s", port, token)) + env.AgentGet(routerA, fmt.Sprintf("/asym-udp-router?label=A&client=%s&port=%d", clientIP, port)) + env.AgentGet(routerB, fmt.Sprintf("/asym-udp-router?label=B&client=%s&port=%d", clientIP, port)) + configStep.End(nil) + + udpStep.Begin() + var st asymUDPStatus + err := tstest.WaitFor(45*time.Second, func() error { + body := env.AgentGet(client, "/asym-udp-status") + if err := json.Unmarshal([]byte(body), &st); err != nil { + return err + } + if st.A == 0 || st.B == 0 { + return fmt.Errorf("UDP counts: A=%d B=%d", st.A, st.B) + } + if st.LastASource != "10.0.0.1" || st.LastBSource != "10.0.0.1" { + return fmt.Errorf("UDP sources: A=%q B=%q, want both 10.0.0.1; UDP counts: A=%d B=%d", st.LastASource, st.LastBSource, st.A, st.B) + } + if st.LastPong != "PONG-A-"+token && st.LastPong != "PONG-B-"+token { + return fmt.Errorf("last pong = %q, want PONG-[AB]-%s; UDP counts: A=%d B=%d", st.LastPong, token, st.A, st.B) + } + return nil + }) + if err != nil { + env.DumpStatus(client) + udpStep.Fatalf("waiting for asymmetric UDP traffic: %v", err) + } + t.Logf("client UDP counts: A=%d B=%d", st.A, st.B) + t.Logf("client UDP sources: A=%s B=%s", st.LastASource, st.LastBSource) + t.Logf("client UDP pong: %s", st.LastPong) + udpStep.End(nil) +} + // TestInterNetworkTCP verifies that vnet routes raw TCP between simulated // networks: a non-Tailscale VM on one NAT'd LAN can reach a webserver on a // different network using a 1:1 NAT, and the webserver sees the client's @@ -1340,3 +1413,31 @@ func TestPeerRelay(t *testing.T) { session.VNI, session.Client1.ShortDisco, session.Client2.ShortDisco, *srv.UDPPort) sessionsStep.End(nil) } + +type asymUDPStatus struct { + A int64 `json:"a"` + B int64 `json:"b"` + LastASource string `json:"lastASource"` + LastBSource string `json:"lastBSource"` + LastPong string `json:"lastPong"` +} + +func mustStatusTailscaleIPv4(t *testing.T, env *vmtest.Env, n *vmtest.Node) string { + t.Helper() + for _, ip := range env.Status(n).Self.TailscaleIPs { + if ip.Is4() { + return ip.String() + } + } + t.Fatalf("%s has no IPv4 Tailscale IP", n.Name()) + panic("unreachable") +} + +func randomHex(t *testing.T, n int) string { + t.Helper() + b := make([]byte, n) + if _, err := rand.Read(b); err != nil { + t.Fatalf("rand.Read: %v", err) + } + return hex.EncodeToString(b) +}