fix(api): validate positive pagination on database history endpoints (#7579)

This commit is contained in:
jxxghp
2026-11-24 15:59:10 +08:00
parent d893e1a8dc
commit 2b0ef727c8
8 changed files with 415 additions and 45 deletions

View File

@@ -7777,6 +7777,7 @@
"count": {
"anyOf": [
{
"minimum": 1,
"type": "integer"
},
{
@@ -7790,6 +7791,7 @@
"page": {
"anyOf": [
{
"minimum": 1,
"type": "integer"
},
{
@@ -14038,6 +14040,7 @@
"count": {
"anyOf": [
{
"minimum": 1,
"type": "integer"
},
{
@@ -14051,6 +14054,7 @@
"page": {
"anyOf": [
{
"minimum": 1,
"type": "integer"
},
{
@@ -15743,6 +15747,7 @@
"count": {
"anyOf": [
{
"minimum": 1,
"type": "integer"
},
{
@@ -15769,6 +15774,7 @@
"page": {
"anyOf": [
{
"minimum": 1,
"type": "integer"
},
{

View File

@@ -5,7 +5,7 @@
import json
import mimetypes
import uuid
from typing import Any, AsyncIterator, Optional
from typing import Annotated, Any, AsyncIterator, Optional
from urllib.parse import unquote
from fastapi import (
@@ -14,6 +14,7 @@ from fastapi import (
Form,
Header,
HTTPException,
Query,
Request,
UploadFile,
status,
@@ -432,16 +433,16 @@ async def run_agent_command(
async def list_agent_chat_sessions(
current_user: ApiPrincipal = Depends(get_current_active_user),
service: AgentChatService = Depends(get_agent_chat_service),
page: int = 1,
count: int = 30,
page: Annotated[int, Query(ge=1, description="从 1 开始的结果页码。")] = 1,
count: Annotated[int, Query(ge=1, description="当前页最多返回的记录数。")] = 30,
) -> _SchemaResponse[list[_SchemaAgentChatSessionSummary]]:
"""
获取当前用户可访问的 Agent 历史会话列表。
:param current_user: 当前登录用户
:param service: Agent 会话应用服务
:param page: 页码
:param count: 每页数量
:param page: 页码,从 1 开始,默认第 1 页
:param count: 每页最多返回的会话数,最小为 1,默认 30 条
:return: 会话摘要列表
"""
chats = await service.list(

View File

@@ -35,6 +35,8 @@ from app.api.dependencies.history import (
from app.api.response import (
COLLECTION_TOTAL_HEADER,
COLLECTION_TOTAL_OPENAPI_KEY,
PositiveCountParam,
PositivePageParam,
ResponseAPIRouter,
)
from app.application.agent import get_running_agent_manager
@@ -304,14 +306,21 @@ def _resolve_download_history_username(token: _SchemaTokenPayload) -> Optional[s
openapi_extra={COLLECTION_TOTAL_OPENAPI_KEY: True},
)
async def download_history(
page: Optional[int] = 1,
count: Optional[int] = 30,
response: Response,
page: PositivePageParam = 1,
count: PositiveCountParam = 30,
query: HistoryQueryService = Depends(get_history_query_service),
_: _SchemaTokenPayload = Depends(verify_token),
response: Response = None, # type: ignore[assignment]
) -> Any:
"""
按下载时间倒序查询下载历史记录
按下载时间倒序分页查询下载历史记录,并通过响应头写入精确总数。
:param response: 由 FastAPI 注入的响应对象,用于设置集合总数响应头
:param page: 页码,从 1 开始,最小为 1;直接调用传入 None 时默认第 1 页
:param count: 每页最多返回条数,最小为 1;直接调用传入 None 时默认 30 条
:param query: 下载与整理历史查询服务
:param _: 已验证的访问令牌载荷
:return: 当前分页窗口内的下载历史记录列表
"""
page = page if page is not None else 1
count = count if count is not None else 30
@@ -353,15 +362,24 @@ def delete_download_history(
)
async def transfer_history(
title: Optional[str] = None,
page: Optional[int] = 1,
count: Optional[int] = 30,
page: PositivePageParam = 1,
count: PositiveCountParam = 30,
status: Optional[bool] = None,
origin: Optional[Literal["external"]] = None,
query: HistoryQueryService = Depends(get_history_query_service),
_: _SchemaTokenPayload = Depends(verify_token),
) -> Any:
"""
查询整理记录,title 支持通配符 * 和 ?(如 *.mkv、*2024*)
按条件分页查询整理记录,title 支持通配符 * 和 ?(如 *.mkv、*2024*)。
:param title: 可选标题或路径匹配条件,支持通配符与分词模糊检索
:param page: 页码,从 1 开始,最小为 1;直接调用传入 None 时默认第 1 页
:param count: 每页最多返回条数,最小为 1;直接调用传入 None 时默认 30 条
:param status: 可选整理成功状态筛选,None 表示不限制
:param origin: 可选来源筛选,external 仅返回外部登记历史
:param query: 下载与整理历史查询服务
:param _: 已验证的访问令牌载荷
:return: 包含当前页整理记录与精确总数的统一响应
"""
page = page if page is not None else 1
count = count if count is not None else 30

View File

@@ -17,7 +17,11 @@ from app.api.context import get_background_task_registry, resolve_background_tas
from app.api.dependencies.agent import get_message_query_service
from app.api.dependencies.auth import get_current_active_superuser, get_current_active_user
from app.api.principal import ApiPrincipal
from app.api.response import ResponseAPIRouter
from app.api.response import (
PositiveCountParam,
PositivePageParam,
ResponseAPIRouter,
)
from app.application.configuration import (
get_api_runtime_config_snapshot,
get_configured_system_config,
@@ -227,17 +231,18 @@ async def web_message(
async def get_message_history(
_: _SchemaTokenPayload = Depends(verify_token),
service: MessageQueryService = Depends(get_message_query_service),
page: Optional[int] = 1,
count: Optional[int] = 20,
page: PositivePageParam = 1,
count: PositiveCountParam = 20,
) -> List[_SchemaMessageHistoryItem]:
"""
分页获取消息表中的全部历史记录,包含接收消息与发送通知。
旧路径 GET /api/v1/message/web 作为兼容入口保留相同行为;仅查询系统已发送通知时使用 GET /api/v1/message/notification。
:param _: 已验证的访问令牌载荷
:param service: 消息历史查询服务
:param page: 页码,从 1 开始,传 None 时默认第 1 页
:param count: 每页最多返回条数,传 None 时默认 20 条
:param page: 页码,从 1 开始,最小为 1;直接调用传入 None 时默认第 1 页
:param count: 每页最多返回条数,最小为 1;直接调用传入 None 时默认 20 条
:return: 按登记时间和主键倒序排列的消息历史列表
"""
messages = await service.list_history(
@@ -251,15 +256,16 @@ async def get_message_history(
async def get_notification_message(
_: _SchemaTokenPayload = Depends(verify_token),
service: MessageQueryService = Depends(get_message_query_service),
page: Optional[int] = 1,
count: Optional[int] = 20,
page: PositivePageParam = 1,
count: PositiveCountParam = 20,
) -> List[_SchemaMessageHistoryItem]:
"""
获取清理水位之后系统发送的通知消息列表,仅包含发送方向(action=1)记录。
:param _: 已验证的访问令牌载荷
:param service: 消息历史查询服务
:param page: 页码,从 1 开始,传 None 时默认第 1 页
:param count: 每页最多返回条数,传 None 时默认 20 条
:param page: 页码,从 1 开始,最小为 1;直接调用传入 None 时默认第 1 页
:param count: 每页最多返回条数,最小为 1;直接调用传入 None 时默认 20 条
:return: 按登记时间和主键倒序排列的系统通知消息列表
"""
clear_before = _get_notification_clear_before()

View File

@@ -47,6 +47,8 @@ from app.api.response import (
COLLECTION_TOTAL_OPENAPI_KEY,
CompatibleCountParam,
CompatiblePageParam,
PositiveCountParam,
PositivePageParam,
ResponseAPIRouter,
resolve_compatible_pagination,
)
@@ -614,14 +616,22 @@ async def seerr_subscribe(
)
async def subscribe_history(
mtype: str,
page: Optional[int] = 1,
count: Optional[int] = 30,
response: Response,
page: PositivePageParam = 1,
count: PositiveCountParam = 30,
query: SubscriptionQueryService = Depends(get_subscription_query_service),
current_user: ApiPrincipal = Depends(get_current_active_user_async),
response: Response = None, # type: ignore[assignment]
) -> Any:
"""
查询电影、电视剧或音乐订阅历史
分页查询电影、电视剧或音乐订阅历史,并通过响应头写入精确总数。
:param mtype: 订阅媒体类型分类
:param response: 由 FastAPI 注入的响应对象,用于设置集合总数响应头
:param page: 页码,从 1 开始,最小为 1;直接调用传入 None 时默认第 1 页
:param count: 每页最多返回条数,最小为 1;直接调用传入 None 时默认 30 条
:param query: 订阅查询服务
:param current_user: 当前已认证用户,非超级用户仅查询本人记录
:return: 当前分页窗口内的订阅历史列表
"""
username = None if current_user.is_superuser else current_user.name
page = page if page is not None else 1

View File

@@ -73,6 +73,22 @@ CompatibleCountParam = Annotated[
),
),
]
# 原生分页接口的页码参数,限制为正整数并保留端点各自的默认页码与直接调用空值回退。
PositivePageParam = Annotated[
Optional[int],
Query(
ge=1,
description="从 1 开始的结果页码。",
),
]
# 原生分页接口的每页条数参数,限制为正整数以避免负数进入数据库 LIMIT 子句。
PositiveCountParam = Annotated[
Optional[int],
Query(
ge=1,
description="当前页最多返回的记录数。",
),
]
_COLLECTION_WINDOW_PARAMETERS = frozenset(
{"page", "count", "limit", "offset", "page_size", "max_results"}
)

View File

@@ -508,16 +508,6 @@
"statement": "super().tool_call_started(tool_name, tool_message)",
"reason": "runtime-mro"
},
{
"path": "app/api/endpoints/history.py",
"owner": "download_history",
"codes": [
"assignment"
],
"fingerprint": "e7327c23ed2dd984fc664c9d0dc8341d955337c6472d02702665ac5e5ecdbad7",
"statement": "@router.get('/download', summary='查询下载历史记录', response_model=List[_SchemaDownloadHistory], openapi_extra={COLLECTION_TOTAL_OPENAPI_KEY: True})\nasync def download_history(page: Optional[int]=1, count: Optional[int]=30, query: HistoryQueryService=Depends(get_history_query_service), _: _SchemaTokenPayload=Depends(verify_token), response: Response=None) -> Any:",
"reason": "fastapi-response-default"
},
{
"path": "app/api/endpoints/mfa.py",
"owner": "passkey_list",
@@ -618,16 +608,6 @@
"statement": "@router.get('/', summary='查询所有订阅', response_model=List[_SchemaSubscribe], openapi_extra={COLLECTION_TOTAL_OPENAPI_KEY: True})\nasync def read_subscribes(response: Response=None, query: SubscriptionQueryService=Depends(get_subscription_query_service), status_service: SubscriptionExecutionStatusService=Depends(get_subscription_execution_status_service), current_user: ApiPrincipal=Depends(get_current_active_user_async), page: CompatiblePageParam=None, count: CompatibleCountParam=None) -> Any:",
"reason": "fastapi-response-default"
},
{
"path": "app/api/endpoints/subscribe.py",
"owner": "subscribe_history",
"codes": [
"assignment"
],
"fingerprint": "ac30ef74741b93c556c16d34d74aa02334a761c24300522c16830145b72775de",
"statement": "@router.get('/history/{mtype}', summary='查询订阅历史', response_model=List[_SchemaSubscribe], openapi_extra={COLLECTION_TOTAL_OPENAPI_KEY: True})\nasync def subscribe_history(mtype: str, page: Optional[int]=1, count: Optional[int]=30, query: SubscriptionQueryService=Depends(get_subscription_query_service), current_user: ApiPrincipal=Depends(get_current_active_user_async), response: Response=None) -> Any:",
"reason": "fastapi-response-default"
},
{
"path": "app/api/endpoints/subscribe.py",
"owner": "user_subscribes",

View File

@@ -0,0 +1,333 @@
"""
验证消息、会话、下载、整理与订阅历史分页接口的正整数参数校验契约。
"""
import asyncio
import json
from pathlib import Path
from types import SimpleNamespace
from typing import Any
from unittest.mock import AsyncMock
import pytest
from fastapi import FastAPI, HTTPException, Response
from fastapi.exceptions import RequestValidationError
from fastapi.testclient import TestClient
from app.adapters.web.security.access import verify_token
from app.api.dependencies.agent import get_agent_chat_service, get_message_query_service
from app.api.dependencies.auth import get_current_active_user, get_current_active_user_async
from app.api.dependencies.history import get_history_query_service
from app.api.dependencies.subscription import get_subscription_query_service
from app.api.endpoints import agent, history, message, subscribe
from app.api.response import ResponseAPIRoute
from app.factory import (
localized_http_exception_handler,
localized_unhandled_exception_handler,
localized_validation_exception_handler,
)
from app.schemas.token import TokenPayload
def _build_pagination_test_app(*, fail_on_service_call: bool) -> tuple[FastAPI, dict[str, Any]]:
"""
构造挂载受测分页路由与统一异常处理器的隔离测试应用。
:param fail_on_service_call: 为真时底层查询桩一旦被调用即抛出异常,用于验证非法参数不会下沉到服务与 SQL 层
:return: 测试 FastAPI 实例与注入的查询服务桩映射
"""
app = FastAPI()
app.router.route_class = ResponseAPIRoute
app.add_exception_handler(HTTPException, localized_http_exception_handler)
app.add_exception_handler(RequestValidationError, localized_validation_exception_handler)
app.add_exception_handler(Exception, localized_unhandled_exception_handler)
app.include_router(message.router, prefix="/api/v1/message")
app.include_router(agent.router, prefix="/api/v1/message/agent")
app.include_router(history.router, prefix="/api/v1/history")
app.include_router(subscribe.router, prefix="/api/v1/subscribe")
principal = SimpleNamespace(
id=1,
name="admin",
is_superuser=True,
notification_identity="user:1",
)
token_payload = TokenPayload(sub="1", username="admin", super_user=True)
if fail_on_service_call:
guard_error = RuntimeError("非法分页参数不得下沉到查询服务或数据库 SQL 层")
message_service = SimpleNamespace(
list_history=AsyncMock(side_effect=guard_error),
list_notifications=AsyncMock(side_effect=guard_error),
)
agent_chat_service = SimpleNamespace(
list=AsyncMock(side_effect=guard_error),
)
history_service = SimpleNamespace(
list_download=AsyncMock(side_effect=guard_error),
count_download=AsyncMock(side_effect=guard_error),
list_transfer=AsyncMock(side_effect=guard_error),
)
subscription_service = SimpleNamespace(
list_history=AsyncMock(side_effect=guard_error),
count_history=AsyncMock(side_effect=guard_error),
)
else:
message_service = SimpleNamespace(
list_history=AsyncMock(return_value=[]),
list_notifications=AsyncMock(return_value=[]),
)
agent_chat_service = SimpleNamespace(
list=AsyncMock(return_value=[]),
)
history_service = SimpleNamespace(
list_download=AsyncMock(return_value=[]),
count_download=AsyncMock(return_value=0),
list_transfer=AsyncMock(return_value={"list": [], "total": 0}),
)
subscription_service = SimpleNamespace(
list_history=AsyncMock(return_value=[]),
count_history=AsyncMock(return_value=0),
)
app.dependency_overrides[verify_token] = lambda: token_payload
app.dependency_overrides[get_current_active_user] = lambda: principal
app.dependency_overrides[get_current_active_user_async] = lambda: principal
app.dependency_overrides[get_message_query_service] = lambda: message_service
app.dependency_overrides[get_agent_chat_service] = lambda: agent_chat_service
app.dependency_overrides[get_history_query_service] = lambda: history_service
app.dependency_overrides[get_subscription_query_service] = lambda: subscription_service
stubs = {
"message": message_service,
"agent_chat": agent_chat_service,
"history": history_service,
"subscription": subscription_service,
}
return app, stubs
@pytest.mark.parametrize(
"path",
[
"/api/v1/message/notification",
"/api/v1/message/history",
"/api/v1/message/web",
"/api/v1/message/agent/sessions",
"/api/v1/history/download",
"/api/v1/history/transfer",
"/api/v1/subscribe/history/电影",
],
)
@pytest.mark.parametrize(
("param_name", "invalid_value"),
[
("count", -1),
("count", 0),
("page", -1),
("page", 0),
],
)
def test_database_paginated_endpoints_reject_non_positive_pagination_with_422(
path: str,
param_name: str,
invalid_value: int,
) -> None:
"""
验证数据库分页接口对负数和零页码或条数返回 422 参数校验错误,避免下沉触发 500。
:param path: 待验证的分页接口路径
:param param_name: 分页查询参数名称
:param invalid_value: 非正整数的非法输入值
"""
app, stubs = _build_pagination_test_app(fail_on_service_call=True)
with TestClient(app, raise_server_exceptions=False) as client:
response = client.get(path, params={param_name: invalid_value})
assert response.status_code == 422
payload = response.json()
assert payload["success"] is False
assert isinstance(payload["data"], list) and payload["data"]
assert any(
issue["location"] == ["query", param_name]
and issue["error_type"] == "greater_than_equal"
for issue in payload["data"]
)
stubs["message"].list_history.assert_not_awaited()
stubs["message"].list_notifications.assert_not_awaited()
stubs["agent_chat"].list.assert_not_awaited()
stubs["history"].list_download.assert_not_awaited()
stubs["history"].list_transfer.assert_not_awaited()
stubs["subscription"].list_history.assert_not_awaited()
def test_database_paginated_endpoints_preserve_defaults_and_large_transfer_page_size(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""
验证省略分页参数时沿用各端点原有默认值,且整理历史继续支持桌面端 1000 条每页窗口。
:param monkeypatch: 用于隔离通知清理水位读取的测试夹具
"""
monkeypatch.setattr(
message,
"_get_notification_clear_before",
lambda: SimpleNamespace(all=0, system=0, media=0),
)
app, stubs = _build_pagination_test_app(fail_on_service_call=False)
with TestClient(app) as client:
assert client.get("/api/v1/message/notification").status_code == 200
assert client.get("/api/v1/message/history").status_code == 200
assert client.get("/api/v1/message/agent/sessions").status_code == 200
assert client.get("/api/v1/history/download").status_code == 200
assert client.get("/api/v1/history/transfer?page=1&count=1000").status_code == 200
assert client.get("/api/v1/subscribe/history/电影").status_code == 200
stubs["message"].list_notifications.assert_awaited_once_with(
page=1,
count=20,
all_clear_before=None,
system_clear_before=None,
media_clear_before=None,
)
stubs["message"].list_history.assert_awaited_once_with(page=1, count=20)
stubs["agent_chat"].list.assert_awaited_once()
assert stubs["agent_chat"].list.await_args.kwargs == {"page": 1, "count": 30}
stubs["history"].list_download.assert_awaited_once_with(page=1, count=30)
stubs["history"].list_transfer.assert_awaited_once_with(
title=None,
page=1,
count=1000,
status=None,
)
stubs["subscription"].list_history.assert_awaited_once_with(
"电影",
page=1,
count=30,
username=None,
)
def test_direct_calls_with_none_pagination_fall_back_to_endpoint_defaults(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""
验证直接以 Python 函数方式传入 None 分页值时仍回退为各端点默认正整数。
:param monkeypatch: 用于隔离通知清理水位读取的测试夹具
"""
monkeypatch.setattr(
message,
"_get_notification_clear_before",
lambda: SimpleNamespace(all=0, system=0, media=0),
)
message_service = SimpleNamespace(list_notifications=AsyncMock(return_value=[]))
history_service = SimpleNamespace(
list_download=AsyncMock(return_value=[]),
count_download=AsyncMock(return_value=0),
)
subscription_service = SimpleNamespace(
list_history=AsyncMock(return_value=[]),
count_history=AsyncMock(return_value=0),
)
principal = SimpleNamespace(
id=1,
name="admin",
is_superuser=True,
notification_identity="user:1",
)
assert asyncio.run(
message.get_notification_message(_=None, service=message_service, page=None, count=None)
) == []
assert asyncio.run(
history.download_history(
response=Response(),
page=None,
count=None,
query=history_service,
_=None,
)
) == []
assert asyncio.run(
subscribe.subscribe_history(
mtype="电影",
response=Response(),
page=None,
count=None,
query=subscription_service,
current_user=principal,
)
) == []
message_service.list_notifications.assert_awaited_once_with(
page=1,
count=20,
all_clear_before=None,
system_clear_before=None,
media_clear_before=None,
)
history_service.list_download.assert_awaited_once_with(page=1, count=30)
subscription_service.list_history.assert_awaited_once_with(
"电影",
page=1,
count=30,
username=None,
)
def test_openapi_and_mcp_schema_declare_minimum_one_for_history_pagination() -> None:
"""
验证 OpenAPI 与外部 MCP 输入合同为分页参数声明 minimum=1 且保留端点默认值。
"""
app, _ = _build_pagination_test_app(fail_on_service_call=False)
openapi = app.openapi()
expected_defaults = {
"/api/v1/message/notification": (1, 20),
"/api/v1/message/history": (1, 20),
"/api/v1/message/web": (1, 20),
"/api/v1/message/agent/sessions": (1, 30),
"/api/v1/history/download": (1, 30),
"/api/v1/history/transfer": (1, 30),
"/api/v1/subscribe/history/{mtype}": (1, 30),
}
for path, (default_page, default_count) in expected_defaults.items():
parameters = {
item["name"]: item["schema"]
for item in openapi["paths"][path]["get"].get("parameters", [])
if item.get("in") == "query"
}
assert "response" not in parameters, path
for field_name, expected_default in (("page", default_page), ("count", default_count)):
schema = parameters[field_name]
assert schema["default"] == expected_default, (path, field_name)
minimums = [schema.get("minimum")] + [
branch.get("minimum")
for branch in schema.get("anyOf", [])
if isinstance(branch, dict)
]
assert 1 in minimums, (path, field_name, schema)
from scripts.generate_agent_api_mcp_schema import generate_schema
stored_schema = json.loads(
(Path(__file__).parents[1] / "app/agent/policy/resources/api_mcp_schema.json").read_text(
encoding="utf-8"
)
)
generated_schema = generate_schema()
stored_branches = {
item["properties"]["operation_id"]["const"]: item["properties"]["query"]
for item in stored_schema["oneOf"]
if item["properties"]["operation_id"].get("const")
in {"download.history.list", "transfer.history", "subscription.history"}
}
generated_branches = {
item["properties"]["operation_id"]["const"]: item["properties"]["query"]
for item in generated_schema["oneOf"]
if item["properties"]["operation_id"].get("const")
in {"download.history.list", "transfer.history", "subscription.history"}
}
assert stored_branches == generated_branches