diff --git a/derp/derphttp/derphttp_client.go b/derp/derphttp/derphttp_client.go index 2a6ed23b1..7d1b9965f 100644 --- a/derp/derphttp/derphttp_client.go +++ b/derp/derphttp/derphttp_client.go @@ -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) diff --git a/derp/derphttp/derphttp_test.go b/derp/derphttp/derphttp_test.go index 3fd40ddac..0febde6a1 100644 --- a/derp/derphttp/derphttp_test.go +++ b/derp/derphttp/derphttp_test.go @@ -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) + } +} diff --git a/wgengine/magicsock/derp.go b/wgengine/magicsock/derp.go index b360202f7..36eff710c 100644 --- a/wgengine/magicsock/derp.go +++ b/wgengine/magicsock/derp.go @@ -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) diff --git a/wgengine/magicsock/magicsock.go b/wgengine/magicsock/magicsock.go index b13f37d36..21406ccd9 100644 --- a/wgengine/magicsock/magicsock.go +++ b/wgengine/magicsock/magicsock.go @@ -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) diff --git a/wgengine/userspace.go b/wgengine/userspace.go index af9e139de..e5d430aa4 100644 --- a/wgengine/userspace.go +++ b/wgengine/userspace.go @@ -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)