cli: add check policy

check policy and policy set share ValidatePolicy; tests and sshTests
run against stand-ins built from the policy. Replaces policy check.

Fixes #3355
This commit is contained in:
Kristoffer Dalby committed 2026-11-11 12:06:27 +01:00
1 parent 0fe0545b3d
commit f5fd1d16cf
11 files changed
+635 -288

No files matched your search

+39 -1
View File
@@ -1,12 +1,50 @@
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 files",
}
var checkPolicyCmd = &cobra.Command{
Use: "policy",
Short: "Check a policy file for errors",
Long: `
Check the policy file for errors and run its "tests" and "sshTests".
The tests run against one node for each user and tag the policy names,
not against your tailnet, so "headscale policy set" can still disagree
with them.`,
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
},
}
+78
View File
@@ -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", "", `policy is empty, use "{}" to allow all`},
{"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))
})
}
+4 -77
View File
@@ -36,9 +36,9 @@ func bypassDatabase() (*db.HSDatabase, error) {
return d, nil
}
// validateOfflinePolicy checks policyBytes against the database's users and
// validateLocalPolicy checks policyBytes against the database's users and
// nodes as a server-side policy write would.
func validateOfflinePolicy(d *db.HSDatabase, policyBytes []byte) error {
func validateLocalPolicy(d *db.HSDatabase, policyBytes []byte) error {
users, err := d.ListUsers(nil)
if err != nil {
return fmt.Errorf("loading users for policy validation: %w", err)
@@ -49,16 +49,7 @@ func validateOfflinePolicy(d *db.HSDatabase, policyBytes []byte) error {
return fmt.Errorf("loading nodes for policy validation: %w", err)
}
// SetPolicy enforces user references, tests, and sshTests for writes;
// the constructor permits stored policies whose tests no longer pass.
pm, err := policy.NewPolicyManager(policyBytes, users, nodes.ViewSlice())
if err != nil {
return fmt.Errorf("parsing policy file: %w", err)
}
_, err = pm.SetPolicy(policyBytes)
return err
return policy.ValidatePolicy(policyBytes, users, nodes.ViewSlice())
}
// openBypassDB confirms the destructive bypass action and opens the database
@@ -81,11 +72,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{
@@ -163,7 +149,7 @@ var setPolicy = &cobra.Command{
}
defer d.Close()
err = validateOfflinePolicy(d, policyBytes)
err = validateLocalPolicy(d, policyBytes)
if err != nil {
return err
}
@@ -199,62 +185,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
},
}
+6
View File
@@ -124,6 +124,12 @@ func NewPolicyManager(pol []byte, users []types.User, nodes views.Slice[types.No
return polMan, err
}
// ValidatePolicy reports whether a policy write of pol would be accepted
// against users and nodes; see [policyv2.ValidatePolicy].
func ValidatePolicy(pol []byte, users []types.User, nodes views.Slice[types.NodeView]) error {
return policyv2.ValidatePolicy(pol, users, nodes)
}
// PolicyManagersForTest returns all available [PolicyManager] implementations to
// be used in tests to validate them in tests that try to determine that they
// behave the same.
+1 -1
View File
@@ -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@"]},
@@ -355,3 +355,99 @@ func compatChecksNotRun(t *testing.T, skips map[string]string, keys ...string) {
}
}
}
// standInTesterSkipReasons lists, keyed <test_id>/<check>, 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 standInTesterSkipReasons = 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 [CheckPolicy] 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, standInTesterSkipReasons, c.TestID+"/", users, nodes)
})
}
}
}
// standInVerdictSkipReasons lists, keyed <test_id>/verdict, the captures
// [CheckPolicy] accepts or refuses differently from [ValidatePolicy] against
// the captured topology.
var standInVerdictSkipReasons = 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: [CheckPolicy] refuses a policy
// exactly when [ValidatePolicy], which "headscale policy set" runs, refuses it
// against the captured topology.
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)
err := ValidatePolicy(b, users, buildGrantsNodesFromCapture(users, c).ViewSlice())
standIn := CheckPolicy(b)
compatCheck(t, standInVerdictSkipReasons, c.TestID+"/verdict", func() string {
if (err == nil) == (standIn == nil) {
return ""
}
return fmt.Sprintf("captured topology: %v\nstand-ins: %v", err, standIn)
})
})
}
}
+262 -5
View File
@@ -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 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,257 @@ 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 [ValidatePolicy], the check `headscale policy set` runs,
// against stand-ins from [standIns] instead of a tailnet.
func CheckPolicy(b []byte) error {
pol, err := ParsePolicy(b)
if err != nil {
return fmt.Errorf("parsing policy: %w", err)
}
var (
users types.Users
nodes types.Nodes
)
// Empty input parses to no policy, which ValidatePolicy refuses.
if pol != nil {
users, nodes = standIns(pol)
}
return ValidatePolicy(b, users, nodes.ViewSlice())
}
// ValidatePolicy reports whether a policy write of b would be accepted
// against users and nodes. It runs the [PolicyManager.SetPolicy] write
// boundary, `tests` and `sshTests` included, on a throwaway manager.
func ValidatePolicy(b []byte, users types.Users, nodes views.Slice[types.NodeView]) error {
pm, err := NewPolicyManager(nil, users, nodes)
if err != nil {
return fmt.Errorf("creating policy manager: %w", err)
}
_, err = pm.SetPolicy(b)
if err != nil {
return err
}
// SSH rules compile per node, so without nodes this cannot catch every
// case. The base URL only fills check-action URLs, which nothing reads.
if nodes.Len() > 0 {
_, err = pm.SSHPolicy("", nodes.At(0))
if err != nil {
return fmt.Errorf("verifying SSH rules: %w", err)
}
}
return nil
}
// standIns returns the users and nodes [CheckPolicy] evaluates pol
// against: a user, with one node, for every user pol names, one for each
// `user:*@domain` in that domain, and a node for every tag pol 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:
// The user: prefix is dropped: user:*@domain becomes a user
// named and mailed *@domain, user:alice@ the user alice.
names[strings.TrimSuffix(strings.TrimPrefix(string(*a), "user:"), "@")] = 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)
}
}
}
+129
View File
@@ -711,3 +711,132 @@ 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{
"*@example.com", "ad", "as", "e@example.com", "g", "gd", "gs", "na", "o",
"r", "ss", "td", "tn", "ts", "xs",
}, names, "one user per user token and per user:*@ domain, sorted")
require.Equal(t, "e@example.com", users[3].Email)
require.Empty(t, users[1].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")
}
t.Run("user:*@domain", func(t *testing.T) {
b := []byte(`{
"acls": [{"action": "accept", "src": ["alice@"], "dst": ["user:*@example.com:22"]}],
"tests": [{"src": "alice@", "accept": ["user:*@example.com:22"]}]
}`)
pol, err := ParsePolicy(b)
require.NoError(t, err)
users, _ := standIns(pol)
var inDomain []string
for _, u := range users {
if strings.HasSuffix(u.Email, "@example.com") {
inDomain = append(inDomain, u.Email)
}
}
require.Len(t, inDomain, 1, "one stand-in in the domain")
require.NoError(t, CheckPolicy(b), "the test reaches the domain's stand-in")
})
}
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", ``, ErrPolicyEmpty},
{"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)
}
})
}
}
+16
View File
@@ -1667,6 +1667,22 @@ func TestReloadPolicyEmpty(t *testing.T) {
})
}
// TestNewStateEmptyPolicyFile: startup takes an empty policy file as no
// policy, although a write, a reload and "headscale check policy" refuse it.
func TestNewStateEmptyPolicyFile(t *testing.T) {
cfg := persistTestConfig(t.TempDir() + "/headscale.db")
cfg.Policy = types.PolicyConfig{
Mode: types.PolicyModeFile,
Path: filepath.Join(t.TempDir(), "policy.hujson"),
}
require.NoError(t, os.WriteFile(cfg.Policy.Path, nil, 0o600))
s, err := NewState(cfg)
require.NoError(t, err)
require.NoError(t, s.Close())
}
// TestNodeWriteChangeWhenPolicyRefreshFails fails both the NodeStore
// writer's SetNodes and the caller's. The write still reached the
// NodeStore, so the change returned with the error must resend the node to
+4 -20
View File
@@ -1890,36 +1890,20 @@ func (s *State) SetPolicyInDB(data string) (*types.Policy, error) {
return s.db.SetPolicy(data)
}
// ValidatePolicy reports whether [State.UpdatePolicy] would accept pol. It
// compiles pol against the current users and nodes on a throwaway policy
// manager; the live policy is not touched.
// ValidatePolicy reports whether [State.UpdatePolicy] would accept pol,
// checking it against the current users and nodes with
// [policy.ValidatePolicy]; the live policy is not touched.
func (s *State) ValidatePolicy(pol []byte) error {
users, err := s.ListAllUsers()
if err != nil {
return fmt.Errorf("loading users: %w", err)
}
nodes := s.ListNodes()
pm, err := policy.NewPolicyManager(nil, users, nodes)
if err != nil {
return fmt.Errorf("creating policy manager: %w", err)
}
_, err = pm.SetPolicy(pol)
err = policy.ValidatePolicy(pol, users, s.ListNodes())
if err != nil {
return invalidPolicyError{err}
}
// SSH rules compile per node, so a server without nodes cannot catch
// every case here.
if nodes.Len() > 0 {
_, err = pm.SSHPolicy(s.cfg.ServerURL, nodes.At(0))
if err != nil {
return invalidPolicyError{fmt.Errorf("verifying SSH rules: %w", err)}
}
}
return nil
}
-184
View File
@@ -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