Skip to content

Commit a10f195

Browse files
authored
fix(API): prevent TypeError and handle integer overflow in paginate() (#10764)
1 parent 3e6b20f commit a10f195

3 files changed

Lines changed: 206 additions & 4 deletions

File tree

‎docs/changelogs/v4.7.7.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ Release Date: Unreleased
1818

1919
## Bugs Fixed
2020

21+
- **API:** Fixed HTTP 500 errors in `ResponseTrait::paginate()` when using a Query Builder with a very large page number or `$perPage = 0`.
2122
- **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.
2223
- **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.
2324
- **Database:** Fixed a bug where `BaseConnection::prepare()` did not reset pretend mode when the closure threw an exception, leaving the connection in pretend mode so that subsequent queries on it were silently discarded.

‎system/API/ResponseTrait.php‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -416,15 +416,24 @@ protected function paginate(BaseBuilder|Model $resource, int $perPage = 20, ?str
416416
];
417417
} else {
418418
// Query Builder, we need to handle pagination manually
419-
$offset = ($page - 1) * $perPage;
420-
$total = (clone $resource)->countAllResults();
421-
$data = $resource->limit($perPage, $offset)->get()->getResultArray();
419+
$total = (int) (clone $resource)->countAllResults();
420+
421+
if ($perPage > 0) {
422+
$totalPages = (int) ceil($total / $perPage);
423+
424+
$offset = $page > $totalPages ? $total : ($page - 1) * $perPage;
425+
} else {
426+
$totalPages = 0;
427+
$offset = 0;
428+
}
429+
430+
$data = $resource->limit($perPage, $offset)->get()->getResultArray();
422431

423432
$meta = [
424433
'page' => $page,
425434
'perPage' => $perPage,
426435
'total' => $total,
427-
'totalPages' => (int) ceil($total / $perPage),
436+
'totalPages' => $totalPages,
428437
];
429438
}
430439

‎tests/system/API/ResponseTraitTest.php‎

Lines changed: 192 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -799,6 +799,198 @@ public function testPaginateWithQueryBuilder(): void
799799
$this->assertSame(3, $responseBody['meta']['totalPages']);
800800
}
801801

