fix: avoid page offset overflow in PaginateSlice and ListOptions (#40572)

A huge `page` value made `(page-1)*pageSize` wrap to a negative int.
`PaginateSlice` then panicked with a slice-bounds error (e.g. the cron
and tags APIs), and `ListOptions.GetSkipTake` caused an index panic in
the pull request commits and files APIs. `PaginateSlice` now compares
the page against `len(list)/pageSize`, and `ListOptions` caps the page
so the offset stays in range.

---------

Co-authored-by: silverwind <me@silverwind.io>
This commit is contained in:
T Mohan Adityaandsilverwind authored and GitHub committed 2026-11-30 08:38:54 +00:00
1 parent b60bf59f09
commit 752b24976c
4 files changed
+13 -4

No files matched your search

+2 -3
View File
@@ -5,6 +5,7 @@ package db
import (
"context"
"math"
"slices"
"gitea.dev/modules/setting"
@@ -68,9 +69,7 @@ func (opts *ListOptions) SetDefaultValues() {
if opts.PageSize > setting.API.MaxResponseItems {
opts.PageSize = setting.API.MaxResponseItems
}
if opts.Page <= 0 {
opts.Page = 1
}
opts.Page = min(max(opts.Page, 1), math.MaxInt/max(opts.PageSize, 1))
}
func (opts ListOptions) ToConds() builder.Cond {
+6
View File
@@ -4,6 +4,7 @@
package paginator
import (
"math"
"testing"
"gitea.dev/models/db"
@@ -34,6 +35,11 @@ func TestPaginator(t *testing.T) {
Start: 10,
End: 20,
},
{
Paginator: &db.ListOptions{Page: math.MaxInt, PageSize: 10},
Skip: (math.MaxInt/10 - 1) * 10,
Take: 10,
},
{
Paginator: db.NewAbsoluteListOptions(-1, -1),
Skip: 0,
+1 -1
View File
@@ -12,7 +12,7 @@ func PaginateSlice[S ~[]E, E any](list S, page, pageSize int) S {
page--
if page*pageSize >= len(list) {
if page > len(list)/pageSize {
return list[len(list):]
}
+4
View File
@@ -4,6 +4,7 @@
package util
import (
"math"
"testing"
"github.com/stretchr/testify/assert"
@@ -17,6 +18,9 @@ func TestPaginateSlice(t *testing.T) {
result = PaginateSlice(stringSlice, 100, 2)
assert.Equal(t, []string{}, result)
assert.Equal(t, []string{}, PaginateSlice(stringSlice, math.MaxInt, 2))
assert.Equal(t, []string{}, PaginateSlice(stringSlice[:4], 3, 2))
result = PaginateSlice(stringSlice, 3, 2)
assert.Equal(t, []string{"e"}, result)