wgengine, wgengine/magicsock, derp/derphttp: add memnet test hooks

To enable synctest across more and more Tailscale tests, this wires up
some existing test-only hooks more, and adds another.

With them and a memnet.Network (and #22833 for memnet UDP support), a
test can run full userspace engines, their DERP server and a STUN
server in a testing/synctest bubble.
 
Updates #22831

Change-Id: I751775a1b3d8c89cbc9d669951f0ec22a00d9696
Signed-off-by: Brad Fitzpatrick <[email protected]>
This commit is contained in:
Brad Fitzpatrick authored and Brad Fitzpatrick committed 2026-12-02 17:39:02 -08:00
1 parent ebb46e100d
commit 24feea8da5
5 files changed
+100 -7

No files matched your search

+14 -5
View File
@@ -668,12 +668,18 @@ func (c *Client) connectLocked(ctx context.Context, caller string, upgradeWebsoc
return c.client, c.connGen, nil
}
// SetURLDialer sets the dialer to use for dialing URLs.
// This dialer is only use for clients created with NewClient, not NewRegionClient.
// If unset or nil, the default dialer is used.
// SetURLDialer sets the dialer to use for the client's TCP connections to
// the DERP server, in place of the default dialer. If unset or nil, the
// default dialer is used.
//
// For clients created with NewClient, it dials the URL's host and port.
// For clients created with NewRegionClient, it dials each node's address
// and port (an IP from the DERP map if set, else the node's hostname),
// and HTTP proxies from the environment are not used.
//
// The primary use for this is the derper mesh mode to connect to each
// other over a VPC network.
// other over a VPC network. Tests also use it to run DERP over an
// in-memory network.
func (c *Client) SetURLDialer(dialer netx.DialFunc) {
c.dialer = dialer
}
@@ -786,6 +792,9 @@ func (c *Client) DialRegionTLS(ctx context.Context, reg *tailcfg.DERPRegion) (tl
}
func (c *Client) dialContext(ctx context.Context, proto, addr string) (net.Conn, error) {
if c.dialer != nil {
return c.dialer(ctx, proto, addr)
}
return netns.NewDialer(c.logf, c.netMon).DialContext(ctx, proto, addr)
}
@@ -819,7 +828,7 @@ func (c *Client) dialNode(ctx context.Context, n *tailcfg.DERPNode) (net.Conn, e
Path: "/", // unused
},
}
if buildfeatures.HasUseProxy {
if buildfeatures.HasUseProxy && c.dialer == nil {
if proxyFromEnv, ok := feature.HookProxyFromEnvironment.GetOk(); ok {
if proxyURL, err := proxyFromEnv(proxyReq); err == nil && proxyURL != nil {
return c.dialNodeUsingProxy(ctx, n, proxyURL)
+44
View File
@@ -745,3 +745,47 @@ func TestConnectThroughProxyHonorsDERPPort(t *testing.T) {
t.Errorf("proxy CONNECT target = %q, want %q", got, want)
}
}
// TestRegionClientURLDialer checks that a region client dials its nodes
// with the dialer from SetURLDialer, instead of the OS or an HTTP proxy
// from the environment.
func TestRegionClientURLDialer(t *testing.T) {
restore := feature.HookProxyFromEnvironment.SetForTest(func(*http.Request) (*url.URL, error) {
return url.Parse("http://127.0.0.1:1") // must not be used
})
defer restore()
region := &tailcfg.DERPRegion{
RegionID: 1,
RegionCode: "test",
Nodes: []*tailcfg.DERPNode{{
Name: "1a",
RegionID: 1,
HostName: "derp.example.com",
IPv4: "127.0.0.1",
IPv6: "none",
DERPPort: 1234,
}},
}
c := derphttp.NewRegionClient(key.NewNode(), t.Logf, netmon.NewStatic(),
func() *tailcfg.DERPRegion { return region })
defer c.Close()
errTestDial := errors.New("test dial")
var mu sync.Mutex
var dials []string
c.SetURLDialer(func(ctx context.Context, network, addr string) (net.Conn, error) {
mu.Lock()
defer mu.Unlock()
dials = append(dials, network+" "+addr)
return nil, errTestDial
})
if err := c.Connect(t.Context()); !errors.Is(err, errTestDial) {
t.Fatalf("Connect = %v; want error wrapping %v", err, errTestDial)
}
mu.Lock()
defer mu.Unlock()
if want := []string{"tcp4 127.0.0.1:1234"}; !slices.Equal(dials, want) {
t.Errorf("dials = %q; want %q", dials, want)
}
}
+3
View File
@@ -423,6 +423,9 @@ func (c *Conn) derpWriteChanForRegion(regionID tailcfg.DERPRegionID, peer key.No
dc.NotePreferred(c.myDerp == regionID)
dc.SetAddressFamilySelector(derpAddrFamSelector{c})
dc.DNSCache = dnscache.Get()
if c.testOnlyDERPDialer != nil {
dc.SetURLDialer(c.testOnlyDERPDialer)
}
ctx, cancel := context.WithCancel(c.connCtx)
ch := make(chan derpWriteRequest, derpWriteQueueDepth)
+22 -2
View File
@@ -41,6 +41,7 @@ import (
"tailscale.com/net/neterror"
"tailscale.com/net/netmon"
"tailscale.com/net/netns"
"tailscale.com/net/netx"
"tailscale.com/net/packet"
"tailscale.com/net/ping"
"tailscale.com/net/portmapper/portmappertype"
@@ -166,6 +167,7 @@ type Conn struct {
derpActiveFunc func()
idleFunc func() time.Duration // nil means unknown
testOnlyPacketListener nettype.PacketListener
testOnlyDERPDialer netx.DialFunc // or nil
onDERPRecv func(tailcfg.DERPRegionID, key.NodePublic, []byte) bool // or nil, see Options.OnDERPRecv
netMon *netmon.Monitor // must be non-nil
health *health.Tracker // or nil
@@ -219,6 +221,7 @@ type Conn struct {
bind *connBind
// cloudInfo is used to query cloud metadata services.
// It's nil if disabled; see Options.TestOnlyPacketListener.
cloudInfo *cloudinfo.CloudInfo
// ============================================================
@@ -491,8 +494,18 @@ type Options struct {
// TestOnlyPacketListener optionally specifies how to create PacketConns.
// Only used by tests.
//
// If set, the portmapper and cloud metadata lookups are disabled,
// as the router and cloud instance they would talk to are on the
// real network, not the one the PacketConns are on.
TestOnlyPacketListener nettype.PacketListener
// TestOnlyDERPDialer optionally specifies how to dial the TCP
// connections to DERP servers. Only used by tests, such as to run
// DERP over an in-memory network with [TestOnlyPacketListener].
// See [derphttp.Client.SetURLDialer].
TestOnlyDERPDialer netx.DialFunc
// NetMon is the network monitor to use.
// It must be non-nil.
NetMon *netmon.Monitor
@@ -678,6 +691,10 @@ func NewConn(opts Options) (*Conn, error) {
c.derpActiveFunc = opts.derpActiveFunc()
c.idleFunc = opts.IdleFunc
c.testOnlyPacketListener = opts.TestOnlyPacketListener
c.testOnlyDERPDialer = opts.TestOnlyDERPDialer
if opts.TestOnlyPacketListener != nil {
c.cloudInfo = nil
}
c.onDERPRecv = opts.OnDERPRecv
// Set up publishers and subscribers. Subscribe calls must return before
@@ -699,7 +716,7 @@ func NewConn(opts Options) (*Conn, error) {
// Don't log the same log messages possibly every few seconds in our
// portmapper.
if buildfeatures.HasPortMapper && !opts.DisablePortMapper {
if buildfeatures.HasPortMapper && !opts.DisablePortMapper && opts.TestOnlyPacketListener == nil {
portmapperLogf := logger.WithPrefix(c.logf, "portmapper: ")
portmapperLogf = netmon.LinkChangeLogLimiter(c.connCtx, portmapperLogf, opts.NetMon)
var disableUPnP func() bool
@@ -1384,7 +1401,10 @@ func (c *Conn) determineEndpoints(ctx context.Context) ([]tailcfg.Endpoint, erro
// If we're on a cloud instance, we might have a public IPv4 or IPv6
// address that we can be reached at. Find those, if they exist, and
// add them.
if addrs, err := c.cloudInfo.GetPublicIPs(ctx); err == nil {
if c.cloudInfo == nil {
// Omitted from the build, or disabled by
// Options.TestOnlyPacketListener.
} else if addrs, err := c.cloudInfo.GetPublicIPs(ctx); err == nil {
var port4, port6 uint16
if addr := c.pconn4.LocalAddr(); addr != nil {
port4 = uint16(addr.Port)
+17
View File
@@ -33,6 +33,7 @@ import (
"tailscale.com/net/dns/resolver"
"tailscale.com/net/ipset"
"tailscale.com/net/netmon"
"tailscale.com/net/netx"
"tailscale.com/net/packet"
"tailscale.com/net/routemanager"
"tailscale.com/net/sockstats"
@@ -46,6 +47,7 @@ import (
"tailscale.com/types/ipproto"
"tailscale.com/types/key"
"tailscale.com/types/logger"
"tailscale.com/types/nettype"
"tailscale.com/types/views"
"tailscale.com/util/checkchange"
"tailscale.com/util/clientmetric"
@@ -268,6 +270,18 @@ type Config struct {
// WireGuard. The pkt slice is borrowed and must be copied if
// the callee needs to retain it.
OnDERPRecv func(regionID tailcfg.DERPRegionID, src key.NodePublic, pkt []byte) (handled bool)
// TestOnlyPacketListener, if non-nil, creates magicsock's UDP sockets
// instead of the OS. It's for tests that run the engine on an
// in-memory network, such as [tailscale.com/net/memnet.Network], in a
// [testing/synctest] bubble. See
// [magicsock.Options.TestOnlyPacketListener].
TestOnlyPacketListener nettype.PacketListener
// TestOnlyDERPDialer, if non-nil, dials magicsock's TCP connections to
// DERP servers instead of the OS. It's the TCP counterpart to
// TestOnlyPacketListener. See [magicsock.Options.TestOnlyDERPDialer].
TestOnlyDERPDialer netx.DialFunc
}
// NewFakeUserspaceEngine returns a new userspace engine for testing.
@@ -444,6 +458,9 @@ func NewUserspaceEngine(logf logger.Logf, conf Config) (_ Engine, reterr error)
PeerByKeyFunc: e.PeerByKey,
ForceDiscoKey: conf.ForceDiscoKey,
OnDERPRecv: conf.OnDERPRecv,
TestOnlyPacketListener: conf.TestOnlyPacketListener,
TestOnlyDERPDialer: conf.TestOnlyDERPDialer,
}
var err error
e.magicConn, err = magicsock.NewConn(magicsockOpts)