Skip to content

Commit

Permalink
🩹 Fix: handle un-matched open brackets in the query params (#3121)
Browse files Browse the repository at this point in the history
* Add logic for counting open brackets

* Add UTs

* update increment/decrement syntax with ++/--

* Update UT to remove duplicate
  • Loading branch information
dojutsu-user authored Sep 6, 2024
1 parent bfcf91d commit cb06bc5
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
21 changes: 17 additions & 4 deletions ctx.go
Original file line number Diff line number Diff line change
Expand Up @@ -1306,15 +1306,24 @@ func parseParamSquareBrackets(k string) (string, error) {
defer bytebufferpool.Put(bb)

kbytes := []byte(k)
openBracketsCount := 0

for i, b := range kbytes {
if b == '[' && kbytes[i+1] != ']' {
if err := bb.WriteByte('.'); err != nil {
return "", fmt.Errorf("failed to write: %w", err)
if b == '[' {
openBracketsCount++
if i+1 < len(kbytes) && kbytes[i+1] != ']' {
if err := bb.WriteByte('.'); err != nil {
return "", fmt.Errorf("failed to write: %w", err)
}
}
continue
}

if b == '[' || b == ']' {
if b == ']' {
openBracketsCount--
if openBracketsCount < 0 {
return "", errors.New("unmatched brackets")
}
continue
}

Expand All @@ -1323,6 +1332,10 @@ func parseParamSquareBrackets(k string) (string, error) {
}
}

if openBracketsCount > 0 {
return "", errors.New("unmatched brackets")
}

return bb.String(), nil
}

Expand Down
8 changes: 8 additions & 0 deletions ctx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4508,6 +4508,10 @@ func Test_Ctx_QueryParser(t *testing.T) {
utils.AssertEqual(t, nil, c.QueryParser(empty))
utils.AssertEqual(t, 0, len(empty.Hobby))

c.Request().URI().SetQueryString("id=1&name[=tom")
q = new(Query)
utils.AssertEqual(t, "unmatched brackets", c.QueryParser(q).Error())

type Query2 struct {
Bool bool
ID int
Expand Down Expand Up @@ -4790,6 +4794,10 @@ func Test_Ctx_QueryParser_Schema(t *testing.T) {
utils.AssertEqual(t, "doe", cq.Data[1].Name)
utils.AssertEqual(t, 12, cq.Data[1].Age)

c.Request().URI().SetQueryString("data[0][name]=john&data[0][age]=10&data[1]name]=doe&data[1][age]=12")
cq = new(CollectionQuery)
utils.AssertEqual(t, "unmatched brackets", c.QueryParser(cq).Error())

c.Request().URI().SetQueryString("data.0.name=john&data.0.age=10&data.1.name=doe&data.1.age=12")
cq = new(CollectionQuery)
utils.AssertEqual(t, nil, c.QueryParser(cq))
Expand Down

0 comments on commit cb06bc5

Please sign in to comment.