diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f0345a1e..936272941 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -178,6 +178,7 @@ is not connected, or refuses is "not found". See [the client docs](https://heads - `--output json` / `--output yaml` now emit the API's shape — camelCase fields, string-encoded IDs, RFC3339 timestamps — instead of the old Protobuf encoding [#3324](https://github.com/juanfont/headscale/pull/3324) - `headscale policy` renames the database-bypass flag from `--bypass-grpc-and-access-database-directly` to `--bypass-server-and-access-database-directly` [#3324](https://github.com/juanfont/headscale/pull/3324) +- `headscale policy check` is now `headscale check policy` and runs offline only: it needs no server, database or config. It runs every check `headscale policy set` runs, including `tests` and `sshTests`, against stand-ins built from the policy: a user, with one node, for every user the policy names, and a node for every tag it declares. So every named user is taken to exist, an IP address or `hosts` entry matches no stand-in node, no user has two nodes and no node has two tags. Its database-bypass flag and its server mode are removed; `headscale policy set` still checks against the live tailnet [#3668](https://github.com/juanfont/headscale/pull/3668) [#3355](https://github.com/juanfont/headscale/issues/3355) #### NixOS module diff --git a/cmd/headscale/cli/check.go b/cmd/headscale/cli/check.go index 9bc70daf1..0a5e3259a 100644 --- a/cmd/headscale/cli/check.go +++ b/cmd/headscale/cli/check.go @@ -1,12 +1,58 @@ package cli -import "github.com/spf13/cobra" +import ( + "fmt" + "os" + + policyv2 "github.com/juanfont/headscale/hscontrol/policy/v2" + "github.com/spf13/cobra" +) func init() { rootCmd.AddCommand(checkCmd) + + checkPolicyCmd.Flags().StringP("file", "f", "", "Path to a policy file in HuJSON format") + mustMarkRequired(checkPolicyCmd, "file") + checkCmd.AddCommand(checkPolicyCmd) } var checkCmd = &cobra.Command{ Use: "check", - Short: "Check configuration or policy without a running server", + Short: "Check configuration or policy files", +} + +var checkPolicyCmd = &cobra.Command{ + Use: "policy", + Short: "Check the Policy file for errors", + Long: ` + Check runs every check "headscale policy set" runs, including the + policy's "tests" and "sshTests", without a server, database or config. + + Instead of a tailnet, it builds stand-ins from the policy: a user, with + one node, for every user the policy names, and a node for every tag it + declares. So: + + - every user the policy names is taken to exist; + - an IP address or hosts entry matches no stand-in node; + - no user has two nodes, and no node has two tags; + - "alice@" and "alice@example.com" are two different users. + + "headscale policy set" checks the policy against the live tailnet.`, + RunE: func(cmd *cobra.Command, args []string) error { + policyPath, _ := cmd.Flags().GetString("file") + + policyBytes, err := os.ReadFile(policyPath) + if err != nil { + return fmt.Errorf("reading policy file: %w", err) + } + + err = policyv2.CheckPolicy(policyBytes) + if err != nil { + return err + } + + fmt.Fprintln(cmd.OutOrStdout(), "Policy is valid") + + return nil + }, } diff --git a/cmd/headscale/cli/check_test.go b/cmd/headscale/cli/check_test.go index c1779dc9a..51853e996 100644 --- a/cmd/headscale/cli/check_test.go +++ b/cmd/headscale/cli/check_test.go @@ -1,8 +1,13 @@ package cli import ( + "bytes" + "os" + "path/filepath" "testing" + policyv2 "github.com/juanfont/headscale/hscontrol/policy/v2" + "github.com/spf13/cobra" "github.com/stretchr/testify/require" ) @@ -30,3 +35,76 @@ func TestSkipsInitConfig(t *testing.T) { }) } } + +func newCheckPolicyCmd(t *testing.T, path string) (*cobra.Command, *bytes.Buffer) { + t.Helper() + + cmd := &cobra.Command{} + cmd.Flags().String("file", path, "") + + var buf bytes.Buffer + + cmd.SetOut(&buf) + + return cmd, &buf +} + +func TestCheckPolicy(t *testing.T) { + const ( + valid = `{"acls":[{"action":"accept","src":["*"],"dst":["*:*"]}]}` + failingTest = `{"acls":[],"tests":[{"src":"alice@","accept":["bob@:22"]}]}` + passingTest = `{"acls":[{"action":"accept","src":["alice@"],"dst":["bob@:22"]}],"tests":[{"src":"alice@","accept":["bob@:22"]}]}` //nolint:gosec // policy fixture + failingSSH = `{"tagOwners":{"tag:web":["alice@"]},"sshTests":[{"src":"alice@","dst":["tag:web"],"accept":["root"]}]}` + ) + + writePolicy := func(t *testing.T, body string) string { + t.Helper() + + p := filepath.Join(t.TempDir(), "policy.hujson") + require.NoError(t, os.WriteFile(p, []byte(body), 0o600)) + + return p + } + + for _, tt := range []struct { + name string + policy string + wantErr string + }{ + {"valid", valid, ""}, + {"empty file", "", ""}, + {"tests pass", passingTest, ""}, + {"tests fail", failingTest, "test(s) failed"}, + {"sshTests fail", failingSSH, "test(s) failed"}, + {"undefined group", `{"acls":[{"action":"accept","src":["group:missing"],"dst":["*:*"]}]}`, policyv2.ErrGroupNotDefined.Error()}, + } { + t.Run(tt.name, func(t *testing.T) { + cmd, out := newCheckPolicyCmd(t, writePolicy(t, tt.policy)) + + err := checkPolicyCmd.RunE(cmd, nil) + if tt.wantErr != "" { + require.ErrorContains(t, err, tt.wantErr) + require.Empty(t, out.String()) + + return + } + + require.NoError(t, err) + require.Equal(t, "Policy is valid\n", out.String()) + }) + } + + t.Run("missing file", func(t *testing.T) { + cmd, _ := newCheckPolicyCmd(t, filepath.Join(t.TempDir(), "nope.hujson")) + require.ErrorIs(t, checkPolicyCmd.RunE(cmd, nil), os.ErrNotExist) + }) + + t.Run("broken config ignored", func(t *testing.T) { + bad := filepath.Join(t.TempDir(), "bad.yaml") + require.NoError(t, os.WriteFile(bad, []byte("server_url: ["), 0o600)) + t.Setenv("HEADSCALE_CONFIG", bad) + + cmd, _ := newCheckPolicyCmd(t, writePolicy(t, valid)) + require.NoError(t, checkPolicyCmd.RunE(cmd, nil)) + }) +} diff --git a/cmd/headscale/cli/policy.go b/cmd/headscale/cli/policy.go index 6c34b2d7d..0d382af76 100644 --- a/cmd/headscale/cli/policy.go +++ b/cmd/headscale/cli/policy.go @@ -81,11 +81,6 @@ func init() { setPolicy.Flags().BoolP(bypassFlag, "", false, "Uses the headscale config to directly access the database, bypassing the API and does not require the server to be running") mustMarkRequired(setPolicy, "file") policyCmd.AddCommand(setPolicy) - - checkPolicy.Flags().StringP("file", "f", "", "Path to a policy file in HuJSON format") - checkPolicy.Flags().BoolP(bypassFlag, "", false, "Open the database directly (no running server required) to resolve user references and to evaluate the policy's tests and sshTests blocks. Required when those checks are needed.") - mustMarkRequired(checkPolicy, "file") - policyCmd.AddCommand(checkPolicy) } var policyCmd = &cobra.Command{ @@ -199,62 +194,3 @@ var setPolicy = &cobra.Command{ return nil }, } - -var checkPolicy = &cobra.Command{ - Use: "check", - Short: "Check the Policy file for errors", - Long: ` - Check validates the policy against the server's live users and nodes, - running any "tests" or "sshTests" block. By default the command calls a - running headscale over its API; pass --` + bypassFlag + ` to - open the database directly when headscale is not running.`, - RunE: func(cmd *cobra.Command, args []string) error { - policyPath, _ := cmd.Flags().GetString("file") - - policyBytes, err := os.ReadFile(policyPath) - if err != nil { - return fmt.Errorf("reading policy file: %w", err) - } - - if bypass, _ := cmd.Flags().GetBool(bypassFlag); bypass { - d, err := openBypassDB(cmd) - if err != nil { - return err - } - defer d.Close() - - err = validateOfflinePolicy(d, policyBytes) - if err != nil { - return err - } - - fmt.Println("Policy is valid") - - return nil - } - - policyStr := string(policyBytes) - - err = withClient(func(ctx context.Context, client *clientv1.ClientWithResponses) error { - resp, err := client.CheckPolicyWithResponse(ctx, clientv1.CheckPolicyJSONRequestBody{ - Policy: &policyStr, - }) - if err != nil { - return err - } - - if resp.StatusCode() != http.StatusOK { - return apiError(resp.StatusCode(), resp.ApplicationproblemJSONDefault) - } - - return nil - }) - if err != nil { - return err - } - - fmt.Println("Policy is valid") - - return nil - }, -} diff --git a/docs/about/faq.md b/docs/about/faq.md index 101112337..1159fb0a4 100644 --- a/docs/about/faq.md +++ b/docs/about/faq.md @@ -153,7 +153,7 @@ Headscale checks if the policy is valid during startup and refuses to start if i indicates which part of the policy is invalid. Follow these steps to fix your policy: - Dump the policy to a file: `headscale policy get --bypass-server-and-access-database-directly > policy.json` -- Edit and fixup `policy.json`. Use the command `headscale policy check --file policy.json` to validate the policy. +- Edit and fixup `policy.json`. Use the command `headscale check policy --file policy.json` to validate the policy. - Load the modified policy: `headscale policy set --bypass-server-and-access-database-directly --file policy.json` - Start Headscale as usual. diff --git a/hscontrol/policy/v2/policy_test.go b/hscontrol/policy/v2/policy_test.go index 4a2d38393..c845223ba 100644 --- a/hscontrol/policy/v2/policy_test.go +++ b/hscontrol/policy/v2/policy_test.go @@ -3176,7 +3176,7 @@ func TestSetPolicy_DuplicateUsername(t *testing.T) { require.NotNil(t, filter, "filter must remain populated after rejected SetPolicy") } -// Empty users → syntax-only check, used by `headscale policy check`. +// Empty users → user-reference validation is skipped. func TestValidateUserReferences_EmptyUsersTolerant(t *testing.T) { polB := []byte(`{ "groups": {"group:admins": ["yala@"]}, diff --git a/hscontrol/policy/v2/policytester_compat_test.go b/hscontrol/policy/v2/policytester_compat_test.go index 56fc0d1bd..b11ba428a 100644 --- a/hscontrol/policy/v2/policytester_compat_test.go +++ b/hscontrol/policy/v2/policytester_compat_test.go @@ -355,3 +355,102 @@ func compatChecksNotRun(t *testing.T, skips map[string]string, keys ...string) { } } } + +// knownStandInDivergences lists, keyed /, every check where +// a tests or sshTests capture replayed against [standIns] differs from SaaS. +// It replaces the captured-topology maps for that replay. A test from an +// unregistered user passes the breakdown here: its stand-in is not reached, +// as on SaaS. +var knownStandInDivergences = map[string]string{ + "policytest-accept-fail-proto-icmp-not-allowed/breakdown": testEntryErrors, + "policytest-proto-icmp/breakdown": testEntryErrors, + + "policytest-dst-unknown-group/breakdown": testUnknownAlias, + "policytest-src-unknown-group/breakdown": testUnknownAlias, + + "sshtest-host-alias-as-dst/verdict": standInNoNodeAtIP, + "sshtest-ip-literal-src/verdict": standInNoNodeAtIP, + "sshtest-malformed-dst-bare-ipv4/verdict": standInNoNodeAtIP, +} + +const standInNoNodeAtIP = "STAND_IN_NO_NODE_AT_IP: the capture names a real node by IP; no stand-in holds a named address" + +// TestStandInsTesterCompat replays the tests and sshTests captures against +// the stand-ins of an offline check instead of the captured topology. +func TestStandInsTesterCompat(t *testing.T) { + t.Parallel() + + for _, dir := range []string{"policytest_results", "sshtest_results"} { + files, err := filepath.Glob(filepath.Join("testdata", dir, "*.hujson")) + require.NoError(t, err) + require.NotEmpty(t, files, "no captures in %s", dir) + + for _, file := range files { + c, err := testcapture.Read(file) + require.NoError(t, err, "reading %s", file) + + t.Run(c.TestID, func(t *testing.T) { + t.Parallel() + + var ( + users types.Users + nodes types.Nodes + ) + + pol, err := ParsePolicy([]byte(c.Input.FullPolicy)) + if err == nil && pol != nil { + users, nodes = standIns(pol) + } + + _ = runTesterCompatFor(t, c, knownStandInDivergences, c.TestID+"/", users, nodes) + }) + } + } +} + +// knownStandInVerdictDivergences lists, keyed /verdict, the +// captures an offline check accepts or refuses differently from the same +// check against the captured topology. +var knownStandInVerdictDivergences = map[string]string{ + "sshtest-host-alias-as-dst/verdict": standInNoNodeAtIP, + "sshtest-ip-literal-src/verdict": standInNoNodeAtIP, + "sshtest-malformed-dst-bare-ipv4/verdict": standInNoNodeAtIP, +} + +// TestStandInsVerdict replays every capture: an offline check refuses a +// policy exactly when the same check against the captured topology does. +func TestStandInsVerdict(t *testing.T) { + t.Parallel() + + files, err := filepath.Glob(filepath.Join("testdata", "*_results", "*.hujson")) + require.NoError(t, err) + require.NotEmpty(t, files) + + users := setupSSHDataCompatUsers() + + for _, file := range files { + c, err := testcapture.Read(file) + require.NoError(t, err, "reading %s", file) + + t.Run(c.TestID, func(t *testing.T) { + t.Parallel() + + b := []byte(c.Input.FullPolicy) + + captured, err := ParsePolicy(b) + if err == nil && captured != nil { + err = checkPolicyWith(b, users, buildGrantsNodesFromCapture(users, c)) + } + + offline := CheckPolicy(b) + + compatCheck(t, knownStandInVerdictDivergences, c.TestID+"/verdict", func() string { + if (err == nil) == (offline == nil) { + return "" + } + + return fmt.Sprintf("captured topology: %v\nstand-ins: %v", err, offline) + }) + }) + } +} diff --git a/hscontrol/policy/v2/test.go b/hscontrol/policy/v2/test.go index dde9b208a..9a4d40fcb 100644 --- a/hscontrol/policy/v2/test.go +++ b/hscontrol/policy/v2/test.go @@ -3,6 +3,7 @@ package v2 import ( "errors" "fmt" + "maps" "net/netip" "slices" "strings" @@ -17,11 +18,13 @@ import ( // Tailscale's policy file `tests` block validates a policy against operator // assertions: from a given src, named dst:port pairs must be accepted, and -// (optionally) other dst:port pairs must be denied. They run at user-write -// boundaries — `headscale policy set`, file-mode reload after a change, -// `headscale policy check` — and reject the write if any assertion fails. -// Boot-time reload of an already-stored policy does not run them, so a -// stale referenced entity (e.g. a deleted user) cannot lock the server out. +// (optionally) other dst:port pairs must be denied. `headscale policy set` +// and file-mode reload after a change reject the write if any assertion +// fails; `headscale check policy` runs them offline against stand-ins, see +// [CheckPolicy]. +// Boot-time loading of an already-stored policy runs them too but only logs +// failures, so a stale referenced entity (e.g. a deleted user) cannot lock +// the server out. // // The tests evaluate against the compiled global filter rules, which fold in // both `acls` and `grants`, so the `tests` block validates the whole policy. @@ -770,3 +773,236 @@ func portsAllowed(requested []tailcfg.PortRange, allowed tailcfg.PortRange) bool return false } + +// Stand-in nodes take addresses from the ranges headscale allocates from +// by default, so `*` and whole-tailnet ranges reach them as they reach real +// nodes. +var ( + standInPrefix4 = netip.MustParsePrefix("100.64.0.0/10") + standInPrefix6 = netip.MustParsePrefix("fd7a:115c:a1e0::/48") +) + +// CheckPolicy runs every check `headscale policy set` runs, including +// `tests` and `sshTests`, against stand-ins from [standIns] instead of a +// tailnet. Empty input is valid, as at startup. +func CheckPolicy(b []byte) error { + pol, err := ParsePolicy(b) + if err != nil || pol == nil { + return err + } + + users, nodes := standIns(pol) + + return checkPolicyWith(b, users, nodes) +} + +// checkPolicyWith runs the [PolicyManager.SetPolicy] write boundary for b +// against users and nodes. +func checkPolicyWith(b []byte, users types.Users, nodes types.Nodes) error { + pm, err := NewPolicyManager(nil, users, nodes.ViewSlice()) + if err != nil { + return err + } + + _, err = pm.SetPolicy(b) + + return err +} + +// standIns returns the users and nodes an offline check evaluates pol +// against: a user, with one node, for every user pol names and a node for +// every tag it declares. Without a tailnet, every user pol names is taken +// to exist, an IP address or host matches no stand-in, no user has two +// nodes, no node has two tags, and `alice@` and `alice@example.com` are two +// users. The stand-ins skip every address inside a prefix pol names, so a +// rule written with an IP never reaches one by accident. +func standIns(pol *Policy) (types.Users, types.Nodes) { + names := make(map[string]bool) + + var free4, free6 netipx.IPSetBuilder + + free4.AddPrefix(standInPrefix4) + free4.Remove(standInPrefix4.Addr()) + free6.AddPrefix(standInPrefix6) + free6.Remove(standInPrefix6.Addr()) + + add := func(v any) { + switch a := v.(type) { + case *Username: + if !strings.HasPrefix(string(*a), "user:*@") { + names[strings.TrimSuffix(string(*a), "@")] = true + } + case *Prefix: + p := netip.Prefix(*a) + if p.Bits() > standInPrefix4.Bits() && p.Addr().Is4() || + p.Bits() > standInPrefix6.Bits() && p.Addr().Is6() { + free4.RemovePrefix(p) + free6.RemovePrefix(p) + } + } + } + + pol.walkNames(add) + + // The builders hold only valid prefixes, so they cannot fail. + set4, _ := free4.IPSet() + set6, _ := free6.IPSet() + next4, next6 := standInAddrs(set4), standInAddrs(set6) + + users := make(types.Users, 0, len(names)) + + for i, name := range slices.Sorted(maps.Keys(names)) { + u := types.User{ID: uint(i + 1), Name: name} //nolint:gosec // bounded by the policy's size + + if strings.Contains(name, "@") { + u.Email = name + } + + users = append(users, u) + } + + tags := slices.Sorted(maps.Keys(pol.TagOwners)) + nodes := make(types.Nodes, 0, len(users)+len(tags)) + + newNode := func(hostname string) *types.Node { + n := &types.Node{ + ID: types.NodeID(len(nodes) + 1), //nolint:gosec // bounded by the policy's size + Hostname: hostname, + IPv4: next4(), + IPv6: next6(), + } + nodes = append(nodes, n) + + return n + } + + for i := range users { + n := newNode(users[i].Name) + n.User = &users[i] + n.UserID = &users[i].ID + } + + for _, tag := range tags { + newNode(string(tag)).Tags = []string{string(tag)} + } + + return users, nodes +} + +// standInAddrs returns a function yielding the addresses of set in order, +// then nil once they run out. +func standInAddrs(set *netipx.IPSet) func() *netip.Addr { + ranges := set.Ranges() + + var next netip.Addr + + return func() *netip.Addr { + for len(ranges) > 0 { + if !next.IsValid() || next.Compare(ranges[0].From()) < 0 { + next = ranges[0].From() + } + + if next.Compare(ranges[0].To()) <= 0 { + a := next + next = next.Next() + + return &a + } + + ranges = ranges[1:] + } + + return nil + } +} + +// walkNames calls fn with every user, alias, owner, auto approver and +// prefix pol names, test entries included. +func (pol *Policy) walkNames(fn func(any)) { + for _, members := range pol.Groups { + for i := range members { + fn(&members[i]) + } + } + + for _, p := range pol.Hosts { + fn(&p) + } + + for _, owners := range pol.TagOwners { + for _, o := range owners { + fn(o) + } + } + + for route, approvers := range pol.AutoApprovers.Routes { + fn(new(Prefix(route))) + + for _, a := range approvers { + fn(a) + } + } + + for _, a := range pol.AutoApprovers.ExitNode { + fn(a) + } + + for _, acl := range pol.ACLs { + for _, a := range acl.Sources { + fn(a) + } + + for _, d := range acl.Destinations { + fn(d.Alias) + } + } + + for _, g := range pol.Grants { + for _, a := range g.Sources { + fn(a) + } + + for _, a := range g.Destinations { + fn(a) + } + } + + for _, na := range pol.NodeAttrs { + for _, a := range na.Targets { + fn(a) + } + } + + for _, ssh := range pol.SSHs { + for _, a := range ssh.Sources { + fn(a) + } + + for _, a := range ssh.Destinations { + fn(a) + } + } + + for _, test := range pol.Tests { + // A malformed entry names nothing here; running the tests reports it. + src, err := parseAlias(test.Src) + if err == nil { + fn(src) + } + + for _, dst := range slices.Concat(test.Accept, test.Deny) { + awp, err := parseDestinationAlias(dst) + if err == nil { + fn(awp.Alias) + } + } + } + + for _, test := range pol.SSHTests { + fn(test.Src) + + for _, a := range test.Dst { + fn(a) + } + } +} diff --git a/hscontrol/policy/v2/test_test.go b/hscontrol/policy/v2/test_test.go index 4dade080d..81139b410 100644 --- a/hscontrol/policy/v2/test_test.go +++ b/hscontrol/policy/v2/test_test.go @@ -711,3 +711,109 @@ func TestFailureBreakdownIsBounded(t *testing.T) { }) } } + +func TestStandIns(t *testing.T) { + pol, err := ParsePolicy([]byte(`{ + "groups": {"group:a": ["g@"]}, + "hosts": {"h": "100.64.0.1", "net": "100.64.0.8/30"}, + "tagOwners": {"tag:t": ["o@"], "tag:u": ["group:a"]}, + "autoApprovers": { + "routes": {"10.0.0.0/8": ["r@"]}, + "exitNode": ["e@example.com"] + }, + "acls": [ + {"action": "accept", "src": ["as@", "user:*@example.com"], "dst": ["ad@:22", "100.64.0.2:22", "100.64.0.0/10:80", "h:22", "net:22"]} + ], + "grants": [{"src": ["gs@"], "dst": ["gd@"], "ip": ["*"]}], + "nodeAttrs": [{"target": ["na@"], "attr": ["randomize-client-port"]}], + "ssh": [{"action": "accept", "src": ["ss@"], "dst": ["autogroup:self"], "users": ["root"]}], + "tests": [{"src": "ts@", "accept": ["td@:22", "100.64.0.3:22"], "deny": ["tn@:80"]}], + "sshTests": [{"src": "xs@", "dst": ["tag:t"], "accept": ["root"]}] + }`)) + require.NoError(t, err) + + users, nodes := standIns(pol) + + names := make([]string, 0, len(users)) + for i, u := range users { + require.Equal(t, uint(i+1), u.ID) + + names = append(names, u.Name) + } + + require.Equal(t, []string{ + "ad", "as", "e@example.com", "g", "gd", "gs", "na", "o", "r", "ss", + "td", "tn", "ts", "xs", + }, names, "one user per user token, sorted; user:*@ is not a user") + require.Equal(t, "e@example.com", users[2].Email) + require.Empty(t, users[0].Email) + + require.Len(t, nodes, len(users)+2, "one node per user and per tag") + + named := []netip.Prefix{ + mp("100.64.0.0/32"), mp("100.64.0.1/32"), mp("100.64.0.2/32"), + mp("100.64.0.3/32"), mp("100.64.0.8/30"), + } + seen := map[netip.Addr]bool{} + + for i, n := range nodes { + require.Equal(t, types.NodeID(i+1), n.ID) + + if i < len(users) { + require.Empty(t, n.Tags) + require.Equal(t, users[i].ID, *n.UserID) + require.Equal(t, &users[i], n.User) + } else { + require.Equal(t, []string{[]string{"tag:t", "tag:u"}[i-len(users)]}, []string(n.Tags)) + require.Nil(t, n.UserID, "tags own a tagged node") + } + + require.True(t, mp("100.64.0.0/10").Contains(*n.IPv4)) + require.True(t, mp("fd7a:115c:a1e0::/48").Contains(*n.IPv6)) + require.NotEqual(t, mp("fd7a:115c:a1e0::/48").Addr(), *n.IPv6) + + for _, p := range named { + require.False(t, p.Contains(*n.IPv4), "%s is named by the policy", n.IPv4) + } + + require.False(t, seen[*n.IPv4] || seen[*n.IPv6], "addresses are unique") + seen[*n.IPv4], seen[*n.IPv6] = true, true + } + + again, againNodes := standIns(pol) + require.Equal(t, users, again) + require.Len(t, againNodes, len(nodes)) + + for i := range nodes { + require.Equal(t, *nodes[i].IPv4, *againNodes[i].IPv4, "stable addresses") + } +} + +func TestCheckPolicy(t *testing.T) { + const acl = `"acls": [{"action": "accept", "src": ["alice@"], "dst": ["tag:web:22"]}], + "tagOwners": {"tag:web": ["alice@"]}` + + for _, tt := range []struct { + name string + policy string + wantErr error + }{ + {"empty", ``, nil}, + {"no tests", `{` + acl + `}`, nil}, + {"tests pass", `{` + acl + `, "tests": [{"src": "alice@", "accept": ["tag:web:22"], "deny": ["tag:web:80"]}]}`, nil}, + {"tests fail", `{` + acl + `, "tests": [{"src": "bob@", "accept": ["tag:web:22"]}]}`, errPolicyTestsFailed}, + {"sshTests pass", `{` + acl + `, "ssh": [{"action": "accept", "src": ["alice@"], "dst": ["tag:web"], "users": ["root"]}], + "sshTests": [{"src": "alice@", "dst": ["tag:web"], "accept": ["root"]}]}`, nil}, + {"sshTests fail", `{` + acl + `, "sshTests": [{"src": "alice@", "dst": ["tag:web"], "accept": ["root"]}]}`, errSSHPolicyTestsFailed}, + {"undefined group", `{"acls": [{"action": "accept", "src": ["group:x"], "dst": ["*:*"]}]}`, ErrGroupNotDefined}, + } { + t.Run(tt.name, func(t *testing.T) { + err := CheckPolicy([]byte(tt.policy)) + if tt.wantErr == nil { + require.NoError(t, err) + } else { + require.ErrorIs(t, err, tt.wantErr) + } + }) + } +} diff --git a/integration/cli_policy_test.go b/integration/cli_policy_test.go index 0c826c4c2..f15162254 100644 --- a/integration/cli_policy_test.go +++ b/integration/cli_policy_test.go @@ -15,190 +15,6 @@ import ( "tailscale.com/tailcfg" ) -// TestPolicyCheckCommand exercises `headscale policy check` across the -// matrix that nblock asked about on PR #3229: -// -// - policyMode: server runs with policy_mode=file vs policy_mode=database. -// `check` reads from `--file`, so the server-side mode should not -// change the outcome; running both proves that. -// - fixture: ACL only, ACL with passing tests, ACL with failing tests. -// - bypass: no-bypass talks to the server over gRPC; bypass opens the -// database directly. -// -// Each policy mode shares one scenario across its sequential checks because -// policy_mode is fixed at boot. The two users + two nodes give the tests -// block real `user@` aliases to resolve against. Check inputs are separate -// from the live policy, which must remain unchanged after every check. -func TestPolicyCheckCommand(t *testing.T) { - IntegrationSkip(t) - - type fixture struct { - name string - policy policyv2.Policy - } - - const ( - user1 = "user1@" - user2 = "user2@" - ) - - aclOnly := policyv2.Policy{ - ACLs: []policyv2.ACL{ - { - Action: policyv2.ActionAccept, - Protocol: "tcp", //nolint:goconst // protocol literal, used inline once - Sources: []policyv2.Alias{usernamep(user1)}, - Destinations: []policyv2.AliasWithPorts{ - aliasWithPorts(usernamep(user2), tailcfg.PortRange{First: 22, Last: 22}), - }, - }, - }, - } - - aclPlusPassingTests := aclOnly - aclPlusPassingTests.Tests = []policyv2.PolicyTest{ - { - Src: user1, - Accept: []string{user2 + ":22"}, - }, - } - - aclPlusFailingTests := aclOnly - aclPlusFailingTests.Tests = []policyv2.PolicyTest{ - { - // Reverse direction is not allowed by the ACL; the test - // asserts ALLOWED, so it must fail. - Src: user2, - Accept: []string{user1 + ":22"}, - }, - } - - fixtures := []fixture{ - {name: "acl-only", policy: aclOnly}, - {name: "acl-plus-passing-tests", policy: aclPlusPassingTests}, - {name: "acl-plus-failing-tests", policy: aclPlusFailingTests}, - } - - type row struct { - name string - fixture fixture - bypass bool - wantErr string - wantStdout string - } - - modes := []types.PolicyMode{types.PolicyModeFile, types.PolicyModeDB} - bypasses := []bool{false, true} - rows := make([]row, 0, len(fixtures)*len(bypasses)) - - for _, f := range fixtures { - for _, bypass := range bypasses { - suffix := "no-bypass" - if bypass { - suffix = "bypass" - } - - r := row{ - name: f.name + "-" + suffix, - fixture: f, - bypass: bypass, - wantStdout: "Policy is valid", - } - if f.name == "acl-plus-failing-tests" { - r.wantErr = "test(s) failed" - r.wantStdout = "" - } - - rows = append(rows, r) - } - } - - // Use a live policy distinct from every check fixture so an accidental - // policy update is observable, including for the ACL-only fixture. - livePolicy := policyv2.Policy{ - ACLs: []policyv2.ACL{ - { - Action: policyv2.ActionAccept, - Sources: []policyv2.Alias{wildcard()}, - Destinations: []policyv2.AliasWithPorts{ - aliasWithPorts(wildcard(), tailcfg.PortRangeAny), - }, - }, - }, - } - livePolicyBytes, err := json.Marshal(livePolicy) - require.NoError(t, err) - - for _, mode := range modes { - t.Run(string(mode), func(t *testing.T) { - spec := ScenarioSpec{ - NodesPerUser: 1, - Users: []string{"user1", "user2"}, //nolint:goconst // matches usernamep("user1@")/("user2@") above - } - - scenario, err := NewScenario(spec) - require.NoError(t, err) - - t.Cleanup(func() { scenario.ShutdownAssertNoPanics(t) }) - - err = scenario.CreateHeadscaleEnv( - []tsic.Option{}, - hsic.WithTestName("cli-policycheck"), - hsic.WithPolicyMode(mode), - hsic.WithACLPolicy(&livePolicy), - ) - require.NoError(t, err) - - headscale, err := scenario.Headscale() - require.NoError(t, err) - - require.EventuallyWithT(t, func(c *assert.CollectT) { - stdout, err := headscale.Execute([]string{"headscale", "policy", "get"}) - assert.NoError(c, err) - assert.JSONEq(c, string(livePolicyBytes), stdout) - }, integrationutil.StatusReadyTimeout, integrationutil.FastPoll, "live policy should be loaded before checks") - - for _, tt := range rows { - t.Run(tt.name, func(t *testing.T) { - pBytes, err := json.Marshal(tt.fixture.policy) - require.NoError(t, err) - - policyFilePath := "/etc/headscale/policy-check-" + tt.name + ".json" - err = headscale.WriteFile(policyFilePath, pBytes) - require.NoError(t, err) - - t.Cleanup(func() { - assert.EventuallyWithT(t, func(c *assert.CollectT) { - stdout, err := headscale.Execute([]string{"headscale", "policy", "get"}) - assert.NoError(c, err) - assert.JSONEq(c, string(livePolicyBytes), stdout) - }, integrationutil.StatusReadyTimeout, integrationutil.FastPoll, "policy check must not alter the live policy") - }) - - cmd := []string{"headscale", "policy", "check", "-f", policyFilePath} //nolint:goconst // CLI invocation - if tt.bypass { - // --force suppresses the "is the server running?" - // confirmation prompt so the command can run - // non-interactively under the test harness. - cmd = append(cmd, "--bypass-server-and-access-database-directly", "--force") - } - - stdout, err := headscale.Execute(cmd) - - if tt.wantErr != "" { - require.ErrorContains(t, err, tt.wantErr) - - return - } - - require.NoError(t, err) - require.Contains(t, stdout, tt.wantStdout) - }) - } - }) - } -} - // TestSSHTestsRejectFailingPolicy asserts `headscale policy set` rejects // a policy whose sshTests fail, surfaces the engine's "test(s) failed" // sentinel, and leaves the stored policy unchanged. The tests name user1's