From 8da5a8743a15139fe390aa1bdab5c3ee9bcd5931 Mon Sep 17 00:00:00 2001 From: Kristoffer Dalby Date: Wed, 19 Mar 2025 10:32:41 +0100 Subject: [PATCH] add testcases Signed-off-by: Kristoffer Dalby --- hscontrol/policy/v2/types.go | 18 +++++++------- hscontrol/policy/v2/types_test.go | 40 +++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 9 deletions(-) diff --git a/hscontrol/policy/v2/types.go b/hscontrol/policy/v2/types.go index 6e644539..677ab649 100644 --- a/hscontrol/policy/v2/types.go +++ b/hscontrol/policy/v2/types.go @@ -8,6 +8,8 @@ import ( "strings" "time" + "slices" + "github.com/juanfont/headscale/hscontrol/types" "github.com/juanfont/headscale/hscontrol/util" "github.com/tailscale/hujson" @@ -237,8 +239,8 @@ func (t Tag) CanBeAutoApprover() bool { type Host string func (h Host) Validate() error { - if isHost(string(h)) { - fmt.Errorf("Hostname %q is invalid", h) + if !isHost(string(h)) { + return fmt.Errorf("Hostname %q is invalid", h) } return nil } @@ -379,10 +381,8 @@ const ( var autogroups = []string{AutoGroupInternet} func (ag AutoGroup) Validate() error { - for _, valid := range autogroups { - if valid == string(ag) { - return nil - } + if slices.Contains(autogroups, string(ag)) { + return nil } return fmt.Errorf("AutoGroup is invalid, got: %q, must be one of %v", ag, autogroups) @@ -525,7 +525,7 @@ Please check the format and try again.`, vs) type AliasEnc struct{ Alias } func (ve *AliasEnc) UnmarshalJSON(b []byte) error { - ptr, err := unmarshalPointer[Alias]( + ptr, err := unmarshalPointer( b, parseAlias, ) @@ -631,7 +631,7 @@ Please check the format and try again.`, s) type AutoApproverEnc struct{ AutoApprover } func (ve *AutoApproverEnc) UnmarshalJSON(b []byte) error { - ptr, err := unmarshalPointer[AutoApprover]( + ptr, err := unmarshalPointer( b, parseAutoApprover, ) @@ -651,7 +651,7 @@ type Owner interface { type OwnerEnc struct{ Owner } func (ve *OwnerEnc) UnmarshalJSON(b []byte) error { - ptr, err := unmarshalPointer[Owner]( + ptr, err := unmarshalPointer( b, parseOwner, ) diff --git a/hscontrol/policy/v2/types_test.go b/hscontrol/policy/v2/types_test.go index 2218685e..b12df112 100644 --- a/hscontrol/policy/v2/types_test.go +++ b/hscontrol/policy/v2/types_test.go @@ -361,6 +361,46 @@ func TestUnmarshalPolicy(t *testing.T) { `, wantErr: `AutoGroup is invalid, got: "autogroup:invalid", must be one of [autogroup:internet]`, }, + { + name: "undefined-hostname-errors", + input: ` +{ + "acls": [ + { + "action": "accept", + "src": [ + "user1" + ], + "dst": [ + "user1:*" + ] + } + ] +} +`, + wantErr: `Host "user1" is not defined in the Policy, please define or remove the reference to it`, + }, + { + name: "defined-hostname-does-not-err", + input: ` +{ + "hosts": { + "user1": "100.100.100.100", + }, + "acls": [ + { + "action": "accept", + "src": [ + "user1" + ], + "dst": [ + "user1:*" + ] + } + ] +} +`, + }, } cmps := append(util.Comparers, cmp.Comparer(func(x, y Prefix) bool {