Skip to content

Commit 576c678

Browse files
committed
fix: validate OrderBy field in query builder, adds stricter check to only allow order by for the whitelisted fields
1 parent 9bfe014 commit 576c678

File tree

1 file changed

+13
-1
lines changed

1 file changed

+13
-1
lines changed

internal/dbutil/builder.go

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,11 +62,23 @@ func BuildPaginatedQuery(baseQuery string, existingArgs []any, opts PaginationOp
6262
}
6363

6464
if opts.OrderBy != "" {
65+
// Validate OrderBy.
66+
parts := strings.Split(opts.OrderBy, ".")
67+
if len(parts) != 2 {
68+
return "", nil, fmt.Errorf("invalid OrderBy format: %s", opts.OrderBy)
69+
}
70+
model, field := parts[0], parts[1]
71+
72+
modelFields, ok := allowedFields[model]
73+
if !ok || !slices.Contains(modelFields, field) {
74+
return "", nil, fmt.Errorf("invalid OrderBy field: %s", opts.OrderBy)
75+
}
76+
6577
order := strings.ToUpper(opts.Order)
6678
if order != "" && order != ASC && order != DESC {
6779
return "", nil, fmt.Errorf("invalid order direction: %s", opts.Order)
6880
}
69-
query += fmt.Sprintf(" ORDER BY %s %s NULLS LAST", opts.OrderBy, order)
81+
query += fmt.Sprintf(" ORDER BY %s.%s %s NULLS LAST", model, field, order)
7082
}
7183

7284
offset := (opts.Page - 1) * opts.PageSize

0 commit comments

Comments
 (0)