Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 28 additions & 5 deletions backend/common/core/pagination.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,27 @@

ModelT = TypeVar('ModelT', bound=SQLModel)

DEFAULT_PAGE_SIZE = 20
MAX_PAGE_SIZE = 500


def normalize_page_args(page: int, size: int) -> tuple[int, int]:
"""Clamp pagination inputs that arrive without bounds.

Page and size come from path parameters that carry no validation, so
``page=0`` used to build a negative OFFSET and ``size=0`` divided by zero
while computing ``total_pages``. Both turned a list request into a 500
instead of returning the first page, and an oversized ``size`` let one
request scan the whole table.
"""
safe_page = page if isinstance(page, int) and page >= 1 else 1
if not isinstance(size, int) or size < 1:
safe_size = DEFAULT_PAGE_SIZE
else:
safe_size = min(size, MAX_PAGE_SIZE)
return safe_page, safe_size


class Paginator:
def __init__(self, session: Session):
self.session = session
Expand All @@ -32,6 +53,7 @@ async def paginate(
desc: bool = False,
**filters
) -> tuple[Sequence[Any], int]:
page, size = normalize_page_args(page, size)
offset = (page - 1) * size
single_model: bool = False
if isinstance(stmt, type) and issubclass(stmt, SQLModel):
Expand Down Expand Up @@ -83,21 +105,22 @@ async def get_paginated_response(
pagination: PaginationParams,
**filters
) -> PaginatedResponse[Any]:
page, size = normalize_page_args(pagination.page, pagination.size)
items, total = await self.paginate(
stmt=stmt,
page=pagination.page,
size=pagination.size,
page=page,
size=size,
order_by=pagination.order_by,
desc=pagination.desc,
**filters
)

total_pages = (total + pagination.size - 1) // pagination.size
total_pages = (total + size - 1) // size

return PaginatedResponse[Any](
items=items,
total=total,
page=pagination.page,
size=pagination.size,
page=page,
size=size,
total_pages=total_pages
)
86 changes: 86 additions & 0 deletions backend/tests/test_pagination_arguments.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
"""Guard: out-of-range page/size must not turn a list request into a 500.

``/pager/{pageNum}/{pageSize}`` style routes hand raw path integers to
``PaginationParams``, so ``size=0`` divided by zero while computing
``total_pages`` and ``page=0`` produced a negative OFFSET for the database.
The checks below cover the normalization directly and through
``Paginator.get_paginated_response`` with a stubbed session.
"""

import asyncio

from sqlmodel import Field, SQLModel

from common.core.pagination import (
DEFAULT_PAGE_SIZE,
MAX_PAGE_SIZE,
Paginator,
normalize_page_args,
)
from common.core.schemas import PaginationParams


class PagedRow(SQLModel, table=True):
__tablename__ = "pagination_guard_row"

id: int | None = Field(default=None, primary_key=True)


class _Result:
def __init__(self, first_value=None):
self._first = first_value

def first(self):
return self._first

def all(self):
return []

def __iter__(self):
return iter(())


class _Session:
def __init__(self, total: int):
self.total = total
self.statements = []

def exec(self, stmt):
self.statements.append(stmt)
if "count" in str(stmt).lower():
return _Result(self.total)
return _Result()


def _paginate(pagination: PaginationParams, total: int = 42):
paginator = Paginator(_Session(total))
return asyncio.run(paginator.get_paginated_response(PagedRow, pagination))


def test_normalize_keeps_valid_arguments():
assert normalize_page_args(3, 40) == (3, 40)


def test_normalize_replaces_out_of_range_arguments():
assert normalize_page_args(0, 0) == (1, DEFAULT_PAGE_SIZE)
assert normalize_page_args(-1, -20) == (1, DEFAULT_PAGE_SIZE)
assert normalize_page_args(1, MAX_PAGE_SIZE + 1) == (1, MAX_PAGE_SIZE)


def test_zero_page_size_does_not_divide_by_zero():
response = _paginate(PaginationParams(page=1, size=0), total=42)
assert response.size == DEFAULT_PAGE_SIZE
assert response.total_pages == 3


def test_negative_page_returns_first_page():
response = _paginate(PaginationParams(page=0, size=20), total=42)
assert response.page == 1
assert response.size == 20
assert response.total_pages == 3


def test_oversized_page_size_is_bounded():
response = _paginate(PaginationParams(page=1, size=100000), total=42)
assert response.size == MAX_PAGE_SIZE
assert response.total_pages == 1
Loading