fix: error if rule has no regex or path

This commit is contained in:
Henrique Dias
2024-11-28 16:57:10 +01:00
parent d418bd2661
commit 64bbdc7b15
2 changed files with 36 additions and 10 deletions
+32 -10
View File
@@ -192,24 +192,46 @@ cors:
} }
func TestConfigRules(t *testing.T) { 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: / directory: /
rules: rules:
- regex: '^.+\.js$' - regex: '^.+\.js$'
- path: /public/access/` - path: /public/access/`
cfg := writeAndParseConfig(t, content, ".yaml") cfg := writeAndParseConfig(t, content, ".yaml")
require.NoError(t, cfg.Validate()) 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.Empty(t, cfg.Rules[0].Path)
require.NotNil(t, cfg.Rules[0].Regex) require.NotNil(t, cfg.Rules[0].Regex)
require.True(t, cfg.Rules[0].Regex.MatchString("/my/path/to/file.js")) 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.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) { func TestConfigEnv(t *testing.T) {
+4
View File
@@ -16,6 +16,10 @@ type Rule struct {
} }
func (r *Rule) Validate() error { 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 != "" { if r.Regex != nil && r.Path != "" {
return errors.New("invalid rule: cannot define both regex and path") return errors.New("invalid rule: cannot define both regex and path")
} }