fix(api): validate nested report fields
This commit is contained in:
1 parent
92171731ae
commit
0aec421ad2
6 files changed
+48
-6
No files matched your search
@@ -45,6 +45,7 @@
|
|||||||
- 2026-08-25: in-process admin sessions are opaque tokens with a 12-hour server and cookie lifetime, capped at 100 active sessions; a restart still invalidates them by design.
|
- 2026-08-25: in-process admin sessions are opaque tokens with a 12-hour server and cookie lifetime, capped at 100 active sessions; a restart still invalidates them by design.
|
||||||
- 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: 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-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-25: strict API conversion also covers nested extra-kitten IDs and inspection resources; no boolean coercion or unbounded resource conversion occurs before domain validation.
|
||||||
- 2026-08-25: free-form input also accepts Russian written dates and month abbreviations, normalizing them to `ДД.ММ`; report dates are then calendar-validated in the domain before storage.
|
- 2026-08-25: free-form input also accepts Russian written dates and month abbreviations, normalizing them to `ДД.ММ`; report dates are then calendar-validated in the domain before storage.
|
||||||
- 2026-08-25: application validation limits text, rows, per-row feather amounts, and attachments across web and VK. Persisted media/review links require HTTPS, and a profile link is accepted only for a VK host.
|
- 2026-08-25: application validation limits text, rows, per-row feather amounts, and attachments across web and VK. Persisted media/review links require HTTPS, and a profile link is accepted only for a VK host.
|
||||||
- 2026-08-25: authenticated admin refresh WebSockets use a separate pool of eight slots so they cannot consume the bounded general HTTP worker pool. History sorting normalizes old string IDs with current numeric IDs.
|
- 2026-08-25: authenticated admin refresh WebSockets use a separate pool of eight slots so they cannot consume the bounded general HTTP worker pool. History sorting normalizes old string IDs with current numeric IDs.
|
||||||
|
|||||||
+25
-5
@@ -12,6 +12,7 @@ from typing import Any
|
|||||||
from .domain import (
|
from .domain import (
|
||||||
CoachingSession,
|
CoachingSession,
|
||||||
InspectionReport,
|
InspectionReport,
|
||||||
|
MAX_INSPECTION_RESOURCES,
|
||||||
TrainingSession,
|
TrainingSession,
|
||||||
calculate_coaching,
|
calculate_coaching,
|
||||||
calculate_inspection,
|
calculate_inspection,
|
||||||
@@ -114,13 +115,17 @@ def _required(payload: dict[str, Any], key: str) -> Any:
|
|||||||
|
|
||||||
def _int(payload: dict[str, Any], key: str) -> int:
|
def _int(payload: dict[str, Any], key: str) -> int:
|
||||||
"""Преобразует значение в int с валидацией и понятным сообщением об ошибке."""
|
"""Преобразует значение в int с валидацией и понятным сообщением об ошибке."""
|
||||||
value = _required(payload, key)
|
return _int_value(_required(payload, key), f"Поле {key}")
|
||||||
|
|
||||||
|
|
||||||
|
def _int_value(value: Any, label: str) -> int:
|
||||||
|
"""Convert one JSON integer while refusing Python's boolean coercion."""
|
||||||
if isinstance(value, bool):
|
if isinstance(value, bool):
|
||||||
raise ApiError(f"Поле {key} должно быть числом")
|
raise ApiError(f"{label} должно быть числом")
|
||||||
try:
|
try:
|
||||||
return int(value)
|
return int(value)
|
||||||
except (TypeError, ValueError) as exc:
|
except (TypeError, ValueError) as exc:
|
||||||
raise ApiError(f"Поле {key} должно быть числом") from exc
|
raise ApiError(f"{label} должно быть числом") from exc
|
||||||
|
|
||||||
|
|
||||||
def calculate_payload(payload: dict[str, Any]) -> dict[str, Any]:
|
def calculate_payload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
@@ -154,7 +159,9 @@ def calculate_payload(payload: dict[str, Any]) -> dict[str, Any]:
|
|||||||
independence = item[2] if len(item) > 2 else "самостоятельно"
|
independence = item[2] if len(item) > 2 else "самостоятельно"
|
||||||
else:
|
else:
|
||||||
raise ApiError("Дополнительный котёнок должен содержать имя и ID")
|
raise ApiError("Дополнительный котёнок должен содержать имя и ID")
|
||||||
extras_list.append((str(name), int(kitten_id), str(independence)))
|
if not isinstance(name, str) or not name.strip():
|
||||||
|
raise ApiError("Укажите имя дополнительного котёнка")
|
||||||
|
extras_list.append((name, _int_value(kitten_id, "ID дополнительного котёнка"), str(independence)))
|
||||||
extras = tuple(extras_list)
|
extras = tuple(extras_list)
|
||||||
session = CoachingSession(
|
session = CoachingSession(
|
||||||
date=str(_required(payload, "date")),
|
date=str(_required(payload, "date")),
|
||||||
@@ -184,7 +191,20 @@ def calculate_payload(payload: dict[str, Any]) -> dict[str, Any]:
|
|||||||
result = calculate_training(session)
|
result = calculate_training(session)
|
||||||
return {"mode": mode, "result": asdict(result), "message": render_training(session, result)}
|
return {"mode": mode, "result": asdict(result), "message": render_training(session, result)}
|
||||||
if mode == "inspection":
|
if mode == "inspection":
|
||||||
resources = tuple((str(name), int(amount)) for name, amount in payload.get("resources", []))
|
raw_resources = payload.get("resources", [])
|
||||||
|
if not isinstance(raw_resources, (list, tuple)):
|
||||||
|
raise ApiError("Поле resources должно быть списком")
|
||||||
|
if len(raw_resources) > MAX_INSPECTION_RESOURCES:
|
||||||
|
raise ApiError(f"В одном отчёте может быть не более {MAX_INSPECTION_RESOURCES} ресурсов")
|
||||||
|
resources_list = []
|
||||||
|
for item in raw_resources:
|
||||||
|
if not isinstance(item, (list, tuple)) or len(item) != 2:
|
||||||
|
raise ApiError("Каждый ресурс должен содержать название и количество")
|
||||||
|
name, amount = item
|
||||||
|
if not isinstance(name, str) or not name.strip():
|
||||||
|
raise ApiError("Укажите название ресурса")
|
||||||
|
resources_list.append((name, _int_value(amount, "Количество ресурса")))
|
||||||
|
resources = tuple(resources_list)
|
||||||
report = InspectionReport(
|
report = InspectionReport(
|
||||||
character_name=str(_required(payload, "character_name")),
|
character_name=str(_required(payload, "character_name")),
|
||||||
character_id=_int(payload, "character_id"),
|
character_id=_int(payload, "character_id"),
|
||||||
|
|||||||
+1
-1
@@ -274,7 +274,7 @@ class InspectionReport:
|
|||||||
if len(self.resources) > MAX_INSPECTION_RESOURCES:
|
if len(self.resources) > MAX_INSPECTION_RESOURCES:
|
||||||
raise ValueError(f"В одном отчёте может быть не более {MAX_INSPECTION_RESOURCES} ресурсов")
|
raise ValueError(f"В одном отчёте может быть не более {MAX_INSPECTION_RESOURCES} ресурсов")
|
||||||
for name, amount in self.resources:
|
for name, amount in self.resources:
|
||||||
if not name.strip() or not isinstance(amount, int) or not 0 <= amount <= MAX_RESOURCE_AMOUNT:
|
if not isinstance(name, str) or not name.strip() or isinstance(amount, bool) or not isinstance(amount, int) or not 0 <= amount <= MAX_RESOURCE_AMOUNT:
|
||||||
raise ValueError(f"Ресурс должен иметь название и количество от 0 до {MAX_RESOURCE_AMOUNT}")
|
raise ValueError(f"Ресурс должен иметь название и количество от 0 до {MAX_RESOURCE_AMOUNT}")
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -77,6 +77,7 @@
|
|||||||
- 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: 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: 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: 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: nested public API values now use the same strict numeric conversion as top-level fields: booleans cannot become IDs or amounts, malformed resources are rejected, and resource rows are bounded before conversion.
|
||||||
- 2026-08-25: report copy now uses a plural construction for several kittens, normative `провёл(-ла)` for lessons, and a readable empty-resource line instead of a standalone `0`.
|
- 2026-08-25: report copy now uses a plural construction for several kittens, normative `провёл(-ла)` for lessons, and a readable empty-resource line instead of a standalone `0`.
|
||||||
- 2026-08-25: free-form inspection parsing now distinguishes a labelled count (or a count immediately after the place) from date fragments and character IDs; it also understands explicit character labels and both `+N ресурс` and legacy `ресурс=N` loot notation.
|
- 2026-08-25: free-form inspection parsing now distinguishes a labelled count (or a count immediately after the place) from date fragments and character IDs; it also understands explicit character labels and both `+N ресурс` and legacy `ресурс=N` loot notation.
|
||||||
- 2026-08-25: free-form coaching input additionally normalizes Russian written month names and common abbreviations (for example, `24 августа` and `1-го сент`) into the existing `ДД.ММ` date field.
|
- 2026-08-25: free-form coaching input additionally normalizes Russian written month names and common abbreviations (for example, `24 августа` and `1-го сент`) into the existing `ДД.ММ` date field.
|
||||||
|
|||||||
@@ -117,6 +117,24 @@ class ApiTests(unittest.TestCase):
|
|||||||
with self.assertRaisesRegex(ApiError, "не более 50 котят"):
|
with self.assertRaisesRegex(ApiError, "не более 50 котят"):
|
||||||
calculate_payload(payload)
|
calculate_payload(payload)
|
||||||
|
|
||||||
|
def test_api_rejects_boolean_and_malformed_nested_report_values(self):
|
||||||
|
coaching = {
|
||||||
|
"mode": "coaching", "date": "15.08", "skill": "ЛУ", "start": "11:00", "end": "11:20",
|
||||||
|
"escort_name": "Белка", "escort_id": 1, "kitten_name": "Первый", "kitten_id": 2,
|
||||||
|
"extra_kittens": [{"name": "Второй", "id": True}],
|
||||||
|
}
|
||||||
|
with self.assertRaisesRegex(ApiError, "ID дополнительного котёнка"):
|
||||||
|
calculate_payload(coaching)
|
||||||
|
inspection = {
|
||||||
|
"mode": "inspection", "character_name": "Белка", "character_id": 1,
|
||||||
|
"place": "дупло", "inspections": 1, "resources": [["паутина", True]],
|
||||||
|
}
|
||||||
|
with self.assertRaisesRegex(ApiError, "Количество ресурса"):
|
||||||
|
calculate_payload(inspection)
|
||||||
|
inspection["resources"] = "паутина=1"
|
||||||
|
with self.assertRaisesRegex(ApiError, "resources должно быть списком"):
|
||||||
|
calculate_payload(inspection)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
@@ -248,6 +248,8 @@ class ReportTests(unittest.TestCase):
|
|||||||
def test_inspection_rejects_negative_resources(self):
|
def test_inspection_rejects_negative_resources(self):
|
||||||
with self.assertRaises(ValueError):
|
with self.assertRaises(ValueError):
|
||||||
InspectionReport("Белка", 1, "дупло", 1, (("вьюнок", -1),))
|
InspectionReport("Белка", 1, "дупло", 1, (("вьюнок", -1),))
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
InspectionReport("Белка", 1, "дупло", 1, (("вьюнок", True),))
|
||||||
|
|
||||||
def test_inspection_resource_aliases_and_typos(self):
|
def test_inspection_resource_aliases_and_typos(self):
|
||||||
report = InspectionReport(
|
report = InspectionReport(
|
||||||
|
|||||||
Reference in new issue
Block a user