From 86129dd5ce856f709fb29a5b166ed46232757f65 Mon Sep 17 00:00:00 2001 From: Kristoffer Dalby Date: Mon, 9 Nov 2026 06:51:00 +0000 Subject: [PATCH] servertest: start a server from a loaded configuration NewServerFromConfig serves a config unchanged; TestServerURLOnly proves a server_url-only file or env config serves both ranges, tailnet.internal and no DNS resolvers. Updates #1926 --- hscontrol/servertest/defaults_test.go | 110 ++++++++++++++++++++++++++ hscontrol/servertest/server.go | 23 +++++- 2 files changed, 131 insertions(+), 2 deletions(-) create mode 100644 hscontrol/servertest/defaults_test.go diff --git a/hscontrol/servertest/defaults_test.go b/hscontrol/servertest/defaults_test.go new file mode 100644 index 000000000..7b26147b3 --- /dev/null +++ b/hscontrol/servertest/defaults_test.go @@ -0,0 +1,110 @@ +package servertest_test + +import ( + "net/netip" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/juanfont/headscale/hscontrol/config" + "github.com/juanfont/headscale/hscontrol/servertest" + "github.com/juanfont/headscale/hscontrol/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "tailscale.com/types/netmap" +) + +// TestServerURLOnly: a configuration that sets only server_url, from a file +// or from the environment, loads as the defaults and serves a client. +func TestServerURLOnly(t *testing.T) { + t.Parallel() + + const serverURL = "https://headscale.example.com" + + tests := []struct { + name string + load func(t *testing.T) (*config.Loaded, error) + }{ + { + name: "file", + load: func(t *testing.T) (*config.Loaded, error) { + t.Helper() + + path := filepath.Join(t.TempDir(), "config.yaml") + require.NoError(t, os.WriteFile(path, []byte("server_url: "+serverURL+"\n"), 0o600)) + + return config.Load(path, true, nil) + }, + }, + { + name: "env", + load: func(t *testing.T) (*config.Loaded, error) { + t.Helper() + + l, err := config.Load(t.TempDir(), false, []string{"HEADSCALE_SERVER_URL=" + serverURL}) + assert.Empty(t, l.File) + + return l, err + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + l, err := tt.load(t) + require.NoError(t, err) + assert.Empty(t, l.Warnings) + + want := config.Default() + want.ServerURL = serverURL + + diff := cmp.Diff(&want, l.Config, + cmpopts.EquateComparable(netip.Prefix{}), + cmpopts.IgnoreFields(types.Config{}, "ConfigDir"), + cmpopts.IgnoreUnexported(types.Config{}), + ) + if diff != "" { + t.Errorf("loaded config (-want +got):\n%s", diff) + } + + cfg := *l.Config + // /var/lib/headscale belongs to the host and is not writable in a test. + dir := t.TempDir() + cfg.Noise.PrivateKeyPath = filepath.Join(dir, "noise_private.key") + cfg.Database.Sqlite.Path = filepath.Join(dir, "db.sqlite") + + ts := servertest.NewServerFromConfig(t, cfg) + c := servertest.NewClient(t, ts, "node1") + c.WaitForCondition(t, "self node", 10*time.Second, func(nm *netmap.NetworkMap) bool { + return nm.SelfNode.Valid() + }) + + nm := c.Netmap() + + addrs := nm.GetAddresses().AsSlice() + require.Len(t, addrs, 2) + + for _, p := range []string{"100.64.0.0/10", "fd7a:115c:a1e0::/48"} { + prefix := netip.MustParsePrefix(p) + assert.True(t, slices.ContainsFunc(addrs, func(a netip.Prefix) bool { + return prefix.Contains(a.Addr()) + }), "no address in %s: %v", prefix, addrs) + } + + // No resolver is chosen for the operator: clients keep their own DNS. + assert.Empty(t, nm.DNS.Resolvers) + assert.Empty(t, nm.DNS.FallbackResolvers) + + require.NotEmpty(t, nm.DNS.Domains) + assert.Equal(t, "tailnet.internal", nm.DNS.Domains[0]) + assert.True(t, strings.HasSuffix(nm.SelfNode.Name(), ".tailnet.internal."), "self name %q", nm.SelfNode.Name()) + }) + } +} diff --git a/hscontrol/servertest/server.go b/hscontrol/servertest/server.go index d41662b0d..0f6b2ef9f 100644 --- a/hscontrol/servertest/server.go +++ b/hscontrol/servertest/server.go @@ -208,6 +208,25 @@ func NewServer(tb testing.TB, opts ...ServerOption) *TestServer { cfg.DNSConfig.Nameservers.Global = sc.dnsResolvers } + return start(tb, cfg, sc.ephemeralTimeout, sc.realListener) +} + +// NewServerFromConfig starts cfg, as loaded, as a test server. Only the +// server URL, set to the in-memory listener, and the DERP map, set +// in-process, differ from serving cfg; the DERP map is never fetched. +// [hscontrol.Headscale.Serve] never runs: no configured listeners, no unix +// socket and no scheduled tasks, so this is not `headscale serve`. +func NewServerFromConfig(tb testing.TB, cfg types.Config) *TestServer { + tb.Helper() + + return start(tb, cfg, cfg.Node.Ephemeral.InactivityTimeout, false) +} + +// start runs cfg through [hscontrol.NewHeadscale], then sets the ephemeral +// timeout and starts the server's subsystems and listener. +func start(tb testing.TB, cfg types.Config, ephemeralTimeout time.Duration, realListener bool) *TestServer { + tb.Helper() + app, err := hscontrol.NewHeadscale(&cfg) if err != nil { tb.Fatalf("servertest: NewHeadscale: %v", err) @@ -215,7 +234,7 @@ func NewServer(tb testing.TB, opts ...ServerOption) *TestServer { // Validate's floor is for clients that reconnect over real networks; // tests shorten it once the configuration has been validated. - cfg.Node.Ephemeral.InactivityTimeout = sc.ephemeralTimeout + cfg.Node.Ephemeral.InactivityTimeout = ephemeralTimeout // Registered first so clients, HTTP, and background subsystems stop first. tb.Cleanup(func() { @@ -255,7 +274,7 @@ func NewServer(tb testing.TB, opts ...ServerOption) *TestServer { ln net.Listener ) - if sc.realListener { + if realListener { var lc net.ListenConfig ln, err = lc.Listen(context.Background(), "tcp", "127.0.0.1:0")