fix(admin): expire in-memory sessions

This commit is contained in:
nyan404 committed 2026-08-25 04:04:35 +03:00
1 parent 3f8674972b
commit 355544de9c
5 files changed
+56 -8

No files matched your search

+1
View File
@@ -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: 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: `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: 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: 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: 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.
+38 -5
View File
@@ -25,7 +25,8 @@ WEB_ROOT = ROOT / "web"
_HISTORY_STORE: CalculationStore | None = None _HISTORY_STORE: CalculationStore | None = None
_IDENTITY_DIR: IdentityDirectory | None = None _IDENTITY_DIR: IdentityDirectory | None = None
_APPLICATION_STORE: ApplicationStore | 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_UPLOAD_URLS: dict[str, float] = {}
_ISSUED_WEB_UPLOADS_LOCK = threading.Lock() _ISSUED_WEB_UPLOADS_LOCK = threading.Lock()
_ADMIN_AUTH_ATTEMPTS: dict[str, list[float]] = {} _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) _ADMIN_UPDATE_SLOTS = threading.BoundedSemaphore(MAX_CONCURRENT_ADMIN_UPDATES)
WEB_UPLOAD_URL_TTL_SECONDS = 30 * 60 WEB_UPLOAD_URL_TTL_SECONDS = 30 * 60
MAX_ISSUED_WEB_UPLOAD_URLS = 1_000 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: 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) _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: def acquire_admin_update_slot() -> bool:
"""Reserve a bounded worker slot for a long-lived admin WebSocket.""" """Reserve a bounded worker slot for a long-lived admin WebSocket."""
return _ADMIN_UPDATE_SLOTS.acquire(blocking=False) 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}=")), "") return next((part.strip().split("=", 1)[1] for part in cookies.split(";") if part.strip().startswith(f"{name}=")), "")
def _admin_session_authorized(self) -> bool: 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: def _admin_authorized(self) -> bool:
expected = os.getenv("BELKI_ADMIN_PASSWORD", "") expected = os.getenv("BELKI_ADMIN_PASSWORD", "")
@@ -212,7 +245,7 @@ class Handler(BaseHTTPRequestHandler):
def _admin_cookie(self, token: str) -> str: def _admin_cookie(self, token: str) -> str:
secure = "; Secure" if self.headers.get("X-Forwarded-Proto", "") == "https" else "" 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: def _serve_admin_updates(self) -> None:
if not self._admin_session_authorized(): if not self._admin_session_authorized():
@@ -335,10 +368,10 @@ class Handler(BaseHTTPRequestHandler):
return return
clear_admin_auth_attempts(client_ip) clear_admin_auth_attempts(client_ip)
token = secrets.token_urlsafe(32) token = secrets.token_urlsafe(32)
_ADMIN_SESSIONS.add(token) remember_admin_session(token)
self._json_with_cookie(200, {"authenticated": True}, self._admin_cookie(token)) self._json_with_cookie(200, {"authenticated": True}, self._admin_cookie(token))
elif self.path == "/api/admin/logout": 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") self._json_with_cookie(200, {"authenticated": False}, "belki_admin_session=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax")
elif self.path == "/api/web/upload": elif self.path == "/api/web/upload":
raw = str(payload.get("data", "")) raw = str(payload.get("data", ""))
+1
View File
@@ -85,6 +85,7 @@ mindmap
bounded application payload bounded application payload
Admin Admin
HttpOnly SameSite session HttpOnly SameSite session
session TTL 12 h / 100 active
password comparison password comparison
Persistence Persistence
parameterized SQL parameterized SQL
+1
View File
@@ -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 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.
- 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: `/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: несколько котят # Обновление 2026-08-16: несколько котят
Калькулятор прокачки принимает `extra_kittens` из веб-формы, API и VK-команды. Общая выплата сопровождающему не суммирует полную ставку на каждого котёнка: первый подопечный использует базовый коэффициент, второй — множитель 1,5, каждый следующий — дополнительный множитель 1,15. Сайт добавляет строки дополнительных котят динамически; VK поддерживает сегмент `доп. котята: Имя [ID], Имя2 [ID]`. Калькулятор прокачки принимает `extra_kittens` из веб-формы, API и VK-команды. Общая выплата сопровождающему не суммирует полную ставку на каждого котёнка: первый подопечный использует базовый коэффициент, второй — множитель 1,5, каждый следующий — дополнительный множитель 1,15. Сайт добавляет строки дополнительных котят динамически; VK поддерживает сегмент `доп. котята: Имя [ID], Имя2 [ID]`.
+15 -3
View File
@@ -2,11 +2,11 @@ import unittest
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, patch
from app.belki.image_host import MAX_MIRRORED_IMAGE_BYTES, ImageHostClient, ImageHostError 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, 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, 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) validate_web_attachments, WEB_UPLOAD_URL_TTL_SECONDS)
from app.belki.api import ApiError from app.belki.api import ApiError
@@ -63,6 +63,18 @@ class ImageHostClientTests(unittest.TestCase):
clear_admin_auth_attempts("192.0.2.1") clear_admin_auth_attempts("192.0.2.1")
self.assertNotIn("192.0.2.1", _ADMIN_AUTH_ATTEMPTS) 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: def test_admin_update_connections_have_a_separate_bounded_pool(self) -> None:
acquired = [acquire_admin_update_slot() for _ in range(MAX_CONCURRENT_ADMIN_UPDATES)] acquired = [acquire_admin_update_slot() for _ in range(MAX_CONCURRENT_ADMIN_UPDATES)]
try: try: