Skip to content

Commit

Permalink
Update regex to prevent greedy matching in REST path and add correspo…
Browse files Browse the repository at this point in the history
…nding test
  • Loading branch information
cognitivegears committed Jan 4, 2025
1 parent d9f23ee commit 497cac1
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
2 changes: 1 addition & 1 deletion internal/operators/restpath.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ var _ plugintypes.Operator = (*restpath)(nil)
func newRESTPath(options plugintypes.OperatorOptions) (plugintypes.Operator, error) {
data := strings.ReplaceAll(options.Arguments, "/", "\\/")
for _, token := range rePathTokenRe.FindAllStringSubmatch(data, -1) {
data = strings.Replace(data, token[0], fmt.Sprintf("(?P<%s>.*)", token[1]), 1)
data = strings.Replace(data, token[0], fmt.Sprintf("(?P<%s>[^?/]*)", token[1]), 1)
}

re, err := memoize.Do(data, func() (interface{}, error) { return regexp.Compile(data) })
Expand Down
27 changes: 27 additions & 0 deletions internal/operators/restpath_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,30 @@ func TestRestPathQueryShouldNotBeIncluded(t *testing.T) {
t.Errorf("Expected id value of 123, got %s", tx.Variables().ArgsPath().Get("id"))
}
}

func TestRestPathQueryShouldNotBeGreedy(t *testing.T) {
waf := corazawaf.NewWAF()
tx := waf.NewTransaction()

exp := "/some-random/url/{id}"
testCases := map[string]string{
"/some-random/url/123?q=test": "123", // ?q=test is query info
"/some-random/url/456/test": "456", // /test is extra path info
}

for path, want := range testCases {

rp, err := newRESTPath(plugintypes.OperatorOptions{
Arguments: exp,
})
if err != nil {
t.Error(err)
}
if !rp.Evaluate(tx, path) {
t.Errorf("Expected %s to match %s", exp, path)
}
if tx.Variables().ArgsPath().Get("id")[0] != want {
t.Errorf("Expected id value of %s, got %s", want, tx.Variables().ArgsPath().Get("id"))
}
}
}

0 comments on commit 497cac1

Please sign in to comment.