mirror of
https://github.com/eduardogsilva/wireguard_webadmin.git
synced 2026-11-22 04:43:18 +01:00
Add gateway sessions page and end sessions on credential change
This commit is contained in:
@@ -1,9 +1,37 @@
|
||||
import hashlib
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from secrets import token_urlsafe
|
||||
|
||||
from auth_gateway.models.auth import UserModel
|
||||
from auth_gateway.models.runtime import RuntimeConfig
|
||||
from auth_gateway.models.session import OIDCStateRecord, SessionRecord
|
||||
from auth_gateway.storage.sqlite import SQLiteStorage
|
||||
|
||||
# The last access is written at most this often, so requests do not write to the database
|
||||
LAST_SEEN_WRITE_INTERVAL = timedelta(minutes=5)
|
||||
|
||||
|
||||
def session_id_hash(session_id: str) -> str:
|
||||
"""Identifies a session outside the gateway (snapshot, revocation) without exposing the session ID."""
|
||||
return hashlib.sha256(session_id.encode()).hexdigest()
|
||||
|
||||
|
||||
def credential_fingerprint(user: UserModel) -> str:
|
||||
"""Changes when the password or the TOTP secret of the user changes."""
|
||||
value = f"{user.password_hash or ''}\0{user.totp_secret or ''}"
|
||||
return hashlib.sha256(value.encode()).hexdigest()[:32]
|
||||
|
||||
|
||||
def session_is_valid(session: SessionRecord, runtime_config: RuntimeConfig) -> bool:
|
||||
"""A session ends when it is revoked or when the credentials of its user change or the user is removed."""
|
||||
if session_id_hash(session.session_id) in runtime_config.revoked_sessions:
|
||||
return False
|
||||
if session.username:
|
||||
user = runtime_config.users.get(session.username)
|
||||
if not user or session.metadata.get("credential") != credential_fingerprint(user):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
class SessionService:
|
||||
def __init__(self, storage: SQLiteStorage, default_session_minutes: int, oidc_state_ttl_minutes: int):
|
||||
@@ -66,6 +94,15 @@ class SessionService:
|
||||
self.storage.save_session(session)
|
||||
return session
|
||||
|
||||
def touch(self, session: SessionRecord) -> None:
|
||||
"""Record the last access, at most once per LAST_SEEN_WRITE_INTERVAL."""
|
||||
now = datetime.now(UTC)
|
||||
last_seen = session.metadata.get("last_seen")
|
||||
if last_seen and now - datetime.fromisoformat(last_seen) < LAST_SEEN_WRITE_INTERVAL:
|
||||
return
|
||||
session.metadata["last_seen"] = now.isoformat()
|
||||
self.storage.save_session(session)
|
||||
|
||||
def delete_session(self, session_id: str | None) -> None:
|
||||
if session_id:
|
||||
self.storage.delete_session(session_id)
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from auth_gateway.config_loader import RuntimeConfigStore
|
||||
from auth_gateway.models.session import SessionRecord
|
||||
from auth_gateway.services.session_service import session_id_hash, session_is_valid
|
||||
from auth_gateway.storage.sqlite import SQLiteStorage
|
||||
|
||||
logger = logging.getLogger("uvicorn.error")
|
||||
|
||||
SNAPSHOT_INTERVAL_SECONDS = 30
|
||||
# A session used in the last minutes is online. The last access is written at most every 5 minutes, so the window
|
||||
# must be longer than that.
|
||||
ONLINE_WINDOW = timedelta(minutes=10)
|
||||
|
||||
|
||||
class SessionSnapshot:
|
||||
"""
|
||||
Active sessions published for the WireGuard WebAdmin (read by Django on the primary server and reported by the
|
||||
cluster agent on workers). The file is only rewritten when its content changes: an active session is published
|
||||
as online without a timestamp, so using it does not change the snapshot.
|
||||
"""
|
||||
|
||||
def __init__(self, storage: SQLiteStorage, config_store: RuntimeConfigStore, path: Path):
|
||||
self.storage = storage
|
||||
self.config_store = config_store
|
||||
self.path = path
|
||||
self._lock = threading.Lock()
|
||||
self._written = None
|
||||
|
||||
@staticmethod
|
||||
def _entry(session: SessionRecord, now: datetime) -> dict:
|
||||
last_seen = session.metadata.get("last_seen") or session.created_at.isoformat()
|
||||
online = now - datetime.fromisoformat(last_seen) < ONLINE_WINDOW
|
||||
entry = {
|
||||
"id": session_id_hash(session.session_id),
|
||||
"username": session.username or "",
|
||||
"email": session.email or "",
|
||||
"groups": session.groups,
|
||||
"factors": session.auth_factors,
|
||||
"host": session.metadata.get("host", ""),
|
||||
"client_ip": session.metadata.get("client_ip", ""),
|
||||
"user_agent": session.metadata.get("user_agent", ""),
|
||||
"created_at": session.created_at.isoformat(),
|
||||
"expires_at": session.expires_at.isoformat(),
|
||||
"online": online,
|
||||
}
|
||||
if not online:
|
||||
entry["last_seen"] = last_seen
|
||||
return entry
|
||||
|
||||
def refresh(self) -> None:
|
||||
with self._lock:
|
||||
now = datetime.now(UTC)
|
||||
self.storage.delete_expired(now)
|
||||
try:
|
||||
runtime_config = self.config_store.get()
|
||||
except Exception as error:
|
||||
logger.warning("Session snapshot skipped: configuration not loaded (%s)", error)
|
||||
return
|
||||
|
||||
entries = []
|
||||
for session in self.storage.list_sessions():
|
||||
if not session_is_valid(session, runtime_config):
|
||||
self.storage.delete_session(session.session_id)
|
||||
continue
|
||||
entries.append(self._entry(session, now))
|
||||
|
||||
content = json.dumps({"sessions": entries}, indent=2, sort_keys=True) + "\n"
|
||||
if content == self._written:
|
||||
return
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temp_path = self.path.with_name(f"{self.path.name}.tmp")
|
||||
temp_path.write_text(content, encoding="utf-8")
|
||||
os.replace(temp_path, self.path)
|
||||
self._written = content
|
||||
Reference in New Issue
Block a user