Add gateway sessions page and end sessions on credential change

This commit is contained in:
Eduardo Silva
2026-11-21 16:43:06 -03:00
parent 7fd1a4fbc3
commit bf71df194d
24 changed files with 957 additions and 13 deletions
@@ -96,9 +96,16 @@ def load_runtime_config(config_dir: Path) -> RuntimeConfig:
users=auth.users,
groups=auth.groups,
policies=auth.policies,
revoked_sessions=_load_revoked_sessions(config_dir),
)
def _load_revoked_sessions(config_dir: Path) -> set[str]:
payload = _load_json(config_dir / "revoked_sessions.json") or {}
sessions = payload.get("sessions", []) if isinstance(payload, dict) else []
return {value for value in sessions if isinstance(value, str)}
class RuntimeConfigStore:
def __init__(self, config_dir: Path):
self.config_dir = config_dir
@@ -112,6 +119,7 @@ class RuntimeConfigStore:
"applications.json",
"routes.json",
"auth_policies.json",
"revoked_sessions.json",
):
path = self.config_dir / filename
if path.exists():
@@ -1,3 +1,4 @@
import asyncio
import logging
import time
from contextlib import asynccontextmanager
@@ -13,6 +14,7 @@ from auth_gateway.config_loader import RuntimeConfigStore
from auth_gateway.limiter import get_real_client_ip, limiter
from auth_gateway.services.oidc_service import OIDCService
from auth_gateway.services.session_service import SessionService
from auth_gateway.services.session_snapshot import SNAPSHOT_INTERVAL_SECONDS, SessionSnapshot
from auth_gateway.settings import settings
from auth_gateway.storage.sqlite import SQLiteStorage
from auth_gateway.web.auth_routes import router as auth_router
@@ -31,7 +33,20 @@ async def lifespan(app: FastAPI):
app.state.session_service = SessionService(storage, settings.session_default_minutes, settings.oidc_state_ttl_minutes)
app.state.oidc_service = OIDCService()
app.state.templates = Jinja2Templates(directory=str(BASE_DIR / "templates"))
app.state.session_snapshot = SessionSnapshot(storage, app.state.config_store, settings.config_dir / "state" / "sessions.json")
snapshot_task = asyncio.create_task(_refresh_session_snapshot(app.state.session_snapshot))
yield
snapshot_task.cancel()
async def _refresh_session_snapshot(session_snapshot: SessionSnapshot):
# Sessions also end without a request (expiration, revocation, changed credentials) and go offline over time
while True:
try:
await asyncio.to_thread(session_snapshot.refresh)
except Exception as error:
_access_logger.warning("Session snapshot failed: %s", error)
await asyncio.sleep(SNAPSHOT_INTERVAL_SECONDS)
app = FastAPI(
@@ -1,7 +1,8 @@
from pydantic import BaseModel, Field
from auth_gateway.models.applications import ApplicationModel
from auth_gateway.models.auth import AuthMethodModel, GroupModel, PolicyModel, UserModel
from auth_gateway.models.routes import AppRoutesModel
from pydantic import BaseModel, Field
class RuntimeConfig(BaseModel):
@@ -11,3 +12,5 @@ class RuntimeConfig(BaseModel):
users: dict[str, UserModel] = Field(default_factory=dict)
groups: dict[str, GroupModel] = Field(default_factory=dict)
policies: dict[str, PolicyModel] = Field(default_factory=dict)
# sha256 of the IDs of sessions ended from the WireGuard WebAdmin
revoked_sessions: set[str] = Field(default_factory=set)
@@ -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
@@ -92,6 +92,9 @@ class SQLiteStorage:
).fetchone()
if not row:
return None
return self._session_from_row(row)
def _session_from_row(self, row: sqlite3.Row) -> SessionRecord:
return SessionRecord(
session_id=row["session_id"],
created_at=self._from_iso(row["created_at"]),
@@ -105,6 +108,17 @@ class SQLiteStorage:
metadata=json.loads(row["metadata_json"]),
)
def list_sessions(self) -> list[SessionRecord]:
with self._lock, self._connect() as connection:
rows = connection.execute("SELECT * FROM sessions ORDER BY created_at").fetchall()
return [self._session_from_row(row) for row in rows]
def delete_expired(self, now: datetime) -> None:
with self._lock, self._connect() as connection:
connection.execute("DELETE FROM sessions WHERE expires_at <= ?", (self._to_iso(now),))
connection.execute("DELETE FROM oidc_states WHERE expires_at <= ?", (self._to_iso(now),))
connection.commit()
def delete_session(self, session_id: str) -> None:
with self._lock, self._connect() as connection:
connection.execute("DELETE FROM sessions WHERE session_id = ?", (session_id,))
@@ -62,6 +62,7 @@ async def auth_check(request: Request):
response = PlainTextResponse("OK", status_code=200)
response.headers["Cache-Control"] = "no-store"
if session:
request.app.state.session_service.touch(session)
if session.username:
response.headers["X-Auth-User"] = _safe_header(session.username)
if session.email:
@@ -1,3 +1,4 @@
from datetime import UTC, datetime
from secrets import token_urlsafe
from urllib.parse import urlencode
@@ -5,11 +6,13 @@ from fastapi import HTTPException, Request
from fastapi.responses import Response
from auth_gateway.config_loader import RuntimeConfigStore
from auth_gateway.limiter import get_real_client_ip
from auth_gateway.models.auth import OIDCMethodModel, TotpMethodModel
from auth_gateway.models.runtime import RuntimeConfig
from auth_gateway.models.session import SessionRecord
from auth_gateway.services.policy_engine import EffectivePolicy, build_effective_policy
from auth_gateway.services.resolver import RequestContext, normalize_host, normalize_path, resolve_request_context
from auth_gateway.services.session_service import credential_fingerprint, session_is_valid
def get_runtime_config(request: Request) -> RuntimeConfig:
@@ -20,7 +23,25 @@ def get_runtime_config(request: Request) -> RuntimeConfig:
def get_session(request: Request) -> SessionRecord | None:
session_service = request.app.state.session_service
cookie_name = request.app.state.settings.cookie_name
return session_service.get_session(request.cookies.get(cookie_name))
session = session_service.get_session(request.cookies.get(cookie_name))
if session and not session_is_valid(session, get_runtime_config(request)):
session_service.delete_session(session.session_id)
return None
return session
def login_metadata(request: Request, username: str | None = None) -> dict:
"""Where the session was opened and, for local users, the fingerprint of their credentials."""
metadata = {
"host": normalize_host(request.headers.get("host", "")),
"client_ip": get_real_client_ip(request),
"user_agent": request.headers.get("user-agent", "")[:200],
"last_seen": datetime.now(UTC).isoformat(),
}
user = get_runtime_config(request).users.get(username) if username else None
if user:
metadata["credential"] = credential_fingerprint(user)
return metadata
def build_external_url(request: Request, path: str, **params: str) -> str:
@@ -22,6 +22,7 @@ from auth_gateway.web.dependencies import (
get_session,
get_session_factors,
get_totp_method,
login_metadata,
resolve_context_from_request,
set_csrf_cookie,
session_is_allowed,
@@ -54,6 +55,7 @@ def _render(request: Request, template_name: str, status_code: int = 200, **cont
def _redirect_with_cookie(request: Request, destination: str, session) -> RedirectResponse:
request.app.state.session_snapshot.refresh()
response = RedirectResponse(destination, status_code=303)
response.set_cookie(
key=request.app.state.settings.cookie_name,
@@ -75,7 +77,7 @@ def _create_authenticated_session(request: Request, *, username=None, email=None
email=email,
subject=subject,
groups=groups,
metadata=metadata,
metadata={**login_metadata(request, username), **(metadata or {})},
add_factors=factors,
expires_in_minutes=expires_in_minutes,
)
@@ -315,7 +317,8 @@ async def login_totp_submit(request: Request, next: str = Form("/"), token: str
refreshed_session = session_service.issue_session(
existing_session=session,
add_factors=["totp"],
metadata=factor_method_metadata(session, "totp", method_name),
# Without a password or OIDC step (TOTP only), the session starts here
metadata={**({} if session else login_metadata(request)), **factor_method_metadata(session, "totp", method_name)},
expires_in_minutes=get_effective_expiration(request, effective_policy, ["totp"]),
)
logger.info("AUTH login ok for '%s' via password+totp (policy: %s)", refreshed_session.username, context.policy_name)
@@ -393,6 +396,7 @@ def _do_logout(request: Request, next_url: str = "/") -> RedirectResponse:
session_cookie = request.cookies.get(request.app.state.settings.cookie_name)
session = request.app.state.session_service.get_session(session_cookie)
request.app.state.session_service.delete_session(session_cookie)
request.app.state.session_snapshot.refresh()
if session:
logger.info("AUTH logout for '%s'", session.username or session.email or "unknown")
response = RedirectResponse(_safe_redirect_path(next_url), status_code=303)