From 752b24976cfc2a5254d4fb8f99ea437280cc89e5 Mon Sep 17 00:00:00 2001 From: T Mohan Aditya Date: Mon, 30 Nov 2026 08:38:54 +0000 Subject: [PATCH] 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 --- models/db/list.go | 5 ++--- models/db/paginator/paginator_test.go | 6 ++++++ modules/util/paginate.go | 2 +- modules/util/paginate_test.go | 4 ++++ 4 files changed, 13 insertions(+), 4 deletions(-) diff --git a/models/db/list.go b/models/db/list.go index 6d1e89bb8b7..d6986a787cf 100644 --- a/models/db/list.go +++ b/models/db/list.go @@ -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 { diff --git a/models/db/paginator/paginator_test.go b/models/db/paginator/paginator_test.go index 7511ed5ea8c..e2ce09ac881 100644 --- a/models/db/paginator/paginator_test.go +++ b/models/db/paginator/paginator_test.go @@ -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, diff --git a/modules/util/paginate.go b/modules/util/paginate.go index 2c248db19a7..4279156eb79 100644 --- a/modules/util/paginate.go +++ b/modules/util/paginate.go @@ -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):] } diff --git a/modules/util/paginate_test.go b/modules/util/paginate_test.go index 010b99985ad..6f7a72f3bfc 100644 --- a/modules/util/paginate_test.go +++ b/modules/util/paginate_test.go @@ -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)