From 9b6e694a004ae39b339f2e16cbd86ba50f046487 Mon Sep 17 00:00:00 2001 From: Alessio Treglia Date: Wed, 13 May 2020 14:14:43 +0100 Subject: [PATCH] client: fix Paginate's arguments validation (#6205) Check both page and defLimit against negative values. Follow up of #6205 Co-authored-by: Federico Kunze <31522760+fedekunze@users.noreply.github.com> --- client/utils.go | 19 +++++++++++++------ client/utils_test.go | 15 +++++++++++++++ 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/client/utils.go b/client/utils.go index 1a71dfcea6..25290991a4 100644 --- a/client/utils.go +++ b/client/utils.go @@ -2,15 +2,22 @@ package client // Paginate returns the correct starting and ending index for a paginated query, // given that client provides a desired page and limit of objects and the handler -// provides the total number of objects. If the start page is invalid, non-positive -// values are returned signaling the request is invalid. -// -// NOTE: The start page is assumed to be 1-indexed. +// provides the total number of objects. The start page is assumed to be 1-indexed. +// If the start page is invalid, non-positive values are returned signaling the +// request is invalid; it returns non-positive values if limit is non-positive and +// defLimit is negative. func Paginate(numObjs, page, limit, defLimit int) (start, end int) { - if page == 0 { + if page <= 0 { // invalid start page return -1, -1 - } else if limit == 0 { + } + + // fallback to default limit if supplied limit is invalid + if limit <= 0 { + if defLimit < 0 { + // invalid default limit + return -1, -1 + } limit = defLimit } diff --git a/client/utils_test.go b/client/utils_test.go index 0f1506c562..c8cb93a9f5 100644 --- a/client/utils_test.go +++ b/client/utils_test.go @@ -39,6 +39,11 @@ func TestPaginate(t *testing.T) { 75, 2, 50, 100, 50, 75, }, + { + "fallback to default limit", + 75, 5, 0, 10, + 40, 50, + }, { "invalid start page", 75, 4, 25, 100, @@ -49,6 +54,16 @@ func TestPaginate(t *testing.T) { 75, 0, 25, 100, -1, -1, }, + { + "invalid negative start page", + 75, -1, 25, 100, + -1, -1, + }, + { + "invalid default limit", + 75, 2, 0, -10, + -1, -1, + }, } for i, tc := range testCases {