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

+1
View File
@@ -42,6 +42,7 @@
- 2026-08-25: `project_mind_map.md` is the current source-controlled project map for Belki and deployment/security boundaries; update it when a data flow, service, or integration changes.
- 2026-08-25: password-only admin login has an in-process five-attempt/15-minute per-source limit; it complements but does not replace an edge rate limit.
- 2026-08-25: free-text parsing normalizes common punctuation, spaced IDs, ID markers and close role-label typos. Do not add generic Russian NER solely for CatWar nicknames: ID and role context are the more reliable authority.
- 2026-08-25: public reports cap coaching at 50 kittens and inspections at 100 resource rows, 100000 inspections and 100000 units per resource; enforce the limits in the shared domain rather than only in one transport.
# 2026-08-16 — несколько котят в прокачке
`CoachingSession.extra_kittens` теперь влияет на баллы сопровождающего через количество подопечных: 1-й ×1, 2-й ×1,5, каждый последующий ×1,15 (коэффициенты перемножаются), вместо сложения полной прибыли. Базовый коэффициент самостоятельности основного котёнка сохраняется. Веб-форма отправляет список `extra_kittens`; VK принимает `доп. котята: ...` в pipe-команде.
+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:
+1
View File
@@ -70,6 +70,7 @@
- 2026-08-25: corrected Russian UX copy in the VK help and attachment flow; the web identity hint now accurately says that a manually completed pair applies only to the current calculation.
- 2026-08-25: natural input normalizes Unicode spaces, dash variants, `ID`/`№` prefixes, spaced IDs, common date/time separators, and close role-label typos before extracting structured fields. Natasha was evaluated for Russian NER through Context7 but not added: game nicknames are better anchored by user-provided IDs and local role context than a generic person model.
- 2026-08-25: impossible status combinations discovered in free text (for example, non-self-sufficient ЗУ) now remain a repairable clarification in the dialogue instead of raising out of the VK handler.
- 2026-08-25: shared domain limits now bound public calculation fan-out: at most 50 coaching kittens, 100 inspection resource rows, 100000 inspections, and 100000 units of one resource. API and VK reject oversized kitten lists before calculation.
- 2026-08-25: `/api/admin/auth` now permits five password attempts per source in a rolling 15-minute window and clears that local budget after a successful sign-in. Edge rate limiting and TLS remain required deployment controls.
# Обновление 2026-08-16: несколько котят
+9
View File
@@ -108,6 +108,15 @@ class ApiTests(unittest.TestCase):
self.assertEqual(row[:3], (700, "training", "vk"))
self.assertIn("#урок", row[3])
def test_api_rejects_an_excessive_extra_kittens_list_before_conversion(self):
payload = {
"mode": "coaching", "date": "15.08", "skill": "ЛУ", "start": "11:00", "end": "11:20",
"escort_name": "Белка", "escort_id": 1, "kitten_name": "Первый", "kitten_id": 2,
"extra_kittens": [[f"Котёнок {index}", index + 3] for index in range(50)],
}
with self.assertRaisesRegex(ApiError, "не более 50 котят"):
calculate_payload(payload)
if __name__ == "__main__":
unittest.main()
+9
View File
@@ -77,6 +77,15 @@ class CalculationTests(unittest.TestCase):
),
)
def test_domain_rejects_excessive_coaching_and_inspection_input(self):
extras = tuple((f"Котёнок {index}", index + 2, "самостоятельно") for index in range(50))
with self.assertRaisesRegex(ValueError, "не более 50 котят"):
CoachingSession("15.08", "ЛУ", "11:00", "12:00", "Белка", 1, "Первый", 2, extra_kittens=extras)
with self.assertRaisesRegex(ValueError, "от 0 до 100000"):
InspectionReport("Белка", 1, "дупло", 100001)
with self.assertRaisesRegex(ValueError, "не более 100 ресурсов"):
InspectionReport("Белка", 1, "дупло", 1, tuple(("вьюнок", 1) for _ in range(101)))
def test_zu_rejects_non_self_kitten(self):
with self.assertRaisesRegex(ValueError, "Для ЗУ все котята должны быть самостоятельными"):
CoachingSession(