From ab558c84c86ac5e1c1ba007979b24cf146470a00 Mon Sep 17 00:00:00 2001 From: Bogdan Date: Thu, 12 Nov 2026 00:32:06 +0100 Subject: [PATCH 1/4] fix(API): prevent TypeError and handle integer overflow in paginate() When a huge page number (e.g. PHP_INT_MAX) is requested via ?page=, the offset calculation `($page - 1) * $perPage` overflows the int type and becomes a float. Passing that float to `BaseBuilder::limit(?int, ?int)` raises a TypeError, which `paginate()` reports as a 500 response ("Paginate Error"). Clamp the requested page to the available range, so the offset always stays within the int type: $page = max(1, min($page, max(1, $totalPages))); This also aligns the Query Builder path with the Pager used by the Model path, which already limits the current page to the page count. --- system/API/ResponseTrait.php | 12 +++-- tests/system/API/ResponseTraitTest.php | 75 ++++++++++++++++++++++++++ 2 files changed, 83 insertions(+), 4 deletions(-) diff --git a/system/API/ResponseTrait.php b/system/API/ResponseTrait.php index 0449e91bf07c..22deafc5fdc7 100644 --- a/system/API/ResponseTrait.php +++ b/system/API/ResponseTrait.php @@ -416,15 +416,19 @@ protected function paginate(BaseBuilder|Model $resource, int $perPage = 20, ?str ]; } else { // Query Builder, we need to handle pagination manually - $offset = ($page - 1) * $perPage; - $total = (clone $resource)->countAllResults(); - $data = $resource->limit($perPage, $offset)->get()->getResultArray(); + // The page is clamped to the available range so that the offset + // cannot overflow the int type when a huge page is requested. + $total = (clone $resource)->countAllResults(); + $totalPages = (int) ceil($total / $perPage); + $page = max(1, min($page, max(1, $totalPages))); + $offset = ($page - 1) * $perPage; + $data = $resource->limit($perPage, $offset)->get()->getResultArray(); $meta = [ 'page' => $page, 'perPage' => $perPage, 'total' => $total, - 'totalPages' => (int) ceil($total / $perPage), + 'totalPages' => $totalPages, ]; } diff --git a/tests/system/API/ResponseTraitTest.php b/tests/system/API/ResponseTraitTest.php index f5d33491a655..a78a71e25bea 100644 --- a/tests/system/API/ResponseTraitTest.php +++ b/tests/system/API/ResponseTraitTest.php @@ -799,6 +799,81 @@ public function testPaginateWithQueryBuilder(): void $this->assertSame(3, $responseBody['meta']['totalPages']); } + public function testPaginateWithQueryBuilderPageOverflow(): void + { + // Mock the database and builder + $db = $this->createStub(BaseConnection::class); + + $builder = $this->getMockBuilder(BaseBuilder::class) + ->setConstructorArgs(['test_table', $db]) + ->onlyMethods(['countAllResults', 'limit', 'get']) + ->getMock(); + + $result = $this->createMock(BaseResult::class); + + $data = [ + ['id' => 1, 'name' => 'Item 1'], + ['id' => 2, 'name' => 'Item 2'], + ]; + + // Mock the query builder chain + $builder->method('countAllResults')->willReturn(50); + $builder->expects($this->once()) + ->method('limit') + ->with(20, 40) + ->willReturnSelf(); + $builder->method('get')->willReturn($result); + $result->method('getResultArray')->willReturn($data); + + $controller = $this->makeController('/api/items?page=' . PHP_INT_MAX); + $this->request->setGlobal('get', ['page' => (string) PHP_INT_MAX]); + + $this->invoke($controller, 'paginate', [$builder, 20]); + + $responseBody = json_decode($this->response->getBody(), true); + + $this->assertSame(3, $responseBody['meta']['page']); + $this->assertSame(20, $responseBody['meta']['perPage']); + $this->assertSame(50, $responseBody['meta']['total']); + $this->assertSame(3, $responseBody['meta']['totalPages']); + $this->assertSame($data, $responseBody['data']); + $this->assertStringContainsString('page=3', $responseBody['links']['self']); + $this->assertNull($responseBody['links']['next']); + } + + public function testPaginateWithQueryBuilderZeroResultsPageOverflow(): void + { + // Mock the database and builder + $db = $this->createStub(BaseConnection::class); + + $builder = $this->getMockBuilder(BaseBuilder::class) + ->setConstructorArgs(['test_table', $db]) + ->onlyMethods(['countAllResults', 'limit', 'get']) + ->getMock(); + + $result = $this->createMock(BaseResult::class); + + // Mock the query builder chain + $builder->method('countAllResults')->willReturn(0); + $builder->expects($this->once()) + ->method('limit') + ->with(20, 0) + ->willReturnSelf(); + $builder->method('get')->willReturn($result); + $result->method('getResultArray')->willReturn([]); + + $controller = $this->makeController('/api/items?page=' . PHP_INT_MAX); + $this->request->setGlobal('get', ['page' => (string) PHP_INT_MAX]); + + $this->invoke($controller, 'paginate', [$builder, 20]); + + $responseBody = json_decode($this->response->getBody(), true); + + $this->assertSame(1, $responseBody['meta']['page']); + $this->assertSame(0, $responseBody['meta']['totalPages']); + $this->assertSame([], $responseBody['data']); + } + public function testPaginateWithCustomPerPage(): void { $data = [ From 24c800738e348f2691fedd9093396c86da7bf9be Mon Sep 17 00:00:00 2001 From: Bogdan Date: Thu, 12 Nov 2026 01:12:06 +0100 Subject: [PATCH 2/4] test(API): satisfy StringCastAssertStringContainsStringRector in paginate overflow test --- system/API/ResponseTrait.php | 12 +++-- tests/system/API/ResponseTraitTest.php | 69 +++++++++++++++++--------- 2 files changed, 52 insertions(+), 29 deletions(-) diff --git a/system/API/ResponseTrait.php b/system/API/ResponseTrait.php index 22deafc5fdc7..75e7b7ae770b 100644 --- a/system/API/ResponseTrait.php +++ b/system/API/ResponseTrait.php @@ -416,13 +416,15 @@ protected function paginate(BaseBuilder|Model $resource, int $perPage = 20, ?str ]; } else { // Query Builder, we need to handle pagination manually - // The page is clamped to the available range so that the offset - // cannot overflow the int type when a huge page is requested. $total = (clone $resource)->countAllResults(); $totalPages = (int) ceil($total / $perPage); - $page = max(1, min($page, max(1, $totalPages))); - $offset = ($page - 1) * $perPage; - $data = $resource->limit($perPage, $offset)->get()->getResultArray(); + + if ($total === 0 || $page > $totalPages) { + $data = []; + } else { + $offset = ($page - 1) * $perPage; + $data = $resource->limit($perPage, $offset)->get()->getResultArray(); + } $meta = [ 'page' => $page, diff --git a/tests/system/API/ResponseTraitTest.php b/tests/system/API/ResponseTraitTest.php index a78a71e25bea..4693e5b0d2c3 100644 --- a/tests/system/API/ResponseTraitTest.php +++ b/tests/system/API/ResponseTraitTest.php @@ -799,7 +799,7 @@ public function testPaginateWithQueryBuilder(): void $this->assertSame(3, $responseBody['meta']['totalPages']); } - public function testPaginateWithQueryBuilderPageOverflow(): void + public function testPaginateWithQueryBuilderOutOfRangePage(): void { // Mock the database and builder $db = $this->createStub(BaseConnection::class); @@ -809,21 +809,46 @@ public function testPaginateWithQueryBuilderPageOverflow(): void ->onlyMethods(['countAllResults', 'limit', 'get']) ->getMock(); - $result = $this->createMock(BaseResult::class); + // Mock the query builder chain + $builder->method('countAllResults')->willReturn(50); + $builder->expects($this->never()) + ->method('limit'); + $builder->expects($this->never()) + ->method('get'); - $data = [ - ['id' => 1, 'name' => 'Item 1'], - ['id' => 2, 'name' => 'Item 2'], - ]; + $controller = $this->makeController('/api/items?page=4'); + $this->request->setGlobal('get', ['page' => '4']); + + $this->invoke($controller, 'paginate', [$builder, 20]); + + $responseBody = json_decode($this->response->getBody(), true); + + $this->assertSame([], $responseBody['data']); + $this->assertSame(4, $responseBody['meta']['page']); + $this->assertSame(20, $responseBody['meta']['perPage']); + $this->assertSame(50, $responseBody['meta']['total']); + $this->assertSame(3, $responseBody['meta']['totalPages']); + $this->assertStringContainsString('page=4', (string) $responseBody['links']['self']); + $this->assertNull($responseBody['links']['next']); + $this->assertStringContainsString('page=3', (string) $responseBody['links']['prev']); + } + + public function testPaginateWithQueryBuilderPageOverflow(): void + { + // Mock the database and builder + $db = $this->createStub(BaseConnection::class); + + $builder = $this->getMockBuilder(BaseBuilder::class) + ->setConstructorArgs(['test_table', $db]) + ->onlyMethods(['countAllResults', 'limit', 'get']) + ->getMock(); // Mock the query builder chain $builder->method('countAllResults')->willReturn(50); - $builder->expects($this->once()) - ->method('limit') - ->with(20, 40) - ->willReturnSelf(); - $builder->method('get')->willReturn($result); - $result->method('getResultArray')->willReturn($data); + $builder->expects($this->never()) + ->method('limit'); + $builder->expects($this->never()) + ->method('get'); $controller = $this->makeController('/api/items?page=' . PHP_INT_MAX); $this->request->setGlobal('get', ['page' => (string) PHP_INT_MAX]); @@ -832,12 +857,11 @@ public function testPaginateWithQueryBuilderPageOverflow(): void $responseBody = json_decode($this->response->getBody(), true); - $this->assertSame(3, $responseBody['meta']['page']); + $this->assertSame(PHP_INT_MAX, $responseBody['meta']['page']); $this->assertSame(20, $responseBody['meta']['perPage']); $this->assertSame(50, $responseBody['meta']['total']); $this->assertSame(3, $responseBody['meta']['totalPages']); - $this->assertSame($data, $responseBody['data']); - $this->assertStringContainsString('page=3', $responseBody['links']['self']); + $this->assertSame([], $responseBody['data']); $this->assertNull($responseBody['links']['next']); } @@ -851,16 +875,12 @@ public function testPaginateWithQueryBuilderZeroResultsPageOverflow(): void ->onlyMethods(['countAllResults', 'limit', 'get']) ->getMock(); - $result = $this->createMock(BaseResult::class); - // Mock the query builder chain $builder->method('countAllResults')->willReturn(0); - $builder->expects($this->once()) - ->method('limit') - ->with(20, 0) - ->willReturnSelf(); - $builder->method('get')->willReturn($result); - $result->method('getResultArray')->willReturn([]); + $builder->expects($this->never()) + ->method('limit'); + $builder->expects($this->never()) + ->method('get'); $controller = $this->makeController('/api/items?page=' . PHP_INT_MAX); $this->request->setGlobal('get', ['page' => (string) PHP_INT_MAX]); @@ -869,7 +889,8 @@ public function testPaginateWithQueryBuilderZeroResultsPageOverflow(): void $responseBody = json_decode($this->response->getBody(), true); - $this->assertSame(1, $responseBody['meta']['page']); + $this->assertSame(PHP_INT_MAX, $responseBody['meta']['page']); + $this->assertSame(0, $responseBody['meta']['total']); $this->assertSame(0, $responseBody['meta']['totalPages']); $this->assertSame([], $responseBody['data']); } From ceb9e5a91e0eebe2ec5817bf3cd0060d2ad6d2d8 Mon Sep 17 00:00:00 2001 From: Bogdan Date: Sat, 14 Nov 2026 23:01:57 +0100 Subject: [PATCH 3/4] fix(API): keep limit(0) semantics and builder reset in paginate() Scope the overflow guard to the offset calculation so that: - $perPage = 0 is still passed to the Query Builder, where limit(0) honours Feature::$limitZeroAsAll, instead of dividing by zero before the builder can apply it; - out-of-range pages still run get(), which resets the builder state as before the overflow guard was added; - a page past the end uses the total as the offset, which cannot overflow the int type for huge page numbers; - the total is cast to int so limit(?int, ?int) never receives a string from countAllResults() under strict types. Adds regression tests for perPage = 0 and for an out-of-range page when countAllResults() returns a numeric string. --- system/API/ResponseTrait.php | 15 ++-- tests/system/API/ResponseTraitTest.php | 120 ++++++++++++++++++++++--- 2 files changed, 117 insertions(+), 18 deletions(-) diff --git a/system/API/ResponseTrait.php b/system/API/ResponseTrait.php index 75e7b7ae770b..4cc5905934ce 100644 --- a/system/API/ResponseTrait.php +++ b/system/API/ResponseTrait.php @@ -416,16 +416,19 @@ protected function paginate(BaseBuilder|Model $resource, int $perPage = 20, ?str ]; } else { // Query Builder, we need to handle pagination manually - $total = (clone $resource)->countAllResults(); - $totalPages = (int) ceil($total / $perPage); + $total = (int) (clone $resource)->countAllResults(); - if ($total === 0 || $page > $totalPages) { - $data = []; + if ($perPage > 0) { + $totalPages = (int) ceil($total / $perPage); + + $offset = $page > $totalPages ? $total : ($page - 1) * $perPage; } else { - $offset = ($page - 1) * $perPage; - $data = $resource->limit($perPage, $offset)->get()->getResultArray(); + $totalPages = 0; + $offset = 0; } + $data = $resource->limit($perPage, $offset)->get()->getResultArray(); + $meta = [ 'page' => $page, 'perPage' => $perPage, diff --git a/tests/system/API/ResponseTraitTest.php b/tests/system/API/ResponseTraitTest.php index 4693e5b0d2c3..93ded944c350 100644 --- a/tests/system/API/ResponseTraitTest.php +++ b/tests/system/API/ResponseTraitTest.php @@ -809,12 +809,18 @@ public function testPaginateWithQueryBuilderOutOfRangePage(): void ->onlyMethods(['countAllResults', 'limit', 'get']) ->getMock(); + $result = $this->createMock(BaseResult::class); + // Mock the query builder chain $builder->method('countAllResults')->willReturn(50); - $builder->expects($this->never()) - ->method('limit'); - $builder->expects($this->never()) - ->method('get'); + $builder->expects($this->once()) + ->method('limit') + ->with(20, 50) + ->willReturnSelf(); + $builder->expects($this->once()) + ->method('get') + ->willReturn($result); + $result->method('getResultArray')->willReturn([]); $controller = $this->makeController('/api/items?page=4'); $this->request->setGlobal('get', ['page' => '4']); @@ -843,12 +849,18 @@ public function testPaginateWithQueryBuilderPageOverflow(): void ->onlyMethods(['countAllResults', 'limit', 'get']) ->getMock(); + $result = $this->createMock(BaseResult::class); + // Mock the query builder chain $builder->method('countAllResults')->willReturn(50); - $builder->expects($this->never()) - ->method('limit'); - $builder->expects($this->never()) - ->method('get'); + $builder->expects($this->once()) + ->method('limit') + ->with(20, 50) + ->willReturnSelf(); + $builder->expects($this->once()) + ->method('get') + ->willReturn($result); + $result->method('getResultArray')->willReturn([]); $controller = $this->makeController('/api/items?page=' . PHP_INT_MAX); $this->request->setGlobal('get', ['page' => (string) PHP_INT_MAX]); @@ -875,12 +887,18 @@ public function testPaginateWithQueryBuilderZeroResultsPageOverflow(): void ->onlyMethods(['countAllResults', 'limit', 'get']) ->getMock(); + $result = $this->createMock(BaseResult::class); + // Mock the query builder chain $builder->method('countAllResults')->willReturn(0); - $builder->expects($this->never()) - ->method('limit'); - $builder->expects($this->never()) - ->method('get'); + $builder->expects($this->once()) + ->method('limit') + ->with(20, 0) + ->willReturnSelf(); + $builder->expects($this->once()) + ->method('get') + ->willReturn($result); + $result->method('getResultArray')->willReturn([]); $controller = $this->makeController('/api/items?page=' . PHP_INT_MAX); $this->request->setGlobal('get', ['page' => (string) PHP_INT_MAX]); @@ -895,6 +913,84 @@ public function testPaginateWithQueryBuilderZeroResultsPageOverflow(): void $this->assertSame([], $responseBody['data']); } + public function testPaginateWithQueryBuilderZeroPerPage(): void + { + // Mock the database and builder + $db = $this->createStub(BaseConnection::class); + + $builder = $this->getMockBuilder(BaseBuilder::class) + ->setConstructorArgs(['test_table', $db]) + ->onlyMethods(['countAllResults', 'limit', 'get']) + ->getMock(); + + $result = $this->createMock(BaseResult::class); + + $data = [ + ['id' => 1], + ['id' => 2], + ]; + + // Mock the query builder chain + $builder->method('countAllResults')->willReturn(50); + $builder->expects($this->once()) + ->method('limit') + ->with(0, 0) + ->willReturnSelf(); + $builder->expects($this->once()) + ->method('get') + ->willReturn($result); + $result->method('getResultArray')->willReturn($data); + + $controller = $this->makeController('/api/items'); + + $this->invoke($controller, 'paginate', [$builder, 0]); + + $responseBody = json_decode($this->response->getBody(), true); + + $this->assertSame(200, $this->response->getStatusCode()); + $this->assertSame(1, $responseBody['meta']['page']); + $this->assertSame(0, $responseBody['meta']['perPage']); + $this->assertSame(50, $responseBody['meta']['total']); + $this->assertSame(0, $responseBody['meta']['totalPages']); + $this->assertSame($data, $responseBody['data']); + } + + public function testPaginateWithQueryBuilderStringTotalFromCountAllResults(): void + { + $db = $this->createStub(BaseConnection::class); + + $builder = $this->getMockBuilder(BaseBuilder::class) + ->setConstructorArgs(['test_table', $db]) + ->onlyMethods(['countAllResults', 'limit', 'get']) + ->getMock(); + + $result = $this->createMock(BaseResult::class); + + // Mock the query builder chain + $builder->method('countAllResults')->willReturn('50'); + $builder->expects($this->once()) + ->method('limit') + ->with(20, 50) + ->willReturnSelf(); + $builder->expects($this->once()) + ->method('get') + ->willReturn($result); + $result->method('getResultArray')->willReturn([]); + + $controller = $this->makeController('/api/items?page=4'); + $this->request->setGlobal('get', ['page' => '4']); + + $this->invoke($controller, 'paginate', [$builder, 20]); + + $responseBody = json_decode($this->response->getBody(), true); + + $this->assertSame(200, $this->response->getStatusCode()); + $this->assertSame([], $responseBody['data']); + $this->assertSame(4, $responseBody['meta']['page']); + $this->assertSame(50, $responseBody['meta']['total']); + $this->assertSame(3, $responseBody['meta']['totalPages']); + } + public function testPaginateWithCustomPerPage(): void { $data = [ From be982cc39c2fc0121491715ef5ac85cb433797fb Mon Sep 17 00:00:00 2001 From: Bogdan Date: Sun, 15 Nov 2026 16:17:40 +0100 Subject: [PATCH 4/4] docs: add changelog entry for paginate() overflow fix --- docs/changelogs/v4.7.7.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/changelogs/v4.7.7.md b/docs/changelogs/v4.7.7.md index d817d9932f94..3f440e313493 100644 --- a/docs/changelogs/v4.7.7.md +++ b/docs/changelogs/v4.7.7.md @@ -18,6 +18,7 @@ Release Date: Unreleased ## Bugs Fixed +- **API:** Fixed HTTP 500 errors in `ResponseTrait::paginate()` when using a Query Builder with a very large page number or `$perPage = 0`. - **Cache:** Fixed a bug where `PredisHandler::increment()` and `PredisHandler::decrement()` updated the unused `'data'` hash field instead of `'__ci_value'`, causing `get()` to return stale values for existing counters. - **CORS:** Fixed a bug where `Cors::hasResponseHeaders()` matched header substrings via `str_contains()`, causing false positives when existing exposed headers shared a prefix with configured exposed headers. - **Database:** Fixed a bug where `Postgre`, `OCI8`, and `SQLSRV` `Forge::_dropKeyAsConstraint()` interpolated table, constraint, and schema names without escaping.