From 0fe0545b3d4dabc428045441ebd1603af87bf643 Mon Sep 17 00:00:00 2001 From: Kristoffer Dalby Date: Fri, 6 Nov 2026 14:05:11 +0000 Subject: [PATCH] cli: add check command group that loads config on demand Updates #3355 --- cmd/headscale/cli/check.go | 12 ++++++++ cmd/headscale/cli/check_test.go | 32 +++++++++++++++++++++ cmd/headscale/cli/root.go | 46 ++++++++++++++++++++++++++----- cmd/headscale/cli/root_test.go | 17 ++++++++++++ hscontrol/policy/v2/types.go | 6 ++++ hscontrol/policy/v2/types_test.go | 13 +++++++++ 6 files changed, 119 insertions(+), 7 deletions(-) create mode 100644 cmd/headscale/cli/check.go create mode 100644 cmd/headscale/cli/check_test.go diff --git a/cmd/headscale/cli/check.go b/cmd/headscale/cli/check.go new file mode 100644 index 000000000..a3ec20160 --- /dev/null +++ b/cmd/headscale/cli/check.go @@ -0,0 +1,12 @@ +package cli + +import "github.com/spf13/cobra" + +func init() { + rootCmd.AddCommand(checkCmd) +} + +var checkCmd = &cobra.Command{ + Use: "check", + Short: "Check configuration or policy files", +} diff --git a/cmd/headscale/cli/check_test.go b/cmd/headscale/cli/check_test.go new file mode 100644 index 000000000..c1779dc9a --- /dev/null +++ b/cmd/headscale/cli/check_test.go @@ -0,0 +1,32 @@ +package cli + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestSkipsInitConfig(t *testing.T) { + tests := []struct { + name string + args []string + want bool + }{ + {"check policy", []string{"check", "policy", "-f", "p"}, true}, + {"check policy with config flag", []string{"-c", "x.yaml", "check", "policy"}, true}, + {"check", []string{"check"}, true}, + {"help check policy", []string{"help", "check", "policy"}, true}, + {"policy get", []string{"policy", "get"}, false}, + {"help nodes", []string{"help", "nodes"}, false}, + {"nodes list", []string{"nodes", "list"}, false}, + } + + // Execute adds the help command; these tests call Find without it. + rootCmd.InitDefaultHelpCmd() + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + require.Equal(t, tt.want, skipsInitConfig(tt.args)) + }) + } +} diff --git a/cmd/headscale/cli/root.go b/cmd/headscale/cli/root.go index ff06ea24b..9b982663b 100644 --- a/cmd/headscale/cli/root.go +++ b/cmd/headscale/cli/root.go @@ -1,6 +1,7 @@ package cli import ( + "fmt" "os" "runtime" "slices" @@ -39,7 +40,20 @@ func init() { }) } -func initConfig() { +// skipsInitConfig reports whether args select the check command group, which +// must work without a loadable config. Find runs lazily because init order +// across files is not guaranteed to have registered every command. +func skipsInitConfig(args []string) bool { + cmd, rest, err := rootCmd.Find(args) + // `help check …` must work wherever `check …` does. + if err == nil && cmd.Name() == "help" && cmd.Parent() == rootCmd { + cmd, _, err = rootCmd.Find(rest) + } + + return err == nil && (cmd == checkCmd || cmd.HasParent() && cmd.Parent() == checkCmd) +} + +func loadConfig() error { if cfgFile == "" { cfgFile = os.Getenv("HEADSCALE_CONFIG") } @@ -47,13 +61,31 @@ func initConfig() { if cfgFile != "" { err := types.LoadConfig(cfgFile, true) if err != nil { - log.Fatal().Caller().Err(err).Msgf("error loading config file %s", cfgFile) - } - } else { - err := types.LoadConfig("", false) - if err != nil { - log.Fatal().Caller().Err(err).Msgf("error loading config") + return fmt.Errorf("loading config file %s: %w", cfgFile, err) } + + return nil + } + + err := types.LoadConfig("", false) + if err != nil { + return fmt.Errorf("loading config: %w", err) + } + + return nil +} + +func initConfig() { + if skipsInitConfig(os.Args[1:]) { + // Loading a config sets the log level; without one, use log.level's default. + zerolog.SetGlobalLevel(zerolog.InfoLevel) + + return + } + + err := loadConfig() + if err != nil { + log.Fatal().Caller().Err(err).Msg("error loading config") } machineOutput := hasMachineOutputFlag() diff --git a/cmd/headscale/cli/root_test.go b/cmd/headscale/cli/root_test.go index 9f444ee45..400b91f4e 100644 --- a/cmd/headscale/cli/root_test.go +++ b/cmd/headscale/cli/root_test.go @@ -8,6 +8,7 @@ import ( "github.com/juanfont/headscale/hscontrol/db" "github.com/juanfont/headscale/hscontrol/types" + "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/spf13/viper" "github.com/stretchr/testify/require" @@ -416,3 +417,19 @@ dns: }) } } + +func TestInitConfigSkippedLogLevel(t *testing.T) { + oldArgs, oldLevel := os.Args, zerolog.GlobalLevel() + + t.Cleanup(func() { + os.Args = oldArgs + + zerolog.SetGlobalLevel(oldLevel) + }) + + os.Args = []string{"headscale", "check", "policy", "-f", "p"} + + zerolog.SetGlobalLevel(zerolog.TraceLevel) + initConfig() + require.Equal(t, zerolog.InfoLevel, zerolog.GlobalLevel(), "log.level's default, as with a config") +} diff --git a/hscontrol/policy/v2/types.go b/hscontrol/policy/v2/types.go index 2769b1252..6b12f96fb 100644 --- a/hscontrol/policy/v2/types.go +++ b/hscontrol/policy/v2/types.go @@ -3411,6 +3411,12 @@ func stripMetadataMembers(v *hujson.Value) { } } +// ParsePolicy parses and validates a policy without users or nodes: syntax, +// shape and cross-reference checks only. Empty input returns nil, nil. +func ParsePolicy(b []byte) (*Policy, error) { + return unmarshalPolicy(b) +} + // unmarshalPolicy takes a byte slice and unmarshals it into a [Policy] struct. // In addition to unmarshalling, it will also validate the policy. // This is the only entrypoint of reading a policy from a file or other source. diff --git a/hscontrol/policy/v2/types_test.go b/hscontrol/policy/v2/types_test.go index 0e4a18775..8976933d3 100644 --- a/hscontrol/policy/v2/types_test.go +++ b/hscontrol/policy/v2/types_test.go @@ -6902,3 +6902,16 @@ func TestSetPolicyBareAtToken(t *testing.T) { } } } + +func TestParsePolicy(t *testing.T) { + pol, err := ParsePolicy([]byte(`{"acls":[{"action":"accept","src":["*"],"dst":["*:*"]}]}`)) + require.NoError(t, err) + require.NotNil(t, pol) + + _, err = ParsePolicy([]byte(`{"acls":[{"action":"accept","src":["group:missing"],"dst":["*:*"]}]}`)) + require.ErrorIs(t, err, ErrGroupNotDefined) + + pol, err = ParsePolicy([]byte("")) + require.NoError(t, err) + require.Nil(t, pol) +}