From 64bbdc7b15f2aea15d143c9f89063bcf7c6c2b04 Mon Sep 17 00:00:00 2001 From: Henrique Dias Date: Thu, 28 Nov 2024 16:55:39 +0100 Subject: [PATCH] fix: error if rule has no regex or path --- lib/config_test.go | 42 ++++++++++++++++++++++++++++++++---------- lib/permissions.go | 4 ++++ 2 files changed, 36 insertions(+), 10 deletions(-) diff --git a/lib/config_test.go b/lib/config_test.go index e223019..b8d48b2 100644 --- a/lib/config_test.go +++ b/lib/config_test.go @@ -192,24 +192,46 @@ cors: } func TestConfigRules(t *testing.T) { - content := ` + t.Run("Only Regex or Path", func(t *testing.T) { + content := ` +directory: / +rules: + - regex: '^.+\.js$' + path: /public/access/` + + writeAndParseConfigWithError(t, content, ".yaml", "cannot define both regex and path") + }) + + t.Run("Regex or Path Required", func(t *testing.T) { + content := ` +directory: / +rules: + - permissions: CRUD` + + writeAndParseConfigWithError(t, content, ".yaml", "must either define a path of a regex") + }) + + t.Run("Parse", func(t *testing.T) { + content := ` directory: / rules: - regex: '^.+\.js$' - path: /public/access/` - cfg := writeAndParseConfig(t, content, ".yaml") - require.NoError(t, cfg.Validate()) + cfg := writeAndParseConfig(t, content, ".yaml") + require.NoError(t, cfg.Validate()) - require.Len(t, cfg.Rules, 2) + require.Len(t, cfg.Rules, 2) - require.Empty(t, cfg.Rules[0].Path) - require.NotNil(t, cfg.Rules[0].Regex) - require.True(t, cfg.Rules[0].Regex.MatchString("/my/path/to/file.js")) - require.False(t, cfg.Rules[0].Regex.MatchString("/my/path/to/file.ts")) + require.Empty(t, cfg.Rules[0].Path) + require.NotNil(t, cfg.Rules[0].Regex) + require.True(t, cfg.Rules[0].Regex.MatchString("/my/path/to/file.js")) + require.False(t, cfg.Rules[0].Regex.MatchString("/my/path/to/file.ts")) + + require.NotEmpty(t, cfg.Rules[1].Path) + require.Nil(t, cfg.Rules[1].Regex) + }) - require.NotEmpty(t, cfg.Rules[1].Path) - require.Nil(t, cfg.Rules[1].Regex) } func TestConfigEnv(t *testing.T) { diff --git a/lib/permissions.go b/lib/permissions.go index 57e5e91..0fe9f26 100644 --- a/lib/permissions.go +++ b/lib/permissions.go @@ -16,6 +16,10 @@ type Rule struct { } func (r *Rule) Validate() error { + if r.Regex == nil && r.Path == "" { + return errors.New("invalid rule: must either define a path of a regex") + } + if r.Regex != nil && r.Path != "" { return errors.New("invalid rule: cannot define both regex and path") }