From e9abc6ae35fce5f163a1c995fe286b417ffbcff4 Mon Sep 17 00:00:00 2001 From: Kristoffer Dalby Date: Sun, 8 Nov 2026 09:14:10 +0000 Subject: [PATCH] hscontrol: validate configuration in NewHeadscale Updates #1926 --- cmd/headscale/cli/policy.go | 8 +- cmd/headscale/cli/root_test.go | 5 +- cmd/headscale/cli/utils.go | 28 +- cmd/headscale/cli/utils_test.go | 16 +- hscontrol/apiv1_nodes_test.go | 2 +- hscontrol/apiv1_policy_test.go | 23 +- hscontrol/apiv2_compat_test.go | 16 +- hscontrol/app.go | 13 +- hscontrol/app_test.go | 212 +++++++++++-- hscontrol/auth_tags_test.go | 25 +- hscontrol/auth_test.go | 21 +- hscontrol/config/default_test.go | 282 ++++++++++++++++++ hscontrol/config/validate.go | 192 +++++++++--- hscontrol/config/validate_test.go | 27 +- hscontrol/handlers_test.go | 23 +- hscontrol/servertest/server.go | 61 ++-- ...stAPIV1AuthRegister_happy_path_parity.json | 5 +- .../TestAPIV1NodeGet_happy_parity.json | 5 +- .../TestAPIV1NodeGet_tagged_node_parity.json | 5 +- .../TestAPIV1NodeList_all_parity.json | 10 +- ...stAPIV1NodeList_filter_by_user_parity.json | 5 +- .../TestAPIV1NodeRegister_happy_parity.json | 5 +- 22 files changed, 732 insertions(+), 257 deletions(-) diff --git a/cmd/headscale/cli/policy.go b/cmd/headscale/cli/policy.go index c5b8ed1bd..69a231d9e 100644 --- a/cmd/headscale/cli/policy.go +++ b/cmd/headscale/cli/policy.go @@ -8,6 +8,7 @@ import ( "os" clientv1 "github.com/juanfont/headscale/gen/client/v1" + "github.com/juanfont/headscale/hscontrol/config" "github.com/juanfont/headscale/hscontrol/db" "github.com/juanfont/headscale/hscontrol/policy" "github.com/spf13/cobra" @@ -22,7 +23,12 @@ var errAborted = errors.New("command aborted by user") // bypassDatabase opens the database directly, bypassing the running server. // The caller must close the returned handle. func bypassDatabase() (*db.HSDatabase, error) { - cfg, err := serverConfig() + // Validated here: the server, which would, is not started. + cfg := serverConfig() + + err := config.Validate(cfg) + logWarnings(config.Warnings(cfg)) + if err != nil { return nil, fmt.Errorf("loading config: %w", err) } diff --git a/cmd/headscale/cli/root_test.go b/cmd/headscale/cli/root_test.go index 8bc9f6ced..cfaeda3fd 100644 --- a/cmd/headscale/cli/root_test.go +++ b/cmd/headscale/cli/root_test.go @@ -376,10 +376,7 @@ dns: require.NoError(t, os.WriteFile(configPath, []byte(config), 0o600)) useLoaded(t, configPath) - cfg, err := serverConfig() - require.NoError(t, err) - - database, err := db.NewHeadscaleDatabase(cfg) + database, err := db.NewHeadscaleDatabase(serverConfig()) require.NoError(t, err) t.Cleanup(func() { _ = database.Close() }) diff --git a/cmd/headscale/cli/utils.go b/cmd/headscale/cli/utils.go index 8f1cfb5b2..0c0a1356d 100644 --- a/cmd/headscale/cli/utils.go +++ b/cmd/headscale/cli/utils.go @@ -16,7 +16,6 @@ import ( "github.com/cenkalti/backoff/v5" clientv1 "github.com/juanfont/headscale/gen/client/v1" "github.com/juanfont/headscale/hscontrol" - "github.com/juanfont/headscale/hscontrol/config" "github.com/juanfont/headscale/hscontrol/types" "github.com/juanfont/headscale/hscontrol/util" "github.com/juanfont/headscale/hscontrol/util/zlog/zf" @@ -87,16 +86,10 @@ func mustMarkRequired(cmd *cobra.Command, names ...string) { } } +// newHeadscaleServerWithConfig builds the server, which validates the +// configuration. func newHeadscaleServerWithConfig() (*hscontrol.Headscale, error) { - cfg, err := serverConfig() - if err != nil { - return nil, fmt.Errorf( - "loading configuration: %w", - err, - ) - } - - app, err := hscontrol.NewHeadscale(cfg) + app, err := hscontrol.NewHeadscale(serverConfig()) if err != nil { return nil, fmt.Errorf("creating new headscale: %w", err) } @@ -104,23 +97,16 @@ func newHeadscaleServerWithConfig() (*hscontrol.Headscale, error) { return app, nil } -// serverConfig is the loaded configuration validated for the server, its -// advisories logged. -func serverConfig() (*types.Config, error) { +// serverConfig is the loaded configuration as the server takes it, +// unvalidated. +func serverConfig() *types.Config { cfg := loaded.Config - err := config.Validate(cfg) - logWarnings(config.Warnings(cfg)) - - if err != nil { - return nil, err - } - // The server never uses the CLI's key, which may be an unread file: // reference. cfg.CLI.APIKey = "" - return cfg, nil + return cfg } // clientRunE wraps a [cobra.Command.RunE] func, injecting a ready API client diff --git a/cmd/headscale/cli/utils_test.go b/cmd/headscale/cli/utils_test.go index a366e4359..3a822a830 100644 --- a/cmd/headscale/cli/utils_test.go +++ b/cmd/headscale/cli/utils_test.go @@ -105,7 +105,17 @@ func TestServerConfigDropsCLIKey(t *testing.T) { dir := t.TempDir() useLoaded(t, writeServerConfig(t, dir, "cli:\n api_key: file:"+filepath.Join(dir, "missing")+"\n")) - cfg, err := serverConfig() - require.NoError(t, err) - assert.Empty(t, cfg.CLI.APIKey) + assert.Empty(t, serverConfig().CLI.APIKey) +} + +// TestBypassDatabaseValidates: the policy commands' --bypass path, which +// starts no server, validates the configuration before opening the +// database. +func TestBypassDatabaseValidates(t *testing.T) { + dir := t.TempDir() + useLoaded(t, writeServerConfig(t, dir, "node:\n ephemeral:\n inactivity_timeout: 1s\n")) + + _, err := bypassDatabase() + require.ErrorContains(t, err, "node.ephemeral.inactivity_timeout is below the minimum") + assert.NoFileExists(t, filepath.Join(dir, "headscale.db")) } diff --git a/hscontrol/apiv1_nodes_test.go b/hscontrol/apiv1_nodes_test.go index 54d3e0a67..5418be403 100644 --- a/hscontrol/apiv1_nodes_test.go +++ b/hscontrol/apiv1_nodes_test.go @@ -112,7 +112,7 @@ func TestAPIV1NodeGet(t *testing.T) { assert.Equal(t, "node-c", got.Node["name"]) assert.Equal(t, "REGISTER_METHOD_AUTH_KEY", got.Node["registerMethod"]) // EmitUnpopulated parity: slices present as [], expiry as null. - assert.Equal(t, []any{}, got.Node["ipAddresses"]) + assert.Equal(t, []any{}, got.Node["approvedRoutes"]) assert.Equal(t, []any{}, got.Node["tags"]) assert.Nil(t, got.Node["expiry"]) assert.Contains(t, got.Node, "user") diff --git a/hscontrol/apiv1_policy_test.go b/hscontrol/apiv1_policy_test.go index 1d184d2f8..a7151c2f2 100644 --- a/hscontrol/apiv1_policy_test.go +++ b/hscontrol/apiv1_policy_test.go @@ -4,7 +4,6 @@ import ( "encoding/json" "net/http" "testing" - "time" "github.com/juanfont/headscale/hscontrol/mapper" "github.com/juanfont/headscale/hscontrol/types" @@ -199,26 +198,8 @@ func TestAPIV1PolicyCheck(t *testing.T) { func createFilePolicyApp(t *testing.T) *Headscale { t.Helper() - tmpDir := t.TempDir() - - cfg := types.Config{ - ServerURL: "http://localhost:8080", - Noise: types.NoiseConfig{PrivateKeyPath: tmpDir + "/noise_private.key"}, - Database: types.DatabaseConfig{ - Type: "sqlite3", - Sqlite: types.SqliteConfig{ - Path: tmpDir + "/headscale_test.db", - }, - }, - OIDC: types.OIDCConfig{}, - Policy: types.PolicyConfig{ - Mode: types.PolicyModeFile, - }, - Tuning: types.Tuning{ - BatchChangeDelay: 100 * time.Millisecond, - BatcherWorkers: 1, - }, - } + cfg := validConfig(t) + cfg.Policy.Mode = types.PolicyModeFile app, err := NewHeadscale(&cfg) require.NoError(t, err) diff --git a/hscontrol/apiv2_compat_test.go b/hscontrol/apiv2_compat_test.go index c1f7d8f38..7bf0620f9 100644 --- a/hscontrol/apiv2_compat_test.go +++ b/hscontrol/apiv2_compat_test.go @@ -292,21 +292,7 @@ func newAPIReplay(t *testing.T, c *testcapture.Capture, useV1 bool) *apiReplay { func newAddressedTestApp(t *testing.T) *Headscale { t.Helper() - tmpDir := t.TempDir() - prefixV4 := netip.MustParsePrefix("100.64.0.0/10") - prefixV6 := netip.MustParsePrefix("fd7a:115c:a1e0::/48") - - cfg := types.Config{ - ServerURL: "http://localhost:8080", - Noise: types.NoiseConfig{PrivateKeyPath: tmpDir + "/noise_private.key"}, - Prefixes: types.PrefixesConfig{V4: &prefixV4, V6: &prefixV6, Allocation: types.IPAllocationStrategySequential}, - Database: types.DatabaseConfig{ - Type: "sqlite3", - Sqlite: types.SqliteConfig{Path: tmpDir + "/headscale_test.db"}, - }, - Policy: types.PolicyConfig{Mode: types.PolicyModeDB}, - Tuning: types.Tuning{BatchChangeDelay: 100 * time.Millisecond, BatcherWorkers: 1}, - } + cfg := validConfig(t) app, err := NewHeadscale(&cfg) require.NoError(t, err) diff --git a/hscontrol/app.go b/hscontrol/app.go index 2b86cf748..057353336 100644 --- a/hscontrol/app.go +++ b/hscontrol/app.go @@ -121,8 +121,19 @@ var ( dumpConfig = envknob.Bool("HEADSCALE_DEBUG_DUMP_CONFIG") ) +// NewHeadscale logs cfg's advisories, validates it and builds the server. +// An invalid cfg is returned as Validate's error before anything is read +// or written. func NewHeadscale(cfg *types.Config) (*Headscale, error) { - var err error + // First: an advisory can explain the error. + for _, w := range config.Warnings(cfg) { + log.Warn().Msg(w) + } + + err := config.Validate(cfg) + if err != nil { + return nil, err + } if profilingEnabled { runtime.SetBlockProfileRate(1) diff --git a/hscontrol/app_test.go b/hscontrol/app_test.go index bc1084207..51b0d3a61 100644 --- a/hscontrol/app_test.go +++ b/hscontrol/app_test.go @@ -4,13 +4,17 @@ import ( "context" "net/http" "net/http/httptest" + "net/netip" "os" "path/filepath" "testing" + "time" + "github.com/juanfont/headscale/hscontrol/config" "github.com/juanfont/headscale/hscontrol/dns" "github.com/juanfont/headscale/hscontrol/types" "github.com/libdns/cloudflare" + "github.com/rs/zerolog" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -169,22 +173,11 @@ func TestNewHeadscaleDNSProvider(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - tmpDir := t.TempDir() - cfg := types.Config{ - ServerURL: "http://localhost:8080", - Noise: types.NoiseConfig{PrivateKeyPath: tmpDir + "/noise_private.key"}, - Database: types.DatabaseConfig{ - Type: "sqlite3", - Sqlite: types.SqliteConfig{Path: tmpDir + "/headscale_test.db"}, - }, - Policy: types.PolicyConfig{Mode: types.PolicyModeDB}, - DNSConfig: types.DNSConfig{ - MagicDNS: true, - BaseDomain: "ts.example.com", - Certificates: types.CertificatesConfig{Enabled: tt.certificates}, - Challenge: tt.challenge, - }, - } + cfg := validConfig(t) + cfg.DNSConfig.MagicDNS = true + cfg.DNSConfig.BaseDomain = "ts.example.com" + cfg.DNSConfig.Certificates.Enabled = tt.certificates + cfg.DNSConfig.Challenge = tt.challenge app, err := NewHeadscale(&cfg) if tt.wantErr != "" { @@ -216,11 +209,25 @@ func TestNewHeadscaleSecrets(t *testing.T) { noFiles bool // fails before startup writes anything }{ { - name: "oidc client secret file missing", + name: "oidc client secret file missing, fallback allowed", set: func(c *types.Config) { // Unreachable, so discovery would fail and fall back, were the // secret read only there. - c.OIDC = types.OIDCConfig{Issuer: "http://127.0.0.1:1", ClientID: "headscale", ClientSecret: missing} + c.OIDC.Issuer = "http://127.0.0.1:1" + c.OIDC.ClientID = "headscale" + c.OIDC.ClientSecret = missing + c.OIDC.OnlyStartIfOIDCIsAvailable = false + }, + wantErr: "oidc.client_secret: ", + noFiles: true, + }, + { + name: "oidc client secret file missing, oidc required", + set: func(c *types.Config) { + c.OIDC.Issuer = "http://127.0.0.1:1" + c.OIDC.ClientID = "headscale" + c.OIDC.ClientSecret = missing + c.OIDC.OnlyStartIfOIDCIsAvailable = true }, wantErr: "oidc.client_secret: ", noFiles: true, @@ -228,10 +235,8 @@ func TestNewHeadscaleSecrets(t *testing.T) { { name: "postgres pass file missing", set: func(c *types.Config) { - c.Database = types.DatabaseConfig{ - Type: types.DatabasePostgres, - Postgres: types.PostgresConfig{Host: "127.0.0.1", Port: 1, Name: "headscale", Pass: missing}, - } + c.Database.Type = types.DatabasePostgres + c.Database.Postgres = types.PostgresConfig{Host: "127.0.0.1", Port: 1, Name: "headscale", Pass: missing} }, wantErr: "database.postgres.pass: ", }, @@ -246,16 +251,8 @@ func TestNewHeadscaleSecrets(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - tmpDir := t.TempDir() - cfg := types.Config{ - ServerURL: "http://localhost:8080", - Noise: types.NoiseConfig{PrivateKeyPath: tmpDir + "/noise_private.key"}, - Database: types.DatabaseConfig{ - Type: "sqlite3", - Sqlite: types.SqliteConfig{Path: tmpDir + "/headscale_test.db"}, - }, - Policy: types.PolicyConfig{Mode: types.PolicyModeDB}, - } + cfg := validConfig(t) + tmpDir := filepath.Dir(cfg.Noise.PrivateKeyPath) tt.set(&cfg) app, err := NewHeadscale(&cfg) @@ -279,3 +276,154 @@ func TestNewHeadscaleSecrets(t *testing.T) { }) } } + +// validConfig is config.Default with what an operator must set, its files +// under a fresh temp dir, and the batcher quick and single-threaded for +// tests. +func validConfig(t *testing.T) types.Config { + t.Helper() + + dir := t.TempDir() + v4 := netip.MustParsePrefix("100.64.0.0/10") + v6 := netip.MustParsePrefix("fd7a:115c:a1e0::/48") + + cfg := config.Default() + cfg.ServerURL = "http://localhost:8080" + cfg.Noise.PrivateKeyPath = filepath.Join(dir, "noise_private.key") + cfg.Database.Type = types.DatabaseSqlite + cfg.Database.Sqlite.Path = filepath.Join(dir, "headscale_test.db") + cfg.Prefixes.V4 = &v4 + cfg.Prefixes.V6 = &v6 + cfg.Policy.Mode = types.PolicyModeDB + cfg.DNSConfig.MagicDNS = false + cfg.DNSConfig.OverrideLocalDNS = false + cfg.Tuning.BatchChangeDelay = 100 * time.Millisecond + cfg.Tuning.BatcherWorkers = 1 + + return cfg +} + +// TestNewHeadscaleRejectsInvalidConfig: a configuration Validate rejects +// stops startup before anything is written. +func TestNewHeadscaleRejectsInvalidConfig(t *testing.T) { + for _, tt := range []struct { + name string + set func(*types.Config) + key string + }{ + {name: "derp url", set: func(c *types.Config) { c.DERP.URLs = []types.HTTPURL{"ftp://h/map"} }, key: "derp.urls[0]"}, + {name: "zero prefix", set: func(c *types.Config) { c.Prefixes.V4 = &netip.Prefix{} }, key: "prefixes.v4"}, + {name: "zero trusted proxy", set: func(c *types.Config) { c.TrustedProxies = []netip.Prefix{{}} }, key: "trusted_proxies[0]"}, + } { + t.Run(tt.name, func(t *testing.T) { + cfg := validConfig(t) + tt.set(&cfg) + + _, err := NewHeadscale(&cfg) + require.ErrorContains(t, err, tt.key) + require.ErrorIs(t, err, types.ErrConfig) + + entries, err := os.ReadDir(filepath.Dir(cfg.Noise.PrivateKeyPath)) + require.NoError(t, err) + assert.Empty(t, entries, "no noise key or database") + }) + } +} + +// TestNewHeadscaleRejectsSharedKey: noise and DERP keys that resolve to +// one file stop startup before anything is written, set from Go or loaded. +func TestNewHeadscaleRejectsSharedKey(t *testing.T) { + shared := func(t *testing.T) (types.Config, string) { + t.Helper() + + cfg := validConfig(t) + dir := filepath.Dir(cfg.Database.Sqlite.Path) + cfg.ConfigDir = dir + cfg.Noise.PrivateKeyPath = "shared.key" + cfg.DERP.Server.Enabled = true + cfg.DERP.Server.STUNAddr = ":3478" + cfg.DERP.Server.PrivateKeyPath = filepath.Join(dir, "shared.key") + + return cfg, dir + } + + t.Run("go", func(t *testing.T) { + cfg, dir := shared(t) + + _, err := NewHeadscale(&cfg) + require.ErrorContains(t, err, "derp.server.private_key_path must differ from noise.private_key_path") + + entries, err := os.ReadDir(dir) + require.NoError(t, err) + assert.Empty(t, entries, "no key or database") + }) + + t.Run("go without config dir", func(t *testing.T) { + cfg, dir := shared(t) + cfg.ConfigDir = "" + + t.Chdir(dir) + + _, err := NewHeadscale(&cfg) + require.ErrorContains(t, err, "derp.server.private_key_path must differ from noise.private_key_path") + + entries, err := os.ReadDir(dir) + require.NoError(t, err) + assert.Empty(t, entries, "no key or database") + }) + + t.Run("loaded", func(t *testing.T) { + cfg, dir := shared(t) + + out, err := config.Marshal(&cfg, ".yaml") + require.NoError(t, err) + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), out, 0o600)) + + l, err := config.Load(filepath.Join(dir, "config.yaml"), true, nil) + require.NoError(t, err) + + _, err = NewHeadscale(l.Config) + require.ErrorContains(t, err, "derp.server.private_key_path must differ from noise.private_key_path") + + entries, err := os.ReadDir(dir) + require.NoError(t, err) + require.Len(t, entries, 1, "no key or database") + assert.Equal(t, "config.yaml", entries[0].Name()) + }) +} + +// TestNewHeadscaleWarnsBeforeRejecting: the advisories are logged even when +// the configuration is rejected; one may explain the error. +func TestNewHeadscaleWarnsBeforeRejecting(t *testing.T) { + buf := captureLog(t, zerolog.WarnLevel) + + cfg := validConfig(t) + v4 := netip.MustParsePrefix("10.0.0.0/8") + cfg.Prefixes.V4 = &v4 + cfg.Tuning.BatchChangeDelay = 0 + + warnings := config.Warnings(&cfg) + require.NotEmpty(t, warnings) + + _, err := NewHeadscale(&cfg) + require.ErrorContains(t, err, "tuning.batch_change_delay must be positive") + assert.Len(t, buf.entries(t, warnings[0]), 1) +} + +// TestNewHeadscaleGoOnlyProvider: an embedder's provider serves node +// certificates without a provider name. +func TestNewHeadscaleGoOnlyProvider(t *testing.T) { + provider := &cloudflare.Provider{APIToken: "go-only"} + + cfg := validConfig(t) + cfg.DNSConfig.MagicDNS = true + cfg.DNSConfig.BaseDomain = "ts.example.com" + cfg.DNSConfig.Certificates.Enabled = true + cfg.DNSConfig.Challenge.Provider = provider + + app, err := NewHeadscale(&cfg) + require.NoError(t, err) + t.Cleanup(func() { _ = app.state.Close() }) + + assert.Same(t, provider, cfg.DNSProvider()) +} diff --git a/hscontrol/auth_tags_test.go b/hscontrol/auth_tags_test.go index 862db06ec..7cf261035 100644 --- a/hscontrol/auth_tags_test.go +++ b/hscontrol/auth_tags_test.go @@ -17,29 +17,8 @@ import ( func createTestAppWithNodeExpiry(t *testing.T, nodeExpiry time.Duration) *Headscale { t.Helper() - tmpDir := t.TempDir() - - cfg := types.Config{ - ServerURL: "http://localhost:8080", - Noise: types.NoiseConfig{PrivateKeyPath: tmpDir + "/noise_private.key"}, - Node: types.NodeConfig{ - Expiry: nodeExpiry, - }, - Database: types.DatabaseConfig{ - Type: "sqlite3", - Sqlite: types.SqliteConfig{ - Path: tmpDir + "/headscale_test.db", - }, - }, - OIDC: types.OIDCConfig{}, - Policy: types.PolicyConfig{ - Mode: types.PolicyModeDB, - }, - Tuning: types.Tuning{ - BatchChangeDelay: 100 * time.Millisecond, - BatcherWorkers: 1, - }, - } + cfg := validConfig(t) + cfg.Node.Expiry = nodeExpiry app, err := NewHeadscale(&cfg) require.NoError(t, err) diff --git a/hscontrol/auth_test.go b/hscontrol/auth_test.go index 77433b482..963e42725 100644 --- a/hscontrol/auth_test.go +++ b/hscontrol/auth_test.go @@ -3362,26 +3362,7 @@ func TestWebFlowReauthDifferentUser(t *testing.T) { func createTestApp(t *testing.T, options ...func(*types.Config)) *Headscale { t.Helper() - tmpDir := t.TempDir() - - cfg := types.Config{ - ServerURL: "http://localhost:8080", - Noise: types.NoiseConfig{PrivateKeyPath: tmpDir + "/noise_private.key"}, - Database: types.DatabaseConfig{ - Type: "sqlite3", - Sqlite: types.SqliteConfig{ - Path: tmpDir + "/headscale_test.db", - }, - }, - OIDC: types.OIDCConfig{}, - Policy: types.PolicyConfig{ - Mode: types.PolicyModeDB, - }, - Tuning: types.Tuning{ - BatchChangeDelay: 100 * time.Millisecond, - BatcherWorkers: 1, - }, - } + cfg := validConfig(t) for _, option := range options { option(&cfg) diff --git a/hscontrol/config/default_test.go b/hscontrol/config/default_test.go index 83016a4b6..11acd2f25 100644 --- a/hscontrol/config/default_test.go +++ b/hscontrol/config/default_test.go @@ -2,21 +2,303 @@ package config import ( "fmt" + "net/netip" + "os" + "path/filepath" "testing" + "github.com/juanfont/headscale/hscontrol/types" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) +// validConfig is Default with the values it leaves to the operator set, so +// it passes Validate. +func validConfig() types.Config { + v4 := netip.MustParsePrefix("100.64.0.0/10") + + cfg := Default() + cfg.ServerURL = "https://headscale.example.com" + cfg.Noise.PrivateKeyPath = "/var/lib/headscale/noise_private.key" + cfg.Database.Type = types.DatabaseSqlite + cfg.Prefixes.V4 = &v4 + cfg.DNSConfig.BaseDomain = "tailnet.example.com" + cfg.DNSConfig.Nameservers.Global = []string{"1.1.1.1"} + + return cfg +} + // TestValidateHintsNameDefaults: the defaults Validate's hints quote, which // types cannot read from Default, are Default's. func TestValidateHintsNameDefaults(t *testing.T) { d := Default() cfg := Default() + cfg.Tuning.BatchChangeDelay = 0 cfg.Tuning.NodeStoreBatchSize = 0 cfg.Tuning.NodeStoreBatchTimeout = 0 err := Validate(&cfg) + require.ErrorContains(t, err, fmt.Sprintf("(default: %s)", d.Tuning.BatchChangeDelay)) require.ErrorContains(t, err, fmt.Sprintf("(default: %d)", d.Tuning.NodeStoreBatchSize)) require.ErrorContains(t, err, fmt.Sprintf("(default: %s)", d.Tuning.NodeStoreBatchTimeout)) } + +// TestValidateGoData: a Config built in Go, which no loader parsed, is +// held to what the loader enforces. +func TestValidateGoData(t *testing.T) { + t.Run("default needs the operator's values", func(t *testing.T) { + d := Default() + assert.Equal(t, []string{ + "noise.private_key_path is required", + "server_url is missing a scheme", + "dns.nameservers.global is required when dns.override_local_dns is true", + "database.type has an unsupported value", + "dns.base_domain is required when dns.magic_dns is true", + "no IP prefix configured for the tailnet", + }, reasons(types.ConfigErrors(Validate(&d)))) + }) + + t.Run("zero config", func(t *testing.T) { + require.Error(t, Validate(&types.Config{})) + }) + + tests := []struct { + name string + set func(*types.Config) + wantErr string // "" validates + hidden string // never in the error + }{ + {name: "valid", set: func(*types.Config) {}}, + { + name: "log level", + set: func(c *types.Config) { c.Log.Level = "verbose" }, + wantErr: "log.level has an unsupported value", + }, + { + name: "enum", + set: func(c *types.Config) { c.Log.Format = "xml" }, + wantErr: "log.format has an unsupported value", + }, + { + name: "file mode", + set: func(c *types.Config) { c.UnixSocketPermission = 0o7777 }, + wantErr: "unix_socket_permission is not a quoted octal file mode", + }, + { + name: "listen address", + set: func(c *types.Config) { c.Addr = "nowhere" }, + wantErr: "listen_addr is not a host:port address", + }, + { + name: "url", + set: func(c *types.Config) { + c.OIDC.Issuer = "ftp://marker@idp.example.com" + c.OIDC.ClientID = "headscale" + c.OIDC.ClientSecret = "secret" + }, + wantErr: "oidc.issuer is not an http:// or https:// URL", + hidden: "marker", + }, + { + name: "url unparsable", + set: func(c *types.Config) { + c.OIDC.Issuer = "https://alice:marker-pass?@idp.example.com" + c.OIDC.ClientID = "headscale" + c.OIDC.ClientSecret = "secret" + }, + wantErr: "oidc.issuer is not an http:// or https:// URL", + hidden: "marker", + }, + { + name: "url list element", + set: func(c *types.Config) { c.DERP.URLs = []types.HTTPURL{"https://h/map", "ftp://u:marker@h/map"} }, + wantErr: "derp.urls[1] is not an http:// or https:// URL", + hidden: "marker", + }, + { + name: "url list", + set: func(c *types.Config) { c.DERP.URLs = []types.HTTPURL{"https://h/map"} }, + }, + { + name: "prefix list element", + set: func(c *types.Config) { + c.TrustedProxies = []netip.Prefix{netip.PrefixFrom(netip.MustParseAddr("10.0.0.1"), 33)} + }, + wantErr: "trusted_proxies[0] is not a valid CIDR", + }, + { + name: "zero prefix list element", + set: func(c *types.Config) { c.TrustedProxies = []netip.Prefix{{}} }, + wantErr: "trusted_proxies[0] is not a valid CIDR", + }, + { + name: "zero prefix", + set: func(c *types.Config) { c.Prefixes.V4 = &netip.Prefix{} }, + wantErr: "prefixes.v4 is not a valid CIDR", + }, + { + name: "batch change delay", + set: func(c *types.Config) { c.Tuning.BatchChangeDelay = 0 }, + wantErr: "tuning.batch_change_delay must be positive", + }, + { + name: "server url trailing slash", + set: func(c *types.Config) { c.ServerURL = "https://h/" }, + wantErr: "server_url must not end in /", + }, + { + name: "server url credentials", + set: func(c *types.Config) { c.ServerURL = "https://marker-user:marker-pass@h/" }, + wantErr: "server_url must not end in /", + hidden: "marker", + }, + { + name: "server url username", + set: func(c *types.Config) { c.ServerURL = "https://marker-user@h/" }, + wantErr: "server_url must not end in /", + hidden: "marker", + }, + { + name: "server url malformed", + set: func(c *types.Config) { c.ServerURL = "https://marker-user:marker-pass@h/%zz" }, + wantErr: "server_url cannot be parsed", + hidden: "marker", + }, + // The parser splits off the query and fragment first: the password + // is read as a port, which its error quotes. + { + name: "server url userinfo before query", + set: func(c *types.Config) { c.ServerURL = "https://alice:marker-pass?@h" }, + wantErr: "server_url cannot be parsed", + hidden: "marker", + }, + { + name: "server url userinfo before fragment", + set: func(c *types.Config) { c.ServerURL = "https://alice:marker-pass#@h" }, + wantErr: "server_url cannot be parsed", + hidden: "marker", + }, + { + name: "server url invalid port", + set: func(c *types.Config) { c.ServerURL = "https://alice:marker-pass@h:port" }, + wantErr: "server_url cannot be parsed", + hidden: "marker", + }, + { + name: "server url single slash", + set: func(c *types.Config) { c.ServerURL = "https:/alice:marker-pass@h" }, + wantErr: "server_url is missing a scheme", + hidden: "marker", + }, + { + name: "server url without scheme shown", + set: func(c *types.Config) { c.ServerURL = "headscale.example.com" }, + wantErr: `server_url: "headscale.example.com"`, + }, + // One error per problem: the rules that predate the value checks + // keep only the empty value. + { + name: "policy mode", + set: func(c *types.Config) { c.Policy.Mode = "bogus" }, + wantErr: "policy.mode has an unsupported value", + }, + { + name: "policy mode empty", + set: func(c *types.Config) { c.Policy.Mode = "" }, + wantErr: "policy.mode has an unsupported value", + }, + { + name: "database type", + set: func(c *types.Config) { c.Database.Type = "bogus" }, + wantErr: "database.type has an unsupported value", + }, + { + name: "allocation", + set: func(c *types.Config) { c.Prefixes.Allocation = "bogus" }, + wantErr: "prefixes.allocation has an unsupported value", + }, + { + name: "acme challenge", + set: func(c *types.Config) { c.TLS.ACME.ChallengeType = "bogus" }, + wantErr: "tls.acme.challenge_type has an unsupported value", + }, + { + name: "pkce method", + set: func(c *types.Config) { + c.OIDC.Issuer = "https://idp.example.com" + c.OIDC.ClientID = "headscale" + c.OIDC.ClientSecret = "secret" + c.OIDC.PKCE.Method = "bogus" + }, + wantErr: "oidc.pkce.method has an unsupported value", + }, + { + name: "metrics listen address", + set: func(c *types.Config) { c.MetricsAddr = "nowhere" }, + wantErr: "metrics_listen_addr is not a host:port address", + }, + // The keys are compared as startup opens them. + { + name: "derp key relative alias", + set: sharedKeys("shared.key", "/etc/headscale/shared.key"), + wantErr: "derp.server.private_key_path must differ from noise.private_key_path", + }, + { + name: "derp key unclean alias", + set: sharedKeys("/etc/headscale/shared.key", "/etc/headscale/./keys/../shared.key"), + wantErr: "derp.server.private_key_path must differ from noise.private_key_path", + }, + { + name: "derp key distinct", + set: sharedKeys("shared.key", "/etc/shared.key"), + }, + // An embedder's Config has no ConfigDir: startup opens a relative + // path from the working directory. + { + name: "derp key alias without config dir", + set: func(c *types.Config) { + wd, err := os.Getwd() + require.NoError(t, err) + + sharedKeys("shared.key", filepath.Join(wd, "shared.key"))(c) + c.ConfigDir = "" + }, + wantErr: "derp.server.private_key_path must differ from noise.private_key_path", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cfg := validConfig() + tt.set(&cfg) + + err := Validate(&cfg) + if tt.wantErr == "" { + require.NoError(t, err) + + return + } + + require.ErrorContains(t, err, tt.wantErr) + require.ErrorIs(t, err, types.ErrConfig) + assert.Len(t, types.ConfigErrors(err), 1, err.Error()) + + if tt.hidden != "" { + requireHidden(t, err, tt.hidden) + } + }) + } +} + +// sharedKeys enables the embedded DERP server with these noise and DERP key +// paths, relative ones resolved against /etc/headscale. +func sharedKeys(noise, derp string) func(*types.Config) { + return func(c *types.Config) { + c.ConfigDir = "/etc/headscale" + c.Noise.PrivateKeyPath = noise + c.DERP.Server.Enabled = true + c.DERP.Server.STUNAddr = "0.0.0.0:3478" + c.DERP.Server.PrivateKeyPath = derp + } +} diff --git a/hscontrol/config/validate.go b/hscontrol/config/validate.go index 01f939c0f..7f66773e2 100644 --- a/hscontrol/config/validate.go +++ b/hscontrol/config/validate.go @@ -1,12 +1,14 @@ package config import ( + "encoding" "errors" "fmt" "net" "net/netip" "net/url" "path/filepath" + "reflect" "strings" "time" @@ -19,13 +21,13 @@ import ( const dnsDocsURL = "https://headscale.net/stable/ref/dns/" var ( - errOIDCIssuerInvalid = errors.New("oidc.issuer must be a valid http(s) URL") errOIDCClientIDRequired = errors.New("oidc.client_id is required when oidc.issuer is set") errOIDCClientSecretRequired = errors.New("oidc.client_secret is required when oidc.issuer is set") errServerURLSuffix = errors.New("server_url cannot be part of base_domain in a way that could make the DERP and headscale server unreachable") errServerURLSame = errors.New("server_url cannot use the same domain as base_domain in a way that could make the DERP and headscale server unreachable") errInvalidPKCEMethod = errors.New("pkce.method must be either 'plain' or 'S256'") errTrustedProxyZeroRange = errors.New("0.0.0.0/0 and ::/0 are not allowed") + errURLSyntax = errors.New("invalid URL syntax") ) // Validate reports every rule c breaks, in one error. It reads no file and @@ -33,6 +35,8 @@ var ( func Validate(c *types.Config) error { v := &configValidator{} + validateValues(c, v) + // OIDC is activated by setting oidc.issuer (see app.go), not by a // dedicated oidc.enabled key. Gate validation on the real activation // condition so a misconfiguration fails at startup. @@ -83,8 +87,9 @@ func Validate(c *types.Config) error { validateListenerCollisions(c, v) - if ct := acme.ChallengeType; ct != types.HTTP01ChallengeType && - ct != types.TLSALPN01ChallengeType && ct != types.DNS01ChallengeType { + // Unset only: validateValues reports an unknown value, here and in the + // other enum rules. + if ct := acme.ChallengeType; ct == "" { v.Add(&types.ConfigError{ Reason: "tls.acme.challenge_type has an unsupported value", Current: []types.KV{{Key: "tls.acme.challenge_type", Value: string(ct)}}, @@ -93,14 +98,33 @@ func Validate(c *types.Config) error { }) } + // Shown without userinfo, which may be a credential. + serverURL := types.HTTPURL(c.ServerURL).Redacted() + if !strings.HasPrefix(c.ServerURL, "http://") && !strings.HasPrefix(c.ServerURL, "https://") { + // Without an @ it holds no userinfo; shown, the common mistake + // (headscale.example.com) is plain to see. + shown := c.ServerURL + if strings.Contains(shown, "@") { + shown = serverURL + } + v.Add(&types.ConfigError{ Reason: "server_url is missing a scheme", - Current: []types.KV{{Key: "server_url", Value: c.ServerURL}}, + Current: []types.KV{{Key: "server_url", Value: shown}}, Hint: "prefix the URL with https:// (recommended) or http://", }) } + // The loader trims it; clients would get URLs with a double slash. + if strings.HasSuffix(c.ServerURL, "/") { + v.Add(&types.ConfigError{ + Reason: "server_url must not end in /", + Current: []types.KV{{Key: "server_url", Value: serverURL}}, + Hint: "remove the trailing slash", + }) + } + // Minimum inactivity time out is keepalive timeout (60s) plus a few seconds // to avoid races minInactivityTimeout := 65 * time.Second @@ -159,6 +183,15 @@ func Validate(c *types.Config) error { } // Validate tuning parameters + // The batcher's ticker panics on a non-positive interval. + if delay := c.Tuning.BatchChangeDelay; delay <= 0 { + v.Add(&types.ConfigError{ + Reason: "tuning.batch_change_delay must be positive", + Current: []types.KV{{Key: "tuning.batch_change_delay", Value: delay.String()}}, + Hint: "set to a positive duration (default: 800ms)", + }) + } + if size := c.Tuning.NodeStoreBatchSize; size <= 0 { v.Add(&types.ConfigError{ Reason: "tuning.node_store_batch_size must be positive", @@ -193,18 +226,98 @@ func Validate(c *types.Config) error { if base := c.DNSConfig.BaseDomain; base != "" { err := isSafeServerURL(c.ServerURL, base) if err != nil { - addServerURLConfigError(v, c.ServerURL, base, err) + addServerURLConfigError(v, serverURL, base, err) } } return v.Err() } -// validatePolicy records a ConfigError for an unknown policy.mode: -// startup would load no policy at all and allow all traffic. +// validateValues parses every value whose type parses text, and each +// element of a list of them, from its own text, as the loader did: a +// Config built in Go was never parsed. +func validateValues(c *types.Config, v *configValidator) { + for _, f := range types.ConfigFields(c) { + if f.Value.Kind() != reflect.Slice { + validateValue(v, f.Path, f.Value) + + continue + } + + for i := range f.Value.Len() { + validateValue(v, fmt.Sprintf("%s[%d]", f.Path, i), f.Value.Index(i)) + } + } +} + +func validateValue(v *configValidator, key string, val reflect.Value) { + if val.Kind() == reflect.Pointer { + if val.IsNil() { + return + } + + val = val.Elem() + } + + // The zero Prefix prints as "" and parses back. + if p, ok := reflect.TypeAssert[netip.Prefix](val); ok { + if !p.IsValid() { + v.Add(&types.ConfigError{ + Reason: key + " is not a valid CIDR", + Hint: `use CIDR form, e.g. "100.64.0.0/10"`, + }) + } + + return + } + + if !reflect.PointerTo(val.Type()).Implements(textUnmarshalerType) { + return + } + + var ( + text []byte + err error + ) + + switch m, ok := reflect.TypeAssert[encoding.TextMarshaler](val); { + case ok: + text, err = m.MarshalText() + case val.Kind() == reflect.String: + text = []byte(val.String()) + default: + return + } + + if err == nil { + err = reflect.New(val.Type()).Interface().(encoding.TextUnmarshaler).UnmarshalText(text) //nolint:forcetypeassert // checked above + } + + if err == nil { + return + } + + // As the loader reports it: the key first, a URL's value hidden. + var leaf *types.ConfigError + if !errors.As(err, &leaf) { + leaf = &types.ConfigError{Reason: err.Error(), Cause: err} + } + + ce := *leaf + ce.Reason = key + " " + leaf.Reason + + if val.Type() != reflect.TypeFor[types.HTTPURL]() { + ce.Current = []types.KV{{Key: key, Value: string(text)}} + } + + v.Add(&ce) +} + +// validatePolicy records a ConfigError for an unset policy.mode: startup +// would load no policy at all and allow all traffic. func validatePolicy(c *types.Config, v *configValidator) { m := c.Policy.Mode - if m == types.PolicyModeFile || m == types.PolicyModeDB { + if m != "" { return } @@ -248,8 +361,9 @@ func validateDERP(c *types.Config, v *configValidator) { Hint: `set derp.server.private_key_path (e.g. "/var/lib/headscale/derp_server_private.key"), or set derp.server.enabled: false`, See: "https://headscale.net/stable/ref/derp/", }) - case filepath.Clean(derpKey) == filepath.Clean(noiseKey): - // Startup would create one key and then refuse it for both uses. + case keyFile(c.AbsPath(derpKey)) == keyFile(c.AbsPath(noiseKey)): + // Resolved, as startup opens them: it would create one key file and + // then refuse it for both uses. v.Add(&types.ConfigError{ Reason: "derp.server.private_key_path must differ from noise.private_key_path", Current: []types.KV{ @@ -273,12 +387,21 @@ func validateDERP(c *types.Config, v *configValidator) { } } -// validateDatabase records a ConfigError when database.type is not one of -// the supported backends. +// keyFile is p as startup opens it, a relative path from the working +// directory (an embedder's Config has no ConfigDir). +func keyFile(p string) string { + abs, err := filepath.Abs(p) + if err != nil { + return filepath.Clean(p) + } + + return abs +} + +// validateDatabase records a ConfigError when database.type is unset. func validateDatabase(c *types.Config, v *configValidator) { t := c.Database.Type - switch t { - case types.DatabaseSqlite, types.DatabasePostgres, "sqlite": + if t != "" { return } @@ -400,9 +523,7 @@ func validatePrefixes(c *types.Config, v *configValidator) { }) } - switch alloc := c.Prefixes.Allocation; alloc { - case types.IPAllocationStrategySequential, types.IPAllocationStrategyRandom: - default: + if alloc := c.Prefixes.Allocation; alloc == "" { v.Add(&types.ConfigError{ Reason: "prefixes.allocation has an unsupported value", Current: []types.KV{{Key: "prefixes.allocation", Value: string(alloc)}}, @@ -509,8 +630,10 @@ func outsideRange(p, r netip.Prefix) bool { return p.Bits() < r.Bits() || !r.Contains(p.Addr()) } +// validatePKCEMethod rejects an unset method; validateValues reports an +// unknown one. func validatePKCEMethod(method types.PKCEMethod) error { - if method != types.PKCEMethodPlain && method != types.PKCEMethodS256 { + if method == "" { return errInvalidPKCEMethod } @@ -518,21 +641,15 @@ func validatePKCEMethod(method types.PKCEMethod) error { } // validateOIDC checks the OIDC settings, called when oidc.issuer is set. It -// fails fast on a setup that cannot work: an invalid PKCE method, a -// malformed issuer URL (which would otherwise surface as an opaque discovery -// error or, worse, resolve to an unintended provider), or a missing client -// id/secret. +// fails fast on a setup that cannot work: an invalid PKCE method or a +// missing client id/secret. The issuer's form is its type's, checked with +// every other value's. func validateOIDC(o types.OIDCConfig) error { err := validatePKCEMethod(o.PKCE.Method) if err != nil { return err } - u, err := url.Parse(string(o.Issuer)) - if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" { - return fmt.Errorf("%w: got %q", errOIDCIssuerInvalid, string(o.Issuer)) - } - if o.ClientID == "" { return errOIDCClientIDRequired } @@ -574,12 +691,8 @@ func isWildcardHost(h string) bool { // validateListenerCollisions records a *ConfigError for each pair of // configured TCP listeners that would bind the same kernel socket. The // ACME HTTP-01 challenge listener is only considered when a hostname is -// set and the HTTP-01 challenge is selected. -// -// Parsing happens up-front, once per listener: a malformed address -// produces a ConfigError tied to its own YAML key, so an operator can -// see exactly which value to fix instead of guessing from a paired -// comparison. +// set and the HTTP-01 challenge is selected. A malformed address is +// skipped: validateValues reports it on its own key. func validateListenerCollisions(c *types.Config, v *configValidator) { type spec struct { key, addr string @@ -613,13 +726,6 @@ func validateListenerCollisions(c *types.Config, v *configValidator) { port, err := types.PortFromAddr(l.addr) if err != nil { - v.Add(&types.ConfigError{ - Reason: "cannot parse " + l.key, - Current: []types.KV{{Key: l.key, Value: l.addr}}, - Detail: err.Error(), - Hint: `use host:port form, e.g. "0.0.0.0:8080"`, - }) - continue } @@ -708,12 +814,14 @@ func addServerURLConfigError(v *configValidator, serverURL, baseDomain string, e }) default: + // Not the parser's error: it quotes the URL, or a part of it + // (invalid port ":"), userinfo included. v.Add(&types.ConfigError{ Reason: "server_url cannot be parsed", Current: []types.KV{{Key: "server_url", Value: serverURL}}, - Detail: err.Error(), + Detail: errURLSyntax.Error(), Hint: "set server_url to an absolute URL, e.g. https://headscale.example.com", - Cause: err, + Cause: errURLSyntax, }) } } diff --git a/hscontrol/config/validate_test.go b/hscontrol/config/validate_test.go index 2acf5c0b7..5cee4c2c2 100644 --- a/hscontrol/config/validate_test.go +++ b/hscontrol/config/validate_test.go @@ -159,9 +159,9 @@ func TestListenersOverlap(t *testing.T) { } } -// TestValidateListenerCollisions_BlamesParseFailure pins each parse -// error to the listener whose address is malformed, even when paired -// with a well-formed sibling. +// TestValidateListenerCollisions_BlamesParseFailure pins one error per +// malformed address, on its own key, even when paired with a well-formed +// sibling. func TestValidateListenerCollisions_BlamesParseFailure(t *testing.T) { tests := []struct { name string @@ -185,18 +185,19 @@ func TestValidateListenerCollisions_BlamesParseFailure(t *testing.T) { } } - v := &configValidator{} - validateListenerCollisions(cfg, v) + var blamed []*types.ConfigError - err := v.Err() - require.Error(t, err) + for _, e := range types.ConfigErrors(Validate(cfg)) { + if len(e.Current) > 0 && (e.Current[0].Key == tt.bad || e.Current[0].Key == tt.good) { + blamed = append(blamed, e) + } + } - errs := types.ConfigErrors(err) - require.Len(t, errs, 1, "expected exactly one parse error") - assert.Equal(t, "cannot parse "+tt.bad, errs[0].Reason) - require.Len(t, errs[0].Current, 1) - assert.Equal(t, tt.bad, errs[0].Current[0].Key) - assert.Equal(t, tt.badAddr, errs[0].Current[0].Value) + require.Len(t, blamed, 1, "expected exactly one parse error") + assert.Equal(t, tt.bad+" is not a host:port address", blamed[0].Reason) + require.Len(t, blamed[0].Current, 1) + assert.Equal(t, tt.bad, blamed[0].Current[0].Key) + assert.Equal(t, tt.badAddr, blamed[0].Current[0].Value) }) } } diff --git a/hscontrol/handlers_test.go b/hscontrol/handlers_test.go index 86ba7deb2..7f8446a2b 100644 --- a/hscontrol/handlers_test.go +++ b/hscontrol/handlers_test.go @@ -8,7 +8,6 @@ import ( "fmt" "net/http" "net/http/httptest" - "net/netip" "net/url" "strings" "sync" @@ -67,27 +66,9 @@ func TestHandleVerifyRequest_OversizedBodyRejected(t *testing.T) { // WriteHeader on first Write locks in a sniffed content type and the // later Header().Set becomes a no-op. func TestVerifyHandler_SuccessSetsJSONContentType(t *testing.T) { - tmpDir := t.TempDir() + cfg := validConfig(t) - prefixV4 := netip.MustParsePrefix("100.64.0.0/10") - prefixV6 := netip.MustParsePrefix("fd7a:115c:a1e0::/48") - - cfg := &types.Config{ - ServerURL: "http://localhost:0", - Noise: types.NoiseConfig{PrivateKeyPath: tmpDir + "/noise_private.key"}, - Prefixes: types.PrefixesConfig{V4: &prefixV4, V6: &prefixV6, Allocation: types.IPAllocationStrategySequential}, - Database: types.DatabaseConfig{ - Type: "sqlite3", - Sqlite: types.SqliteConfig{ - Path: tmpDir + "/headscale_test.db", - }, - }, - Policy: types.PolicyConfig{ - Mode: types.PolicyModeDB, - }, - } - - h, err := NewHeadscale(cfg) + h, err := NewHeadscale(&cfg) require.NoError(t, err) reqBody, err := json.Marshal(tailcfg.DERPAdmitClientRequest{ diff --git a/hscontrol/servertest/server.go b/hscontrol/servertest/server.go index df76b213c..ae9b4a99e 100644 --- a/hscontrol/servertest/server.go +++ b/hscontrol/servertest/server.go @@ -17,6 +17,7 @@ import ( "time" hscontrol "github.com/juanfont/headscale/hscontrol" + "github.com/juanfont/headscale/hscontrol/config" hsdns "github.com/juanfont/headscale/hscontrol/dns" "github.com/juanfont/headscale/hscontrol/state" "github.com/juanfont/headscale/hscontrol/types" @@ -165,40 +166,31 @@ func NewServer(tb testing.TB, opts ...ServerOption) *TestServer { prefixV4 := sc.prefixV4 prefixV6 := netip.MustParsePrefix("fd7a:115c:a1e0::/48") - cfg := types.Config{ - // Placeholder; updated below once the in-memory server starts. - ServerURL: "http://localhost:0", - Noise: types.NoiseConfig{PrivateKeyPath: tmpDir + "/noise_private.key"}, - Node: types.NodeConfig{ - Expiry: sc.nodeExpiry, - Ephemeral: types.EphemeralConfig{ - InactivityTimeout: sc.ephemeralTimeout, - }, - }, - Prefixes: types.PrefixesConfig{ - V4: &prefixV4, - V6: &prefixV6, - Allocation: types.IPAllocationStrategySequential, - }, - Database: types.DatabaseConfig{ - Type: "sqlite3", - Sqlite: types.SqliteConfig{ - Path: tmpDir + "/headscale_test.db", - }, - }, - Policy: types.PolicyConfig{ - Mode: types.PolicyModeDB, - }, - Taildrop: types.TaildropConfig{Enabled: sc.taildropEnabled}, - LogTail: types.LogTailConfig{Enabled: sc.logTailEnabled}, - Tuning: types.Tuning{ - BatchChangeDelay: sc.batchDelay, - BatcherWorkers: sc.batcherWorkers, - NodeMapSessionBufferedChanSize: sc.bufferedChanSize, - NodeStoreBatchTimeout: sc.nodeStoreBatchTimeout, - }, + cfg := config.Default() + // Placeholder; updated below once the in-memory server starts. + cfg.ServerURL = "http://localhost:0" + cfg.Noise.PrivateKeyPath = tmpDir + "/noise_private.key" + cfg.Node.Expiry = sc.nodeExpiry + cfg.Prefixes.V4 = &prefixV4 + cfg.Prefixes.V6 = &prefixV6 + cfg.Database.Type = types.DatabaseSqlite + cfg.Database.Sqlite.Path = tmpDir + "/headscale_test.db" + cfg.Policy.Mode = types.PolicyModeDB + cfg.Taildrop.Enabled = sc.taildropEnabled + cfg.LogTail.Enabled = sc.logTailEnabled + cfg.Tuning.BatchChangeDelay = sc.batchDelay + cfg.Tuning.BatcherWorkers = sc.batcherWorkers + cfg.Tuning.NodeMapSessionBufferedChanSize = sc.bufferedChanSize + + if sc.nodeStoreBatchTimeout > 0 { + cfg.Tuning.NodeStoreBatchTimeout = sc.nodeStoreBatchTimeout } + // Off unless an option sets them: each needs a value Default leaves + // to the operator. + cfg.DNSConfig.MagicDNS = false + cfg.DNSConfig.OverrideLocalDNS = false + if sc.magicDNSDomain != "" { cfg.DNSConfig.MagicDNS = true cfg.DNSConfig.BaseDomain = sc.magicDNSDomain @@ -207,6 +199,7 @@ func NewServer(tb testing.TB, opts ...ServerOption) *TestServer { if sc.certProvider != nil { cfg.DNSConfig.Certificates = types.CertificatesConfig{Enabled: true, Zone: cfg.DNSConfig.BaseDomain} cfg.DNSConfig.Challenge.Provider = sc.certProvider + cfg.DNSConfig.Challenge.PropagationTimeout = 0 } if len(sc.dnsResolvers) > 0 { @@ -219,6 +212,10 @@ func NewServer(tb testing.TB, opts ...ServerOption) *TestServer { tb.Fatalf("servertest: NewHeadscale: %v", err) } + // 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 + // Registered first so clients, HTTP, and background subsystems stop first. tb.Cleanup(func() { err := app.GetState().Close() diff --git a/hscontrol/testdata/apiv1_golden/TestAPIV1AuthRegister_happy_path_parity.json b/hscontrol/testdata/apiv1_golden/TestAPIV1AuthRegister_happy_path_parity.json index bb7b041b1..26b2c2f64 100644 --- a/hscontrol/testdata/apiv1_golden/TestAPIV1AuthRegister_happy_path_parity.json +++ b/hscontrol/testdata/apiv1_golden/TestAPIV1AuthRegister_happy_path_parity.json @@ -10,7 +10,10 @@ "expiry": null, "givenName": "regnode", "id": "1", - "ipAddresses": [], + "ipAddresses": [ + "100.64.0.1", + "fd7a:115c:a1e0::1" + ], "lastSeen": "\u003ctimestamp\u003e", "machineKey": "\u003csecret\u003e", "name": "regnode", diff --git a/hscontrol/testdata/apiv1_golden/TestAPIV1NodeGet_happy_parity.json b/hscontrol/testdata/apiv1_golden/TestAPIV1NodeGet_happy_parity.json index d77237634..a1aa00a2d 100644 --- a/hscontrol/testdata/apiv1_golden/TestAPIV1NodeGet_happy_parity.json +++ b/hscontrol/testdata/apiv1_golden/TestAPIV1NodeGet_happy_parity.json @@ -10,7 +10,10 @@ "expiry": null, "givenName": "node-a", "id": "1", - "ipAddresses": [], + "ipAddresses": [ + "100.64.0.1", + "fd7a:115c:a1e0::1" + ], "lastSeen": "\u003ctimestamp\u003e", "machineKey": "\u003csecret\u003e", "name": "node-a", diff --git a/hscontrol/testdata/apiv1_golden/TestAPIV1NodeGet_tagged_node_parity.json b/hscontrol/testdata/apiv1_golden/TestAPIV1NodeGet_tagged_node_parity.json index 948d949a6..321bde28e 100644 --- a/hscontrol/testdata/apiv1_golden/TestAPIV1NodeGet_tagged_node_parity.json +++ b/hscontrol/testdata/apiv1_golden/TestAPIV1NodeGet_tagged_node_parity.json @@ -10,7 +10,10 @@ "expiry": null, "givenName": "node-b", "id": "1", - "ipAddresses": [], + "ipAddresses": [ + "100.64.0.1", + "fd7a:115c:a1e0::1" + ], "lastSeen": "\u003ctimestamp\u003e", "machineKey": "\u003csecret\u003e", "name": "node-b", diff --git a/hscontrol/testdata/apiv1_golden/TestAPIV1NodeList_all_parity.json b/hscontrol/testdata/apiv1_golden/TestAPIV1NodeList_all_parity.json index 599be07d1..80b2de7fa 100644 --- a/hscontrol/testdata/apiv1_golden/TestAPIV1NodeList_all_parity.json +++ b/hscontrol/testdata/apiv1_golden/TestAPIV1NodeList_all_parity.json @@ -11,7 +11,10 @@ "expiry": null, "givenName": "node-a", "id": "1", - "ipAddresses": [], + "ipAddresses": [ + "100.64.0.1", + "fd7a:115c:a1e0::1" + ], "lastSeen": "\u003ctimestamp\u003e", "machineKey": "\u003csecret\u003e", "name": "node-a", @@ -60,7 +63,10 @@ "expiry": null, "givenName": "node-b", "id": "2", - "ipAddresses": [], + "ipAddresses": [ + "100.64.0.2", + "fd7a:115c:a1e0::2" + ], "lastSeen": "\u003ctimestamp\u003e", "machineKey": "\u003csecret\u003e", "name": "node-b", diff --git a/hscontrol/testdata/apiv1_golden/TestAPIV1NodeList_filter_by_user_parity.json b/hscontrol/testdata/apiv1_golden/TestAPIV1NodeList_filter_by_user_parity.json index ddd3f03f2..411a629e0 100644 --- a/hscontrol/testdata/apiv1_golden/TestAPIV1NodeList_filter_by_user_parity.json +++ b/hscontrol/testdata/apiv1_golden/TestAPIV1NodeList_filter_by_user_parity.json @@ -11,7 +11,10 @@ "expiry": null, "givenName": "node-a", "id": "1", - "ipAddresses": [], + "ipAddresses": [ + "100.64.0.1", + "fd7a:115c:a1e0::1" + ], "lastSeen": "\u003ctimestamp\u003e", "machineKey": "\u003csecret\u003e", "name": "node-a", diff --git a/hscontrol/testdata/apiv1_golden/TestAPIV1NodeRegister_happy_parity.json b/hscontrol/testdata/apiv1_golden/TestAPIV1NodeRegister_happy_parity.json index a2728ca5e..b56cb4b4c 100644 --- a/hscontrol/testdata/apiv1_golden/TestAPIV1NodeRegister_happy_parity.json +++ b/hscontrol/testdata/apiv1_golden/TestAPIV1NodeRegister_happy_parity.json @@ -10,7 +10,10 @@ "expiry": null, "givenName": "registered-node", "id": "1", - "ipAddresses": [], + "ipAddresses": [ + "100.64.0.1", + "fd7a:115c:a1e0::1" + ], "lastSeen": "\u003ctimestamp\u003e", "machineKey": "\u003csecret\u003e", "name": "registered-node",