fix(domain): bound public report input sizes

This commit is contained in:
nyan404 committed 2026-08-25 03:50:35 +03:00
1 parent 1c2bfa9594
commit c0a6f6286e
7 files changed
+39 -4

No files matched your search

+2
View File
@@ -143,6 +143,8 @@ def calculate_payload(payload: dict[str, Any]) -> dict[str, Any]:
raw_extras = payload.get("extra_kittens", [])
if not isinstance(raw_extras, (list, tuple)):
raise ApiError("Поле extra_kittens должно быть списком")
if len(raw_extras) > 49:
raise ApiError("В одном заходе может участвовать не более 50 котят")
extras_list = []
for item in raw_extras:
if isinstance(item, dict):
+12 -4
View File
@@ -23,6 +23,10 @@ _CLOCK_RE = re.compile(r"^(?:[01]\d|2[0-3]):[0-5]\d$")
# values from turning a simple estimate into an unbounded exponentiation.
MAX_GOAL_MINUTES_PER_SESSION = 24 * 60
MAX_GOAL_KITTENS = 50
MAX_COACHING_KITTENS = 50
MAX_INSPECTIONS = 100_000
MAX_INSPECTION_RESOURCES = 100
MAX_RESOURCE_AMOUNT = 100_000
def parse_clock(value: str) -> int:
@@ -91,6 +95,8 @@ class CoachingSession:
_positive_id(kitten_id, "ID дополнительного котёнка")
if independence not in ("самостоятельно", "несамостоятельно"):
raise ValueError("Некорректный статус самостоятельности")
if 1 + len(self.extra_kittens) > MAX_COACHING_KITTENS:
raise ValueError(f"В одном заходе может участвовать не более {MAX_COACHING_KITTENS} котят")
statuses = (self.kitten_independence,) + tuple(independence for _, _, independence in self.extra_kittens)
nonself_count = sum(status == "несамостоятельно" for status in statuses)
if self.skill == "ЗУ" and any(s != "самостоятельно" for s in statuses):
@@ -250,11 +256,13 @@ class InspectionReport:
_positive_id(self.character_id, "ID персонажа")
if self.place not in ("дупло", "расщелина"):
raise ValueError("Место должно быть дуплом или расщелиной")
if isinstance(self.inspections, bool) or not isinstance(self.inspections, int) or self.inspections < 0:
raise ValueError("Количество осмотров должно быть неотрицательным целым")
if isinstance(self.inspections, bool) or not isinstance(self.inspections, int) or not 0 <= self.inspections <= MAX_INSPECTIONS:
raise ValueError(f"Количество осмотров должно быть целым числом от 0 до {MAX_INSPECTIONS}")
if len(self.resources) > MAX_INSPECTION_RESOURCES:
raise ValueError(f"В одном отчёте может быть не более {MAX_INSPECTION_RESOURCES} ресурсов")
for name, amount in self.resources:
if not name.strip() or not isinstance(amount, int) or amount < 0:
raise ValueError("Ресурс должен иметь название и неотрицательное целое количество")
if not name.strip() or not isinstance(amount, int) or not 0 <= amount <= MAX_RESOURCE_AMOUNT:
raise ValueError(f"Ресурс должен иметь название и количество от 0 до {MAX_RESOURCE_AMOUNT}")
@dataclass(frozen=True)
+5
View File
@@ -15,6 +15,7 @@ from urllib.parse import urlencode
from urllib.request import Request, urlopen
from .api import ApiError, calculate_payload
from .domain import MAX_COACHING_KITTENS
from .history import CalculationStore
from .image_host import ImageHostClient
from .identity import Identity, IdentityDirectory
@@ -163,11 +164,15 @@ def _extra_kittens(value: str) -> tuple[tuple[str, int, str], ...]:
item = item[:status.start()].strip()
name, kitten_id = _person(item)
result.append((name, kitten_id, independence))
if len(result) >= MAX_COACHING_KITTENS:
raise ValueError(f"Можно добавить не более {MAX_COACHING_KITTENS - 1} дополнительных котят")
return tuple(result)
def _validate_independence(skill: str, primary: str, extras: tuple[tuple[str, int, str], ...] | list[tuple[str, int, str]]) -> None:
statuses = (primary,) + tuple(independence for _, _, independence in extras)
if len(statuses) > MAX_COACHING_KITTENS:
raise ValueError(f"В одном заходе может участвовать не более {MAX_COACHING_KITTENS} котят")
if skill == "ЗУ" and any(s != "самостоятельно" for s in statuses):
raise ValueError("Для ЗУ все котята должны быть самостоятельными")
if skill == "ЛУ" and sum(status == "несамостоятельно" for status in statuses) > 1: