diff --git a/MEMORY.md b/MEMORY.md index 1da5999..8d48998 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -41,6 +41,7 @@ - 2026-08-25: natural bulk parsing prioritizes explicit Russian mentor/student labels, then falls back to the original pair order when labels are absent. - 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: 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: 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: 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. diff --git a/app/main.py b/app/main.py index 727b5b5..503eeaa 100644 --- a/app/main.py +++ b/app/main.py @@ -25,7 +25,8 @@ WEB_ROOT = ROOT / "web" _HISTORY_STORE: CalculationStore | None = None _IDENTITY_DIR: IdentityDirectory | None = None _APPLICATION_STORE: ApplicationStore | None = None -_ADMIN_SESSIONS: set[str] = set() +_ADMIN_SESSIONS: dict[str, float] = {} +_ADMIN_SESSIONS_LOCK = threading.Lock() _ISSUED_WEB_UPLOAD_URLS: dict[str, float] = {} _ISSUED_WEB_UPLOADS_LOCK = threading.Lock() _ADMIN_AUTH_ATTEMPTS: dict[str, list[float]] = {} @@ -40,6 +41,8 @@ MAX_ADMIN_AUTH_ATTEMPTS = 5 _ADMIN_UPDATE_SLOTS = threading.BoundedSemaphore(MAX_CONCURRENT_ADMIN_UPDATES) WEB_UPLOAD_URL_TTL_SECONDS = 30 * 60 MAX_ISSUED_WEB_UPLOAD_URLS = 1_000 +ADMIN_SESSION_TTL_SECONDS = 12 * 60 * 60 +MAX_ADMIN_SESSIONS = 100 def detect_raster_image_type(body: bytes) -> str | None: @@ -112,6 +115,36 @@ def clear_admin_auth_attempts(client_ip: str) -> None: _ADMIN_AUTH_ATTEMPTS.pop(client_ip, None) +def remember_admin_session(token: str, *, now: float | None = None) -> None: + """Keep a bounded, expiring set of opaque admin session tokens.""" + timestamp = time.monotonic() if now is None else now + with _ADMIN_SESSIONS_LOCK: + expired = [item for item, expiry in _ADMIN_SESSIONS.items() if expiry <= timestamp] + for item in expired: + del _ADMIN_SESSIONS[item] + if token not in _ADMIN_SESSIONS and len(_ADMIN_SESSIONS) >= MAX_ADMIN_SESSIONS: + oldest = min(_ADMIN_SESSIONS, key=_ADMIN_SESSIONS.__getitem__) + del _ADMIN_SESSIONS[oldest] + _ADMIN_SESSIONS[token] = timestamp + ADMIN_SESSION_TTL_SECONDS + + +def admin_session_authorized(token: str, *, now: float | None = None) -> bool: + timestamp = time.monotonic() if now is None else now + with _ADMIN_SESSIONS_LOCK: + expiry = _ADMIN_SESSIONS.get(token) + if expiry is None: + return False + if expiry <= timestamp: + del _ADMIN_SESSIONS[token] + return False + return True + + +def forget_admin_session(token: str) -> None: + with _ADMIN_SESSIONS_LOCK: + _ADMIN_SESSIONS.pop(token, None) + + def acquire_admin_update_slot() -> bool: """Reserve a bounded worker slot for a long-lived admin WebSocket.""" return _ADMIN_UPDATE_SLOTS.acquire(blocking=False) @@ -189,7 +222,7 @@ class Handler(BaseHTTPRequestHandler): return next((part.strip().split("=", 1)[1] for part in cookies.split(";") if part.strip().startswith(f"{name}=")), "") def _admin_session_authorized(self) -> bool: - return self._session_token("belki_admin_session") in _ADMIN_SESSIONS + return admin_session_authorized(self._session_token("belki_admin_session")) def _admin_authorized(self) -> bool: expected = os.getenv("BELKI_ADMIN_PASSWORD", "") @@ -212,7 +245,7 @@ class Handler(BaseHTTPRequestHandler): def _admin_cookie(self, token: str) -> str: secure = "; Secure" if self.headers.get("X-Forwarded-Proto", "") == "https" else "" - return f"belki_admin_session={token}; Path=/; HttpOnly; SameSite=Lax{secure}" + return f"belki_admin_session={token}; Path=/; Max-Age={ADMIN_SESSION_TTL_SECONDS}; HttpOnly; SameSite=Lax{secure}" def _serve_admin_updates(self) -> None: if not self._admin_session_authorized(): @@ -335,10 +368,10 @@ class Handler(BaseHTTPRequestHandler): return clear_admin_auth_attempts(client_ip) token = secrets.token_urlsafe(32) - _ADMIN_SESSIONS.add(token) + remember_admin_session(token) self._json_with_cookie(200, {"authenticated": True}, self._admin_cookie(token)) elif self.path == "/api/admin/logout": - _ADMIN_SESSIONS.discard(self._session_token("belki_admin_session")) + forget_admin_session(self._session_token("belki_admin_session")) self._json_with_cookie(200, {"authenticated": False}, "belki_admin_session=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax") elif self.path == "/api/web/upload": raw = str(payload.get("data", "")) diff --git a/project_mind_map.md b/project_mind_map.md index 56cba87..7e01a5c 100644 --- a/project_mind_map.md +++ b/project_mind_map.md @@ -85,6 +85,7 @@ mindmap bounded application payload Admin HttpOnly SameSite session + session TTL 12 h / 100 active password comparison Persistence parameterized SQL diff --git a/structure_and_data.md b/structure_and_data.md index ba06aa0..fe67e66 100644 --- a/structure_and_data.md +++ b/structure_and_data.md @@ -80,6 +80,7 @@ - 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: `/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-25: server-memory admin sessions now expire after 12 hours and are capped at 100 active tokens; the browser cookie carries the same maximum age. # Обновление 2026-08-16: несколько котят Калькулятор прокачки принимает `extra_kittens` из веб-формы, API и VK-команды. Общая выплата сопровождающему не суммирует полную ставку на каждого котёнка: первый подопечный использует базовый коэффициент, второй — множитель 1,5, каждый следующий — дополнительный множитель 1,15. Сайт добавляет строки дополнительных котят динамически; VK поддерживает сегмент `доп. котята: Имя [ID], Имя2 [ID]`. diff --git a/tests/test_image_host.py b/tests/test_image_host.py index 88a8544..e11d3c9 100644 --- a/tests/test_image_host.py +++ b/tests/test_image_host.py @@ -2,11 +2,11 @@ import unittest from unittest.mock import MagicMock, patch from app.belki.image_host import MAX_MIRRORED_IMAGE_BYTES, ImageHostClient, ImageHostError -from app.main import (MAX_ADMIN_AUTH_ATTEMPTS, MAX_CONCURRENT_ADMIN_UPDATES, MAX_CONCURRENT_REQUESTS, MAX_ISSUED_WEB_UPLOAD_URLS, MAX_JSON_BODY_BYTES, +from app.main import (ADMIN_SESSION_TTL_SECONDS, MAX_ADMIN_AUTH_ATTEMPTS, MAX_ADMIN_SESSIONS, MAX_CONCURRENT_ADMIN_UPDATES, MAX_CONCURRENT_REQUESTS, MAX_ISSUED_WEB_UPLOAD_URLS, MAX_JSON_BODY_BYTES, REQUEST_READ_TIMEOUT_SECONDS, ADMIN_AUTH_WINDOW_SECONDS, BelkiHTTPServer, Handler, - _ADMIN_AUTH_ATTEMPTS, _ISSUED_WEB_UPLOAD_URLS, allow_admin_auth_attempt, + _ADMIN_AUTH_ATTEMPTS, _ADMIN_SESSIONS, _ISSUED_WEB_UPLOAD_URLS, admin_session_authorized, allow_admin_auth_attempt, acquire_admin_update_slot, clear_admin_auth_attempts, detect_raster_image_type, - remember_issued_web_upload, release_admin_update_slot, safe_upload_name, + forget_admin_session, remember_admin_session, remember_issued_web_upload, release_admin_update_slot, safe_upload_name, validate_web_attachments, WEB_UPLOAD_URL_TTL_SECONDS) from app.belki.api import ApiError @@ -63,6 +63,18 @@ class ImageHostClientTests(unittest.TestCase): clear_admin_auth_attempts("192.0.2.1") self.assertNotIn("192.0.2.1", _ADMIN_AUTH_ATTEMPTS) + def test_admin_sessions_expire_and_have_a_fixed_capacity(self) -> None: + _ADMIN_SESSIONS.clear() + remember_admin_session("active", now=100) + self.assertTrue(admin_session_authorized("active", now=100)) + self.assertFalse(admin_session_authorized("active", now=100 + ADMIN_SESSION_TTL_SECONDS)) + for index in range(MAX_ADMIN_SESSIONS + 1): + remember_admin_session(f"token-{index}", now=index) + self.assertEqual(len(_ADMIN_SESSIONS), MAX_ADMIN_SESSIONS) + self.assertNotIn("token-0", _ADMIN_SESSIONS) + forget_admin_session("token-1") + self.assertNotIn("token-1", _ADMIN_SESSIONS) + def test_admin_update_connections_have_a_separate_bounded_pool(self) -> None: acquired = [acquire_admin_update_slot() for _ in range(MAX_CONCURRENT_ADMIN_UPDATES)] try: