feat!: simplified rule with regex instead of boolean

BREAKING CHANGE: the "regex" field in the rule is now a regular expression instead of a boolean.
This commit is contained in:
Henrique Dias
2024-07-29 10:11:02 +02:00
parent d3732322bc
commit e7e9c3176d
7 changed files with 22 additions and 25 deletions
+6 -1
View File
@@ -6,6 +6,7 @@ import (
"path/filepath"
"strings"
"github.com/go-viper/mapstructure/v2"
"github.com/spf13/pflag"
"github.com/spf13/viper"
)
@@ -101,7 +102,11 @@ func ParseConfig(filename string, flags *pflag.FlagSet) (*Config, error) {
}
cfg := &Config{}
err = v.Unmarshal(cfg)
err = v.Unmarshal(cfg, viper.DecodeHook(mapstructure.ComposeDecodeHookFunc(
mapstructure.StringToTimeDurationHookFunc(),
mapstructure.StringToSliceHookFunc(","),
mapstructure.TextUnmarshallerHookFunc(),
)))
if err != nil {
return nil, err
}
+5 -7
View File
@@ -176,11 +176,9 @@ auth: false
scope: /
modify: true
rules:
- path: '^.+\.js$'
regex: true
- regex: '^.+\.js$'
modify: true
- path: /public/access/
regex: false
modify: true`
cfg := writeAndParseConfig(t, content, ".yaml")
@@ -189,12 +187,12 @@ rules:
require.Len(t, cfg.Rules, 2)
require.Empty(t, cfg.Rules[0].Path)
require.NotNil(t, cfg.Rules[0].Regexp)
require.True(t, cfg.Rules[0].Regexp.MatchString("/my/path/to/file.js"))
require.False(t, cfg.Rules[0].Regexp.MatchString("/my/path/to/file.ts"))
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].Regexp)
require.Nil(t, cfg.Rules[1].Regex)
}
func TestConfigEnv(t *testing.T) {
+1 -2
View File
@@ -161,8 +161,7 @@ users:
- username: basic
password: basic
rules:
- path: "^.+.js$"
regex: true
- regex: "^.+.js$"
modify: false
- path: "/b"
modify: false
+6 -13
View File
@@ -1,6 +1,7 @@
package lib
import (
"errors"
"fmt"
"net/http"
"regexp"
@@ -15,23 +16,15 @@ var readMethods = []string{
}
type Rule struct {
Regex bool
Allow bool
Modify bool
Path string
// TODO: remove Regex and replace by this. It encodes
Regexp *regexp.Regexp `mapstructure:"-"`
Regex *regexp.Regexp
}
func (r *Rule) Validate() error {
if r.Regex {
rp, err := regexp.Compile(r.Path)
if err != nil {
return fmt.Errorf("invalid rule: %w", err)
}
r.Regexp = rp
r.Path = ""
r.Regex = false
if r.Regex != nil && r.Path != "" {
return errors.New("invalid rule: cannot define both regex and path")
}
return nil
@@ -39,8 +32,8 @@ func (r *Rule) Validate() error {
// Matches checks if [Rule] matches the given path.
func (r *Rule) Matches(path string) bool {
if r.Regexp != nil {
return r.Regexp.MatchString(path)
if r.Regex != nil {
return r.Regex.MatchString(path)
}
return strings.HasPrefix(path, r.Path)