mirror of
https://github.com/juanfont/headscale.git
synced 2026-11-19 20:04:32 +09:00
cli: check policies offline
tests and sshTests run against stand-in users and nodes built from the policy. --database, --server and the policy check stub are gone. Fixes #3355
This commit is contained in:
1 parent
f8158a0a66
commit
e815fc244d
10 files changed
+575
-257
No files matched your search
@@ -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
|
||||
},
|
||||
}
|
||||
@@ -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))
|
||||
})
|
||||
}
|
||||
@@ -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
|
||||
},
|
||||
}
|
||||
Reference in new issue
Block a user