Skip to content

Commit

Permalink
fix: error if rule has no regex or path
Browse files Browse the repository at this point in the history
  • Loading branch information
hacdias committed Nov 28, 2024
1 parent d418bd2 commit 64bbdc7
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 10 deletions.
42 changes: 32 additions & 10 deletions lib/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
4 changes: 4 additions & 0 deletions lib/permissions.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
Expand Down

0 comments on commit 64bbdc7

Please sign in to comment.