net/netns: compose caller ControlContext with namespace setup

Prepare for shared socket policy for DERP, control, and log uploads.
Callers need to configure options such as TCP user timeout on the same
socket that netns configures to avoid routing loops.

Use ControlContext for dialer namespace setup and run any caller-supplied
ControlContext afterward, only if namespace setup succeeds. Reject a
non-nil Control unconditionally with a panic directing callers to
ControlContext, including when netns is disabled, rather than support
both hook types and their precedence rules. Listener Control hooks
remain unchanged.

Existing in-tree FromDialer callers supply neither hook, so no caller
migration is required. Keep socket defaults and proxy-wrapping behavior
unchanged. Test hook ordering, context and argument forwarding, errors,
legacy-hook rejection, disabled mode, and proxy delegation.

Updates tailscale/corp#50948

Change-Id: I9d778273f3257fe8a298463ef29ec2dd5d5fb7b0
Signed-off-by: James Tucker <[email protected]>
This commit is contained in:
James Tucker committed 2026-11-11 00:50:19 +00:00
1 parent 1f6259a88b
commit dcc58e2ee3
2 files changed
+207 -6

No files matched your search

+176
View File
@@ -0,0 +1,176 @@
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
package netns
import (
"context"
"errors"
"fmt"
"net"
"slices"
"syscall"
"testing"
"tailscale.com/net/netmon"
)
func TestSetNamespaceControl(t *testing.T) {
for _, callerHook := range []bool{false, true} {
for _, failure := range []string{"none", "namespace", "caller"} {
t.Run(fmt.Sprintf("caller=%v/%s", callerHook, failure), func(t *testing.T) {
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
raw := &struct{ syscall.RawConn }{}
const network, address = "tcp4", "192.0.2.1:443"
var calls []string
namespaceErr := errors.New("namespace failed")
callerErr := errors.New("caller failed")
check := func(name, n, a string, c syscall.RawConn) {
t.Helper()
calls = append(calls, name)
if n != network || a != address || c != raw {
t.Errorf("%s arguments = (%q, %q, %v); want (%q, %q, %v)", name, n, a, c, network, address, raw)
}
}
var d net.Dialer
if callerHook {
d.ControlContext = func(gotCtx context.Context, n, a string, c syscall.RawConn) error {
check("caller", n, a, c)
if gotCtx != ctx {
t.Error("ControlContext context was replaced")
}
if failure == "caller" {
return callerErr
}
return nil
}
}
setNamespaceControl(&d, func(n, a string, c syscall.RawConn) error {
check("namespace", n, a, c)
if failure == "namespace" {
return namespaceErr
}
return nil
})
if d.Control != nil {
t.Fatal("namespace setup installed Control instead of ControlContext")
}
err := d.ControlContext(ctx, network, address, raw)
wantCalls := []string{"namespace"}
var wantErr error
if failure == "namespace" {
wantErr = namespaceErr
} else if callerHook {
wantCalls = append(wantCalls, "caller")
if failure == "caller" {
wantErr = callerErr
}
}
if err != wantErr {
t.Errorf("error = %v; want %v", err, wantErr)
}
if !slices.Equal(calls, wantCalls) {
t.Errorf("calls = %v; want %v", calls, wantCalls)
}
})
}
}
}
func TestFromDialerControlContext(t *testing.T) {
// These globals also control proxy wrapping on platforms without SOCKS.
// Do not run this test in parallel.
wasDisabled, origWrap := disabled.Load(), wrapDialer
t.Cleanup(func() {
disabled.Store(wasDisabled)
wrapDialer = origWrap
})
for _, disable := range []bool{false, true} {
for _, proxy := range []bool{false, true} {
for _, callerHook := range []bool{false, true} {
t.Run(fmt.Sprintf("disabled=%v/proxy=%v/caller=%v", disable, proxy, callerHook), func(t *testing.T) {
disabled.Store(disable)
wrapDialer = nil // do not depend on the process proxy environment
wrapped := false
if proxy {
wrapDialer = func(d Dialer) Dialer {
wrapped = true
return &controlTestProxy{d}
}
}
callerErr := errors.New("caller stopped dial")
called := false
d := &net.Dialer{KeepAlive: -1}
if callerHook {
d.ControlContext = func(context.Context, string, string, syscall.RawConn) error {
called = true
return callerErr
}
}
got := FromDialer(t.Logf, netmon.NewStatic(), d)
if want := proxy && !disable; wrapped != want {
t.Errorf("proxy wrapped = %v; want %v", wrapped, want)
}
if disable && got != d {
t.Error("disabled FromDialer did not return the original dialer")
}
if d.Control != nil {
t.Error("FromDialer installed a legacy Control hook")
}
if want := !disable || callerHook; (d.ControlContext != nil) != want {
t.Fatalf("ControlContext installed = %v; want %v", d.ControlContext != nil, want)
}
if d.KeepAlive != -1 {
t.Error("FromDialer changed keepalive policy")
}
if !callerHook {
return
}
// Loopback namespace setup requires no external network or
// privileges. The caller hook aborts before connect.
c, err := got.DialContext(t.Context(), "tcp4", "127.0.0.1:1")
if c != nil {
c.Close()
t.Error("dial returned a connection despite hook error")
}
if !called || !errors.Is(err, callerErr) {
t.Errorf("called = %v, dial error = %v; want caller error", called, err)
}
})
}
}
}
}
func TestFromDialerRejectsControl(t *testing.T) {
wasDisabled := disabled.Load()
t.Cleanup(func() { disabled.Store(wasDisabled) })
for _, disable := range []bool{false, true} {
for _, contextual := range []bool{false, true} {
t.Run(fmt.Sprintf("disabled=%v/context=%v", disable, contextual), func(t *testing.T) {
disabled.Store(disable)
d := &net.Dialer{Control: func(string, string, syscall.RawConn) error {
t.Fatal("Control must not be called")
return nil
}}
if contextual {
d.ControlContext = func(context.Context, string, string, syscall.RawConn) error {
t.Fatal("ControlContext must not be called")
return nil
}
}
defer func() {
if got := recover(); got != "netns.FromDialer: use ControlContext instead of Control" {
t.Errorf("panic = %v; want rejection of Control", got)
}
}()
FromDialer(t.Logf, netmon.NewStatic(), d)
})
}
}
}
// controlTestProxy verifies that a wrapper uses the configured underlying dialer.
// It does not implement the SOCKS protocol.
type controlTestProxy struct{ Dialer }
+31 -6
View File
@@ -19,6 +19,7 @@ import (
"net/netip"
"runtime"
"sync/atomic"
"syscall"
"tailscale.com/net/netknob"
"tailscale.com/net/netmon"
@@ -97,7 +98,7 @@ func Listener(logf logger.Logf, netMon *netmon.Monitor) *net.ListenConfig {
return &net.ListenConfig{Control: control(logf, netMon)}
}
// NewDialer returns a new Dialer using a net.Dialer with its Control
// NewDialer returns a new Dialer using a net.Dialer with its ControlContext
// hook func initialized as necessary to run in a logical network
// namespace that doesn't route back into Tailscale. It also handles
// using a SOCKS if configured in the environment with ALL_PROXY.
@@ -110,24 +111,48 @@ func NewDialer(logf logger.Logf, netMon *netmon.Monitor) Dialer {
})
}
// FromDialer returns sets d.Control as necessary to run in a logical
// network namespace that doesn't route back into Tailscale. It also
// handles using a SOCKS if configured in the environment with
// ALL_PROXY.
// FromDialer configures d to run in a logical network namespace that doesn't
// route back into Tailscale. Namespace setup runs before any caller-supplied
// ControlContext hook; if setup fails, the caller's hook is not run.
// FromDialer panics if d.Control is non-nil; use ControlContext instead, even
// when netns is disabled.
//
// FromDialer modifies d and may wrap it to use SOCKS if configured by ALL_PROXY.
// The hooks apply to the underlying socket (to the proxy when using SOCKS).
// When netns is disabled, d is returned unchanged and without proxy wrapping.
func FromDialer(logf logger.Logf, netMon *netmon.Monitor, d *net.Dialer) Dialer {
if netMon == nil {
panic("netns.FromDialer called with nil netMon")
}
if d.Control != nil {
panic("netns.FromDialer: use ControlContext instead of Control")
}
if disabled.Load() {
return d
}
d.Control = control(logf, netMon)
setNamespaceControl(d, control(logf, netMon))
if wrapDialer != nil {
return wrapDialer(d)
}
return d
}
// setNamespaceControl installs namespace setup without discarding the caller's
// socket configuration, such as TCP keepalive or user-timeout options. Namespace
// setup runs first; the caller's ControlContext hook runs only if it succeeds.
func setNamespaceControl(d *net.Dialer, namespaceControl func(string, string, syscall.RawConn) error) {
callerControlContext := d.ControlContext
d.ControlContext = func(ctx context.Context, network, address string, c syscall.RawConn) error {
if err := namespaceControl(network, address, c); err != nil {
return err
}
if callerControlContext != nil {
return callerControlContext(ctx, network, address, c)
}
return nil
}
}
// IsSOCKSDialer reports whether d is SOCKS-proxying dialer as returned by
// NewDialer or FromDialer.
func IsSOCKSDialer(d Dialer) bool {