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

+38 -5
View File
@@ -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", ""))