fix(applications): bound public submission data
This commit is contained in:
1 parent
038d1f41a5
commit
61036641f8
3 files changed
+81
-5
No files matched your search
@@ -16,6 +16,12 @@ APPLICATION_TYPES = {
|
||||
"flying_squirrel": "Стать белкой-летягой",
|
||||
"curator": "Стать куратором",
|
||||
}
|
||||
MAX_APPLICATION_NAME_LENGTH = 100
|
||||
MAX_APPLICATION_ATTACHMENTS = 10
|
||||
MAX_APPLICATION_FEATHERS = 100
|
||||
MAX_APPLICATION_TEXT_LENGTH = 500
|
||||
MAX_APPLICATION_URL_LENGTH = 2_048
|
||||
MAX_APPLICATION_FEATHER_AMOUNT = 100_000
|
||||
|
||||
|
||||
class ApplicationError(ValueError):
|
||||
@@ -33,16 +39,48 @@ def _positive_id(value: Any, label: str) -> int:
|
||||
|
||||
|
||||
def _normalise_vk_link(value: Any) -> str:
|
||||
"""Сохраняет VK-ссылку с HTTPS, но не заставляет пользователя вводить протокол."""
|
||||
"""Accept a real VK HTTPS link without making users type the protocol."""
|
||||
link = str(value or "").strip()
|
||||
if not link:
|
||||
return ""
|
||||
if len(link) > MAX_APPLICATION_URL_LENGTH:
|
||||
raise ApplicationError("Ссылка VK слишком длинная")
|
||||
parsed = urlparse(link)
|
||||
if not parsed.scheme and parsed.path.split("/", 1)[0].lower() in {"vk.com", "www.vk.com", "vk.ru", "www.vk.ru"}:
|
||||
return f"https://{link}"
|
||||
link = f"https://{link}"
|
||||
parsed = urlparse(link)
|
||||
host = (parsed.hostname or "").lower()
|
||||
if parsed.scheme != "https" or host not in {"vk.com", "www.vk.com", "vk.ru", "www.vk.ru", "m.vk.com", "m.vk.ru"}:
|
||||
raise ApplicationError("Укажите HTTPS-ссылку на страницу VK")
|
||||
return link
|
||||
|
||||
|
||||
def _https_link(value: Any, label: str) -> str:
|
||||
link = str(value or "").strip()
|
||||
if len(link) > MAX_APPLICATION_URL_LENGTH:
|
||||
raise ApplicationError(f"{label} слишком длинная")
|
||||
parsed = urlparse(link)
|
||||
if parsed.scheme != "https" or not parsed.hostname:
|
||||
raise ApplicationError(f"{label} должна начинаться с https://")
|
||||
return link
|
||||
|
||||
|
||||
def _attachments(value: Any) -> list[dict[str, str]]:
|
||||
if not isinstance(value, list) or len(value) > MAX_APPLICATION_ATTACHMENTS:
|
||||
raise ApplicationError(f"Можно приложить не более {MAX_APPLICATION_ATTACHMENTS} изображений")
|
||||
attachments: list[dict[str, str]] = []
|
||||
for item in value:
|
||||
if not isinstance(item, dict):
|
||||
raise ApplicationError("Некорректное вложение")
|
||||
url = _https_link(item.get("url"), "Ссылка на вложение")
|
||||
attachment = {"type": "photo", "url": url}
|
||||
name = str(item.get("name", "")).strip()
|
||||
if name:
|
||||
attachment["name"] = name[:MAX_APPLICATION_NAME_LENGTH]
|
||||
attachments.append(attachment)
|
||||
return attachments
|
||||
|
||||
|
||||
def validate_application(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Возвращает очищенную заявку и проверяет обязательные поля её типа."""
|
||||
if not isinstance(payload, dict):
|
||||
@@ -53,11 +91,13 @@ def validate_application(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
name = str(payload.get("name", "")).strip()
|
||||
if not name:
|
||||
raise ApplicationError("Укажите имя персонажа")
|
||||
if len(name) > MAX_APPLICATION_NAME_LENGTH:
|
||||
raise ApplicationError(f"Имя персонажа не должно быть длиннее {MAX_APPLICATION_NAME_LENGTH} символов")
|
||||
result: dict[str, Any] = {
|
||||
"type": application_type,
|
||||
"name": name,
|
||||
"character_id": _positive_id(payload.get("character_id"), "ID персонажа"),
|
||||
"attachments": [item for item in payload.get("attachments", []) if isinstance(item, dict)],
|
||||
"attachments": _attachments(payload.get("attachments", [])),
|
||||
"vk_link": _normalise_vk_link(payload.get("vk_link")),
|
||||
}
|
||||
if application_type == "kitten":
|
||||
@@ -71,19 +111,28 @@ def validate_application(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
result["practice_review_link"] = str(payload.get("practice_review_link", "")).strip()
|
||||
if practiced_before and not result["practice_review_link"]:
|
||||
raise ApplicationError("Приложите ссылку на комментарий с прошлой практики")
|
||||
if result["practice_review_link"]:
|
||||
result["practice_review_link"] = _https_link(result["practice_review_link"], "Ссылка на комментарий")
|
||||
elif application_type == "curator":
|
||||
if not result["attachments"]:
|
||||
raise ApplicationError("Для заявки куратором приложите скриншот ЛУ с дробью")
|
||||
elif application_type == "feather_donation":
|
||||
feathers = []
|
||||
for item in payload.get("feathers", []):
|
||||
raw_feathers = payload.get("feathers", [])
|
||||
if not isinstance(raw_feathers, list) or len(raw_feathers) > MAX_APPLICATION_FEATHERS:
|
||||
raise ApplicationError(f"Можно указать не более {MAX_APPLICATION_FEATHERS} строк с перьями")
|
||||
for item in raw_feathers:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
color = str(item.get("color", "")).strip()
|
||||
source = str(item.get("source", "")).strip()
|
||||
if not color or not source:
|
||||
raise ApplicationError("Для каждого пера укажите цвет и источник добычи")
|
||||
if len(color) > MAX_APPLICATION_TEXT_LENGTH or len(source) > MAX_APPLICATION_TEXT_LENGTH:
|
||||
raise ApplicationError(f"Описание пера не должно быть длиннее {MAX_APPLICATION_TEXT_LENGTH} символов")
|
||||
amount = _positive_id(item.get("amount"), "Количество перьев")
|
||||
if amount > MAX_APPLICATION_FEATHER_AMOUNT:
|
||||
raise ApplicationError(f"Количество перьев не должно превышать {MAX_APPLICATION_FEATHER_AMOUNT}")
|
||||
feathers.append({"color": color, "amount": amount, "source": source})
|
||||
if not feathers:
|
||||
raise ApplicationError("Добавьте хотя бы одно перо")
|
||||
|
||||
@@ -67,6 +67,7 @@
|
||||
- 2026-08-25: VK image mirroring checks the advertised byte length and reads at most 15 MiB plus a one-byte sentinel before uploading. Oversized upstream photos no longer allocate unbounded memory in the bot process.
|
||||
- 2026-08-25: `BelkiHTTPServer` supersedes the unbounded standard threaded server. It rejects oversized declared JSON before reading, times out a slow client after 15 seconds, and serves at most 32 concurrent connections.
|
||||
- 2026-08-25: long-lived authenticated admin refresh WebSockets now have a separate eight-connection pool, so they cannot consume all 32 request workers; additional connections receive an explicit temporary-unavailable response.
|
||||
- 2026-08-25: application validation now bounds names, attachment and feather rows, and descriptive text for both web and VK submissions. Stored attachment and review links must be HTTPS; the optional profile link is restricted to a real VK host.
|
||||
- 2026-08-25: one-line VK/web recognition now gives explicit role labels priority over position. `сопровождающий`/`наставник`/`учитель` identify the escort, while `ученик`/`котёнок`/`бельчонок`/`подопечный` identify the ward; unlabeled pairs retain the original order-based fallback.
|
||||
- 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.
|
||||
|
||||
@@ -2,7 +2,8 @@ import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from app.belki.applications import ApplicationError, ApplicationStore, validate_application
|
||||
from app.belki.applications import (MAX_APPLICATION_ATTACHMENTS, MAX_APPLICATION_FEATHERS,
|
||||
ApplicationError, ApplicationStore, validate_application)
|
||||
from app.belki.google_sheets_export import GoogleSheetsExportConfig, GoogleSheetsExportService
|
||||
from app.belki.identity import IdentityDirectory
|
||||
from app.belki.vk_bot import ApplicationDialog
|
||||
@@ -27,6 +28,31 @@ class ApplicationTests(unittest.TestCase):
|
||||
expected = link if link.startswith("https://") else f"https://{link}"
|
||||
self.assertEqual(application["vk_link"], expected)
|
||||
|
||||
def test_application_rejects_non_vk_or_insecure_profile_links(self) -> None:
|
||||
for link in ("http://vk.com/id1", "https://vk.com.evil.test/id1", "https://example.test"):
|
||||
with self.subTest(link=link), self.assertRaisesRegex(ApplicationError, "HTTPS-ссылку на страницу VK"):
|
||||
validate_application({
|
||||
"type": "flying_squirrel", "name": "Муся", "character_id": 1337,
|
||||
"practiced_before": False, "vk_link": link,
|
||||
})
|
||||
|
||||
def test_application_bounds_attachment_and_feather_fan_out(self) -> None:
|
||||
too_many_attachments = [{"url": "https://img.example.test/photo.jpg"}] * (MAX_APPLICATION_ATTACHMENTS + 1)
|
||||
with self.assertRaisesRegex(ApplicationError, "не более"):
|
||||
validate_application({"type": "kitten", "name": "Муся", "character_id": 1337, "attachments": too_many_attachments})
|
||||
too_many_feathers = [{"amount": 1, "color": "синее", "source": "запасы"}] * (MAX_APPLICATION_FEATHERS + 1)
|
||||
with self.assertRaisesRegex(ApplicationError, "не более"):
|
||||
validate_application({"type": "feather_donation", "name": "Муся", "character_id": 1337, "feathers": too_many_feathers})
|
||||
|
||||
def test_application_requires_https_attachment_and_practice_review_links(self) -> None:
|
||||
with self.assertRaisesRegex(ApplicationError, "(?i)вложение.*https"):
|
||||
validate_application({"type": "kitten", "name": "Муся", "character_id": 1337, "attachments": [{"url": "http://example.test/a.jpg"}]})
|
||||
with self.assertRaisesRegex(ApplicationError, "(?i)комментарий.*https"):
|
||||
validate_application({
|
||||
"type": "flying_squirrel", "name": "Муся", "character_id": 1337,
|
||||
"practiced_before": True, "practice_review_link": "http://example.test/review",
|
||||
})
|
||||
|
||||
def test_feather_donation_is_saved_and_accepted(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
store = ApplicationStore(sqlite_path=Path(directory) / "applications.sqlite3")
|
||||
|
||||
Reference in new issue
Block a user