Skip to content

Commit 99af6d0

Browse files
committed
Improve query limit parameter validation
Signed-off-by: Carlos Martín <[email protected]>
1 parent 6666a5f commit 99af6d0

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

server/handler/query.go

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import (
1616

1717
type queryRequest struct {
1818
Query string `json:"query"`
19-
Limit int `json:"limit"`
19+
Limit int `json:"limit,omitempty"`
2020
}
2121

2222
// genericVals returns a slice of interface{}, each one a pointer to the proper
@@ -50,12 +50,14 @@ func Query(db *sql.DB) RequestProcessFunc {
5050
return func(r *http.Request) (*serializer.Response, error) {
5151
var queryRequest queryRequest
5252
body, err := ioutil.ReadAll(r.Body)
53-
if err == nil {
54-
err = json.Unmarshal(body, &queryRequest)
53+
if err != nil {
54+
return nil, err
5555
}
5656

57+
err = json.Unmarshal(body, &queryRequest)
5758
if err != nil {
58-
return nil, err
59+
return nil, serializer.NewHTTPError(http.StatusBadRequest,
60+
`Bad Request. Expected body: { "query": "SQL statement", "limit": 1234 }`)
5961
}
6062

6163
query := addLimit(queryRequest.Query, queryRequest.Limit)
@@ -184,9 +186,14 @@ func unmarshallUAST(data interface{}) ([]*uast.Node, error) {
184186
// addLimit adds LIMIT to the query, performing basic tests to skip it
185187
// for DESCRIBE TABLE, SHOW TABLES, and avoid '; limit'
186188
func addLimit(query string, limit int) string {
189+
if limit <= 0 {
190+
return query
191+
}
192+
187193
query = strings.TrimRight(strings.TrimSpace(query), ";")
188194
if strings.HasPrefix(strings.ToUpper(query), "SELECT") {
189195
return fmt.Sprintf("%s LIMIT %d", query, limit)
190196
}
197+
191198
return query
192199
}

0 commit comments

Comments
 (0)