fix(identity): validate persistent character pairs
This commit is contained in:
1 parent
0aec421ad2
commit
6af34d4706
8 files changed
+44
-1
No files matched your search
@@ -35,6 +35,7 @@
|
|||||||
- 2026-08-25: public goal calculations reject non-finite scores and bound session length to 1–1440 minutes and kitten count to 1–50, consistently across domain, API, and VK input.
|
- 2026-08-25: public goal calculations reject non-finite scores and bound session length to 1–1440 minutes and kitten count to 1–50, consistently across domain, API, and VK input.
|
||||||
- 2026-08-25: screenshot uploads are public by product design but are bounded before JSON parsing (20 MiB) and after base64 decoding (15 MiB); only verified PNG/JPEG/WebP bytes and basename-only filenames reach image hosting.
|
- 2026-08-25: screenshot uploads are public by product design but are bounded before JSON parsing (20 MiB) and after base64 decoding (15 MiB); only verified PNG/JPEG/WebP bytes and basename-only filenames reach image hosting.
|
||||||
- 2026-08-25: public web identity completion is deliberately ephemeral; it no longer writes the identity directory used by VK, and unused global web-profile endpoints were removed.
|
- 2026-08-25: public web identity completion is deliberately ephemeral; it no longer writes the identity directory used by VK, and unused global web-profile endpoints were removed.
|
||||||
|
- 2026-08-25: `Identity` is the shared invariant boundary for persistent profile/directory pairs: names are normalized and bounded to 100 characters, and character/actor IDs must be positive integers.
|
||||||
- 2026-08-25: public JSON cannot choose arbitrary attachment URLs. Web attachments are accepted only after the running process issued their image-host URL through `/api/web/upload`; the bounded in-memory registry expires entries after 30 minutes.
|
- 2026-08-25: public JSON cannot choose arbitrary attachment URLs. Web attachments are accepted only after the running process issued their image-host URL through `/api/web/upload`; the bounded in-memory registry expires entries after 30 minutes.
|
||||||
- 2026-08-25: VK attachment mirroring has a strict 15 MiB transfer cap, including a Content-Length precheck and bounded read.
|
- 2026-08-25: VK attachment mirroring has a strict 15 MiB transfer cap, including a Content-Length precheck and bounded read.
|
||||||
- 2026-08-25: after the byte cap, VK attachment mirroring accepts only PNG/JPEG/WebP signatures and does not trust the external response Content-Type.
|
- 2026-08-25: after the byte cap, VK attachment mirroring accepts only PNG/JPEG/WebP signatures and does not trust the external response Content-Type.
|
||||||
|
|||||||
@@ -85,10 +85,14 @@ def resolve_identity_payload(payload: dict[str, Any]) -> dict[str, Any]:
|
|||||||
raw_id = payload.get("character_id")
|
raw_id = payload.get("character_id")
|
||||||
if not name and raw_id in (None, ""):
|
if not name and raw_id in (None, ""):
|
||||||
raise ApiError("Укажите имя или ID персонажа")
|
raise ApiError("Укажите имя или ID персонажа")
|
||||||
|
if isinstance(raw_id, bool):
|
||||||
|
raise ApiError("ID персонажа должно быть числом")
|
||||||
try:
|
try:
|
||||||
character_id = int(raw_id) if raw_id not in (None, "") else None
|
character_id = int(raw_id) if raw_id not in (None, "") else None
|
||||||
except (TypeError, ValueError) as exc:
|
except (TypeError, ValueError) as exc:
|
||||||
raise ApiError("ID персонажа должно быть числом") from exc
|
raise ApiError("ID персонажа должно быть числом") from exc
|
||||||
|
if character_id is not None and character_id <= 0:
|
||||||
|
raise ApiError("ID персонажа должно быть положительным")
|
||||||
directory = _identity_directory()
|
directory = _identity_directory()
|
||||||
identity = directory.resolve(name=name, character_id=character_id)
|
identity = directory.resolve(name=name, character_id=character_id)
|
||||||
if identity:
|
if identity:
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ from dataclasses import dataclass
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
|
MAX_IDENTITY_NAME_LENGTH = 100
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
class Identity:
|
class Identity:
|
||||||
@@ -16,6 +18,14 @@ class Identity:
|
|||||||
name: str
|
name: str
|
||||||
character_id: int
|
character_id: int
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
name = self.name.strip() if isinstance(self.name, str) else ""
|
||||||
|
if not name or len(name) > MAX_IDENTITY_NAME_LENGTH:
|
||||||
|
raise ValueError(f"Имя персонажа должно содержать от 1 до {MAX_IDENTITY_NAME_LENGTH} символов")
|
||||||
|
if isinstance(self.character_id, bool) or not isinstance(self.character_id, int) or self.character_id <= 0:
|
||||||
|
raise ValueError("ID персонажа должен быть положительным целым числом")
|
||||||
|
object.__setattr__(self, "name", name)
|
||||||
|
|
||||||
|
|
||||||
class IdentityDirectory:
|
class IdentityDirectory:
|
||||||
"""
|
"""
|
||||||
@@ -151,6 +161,8 @@ class IdentityDirectory:
|
|||||||
|
|
||||||
Запоминает, что actor_id представляет персонажа character_id с именем name.
|
Запоминает, что actor_id представляет персонажа character_id с именем name.
|
||||||
"""
|
"""
|
||||||
|
if isinstance(actor_id, bool) or not isinstance(actor_id, int) or actor_id <= 0:
|
||||||
|
raise ValueError("ID автора должен быть положительным целым числом")
|
||||||
identity = self.remember(name=name, character_id=character_id)
|
identity = self.remember(name=name, character_id=character_id)
|
||||||
self._profiles[actor_id] = identity
|
self._profiles[actor_id] = identity
|
||||||
if self.database_url.startswith(("postgres://", "postgresql://")):
|
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||||||
|
|||||||
+4
-1
@@ -115,7 +115,10 @@ def _person(value: str) -> tuple[str, int]:
|
|||||||
match = _PERSON_RE.fullmatch(value)
|
match = _PERSON_RE.fullmatch(value)
|
||||||
if not match:
|
if not match:
|
||||||
raise ValueError("Укажите имя и ID в формате Имя [12345]")
|
raise ValueError("Укажите имя и ID в формате Имя [12345]")
|
||||||
return match.group("name").strip(), int(match.group("id"))
|
character_id = int(match.group("id"))
|
||||||
|
if character_id <= 0:
|
||||||
|
raise ValueError("ID персонажа должен быть положительным числом")
|
||||||
|
return match.group("name").strip(), character_id
|
||||||
|
|
||||||
|
|
||||||
def _natural_people(text: str) -> tuple[list[tuple[str, int]], list[tuple[str, int]], list[tuple[str, int]]]:
|
def _natural_people(text: str) -> tuple[list[tuple[str, int]], list[tuple[str, int]], list[tuple[str, int]]]:
|
||||||
|
|||||||
@@ -63,6 +63,7 @@
|
|||||||
- 2026-08-25: hardened the public goal calculator: point values must be finite, one session is limited to 1–1440 minutes, and one calculation to 1–50 kittens. The same validation is applied by the domain, JSON API, and VK dialogue, with regression tests for `NaN`, infinity, and excessive values.
|
- 2026-08-25: hardened the public goal calculator: point values must be finite, one session is limited to 1–1440 minutes, and one calculation to 1–50 kittens. The same validation is applied by the domain, JSON API, and VK dialogue, with regression tests for `NaN`, infinity, and excessive values.
|
||||||
- 2026-08-25: hardened public JSON and screenshot uploads. The web handler caps encoded JSON at 20 MiB before parsing, decodes at most 15 MiB of image bytes, accepts only PNG/JPEG/WebP signatures, rejects MIME mismatches, and strips path components from upload names. The public UI advertises the same supported formats.
|
- 2026-08-25: hardened public JSON and screenshot uploads. The web handler caps encoded JSON at 20 MiB before parsing, decodes at most 15 MiB of image bytes, accepts only PNG/JPEG/WebP signatures, rejects MIME mismatches, and strips path components from upload names. The public UI advertises the same supported formats.
|
||||||
- 2026-08-25: removed unused public web-profile endpoints and made `/api/resolve-identity` stateless for submitted pairs. A browser can fill its current inspection form, but cannot overwrite the persistent identity directory shared with VK users.
|
- 2026-08-25: removed unused public web-profile endpoints and made `/api/resolve-identity` stateless for submitted pairs. A browser can fill its current inspection form, but cannot overwrite the persistent identity directory shared with VK users.
|
||||||
|
- 2026-08-25: persistent identity and profile pairs now require a non-empty name up to 100 characters and a positive integer ID. VK input and public identity lookup reject zero, negative, and boolean IDs before lookup or persistence.
|
||||||
- 2026-08-25: web calculations and applications now accept attachment URLs only when the same web process received them from the image-host upload endpoint. This prevents public JSON from planting arbitrary browser-fetchable URLs in the admin interface; the in-memory authorization is capped at 1000 URLs and expires after 30 minutes, matching the active upload-and-submit flow.
|
- 2026-08-25: web calculations and applications now accept attachment URLs only when the same web process received them from the image-host upload endpoint. This prevents public JSON from planting arbitrary browser-fetchable URLs in the admin interface; the in-memory authorization is capped at 1000 URLs and expires after 30 minutes, matching the active upload-and-submit flow.
|
||||||
- 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: 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: VK photo mirroring also verifies PNG/JPEG/WebP byte signatures and derives the upload MIME type and extension from those bytes, never from an upstream HTTP header.
|
- 2026-08-25: VK photo mirroring also verifies PNG/JPEG/WebP byte signatures and derives the upload MIME type and extension from those bytes, never from an upstream HTTP header.
|
||||||
|
|||||||
@@ -93,6 +93,11 @@ class ApiTests(unittest.TestCase):
|
|||||||
self.assertEqual(response["status"], "provided")
|
self.assertEqual(response["status"], "provided")
|
||||||
self.assertIsNone(directory.resolve(character_id=1617140))
|
self.assertIsNone(directory.resolve(character_id=1617140))
|
||||||
|
|
||||||
|
def test_identity_lookup_rejects_boolean_and_non_positive_ids(self):
|
||||||
|
for character_id in (True, 0, -1):
|
||||||
|
with self.subTest(character_id=character_id), self.assertRaises(ApiError):
|
||||||
|
resolve_identity_payload({"character_id": character_id})
|
||||||
|
|
||||||
def test_calculation_store_persists_full_record(self):
|
def test_calculation_store_persists_full_record(self):
|
||||||
with TemporaryDirectory() as directory:
|
with TemporaryDirectory() as directory:
|
||||||
path = f"{directory}/history.sqlite3"
|
path = f"{directory}/history.sqlite3"
|
||||||
|
|||||||
@@ -104,6 +104,14 @@ class ApplicationTests(unittest.TestCase):
|
|||||||
self.assertIn("отправлена", dialog.handle(55, 55, "готово").lower())
|
self.assertIn("отправлена", dialog.handle(55, 55, "готово").lower())
|
||||||
self.assertEqual(store.list()[0]["application"]["type"], "kitten")
|
self.assertEqual(store.list()[0]["application"]["type"], "kitten")
|
||||||
|
|
||||||
|
def test_identity_directory_rejects_invalid_persistent_pairs(self) -> None:
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
identities = IdentityDirectory(db_path=Path(directory) / "identities.sqlite3")
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
identities.remember(name="", character_id=1)
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
identities.remember(name="Белка", character_id=0)
|
||||||
|
|
||||||
def test_vk_application_uses_keyboard_for_menu_and_branches(self) -> None:
|
def test_vk_application_uses_keyboard_for_menu_and_branches(self) -> None:
|
||||||
with tempfile.TemporaryDirectory() as directory:
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
store = ApplicationStore(sqlite_path=Path(directory) / "applications.sqlite3")
|
store = ApplicationStore(sqlite_path=Path(directory) / "applications.sqlite3")
|
||||||
|
|||||||
@@ -104,6 +104,15 @@ class VkConversationTests(unittest.TestCase):
|
|||||||
dialog.handle(1, "/лу")
|
dialog.handle(1, "/лу")
|
||||||
self.assertIn("отмен", dialog.handle(1, "/отмена").lower())
|
self.assertIn("отмен", dialog.handle(1, "/отмена").lower())
|
||||||
|
|
||||||
|
def test_person_input_rejects_a_non_positive_id(self):
|
||||||
|
dialog = BelkiDialog()
|
||||||
|
dialog.handle(1, "/лу")
|
||||||
|
dialog.handle(1, "15.08")
|
||||||
|
dialog.handle(1, "ЛУ")
|
||||||
|
dialog.handle(1, "11:00")
|
||||||
|
dialog.handle(1, "11:20")
|
||||||
|
self.assertIn("положительным", dialog.handle(1, "Белка [0]").lower())
|
||||||
|
|
||||||
def test_bulk_inspector_returns_fields_and_missing_questions(self):
|
def test_bulk_inspector_returns_fields_and_missing_questions(self):
|
||||||
inspected = inspect_bulk_text("/лу 15.08 11:00 11:20 | Белка [1] | Котёнок [2]")
|
inspected = inspect_bulk_text("/лу 15.08 11:00 11:20 | Белка [1] | Котёнок [2]")
|
||||||
self.assertEqual(inspected["status"], "needs_clarification")
|
self.assertEqual(inspected["status"], "needs_clarification")
|
||||||
|
|||||||
Reference in new issue
Block a user