auth: purge expired sessions in worker tick

This commit is contained in:
Ivo Oskamp 2026-05-28 16:13:32 +02:00
parent 3e12196832
commit 98734b1c31

View File

@ -14,10 +14,13 @@ from .config import (
SCAN_TARGET_MAX_RETRIES, SCAN_TARGET_MAX_RETRIES,
SCAN_TARGET_TIMEOUT_SEC, SCAN_TARGET_TIMEOUT_SEC,
) )
from .auth.sessions import purge_expired
from .db import SessionLocal from .db import SessionLocal
from .models import PermissionDeviation, ScanJob, ScanTarget, TenantProfile from .models import PermissionDeviation, ScanJob, ScanTarget, TenantProfile
from .scanners import AuthConfig, ProbeResult, probe, scan from .scanners import AuthConfig, ProbeResult, probe, scan
_SESSION_PURGE_INTERVAL_SEC = 300
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@ -25,6 +28,7 @@ class ScanWorker:
def __init__(self) -> None: def __init__(self) -> None:
self._stop_event = threading.Event() self._stop_event = threading.Event()
self._thread: threading.Thread | None = None self._thread: threading.Thread | None = None
self._last_session_purge: float = 0.0
def start(self) -> None: def start(self) -> None:
if self._thread and self._thread.is_alive(): if self._thread and self._thread.is_alive():
@ -41,10 +45,25 @@ class ScanWorker:
def _run(self) -> None: def _run(self) -> None:
while not self._stop_event.is_set(): while not self._stop_event.is_set():
self._maybe_purge_sessions()
did_work = self._process_next_job() did_work = self._process_next_job()
if not did_work: if not did_work:
self._stop_event.wait(SCAN_JOB_POLL_INTERVAL_SEC) self._stop_event.wait(SCAN_JOB_POLL_INTERVAL_SEC)
def _maybe_purge_sessions(self) -> None:
now = time.monotonic()
if now - self._last_session_purge < _SESSION_PURGE_INTERVAL_SEC:
return
self._last_session_purge = now
try:
with SessionLocal() as db:
removed = purge_expired(db)
db.commit()
if removed:
log.info("purged %d expired auth sessions", removed)
except Exception:
log.exception("auth session purge failed")
def _process_next_job(self) -> bool: def _process_next_job(self) -> bool:
with SessionLocal() as db: with SessionLocal() as db:
# Atomic claim: lock the chosen queued row and skip rows already # Atomic claim: lock the chosen queued row and skip rows already