802+
public function testPaginateWithQueryBuilderOutOfRangePage(): void
803+
{
804+
// Mock the database and builder
805+
$db = $this->createStub(BaseConnection::class);
806+
807+
$builder = $this->getMockBuilder(BaseBuilder::class)
808+
->setConstructorArgs(['test_table', $db])
809+
->onlyMethods(['countAllResults', 'limit', 'get'])
810+
->getMock();
811+
812+
$result = $this->createMock(BaseResult::class);
813+
814+
// Mock the query builder chain
815+
$builder->method('countAllResults')->willReturn(50);
816+
$builder->expects($this->once())
817+
->method('limit')
818+
->with(20, 50)
819+
->willReturnSelf();
820+
$builder->expects($this->once())
821+
->method('get')
822+
->willReturn($result);
823+
$result->method('getResultArray')->willReturn([]);
824+
825+
$controller = $this->makeController('/api/items?page=4');
826+
$this->request->setGlobal('get', ['page' => '4']);
827+
828+
$this->invoke($controller, 'paginate', [$builder, 20]);
829+
830+
$responseBody = json_decode($this->response->getBody(), true);
831+
832+
$this->assertSame([], $responseBody['data']);
833+
$this->assertSame(4, $responseBody['meta']['page']);
834+
$this->assertSame(20, $responseBody['meta']['perPage']);
835+
$this->assertSame(50, $responseBody['meta']['total']);
836+
$this->assertSame(3, $responseBody['meta']['totalPages']);
837+
$this->assertStringContainsString('page=4', (string) $responseBody['links']['self']);
838+
$this->assertNull($responseBody['links']['next']);
839+
$this->assertStringContainsString('page=3', (string) $responseBody['links']['prev']);
840+
}
841+
842+
public function testPaginateWithQueryBuilderPageOverflow(): void
843+
{
844+
// Mock the database and builder
845+
$db = $this->createStub(BaseConnection::class);
846+
847+
$builder = $this->getMockBuilder(BaseBuilder::class)
848+
->setConstructorArgs(['test_table', $db])
849+
->onlyMethods(['countAllResults', 'limit', 'get'])
850+
->getMock();
851+
852+
$result = $this->createMock(BaseResult::class);
853+
854+
// Mock the query builder chain
855+
$builder->method('countAllResults')->willReturn(50);
856+
$builder->expects($this->once())
857+
->method('limit')
858+
->with(20, 50)
859+
->willReturnSelf();
860+
$builder->expects($this->once())
861+
->method('get')
862+
->willReturn($result);
863+
$result->method('getResultArray')->willReturn([]);
864+
865+
$controller = $this->makeController('/api/items?page=' . PHP_INT_MAX);
866+
$this->request->setGlobal('get', ['page' => (string) PHP_INT_MAX]);
867+
868+
$this->invoke($controller, 'paginate', [$builder, 20]);
869+
870+
$responseBody = json_decode($this->response->getBody(), true);
871+
872+
$this->assertSame(PHP_INT_MAX, $responseBody['meta']['page']);
873+
$this->assertSame(20, $responseBody['meta']['perPage']);
874+
$this->assertSame(50, $responseBody['meta']['total']);
875+
$this->assertSame(3, $responseBody['meta']['totalPages']);
876+
$this->assertSame([], $responseBody['data']);
877+
$this->assertNull($responseBody['links']['next']);
878+
}
879+
880+
public function testPaginateWithQueryBuilderZeroResultsPageOverflow(): void
881+
{
882+
// Mock the database and builder
883+
$db = $this->createStub(BaseConnection::class);
884+
885+
$builder = $this->getMockBuilder(BaseBuilder::class)
886+
->setConstructorArgs(['test_table', $db])
887+
->onlyMethods(['countAllResults', 'limit', 'get'])
888+
->getMock();
889+
890+
$result = $this->createMock(BaseResult::class);
891+
892+
// Mock the query builder chain
893+
$builder->method('countAllResults')->willReturn(0);
894+
$builder->expects($this->once())
895+
->method('limit')
896+
->with(20, 0)
897+
->willReturnSelf();
898+
$builder->expects($this->once())
899+
->method('get')
900+
->willReturn($result);
901+
$result->method('getResultArray')->willReturn([]);
902+
903+
$controller = $this->makeController('/api/items?page=' . PHP_INT_MAX);
904+
$this->request->setGlobal('get', ['page' => (string) PHP_INT_MAX]);
905+
906+
$this->invoke($controller, 'paginate', [$builder, 20]);
907+
908+
$responseBody = json_decode($this->response->getBody(), true);
909+
910+
$this->assertSame(PHP_INT_MAX, $responseBody['meta']['page']);
911+
$this->assertSame(0, $responseBody['meta']['total']);
912+
$this->assertSame(0, $responseBody['meta']['totalPages']);
913+
$this->assertSame([], $responseBody['data']);
914+
}
915+
916+
public function testPaginateWithQueryBuilderZeroPerPage(): void
917+
{
918+
// Mock the database and builder
919+
$db = $this->createStub(BaseConnection::class);
920+
921+
$builder = $this->getMockBuilder(BaseBuilder::class)
922+
->setConstructorArgs(['test_table', $db])
923+
->onlyMethods(['countAllResults', 'limit', 'get'])
924+
->getMock();
925+
926+
$result = $this->createMock(BaseResult::class);
927+
928+
$data = [
929+
['id' => 1],
930+
['id' => 2],
931+
];
932+
933+
// Mock the query builder chain
934+
$builder->method('countAllResults')->willReturn(50);
935+
$builder->expects($this->once())
936+
->method('limit')
937+
->with(0, 0)
938+
->willReturnSelf();
939+
$builder->expects($this->once())
940+
->method('get')
941+
->willReturn($result);
942+
$result->method('getResultArray')->willReturn($data);
943+
944+
$controller = $this->makeController('/api/items');
945+
946+
$this->invoke($controller, 'paginate', [$builder, 0]);
947+
948+
$responseBody = json_decode($this->response->getBody(), true);
949+
950+
$this->assertSame(200, $this->response->getStatusCode());
951+
$this->assertSame(1, $responseBody['meta']['page']);
952+
$this->assertSame(0, $responseBody['meta']['perPage']);
953+
$this->assertSame(50, $responseBody['meta']['total']);
954+
$this->assertSame(0, $responseBody['meta']['totalPages']);
955+
$this->assertSame($data, $responseBody['data']);
956+
}
957+
958+
public function testPaginateWithQueryBuilderStringTotalFromCountAllResults(): void
959+
{
960+
$db = $this->createStub(BaseConnection::class);
961+
962+
$builder = $this->getMockBuilder(BaseBuilder::class)
963+
->setConstructorArgs(['test_table', $db])
964+
->onlyMethods(['countAllResults', 'limit', 'get'])
965+
->getMock();
966+
967+
$result = $this->createMock(BaseResult::class);
968+
969+
// Mock the query builder chain
970+
$builder->method('countAllResults')->willReturn('50');
971+
$builder->expects($this->once())
972+
->method('limit')
973+
->with(20, 50)
974+
->willReturnSelf();
975+
$builder->expects($this->once())
976+
->method('get')
977+
->willReturn($result);
978+
$result->method('getResultArray')->willReturn([]);
979+
980+
$controller = $this->makeController('/api/items?page=4');
981+
$this->request->setGlobal('get', ['page' => '4']);
982+
983+
$this->invoke($controller, 'paginate', [$builder, 20]);
984+
985+
$responseBody = json_decode($this->response->getBody(), true);
986+
987+
$this->assertSame(200, $this->response->getStatusCode());
988+
$this->assertSame([], $responseBody['data']);
989+
$this->assertSame(4, $responseBody['meta']['page']);
990+
$this->assertSame(50, $responseBody['meta']['total']);
991+
$this->assertSame(3, $responseBody['meta']['totalPages']);
992+
}
993+
802994
public function testPaginateWithCustomPerPage(): void
803995
{
804996
$data = [

0 commit comments

Comments
 (0)