From eed85042d221dea30f8e1624a24058996f84b74e Mon Sep 17 00:00:00 2001 From: CaliBrain Date: Wed, 25 Nov 2026 01:47:56 -0500 Subject: [PATCH] general fixes (#1752) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Fix #1751 - Fix #GHSA NB: Everyone is signed out once after upgrading. Existing builtin, OIDC and CWA cookies don't carry a nonce, and pre-fix cookies can't be trusted anyway. Proxy auth isn't affected. ## Summary by CodeRabbit * **New Features** * Sessions are revalidated against current account status and permissions. Changes to a user’s role, password, or account status can invalidate their existing sessions, including active WebSocket connections. * Series details are combined more consistently when viewing book and release information, preserving the listed book’s series data when available. * **Security** * User responses no longer include session security tokens. --- shelfmark/api/websocket.py | 34 +- shelfmark/core/admin_routes.py | 29 +- shelfmark/core/auth_middleware.py | 30 +- shelfmark/core/auth_routes.py | 10 +- shelfmark/core/oidc_routes.py | 2 + shelfmark/core/self_user_routes.py | 5 + shelfmark/core/session_auth.py | 92 ++++ shelfmark/core/socket_handlers.py | 17 +- shelfmark/core/user_db.py | 42 +- shelfmark/main.py | 13 +- src/frontend/src/App.tsx | 11 +- .../src/tests/bookTransformers.test.ts | 35 ++ src/frontend/src/utils/bookTransformers.ts | 32 ++ tests/core/sessions.py | 100 +++++ tests/core/test_activity_routes_api.py | 34 +- tests/core/test_api_key_env.py | 1 + tests/core/test_auth_api.py | 1 + tests/core/test_auth_routes.py | 13 +- tests/core/test_debug_routes_admin.py | 5 +- tests/core/test_download_api_guardrails.py | 25 +- tests/core/test_error_text_in_responses.py | 7 +- tests/core/test_notifications_settings_api.py | 7 +- tests/core/test_onboarding_routes.py | 7 +- tests/core/test_provider_account_access.py | 5 +- tests/core/test_queue_routes.py | 25 +- tests/core/test_release_routes.py | 1 + tests/core/test_release_routes_policy.py | 1 + tests/core/test_request_routes_api.py | 32 +- tests/core/test_session_revocation.py | 400 ++++++++++++++++++ tests/core/test_settings_routes.py | 7 +- tests/core/test_socket_handlers.py | 16 +- 31 files changed, 919 insertions(+), 120 deletions(-) create mode 100644 shelfmark/core/session_auth.py create mode 100644 tests/core/sessions.py create mode 100644 tests/core/test_session_revocation.py diff --git a/shelfmark/api/websocket.py b/shelfmark/api/websocket.py index e469690c..39f45ef7 100644 --- a/shelfmark/api/websocket.py +++ b/shelfmark/api/websocket.py @@ -5,7 +5,7 @@ from __future__ import annotations import threading from typing import TYPE_CHECKING, Any -from flask_socketio import SocketIO, join_room, leave_room +from flask_socketio import SocketIO, disconnect, join_room, leave_room from shelfmark.core.logger import setup_logger from shelfmark.core.viewer_redaction import viewer_download_id @@ -29,6 +29,7 @@ class WebSocketManager: self._connection_lock = threading.Lock() self._user_rooms: dict[str, int] = {} # room_name -> ref count self._sid_rooms: dict[str, str] = {} # sid -> room_name + self._sid_users: dict[str, int] = {} # sid -> users.db id of its signed-in session self._rooms_lock = threading.Lock() self._queue_status_fn: Callable | None = None # Reference to queue_status() @@ -130,6 +131,37 @@ class WebSocketManager: del is_admin, db_user_id # Backward-compatible signature; routing is SID-based. with self._rooms_lock: self._set_sid_room_locked(sid, None) + self._sid_users.pop(sid, None) + + def set_sid_user(self, sid: str, user_id: int | None) -> None: + """Record which signed-in user a SID belongs to, for ``disconnect_user``. + + Kept apart from the room: an admin's SID sits in the shared admins room. + """ + with self._rooms_lock: + if user_id is None: + self._sid_users.pop(sid, None) + else: + self._sid_users[sid] = user_id + + def disconnect_user(self, user_id: int) -> None: + """Close every Socket.IO connection of a user. + + For when the user's role changes, their sessions are revoked or they are deleted: + the rooms were chosen from the session at connect time, and the client's reconnect + is checked against the user's current state. Needs a Flask app context. + """ + if self._get_socketio() is None: + return + with self._rooms_lock: + sids = [sid for sid, owner in self._sid_users.items() if owner == user_id] + for sid in sids: + try: + disconnect(sid=sid, namespace="/") + except KeyError, RuntimeError, ValueError: + logger.warning("Could not disconnect Socket.IO client %s of user %s", sid, user_id) + if sids: + logger.info("Disconnected %d Socket.IO client(s) of user %s", len(sids), user_id) def broadcast_status_update(self, status_data: dict[str, Any]) -> None: """Broadcast status update to all connected clients, filtered by user room.""" diff --git a/shelfmark/core/admin_routes.py b/shelfmark/core/admin_routes.py index 199f81d3..77090ecc 100644 --- a/shelfmark/core/admin_routes.py +++ b/shelfmark/core/admin_routes.py @@ -35,12 +35,15 @@ from shelfmark.core.auth_modes import ( from shelfmark.core.config import config as app_config from shelfmark.core.cwa_user_sync import sync_cwa_users_from_rows from shelfmark.core.logger import setup_logger +from shelfmark.core.request_helpers import get_session_db_user_id +from shelfmark.core.session_auth import SESSION_NONCE_KEY, stamp_session_nonce if TYPE_CHECKING: from collections.abc import Callable from flask.typing import ResponseReturnValue + from shelfmark.api.websocket import WebSocketManager from shelfmark.core.user_db import UserDB P = ParamSpec("P") @@ -90,6 +93,7 @@ def _sanitize_user(user: dict) -> dict: """Remove sensitive fields from user dict before returning to client.""" sanitized = dict(user) sanitized.pop("password_hash", None) + sanitized.pop(SESSION_NONCE_KEY, None) return sanitized @@ -167,9 +171,23 @@ def _sync_all_cwa_users(user_db: UserDB) -> dict[str, int]: return sync_cwa_users_from_rows(user_db, rows) -def register_admin_routes(app: Flask, user_db: UserDB) -> None: +def register_admin_routes( + app: Flask, + user_db: UserDB, + *, + ws_manager: WebSocketManager | None = None, +) -> None: """Register admin user management routes on the Flask app.""" + def _disconnect_live_sockets(user_id: int) -> None: + """Drop the user's open Socket.IO connections so they reconnect under the new rules. + + A socket joined its room with the session it connected with; reconnecting checks + that session again (see socket_handlers). + """ + if ws_manager is not None: + ws_manager.disconnect_user(user_id) + def _require_admin( f: Callable[P, ResponseReturnValue], ) -> Callable[P, ResponseReturnValue]: @@ -411,6 +429,12 @@ def register_admin_routes(app: Flask, user_db: UserDB) -> None: if user_fields: user_db.update_user(user_id, **user_fields) + # A new password revokes the user's sessions (update_user rotates the nonce). An admin + # setting their own password keeps the session they did it from. + is_self = get_session_db_user_id(session) == user_id + if role_changed or (password_hash is not None and not is_self): + _disconnect_live_sockets(user_id) + if validated_settings is not None: user_db.set_user_settings(user_id, validated_settings) # Ensure runtime reads see updated per-user overrides immediately. @@ -426,6 +450,8 @@ def register_admin_routes(app: Flask, user_db: UserDB) -> None: updated = user_db.get_user(user_id=user_id) if not isinstance(updated, dict): return jsonify({"error": "User not found"}), 404 + if password_hash is not None and is_self: + stamp_session_nonce(session, updated) result = _serialize_user( updated, g.auth_mode, @@ -513,5 +539,6 @@ def register_admin_routes(app: Flask, user_db: UserDB) -> None: ), 400 user_db.delete_user(user_id) + _disconnect_live_sockets(user_id) logger.info("Admin deleted user %s: %s", user_id, user["username"]) return jsonify({"success": True}) diff --git a/shelfmark/core/auth_middleware.py b/shelfmark/core/auth_middleware.py index 14650200..0289f032 100644 --- a/shelfmark/core/auth_middleware.py +++ b/shelfmark/core/auth_middleware.py @@ -1,5 +1,6 @@ -"""Request hooks for the two ways a request can be authenticated without logging in: the -SHELFMARK_API_KEY credentials and the reverse proxy's identity headers. +"""Request hooks for the two ways a request can be authenticated without logging in (the +SHELFMARK_API_KEY credentials and the reverse proxy's identity headers), and the hook that +checks a signed-in session against users.db on every request. """ from __future__ import annotations @@ -14,6 +15,7 @@ from shelfmark.core.config import config as app_config from shelfmark.core.external_user_linking import upsert_external_user from shelfmark.core.logger import setup_logger from shelfmark.core.request_helpers import normalize_optional_text +from shelfmark.core.session_auth import revalidate_session from shelfmark.core.stats_routes import STATS_PATH if TYPE_CHECKING: @@ -56,12 +58,13 @@ def register_auth_middleware( resolve_auth_mode: Callable[[], str], get_user_db: Callable[[], UserDB | None], ) -> None: - """Register the API-key and proxy-auth ``before_request`` hooks and the cookie-stripping - ``after_request`` hook. + """Register the API-key, proxy-auth and session-revalidation ``before_request`` hooks and + the cookie-stripping ``after_request`` hook. Call this at the place the hooks should take in the hook order: ``before_request`` hooks run in registration order, ``after_request`` hooks in reverse. The API-key hook must come first - because the proxy hook skips requests it already authenticated. + because the later hooks skip requests it already authenticated, and the session check must + run before any route reads the session. """ @app.before_request @@ -268,6 +271,23 @@ def register_auth_middleware( else: return None + @app.before_request + def session_revalidation_middleware() -> Response | tuple[Response, int] | None: + """Sign out or refresh a session whose user changed in users.db since sign-in. + + The routes trust ``session["is_admin"]`` and ``session["user_id"]``, which sign-in + copied into the cookie; this keeps them true to the user's current row, so a + demotion, deletion or password change ends what the old cookie could do. + """ + if g.get("api_key_auth"): + return None + try: + revalidate_session(session, user_db=get_user_db(), auth_mode=resolve_auth_mode()) + except _OPERATIONAL_ERRORS: + logger.exception("Session revalidation error") + return jsonify({"error": "Authentication error"}), 500 + return None + @app.after_request def strip_cookie_for_api_key_requests(response: Response) -> Response: """Keyed requests never mint or refresh a session cookie, even if a handler dirties the session.""" diff --git a/shelfmark/core/auth_routes.py b/shelfmark/core/auth_routes.py index e226524b..45490eb9 100644 --- a/shelfmark/core/auth_routes.py +++ b/shelfmark/core/auth_routes.py @@ -16,6 +16,7 @@ from flask import jsonify, request, session from shelfmark.core.config import config as app_config from shelfmark.core.cwa_user_sync import upsert_cwa_user from shelfmark.core.logger import setup_logger +from shelfmark.core.session_auth import stamp_session_nonce if TYPE_CHECKING: from collections.abc import Callable @@ -264,6 +265,7 @@ def register_auth_routes( session["user_id"] = username session["db_user_id"] = db_user["id"] session["is_admin"] = is_admin + stamp_session_nonce(session, db_user) session.permanent = remember_me clear_failed_logins(username) logger.info( @@ -308,7 +310,7 @@ def register_auth_routes( is_admin = (user_role & 1) == 1 cwa_email = row[2] or None - db_user_id = None + db_user = None user_db = get_user_db() if user_db is not None: role = "admin" if is_admin else "user" @@ -319,13 +321,13 @@ def register_auth_routes( role=role, context="cwa_login", ) - db_user_id = db_user["id"] # Successful authentication - create session and clear failed attempts session["user_id"] = username session["is_admin"] = is_admin - if db_user_id is not None: - session["db_user_id"] = db_user_id + if db_user is not None: + session["db_user_id"] = db_user["id"] + stamp_session_nonce(session, db_user) session.permanent = remember_me clear_failed_logins(username) logger.info( diff --git a/shelfmark/core/oidc_routes.py b/shelfmark/core/oidc_routes.py index b407d646..eb2ce54f 100644 --- a/shelfmark/core/oidc_routes.py +++ b/shelfmark/core/oidc_routes.py @@ -22,6 +22,7 @@ from shelfmark.core.oidc_auth import ( parse_group_claims, provision_oidc_user, ) +from shelfmark.core.session_auth import stamp_session_nonce from shelfmark.download.network import get_ssl_verify if TYPE_CHECKING: @@ -356,6 +357,7 @@ def register_oidc_routes(app: Flask, user_db: UserDB) -> None: session["user_id"] = user["username"] session["is_admin"] = user.get("role") == "admin" session["db_user_id"] = user["id"] + stamp_session_nonce(session, user) session.permanent = True logger.info("OIDC login successful: %s (admin=%s)", user["username"], is_admin) diff --git a/shelfmark/core/self_user_routes.py b/shelfmark/core/self_user_routes.py index edf1a776..d844db48 100644 --- a/shelfmark/core/self_user_routes.py +++ b/shelfmark/core/self_user_routes.py @@ -23,6 +23,7 @@ from shelfmark.core.auth_modes import ( ) from shelfmark.core.config import config as app_config from shelfmark.core.logger import setup_logger +from shelfmark.core.session_auth import SESSION_NONCE_KEY, stamp_session_nonce from shelfmark.core.user_settings_overrides import ( build_user_preferences_payload as _build_user_preferences_payload, ) @@ -101,6 +102,7 @@ def _get_self_edit_capabilities(user: Mapping[str, Any]) -> dict[str, Any]: def _serialize_self_user(user: Mapping[str, Any], auth_mode: str) -> dict[str, Any]: payload = dict(user) payload.pop("password_hash", None) + payload.pop(SESSION_NONCE_KEY, None) payload["auth_source"] = normalize_auth_source( payload.get("auth_source"), payload.get("oidc_subject"), @@ -502,6 +504,9 @@ def register_self_user_routes( updated = user_db.get_user(user_id=user_id) if not updated: return jsonify({"error": "User not found"}), 404 + if password_hash is not None: + # The new password signed out every other session; this one stays signed in. + stamp_session_nonce(session, updated) result = _serialize_self_user(updated, g.auth_mode) result["settings"] = user_db.get_user_settings(user_id) diff --git a/shelfmark/core/session_auth.py b/shelfmark/core/session_auth.py new file mode 100644 index 00000000..63a8f9be --- /dev/null +++ b/shelfmark/core/session_auth.py @@ -0,0 +1,92 @@ +"""Tie a signed-in session to the current state of its user in users.db. + +The session cookie is signed but kept by the browser, so whatever sign-in copied into it +(the user, the admin flag) stays readable until the cookie expires. ``revalidate_session`` +checks a session against users.db on each request: it signs the session out when the user +was deleted, can no longer sign in under the active auth mode, or had their sessions revoked +(a password change rotates ``users.session_nonce``), and it takes the admin flag from the +user's current role, so a demotion applies to sessions that already exist. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from shelfmark.core.auth_modes import ( + AUTH_MODE_NONE, + AUTH_SOURCE_CWA, + AUTH_SOURCE_PROXY, + is_user_active_for_auth_mode, +) +from shelfmark.core.logger import setup_logger +from shelfmark.core.request_helpers import get_session_db_user_id + +if TYPE_CHECKING: + from collections.abc import Mapping, MutableMapping + + from shelfmark.core.user_db import UserDB + +logger = setup_logger(__name__) + +SESSION_NONCE_KEY = "session_nonce" + +# "none" has no users to check, and proxy auth rebuilds the session from the proxy's +# headers on every request (see auth_middleware.proxy_auth_middleware). +_UNCHECKED_AUTH_MODES = frozenset({AUTH_MODE_NONE, AUTH_SOURCE_PROXY}) + + +def stamp_session_nonce(sess: MutableMapping[str, Any], user: Mapping[str, Any]) -> None: + """Record the user's current session nonce in a session that is signing in as them.""" + sess[SESSION_NONCE_KEY] = user.get("session_nonce") + + +def _sign_out(sess: MutableMapping[str, Any], reason: str) -> bool: + logger.info("Signed out session for user '%s': %s", sess.get("user_id"), reason) + sess.clear() + return False + + +def revalidate_session( + sess: MutableMapping[str, Any], + *, + user_db: UserDB | None, + auth_mode: str, +) -> bool: + """Check a signed-in session against users.db, refreshing or clearing it in place. + + Returns False when the session was signed out, True otherwise (including when there + is no signed-in session to check). Database errors propagate to the caller. + """ + if auth_mode in _UNCHECKED_AUTH_MODES or "user_id" not in sess: + return True + + if user_db is None: + # CWA sign-in works without users.db and then links no user. The other modes + # cannot sign anyone in without it, so a session from before it went away is stale. + if auth_mode == AUTH_SOURCE_CWA: + return True + return _sign_out(sess, "the user database is unavailable") + + db_user_id = get_session_db_user_id(sess) + if db_user_id is None: + return _sign_out(sess, "the session is not linked to a user") + + user = user_db.get_user_cached(user_id=db_user_id) + if user is None: + return _sign_out(sess, f"user {db_user_id} no longer exists") + if not is_user_active_for_auth_mode(user, auth_mode): + return _sign_out(sess, f"user {db_user_id} cannot sign in with auth mode '{auth_mode}'") + + nonce = user.get("session_nonce") + if not nonce or sess.get(SESSION_NONCE_KEY) != nonce: + return _sign_out(sess, f"the sessions of user {db_user_id} were revoked") + + is_admin = user.get("role") == "admin" + if sess.get("is_admin") != is_admin: + logger.info( + "Session for user '%s' now has is_admin=%s from the user's current role", + sess.get("user_id"), + is_admin, + ) + sess["is_admin"] = is_admin + return True diff --git a/shelfmark/core/socket_handlers.py b/shelfmark/core/socket_handlers.py index d5cc3c67..5c875bd5 100644 --- a/shelfmark/core/socket_handlers.py +++ b/shelfmark/core/socket_handlers.py @@ -5,10 +5,11 @@ from __future__ import annotations import sqlite3 from typing import TYPE_CHECKING -from flask import request +from flask import request, session from flask_socketio import emit from shelfmark.core.logger import setup_logger +from shelfmark.core.request_helpers import get_session_db_user_id from shelfmark.core.viewer_redaction import redact_status from shelfmark.download import orchestrator as backend @@ -35,12 +36,22 @@ def register_socket_handlers( *, ws_manager: WebSocketManager, resolve_status_scope: Callable[..., tuple[bool, int | None, bool]], + revalidate_session: Callable[[], object], ) -> None: """Register the connect, disconnect and request_status handlers. ``resolve_status_scope`` stays in ``main.py`` because the HTTP routes use it too. + ``revalidate_session`` checks the session against users.db: Socket.IO events do not + pass through Flask's ``before_request`` hooks, so the handlers call it themselves. """ + def _revalidate() -> None: + try: + revalidate_session() + except _OPERATIONAL_ERRORS: + logger.exception("Socket.IO session revalidation error") + session.clear() + @socketio.on("connect") def handle_connect() -> None: """Handle client connection.""" @@ -50,12 +61,14 @@ def register_socket_handlers( ws_manager.client_connected() # Join appropriate room based on authenticated user session + _revalidate() is_admin, db_user_id, can_access_status = resolve_status_scope() sid = _get_request_sid() if sid is None: logger.warning("Socket.IO connect event missing sid") return ws_manager.join_user_room(sid, is_admin=is_admin, db_user_id=db_user_id) + ws_manager.set_sid_user(sid, get_session_db_user_id(session)) # Send initial status to the newly connected client (filtered) try: @@ -86,6 +99,7 @@ def register_socket_handlers( def handle_status_request() -> None: """Handle manual status request from client.""" try: + _revalidate() is_admin, db_user_id, can_access_status = resolve_status_scope() sid = _get_request_sid() if sid is None: @@ -93,6 +107,7 @@ def register_socket_handlers( emit("status_update", {}) return ws_manager.sync_user_room(sid, is_admin=is_admin, db_user_id=db_user_id) + ws_manager.set_sid_user(sid, get_session_db_user_id(session)) if not can_access_status: emit("status_update", {}) diff --git a/shelfmark/core/user_db.py b/shelfmark/core/user_db.py index 509c73d1..1714907b 100644 --- a/shelfmark/core/user_db.py +++ b/shelfmark/core/user_db.py @@ -2,6 +2,7 @@ import json import os +import secrets import sqlite3 import threading import time @@ -41,7 +42,8 @@ CREATE TABLE IF NOT EXISTS users ( oidc_subject TEXT UNIQUE, auth_source TEXT NOT NULL DEFAULT 'builtin', role TEXT NOT NULL DEFAULT 'user', - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + session_nonce TEXT ); CREATE TABLE IF NOT EXISTS user_settings ( @@ -164,6 +166,16 @@ def _book_data_with_failed_release(request_row: dict[str, Any]) -> dict[str, Any return {**book_data, "failed_releases": [*tried, {"source": source, "source_id": source_id}]} +def new_session_nonce() -> str: + """Return a fresh value for users.session_nonce. + + A session cookie carries the nonce its user had at sign-in, and stops working once the + nonce changes. It is random rather than a counter so that a users.db rebuilt from scratch, + which hands out the same user ids again, cannot match a cookie from the old database. + """ + return secrets.token_hex(16) + + def get_users_db_path(config_dir: str | None = None) -> str: """Return the configured users database path.""" root = config_dir or os.environ.get("CONFIG_DIR", "/config") @@ -248,6 +260,7 @@ class UserDB: try: conn.executescript(_CREATE_TABLES_SQL) self._migrate_auth_source_column(conn) + self._migrate_session_nonce_column(conn) self._migrate_request_delivery_columns(conn) self._migrate_download_history_queued_at(conn) self._migrate_download_history_retry_payload(conn) @@ -273,6 +286,21 @@ class UserDB: "UPDATE users SET auth_source = 'builtin' WHERE auth_source IS NULL OR auth_source = ''" ) + def _migrate_session_nonce_column(self, conn: sqlite3.Connection) -> None: + """Ensure users.session_nonce exists and every user has one. + + Rows that had none get a fresh nonce, so session cookies issued before the + column existed no longer match and their holders sign in again. + """ + columns = conn.execute("PRAGMA table_info(users)").fetchall() + column_names = {str(col["name"]) for col in columns} + if "session_nonce" not in column_names: + conn.execute("ALTER TABLE users ADD COLUMN session_nonce TEXT") + conn.execute( + "UPDATE users SET session_nonce = lower(hex(randomblob(16))) " + "WHERE session_nonce IS NULL OR session_nonce = ''" + ) + def _migrate_request_delivery_columns(self, conn: sqlite3.Connection) -> None: """Ensure request delivery-state columns exist and backfill historical rows.""" columns = conn.execute("PRAGMA table_info(download_requests)").fetchall() @@ -345,9 +373,10 @@ class UserDB: try: cursor = conn.execute( """INSERT INTO users ( - username, email, display_name, password_hash, oidc_subject, auth_source, role + username, email, display_name, password_hash, oidc_subject, auth_source, + role, session_nonce ) - VALUES (?, ?, ?, ?, ?, ?, ?)""", + VALUES (?, ?, ?, ?, ?, ?, ?, ?)""", ( username, email, @@ -356,6 +385,7 @@ class UserDB: oidc_subject, auth_source, role, + new_session_nonce(), ), ) conn.commit() @@ -470,6 +500,12 @@ class UserDB: raise ValueError(msg) for column, value in kwargs.items(): conn.execute(self._USER_UPDATE_STATEMENTS[column], (value, user_id)) + if "password_hash" in kwargs: + # A new password ends every session signed in with the old one. + conn.execute( + "UPDATE users SET session_nonce = ? WHERE id = ?", + (new_session_nonce(), user_id), + ) conn.commit() self._drop_user_cache() finally: diff --git a/shelfmark/main.py b/shelfmark/main.py index da158718..670ac002 100644 --- a/shelfmark/main.py +++ b/shelfmark/main.py @@ -76,6 +76,7 @@ from shelfmark.core.request_helpers import ( from shelfmark.core.requests_service import ( sync_delivery_states_from_queue_status, ) +from shelfmark.core.session_auth import revalidate_session from shelfmark.core.settings_routes import register_settings_routes from shelfmark.core.socket_handlers import register_socket_handlers from shelfmark.core.socketio_origins import build_cors_allowed_origins @@ -202,7 +203,7 @@ try: ) register_oidc_routes(app, user_db) - register_admin_routes(app, user_db) + register_admin_routes(app, user_db, ws_manager=ws_manager) register_self_user_routes( app, user_db, @@ -644,8 +645,16 @@ register_settings_routes(app, login_required) register_onboarding_routes(app, login_required) +def _revalidate_socket_session() -> bool: + """Check the session of a Socket.IO event against users.db (no before_request runs there).""" + return revalidate_session(session, user_db=user_db, auth_mode=get_auth_mode()) + + register_socket_handlers( - socketio, ws_manager=ws_manager, resolve_status_scope=_resolve_status_scope + socketio, + ws_manager=ws_manager, + resolve_status_scope=_resolve_status_scope, + revalidate_session=_revalidate_socket_session, ) diff --git a/src/frontend/src/App.tsx b/src/frontend/src/App.tsx index 0343d615..2c3e13be 100644 --- a/src/frontend/src/App.tsx +++ b/src/frontend/src/App.tsx @@ -85,6 +85,7 @@ import { buildLoginRedirectPath, getReturnToFromSearch } from './utils/authRedir import { withBasePath } from './utils/basePath'; import { emitBookTargetChange } from './utils/bookTargetEvents'; import { bookSupportsTargets } from './utils/bookTargetLoader'; +import { mergeSeriesFields } from './utils/bookTransformers'; import { buildSearchQuery } from './utils/buildSearchQuery'; import { wasDownloadQueuedAfterResponseError } from './utils/downloadRecovery'; import { getDynamicOptionGroup } from './utils/dynamicFieldOptions'; @@ -996,10 +997,7 @@ function App() { setSelectedBook({ ...metadataBook, description: fullBook.description || metadataBook.description, - series_id: fullBook.series_id || metadataBook.series_id, - series_name: fullBook.series_name, - series_position: fullBook.series_position, - series_count: fullBook.series_count, + ...mergeSeriesFields(metadataBook, fullBook), }); } catch (error) { console.error('Failed to load book description, using search data:', error); @@ -1618,10 +1616,7 @@ function App() { setReleaseBook({ ...book, description: fullBook.description || book.description, - series_id: fullBook.series_id || book.series_id, - series_name: fullBook.series_name, - series_position: fullBook.series_position, - series_count: fullBook.series_count, + ...mergeSeriesFields(book, fullBook), }); } catch (error) { console.error('Failed to load book description, using search data:', error); diff --git a/src/frontend/src/tests/bookTransformers.test.ts b/src/frontend/src/tests/bookTransformers.test.ts index cf1dc002..91bee5dc 100644 --- a/src/frontend/src/tests/bookTransformers.test.ts +++ b/src/frontend/src/tests/bookTransformers.test.ts @@ -2,6 +2,7 @@ import { describe, it, expect } from 'vitest'; import { isMetadataBook, type Release } from '../types/index'; import { + mergeSeriesFields, transformMetadataToBook, transformReleaseToDirectBook, transformSourceRecordToBook, @@ -104,3 +105,37 @@ describe('bookTransformers.transformMetadataToBook', () => { expect(transformMetadataToBook(metadata).library).toBeUndefined(); }); }); + +describe('bookTransformers.mergeSeriesFields', () => { + const featured = { + series_id: '1098', + series_name: 'Sherlock Holmes', + series_position: 3, + series_count: 10, + }; + + it('keeps the series the book was listed in over the featured one', () => { + const viewed = { + series_id: '4786', + series_name: 'The Adventures of Sherlock Holmes', + series_position: 1, + series_count: 12, + }; + + expect(mergeSeriesFields(viewed, featured)).toEqual(viewed); + }); + + it('takes the full record series when the listed book has none', () => { + expect(mergeSeriesFields({}, featured)).toEqual(featured); + }); + + it('fills missing fields only from the same series', () => { + expect(mergeSeriesFields({ series_name: 'Sherlock Holmes' }, featured)).toEqual(featured); + expect(mergeSeriesFields({ series_id: '4786', series_position: 1 }, featured)).toEqual({ + series_id: '4786', + series_name: undefined, + series_position: 1, + series_count: undefined, + }); + }); +}); diff --git a/src/frontend/src/utils/bookTransformers.ts b/src/frontend/src/utils/bookTransformers.ts index 546f5e9d..a9ef0ca0 100644 --- a/src/frontend/src/utils/bookTransformers.ts +++ b/src/frontend/src/utils/bookTransformers.ts @@ -112,6 +112,38 @@ export function transformMetadataToBook(data: MetadataBookData): Book { }; } +type SeriesFields = Pick; + +/** + * Series fields for a listed book once its full record has been fetched. + * + * A book can belong to several series, but the full record carries only one + * (Hardcover's featured series). When the listed book already names a series, + * as it does in a series view, it is kept so the modals and the download name + * match what is on screen. The full record only fills what is missing. + */ +export function mergeSeriesFields(book: SeriesFields, fullBook: SeriesFields): SeriesFields { + if (!book.series_id && !book.series_name) { + return { + series_id: fullBook.series_id, + series_name: fullBook.series_name, + series_position: fullBook.series_position, + series_count: fullBook.series_count, + }; + } + + const sameSeries = book.series_id + ? book.series_id === fullBook.series_id + : book.series_name === fullBook.series_name; + const fromFullBook: SeriesFields = sameSeries ? fullBook : {}; + return { + series_id: book.series_id || fromFullBook.series_id, + series_name: book.series_name || fromFullBook.series_name, + series_position: book.series_position ?? fromFullBook.series_position, + series_count: book.series_count ?? fromFullBook.series_count, + }; +} + const toOptionalText = (value: unknown): string | undefined => { if (typeof value === 'string' && value.trim()) { return value.trim(); diff --git a/tests/core/sessions.py b/tests/core/sessions.py new file mode 100644 index 00000000..e2cf8588 --- /dev/null +++ b/tests/core/sessions.py @@ -0,0 +1,100 @@ +"""Seed a test client's session the way a real sign-in does. + +The app checks every session against users.db (``shelfmark.core.session_auth``): the session +must name a user that exists, carry that user's session nonce, and its admin flag follows the +user's role. A hand-written session cookie therefore needs a matching user row. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any +from unittest.mock import patch + +from shelfmark.core.session_auth import SESSION_NONCE_KEY + +if TYPE_CHECKING: + from flask.testing import FlaskClient + + from shelfmark.core.user_db import UserDB + + +def _main_user_db() -> UserDB: + import shelfmark.main as main + + if main.user_db is None: + msg = "shelfmark.main has no user database" + raise RuntimeError(msg) + return main.user_db + + +def ensure_user( + user_db: UserDB, + *, + username: str, + db_user_id: int | None = None, + is_admin: bool = False, +) -> dict[str, Any]: + """Return the users.db row a session for ``username`` / ``db_user_id`` would belong to. + + With ``db_user_id`` that user must exist. Without it a user named ``username`` is reused + or created. Either way the row's role is set to match ``is_admin``. + """ + role = "admin" if is_admin else "user" + if db_user_id is None: + user = user_db.get_user(username=username) or user_db.create_user( + username=username, role=role + ) + else: + user = user_db.get_user(user_id=db_user_id) + if user is None: + msg = f"No user {db_user_id} in users.db; create it first or pass no db_user_id" + raise LookupError(msg) + if user.get("role") != role: + user_db.update_user(user["id"], role=role) + user = {**user, "role": role} + return user + + +def sign_in( + client: FlaskClient, + *, + user_id: str = "someone", + db_user_id: int | None = None, + is_admin: bool = False, +) -> dict[str, Any]: + """Give ``client`` a valid signed-in session as a user of ``shelfmark.main``'s users.db. + + Returns the user's row. + """ + user = ensure_user( + _main_user_db(), + username=user_id, + db_user_id=db_user_id, + is_admin=is_admin, + ) + with client.session_transaction() as sess: + sess["user_id"] = user_id + sess["db_user_id"] = user["id"] + sess["is_admin"] = is_admin + sess[SESSION_NONCE_KEY] = user["session_nonce"] + return user + + +def forge_session(client: FlaskClient, **fields: Any) -> None: + """Replace the client's session with exactly ``fields``, with no user row behind it. + + What a stale or hand-made cookie looks like: the session check signs it out, unless a + test patches the check away with ``skip_session_check`` to reach a route's own guard. + """ + with client.session_transaction() as sess: + sess.clear() + sess.update(fields) + + +def skip_session_check() -> Any: + """Patch out the per-request session check of ``shelfmark.main``. + + For tests of the identity guards routes keep behind it: with the check in place a + session without a valid user never reaches them. + """ + return patch("shelfmark.core.auth_middleware.revalidate_session", return_value=True) diff --git a/tests/core/test_activity_routes_api.py b/tests/core/test_activity_routes_api.py index 5d651314..e2399ab5 100644 --- a/tests/core/test_activity_routes_api.py +++ b/tests/core/test_activity_routes_api.py @@ -15,6 +15,7 @@ import pytest from shelfmark.core.models import DownloadTask, QueueStatus from shelfmark.core.viewer_redaction import public_download_id +from tests.core.sessions import forge_session, sign_in, skip_session_check @pytest.fixture(scope="module") @@ -33,13 +34,7 @@ def client(main_module): def _set_session(client, *, user_id: str, db_user_id: int | None, is_admin: bool) -> None: - with client.session_transaction() as sess: - sess["user_id"] = user_id - sess["is_admin"] = is_admin - if db_user_id is not None: - sess["db_user_id"] = db_user_id - elif "db_user_id" in sess: - del sess["db_user_id"] + sign_in(client, user_id=user_id, db_user_id=db_user_id, is_admin=is_admin) def _create_user(main_module, *, prefix: str, role: str = "user") -> dict: @@ -511,9 +506,12 @@ class TestActivityRoutes: def test_dismiss_requires_db_identity(self, main_module, client): user = _create_user(main_module, prefix="reader") - _set_session(client, user_id=user["username"], db_user_id=None, is_admin=False) + forge_session(client, user_id=user["username"], is_admin=False) - with patch.object(main_module, "get_auth_mode", return_value="builtin"): + with ( + patch.object(main_module, "get_auth_mode", return_value="builtin"), + skip_session_check(), + ): with patch("shelfmark.core.activity_routes.logger.warning") as mock_warning: response = client.post( "/api/activity/dismiss", @@ -1002,7 +1000,7 @@ class TestActivityRoutes: def test_no_auth_dismiss_many_ignores_stale_session_db_identity(self, main_module, client): stale_db_user_id = 999999999 - _set_session( + forge_session( client, user_id="stale-session-user", db_user_id=stale_db_user_id, is_admin=False ) @@ -1071,9 +1069,12 @@ class TestActivityRoutes: def test_dismiss_many_with_stale_db_identity_returns_identity_unavailable( self, main_module, client ): - _set_session(client, user_id="stale-session-user", db_user_id=999999999, is_admin=False) + forge_session(client, user_id="stale-session-user", db_user_id=999999999, is_admin=False) - with patch.object(main_module, "get_auth_mode", return_value="builtin"): + with ( + patch.object(main_module, "get_auth_mode", return_value="builtin"), + skip_session_check(), + ): response = client.post( "/api/activity/dismiss-many", json={"items": [{"item_type": "download", "item_key": "download:test-stale"}]}, @@ -1087,6 +1088,8 @@ class TestActivityRoutes: ): user = _create_user(main_module, prefix="reader") _set_session(client, user_id=user["username"], db_user_id=user["id"], is_admin=False) + # The session check answers from the user cache, so only the route's lookup fails. + main_module.user_db.get_user_cached(user_id=user["id"]) with ( patch.object(main_module, "get_auth_mode", return_value="builtin"), @@ -1112,9 +1115,12 @@ class TestActivityRoutes: def test_clear_history_logs_identity_failure(self, main_module, client): admin = _create_user(main_module, prefix="admin", role="admin") - _set_session(client, user_id=admin["username"], db_user_id=None, is_admin=True) + forge_session(client, user_id=admin["username"], is_admin=True) - with patch.object(main_module, "get_auth_mode", return_value="builtin"): + with ( + patch.object(main_module, "get_auth_mode", return_value="builtin"), + skip_session_check(), + ): with patch("shelfmark.core.activity_routes.logger.warning") as mock_warning: response = client.delete("/api/activity/history") diff --git a/tests/core/test_api_key_env.py b/tests/core/test_api_key_env.py index efd52b1a..3ea05c8b 100644 --- a/tests/core/test_api_key_env.py +++ b/tests/core/test_api_key_env.py @@ -128,6 +128,7 @@ def _cookie_client(app, user, *, is_admin=False, permanent=False): sess["user_id"] = user["username"] sess["is_admin"] = is_admin sess["db_user_id"] = user["id"] + sess["session_nonce"] = user["session_nonce"] sess.permanent = permanent return client diff --git a/tests/core/test_auth_api.py b/tests/core/test_auth_api.py index 693e0a0e..2c9e6250 100644 --- a/tests/core/test_auth_api.py +++ b/tests/core/test_auth_api.py @@ -186,6 +186,7 @@ class TestLoginSemantics: sess["user_id"] = "alice" sess["db_user_id"] = user["id"] sess["is_admin"] = True + sess["session_nonce"] = user["session_nonce"] with patch.object(main_module, "get_auth_mode", return_value="builtin"): response = client.get("/api/auth/check") diff --git a/tests/core/test_auth_routes.py b/tests/core/test_auth_routes.py index e3ef2779..c8c55ed3 100644 --- a/tests/core/test_auth_routes.py +++ b/tests/core/test_auth_routes.py @@ -551,16 +551,22 @@ class TestAuthCheck: sess["user_id"] = "alice" sess["db_user_id"] = user["id"] sess["is_admin"] = False + sess["session_nonce"] = user["session_nonce"] with _mode(main_module, "builtin"): body = client.get("/api/auth/check").get_json() assert body["authenticated"] is True assert body["is_admin"] is False assert body["username"] == "alice" - def test_cwa_session_admin_flag_comes_from_the_session(self, main_module, client): + def test_cwa_session_admin_flag_comes_from_the_linked_users_role( + self, main_module, client, temp_user_db + ): + user = temp_user_db.create_user(username="cwa_fake", auth_source="cwa", role="admin") with client.session_transaction() as sess: sess["user_id"] = "cwa_fake" - sess["is_admin"] = True + sess["db_user_id"] = user["id"] + sess["is_admin"] = False + sess["session_nonce"] = user["session_nonce"] with _mode(main_module, "cwa"): body = client.get("/api/auth/check").get_json() assert body == { @@ -643,6 +649,9 @@ class TestAuthCheck: sess["user_id"] = "alice" sess["db_user_id"] = user["id"] sess["is_admin"] = False + sess["session_nonce"] = user["session_nonce"] + # The session check answers from the user cache, so only the route's lookup fails. + temp_user_db.get_user_cached(user_id=user["id"]) def boom(**kwargs): raise sqlite3.Error("fake") diff --git a/tests/core/test_debug_routes_admin.py b/tests/core/test_debug_routes_admin.py index 51b1dcd8..2f8c711b 100644 --- a/tests/core/test_debug_routes_admin.py +++ b/tests/core/test_debug_routes_admin.py @@ -10,6 +10,7 @@ from unittest.mock import patch import pytest from shelfmark.core.config import config as app_config +from tests.core.sessions import sign_in _DEBUG_OVERRIDES: dict[str, object] = {"DEBUG": True, "USING_EXTERNAL_BYPASSER": True} _ORIGINAL_CONFIG_GET = app_config.get @@ -43,9 +44,7 @@ def client(main_module): def _set_session(client, *, user_id: str, is_admin: bool) -> None: - with client.session_transaction() as sess: - sess["user_id"] = user_id - sess["is_admin"] = is_admin + sign_in(client, user_id=user_id, is_admin=is_admin) @pytest.fixture diff --git a/tests/core/test_download_api_guardrails.py b/tests/core/test_download_api_guardrails.py index 3d416cf6..e2b58903 100644 --- a/tests/core/test_download_api_guardrails.py +++ b/tests/core/test_download_api_guardrails.py @@ -9,6 +9,7 @@ from unittest.mock import patch import pytest from shelfmark.core.models import DownloadTask, QueueStatus +from tests.core.sessions import sign_in @pytest.fixture(scope="module") @@ -30,14 +31,10 @@ def _set_authenticated_session( client, *, user_id: str = "alice", - db_user_id: int | None = 7, + db_user_id: int | None = None, is_admin: bool = False, -) -> None: - with client.session_transaction() as sess: - sess["user_id"] = user_id - sess["is_admin"] = is_admin - if db_user_id is not None: - sess["db_user_id"] = db_user_id +) -> dict: + return sign_in(client, user_id=user_id, db_user_id=db_user_id, is_admin=is_admin) def _create_user(main_module, *, prefix: str, role: str = "user") -> dict: @@ -95,10 +92,9 @@ class TestReleaseDownloadEndpointGuardrails: ) return True, None - _set_authenticated_session( + bob = _set_authenticated_session( client, user_id="bob", - db_user_id=19, is_admin=False, ) payload = { @@ -117,7 +113,7 @@ class TestReleaseDownloadEndpointGuardrails: assert resp.get_json() == {"status": "queued", "priority": 3} assert captured["release_data"] == {**payload, "content_type": "ebook"} assert captured["priority"] == 3 - assert captured["user_id"] == 19 + assert captured["user_id"] == bob["id"] assert captured["username"] == "bob" def test_missing_content_type_infers_audiobook_from_format(self, main_module, client): @@ -299,7 +295,8 @@ class TestReleaseDownloadEndpointGuardrails: "on_behalf_of_user_id": 7, } - with patch.object(main_module, "get_auth_mode", return_value="builtin"): + # CWA sign-in works without users.db, so that is where a signed-in admin meets this. + with patch.object(main_module, "get_auth_mode", return_value="cwa"): with patch.object(main_module, "user_db", None): with patch.object(main_module.backend, "queue_release") as mock_queue_release: resp = client.post("/api/releases/download", json=payload) @@ -826,10 +823,9 @@ class TestStatusEndpointGuardrails: observed["user_id"] = user_id return {"queued": {}, "downloading": {}, "completed": {}, "failed": {}, "cancelled": {}} - _set_authenticated_session( + reader = _set_authenticated_session( client, user_id="reader", - db_user_id=55, is_admin=False, ) with patch.object(main_module, "get_auth_mode", return_value="builtin"): @@ -837,7 +833,7 @@ class TestStatusEndpointGuardrails: resp = client.get("/api/status") assert resp.status_code == 200 - assert observed["user_id"] == 55 + assert observed["user_id"] == reader["id"] def test_admin_status_is_unscoped(self, main_module, client): observed: dict[str, object] = {} @@ -849,7 +845,6 @@ class TestStatusEndpointGuardrails: _set_authenticated_session( client, user_id="admin", - db_user_id=1, is_admin=True, ) with patch.object(main_module, "get_auth_mode", return_value="builtin"): diff --git a/tests/core/test_error_text_in_responses.py b/tests/core/test_error_text_in_responses.py index 792d3d1f..707afbe1 100644 --- a/tests/core/test_error_text_in_responses.py +++ b/tests/core/test_error_text_in_responses.py @@ -14,6 +14,8 @@ from unittest.mock import patch import pytest +from tests.core.sessions import sign_in + _LEAK = "/srv/shelfmark/secret/path token=abc123" @@ -37,10 +39,7 @@ def _boom(*_args, **_kwargs): def _admin_session(client) -> None: - with client.session_transaction() as sess: - sess["user_id"] = "alice" - sess["is_admin"] = True - sess["db_user_id"] = 7 + sign_in(client, user_id="alice", is_admin=True) class _Source: diff --git a/tests/core/test_notifications_settings_api.py b/tests/core/test_notifications_settings_api.py index ef8ea350..f4e21f4c 100644 --- a/tests/core/test_notifications_settings_api.py +++ b/tests/core/test_notifications_settings_api.py @@ -8,6 +8,8 @@ from unittest.mock import patch import pytest +from tests.core.sessions import sign_in + @pytest.fixture(scope="module") def main_module(): @@ -30,10 +32,7 @@ def _create_user(main_module, *, prefix: str, role: str) -> dict: def _set_session(client, *, user_id: str, db_user_id: int, is_admin: bool) -> None: - with client.session_transaction() as sess: - sess["user_id"] = user_id - sess["db_user_id"] = db_user_id - sess["is_admin"] = is_admin + sign_in(client, user_id=user_id, db_user_id=db_user_id, is_admin=is_admin) class TestNotificationsSettingsApi: diff --git a/tests/core/test_onboarding_routes.py b/tests/core/test_onboarding_routes.py index cdbd264e..568d8729 100644 --- a/tests/core/test_onboarding_routes.py +++ b/tests/core/test_onboarding_routes.py @@ -7,6 +7,8 @@ from unittest.mock import patch import pytest +from tests.core.sessions import sign_in + @pytest.fixture(scope="module") def main_module(): @@ -24,10 +26,7 @@ def client(main_module): def _sign_in(client, *, is_admin: bool) -> None: - with client.session_transaction() as sess: - sess["user_id"] = "someone" - sess["db_user_id"] = 7 - sess["is_admin"] = is_admin + sign_in(client, user_id="someone", is_admin=is_admin) @pytest.fixture diff --git a/tests/core/test_provider_account_access.py b/tests/core/test_provider_account_access.py index 4818e05c..567f1d0e 100644 --- a/tests/core/test_provider_account_access.py +++ b/tests/core/test_provider_account_access.py @@ -8,6 +8,7 @@ from unittest.mock import patch import pytest from shelfmark.metadata_providers.hardcover import HardcoverProvider +from tests.core.sessions import sign_in @pytest.fixture(scope="module") @@ -73,9 +74,7 @@ def client(main_module, provider): def _session(client, *, is_admin: bool) -> None: - with client.session_transaction() as sess: - sess["user_id"] = "someone" - sess["is_admin"] = is_admin + sign_in(client, user_id="someone", is_admin=is_admin) def _as(main_module, client, *, is_admin: bool, auth_mode: str = "builtin"): diff --git a/tests/core/test_queue_routes.py b/tests/core/test_queue_routes.py index 523fff0f..c088ba37 100644 --- a/tests/core/test_queue_routes.py +++ b/tests/core/test_queue_routes.py @@ -18,6 +18,7 @@ import pytest from shelfmark.core.models import DownloadTask from shelfmark.core.viewer_redaction import viewer_download_id +from tests.core.sessions import forge_session, sign_in, skip_session_check @pytest.fixture(scope="module") @@ -35,12 +36,8 @@ def client(main_module): return main_module.app.test_client() -def _login(client, *, user_id="alice", db_user_id: int | None = 7, is_admin=False) -> None: - with client.session_transaction() as sess: - sess["user_id"] = user_id - sess["is_admin"] = is_admin - if db_user_id is not None: - sess["db_user_id"] = db_user_id +def _login(client, *, user_id="alice", db_user_id: int | None = None, is_admin=False) -> None: + sign_in(client, user_id=user_id, db_user_id=db_user_id, is_admin=is_admin) def _create_user(main_module, *, prefix: str) -> dict: @@ -247,8 +244,8 @@ class TestCancel: assert resp.status_code == 404 def test_a_user_without_a_database_identity_is_a_403(self, main_module, client): - _login(client, user_id="ghost", db_user_id=None) - with _builtin(main_module): + forge_session(client, user_id="ghost", is_admin=False) + with _builtin(main_module), skip_session_check(): with patch.object(main_module.backend.book_queue, "get_task", return_value=_task()): resp = client.delete("/api/download/task-1/cancel") @@ -312,8 +309,8 @@ class TestPriority: assert resp.get_json() == {"error": "Invalid priority value"} def test_a_user_without_a_database_identity_is_a_403(self, main_module, client): - _login(client, user_id="ghost", db_user_id=None) - with _builtin(main_module): + forge_session(client, user_id="ghost", is_admin=False) + with _builtin(main_module), skip_session_check(): resp = client.put("/api/queue/task-1/priority", json={"priority": 1}) assert resp.status_code == 403 @@ -432,8 +429,8 @@ class TestQueueViews: assert resp.get_json() == {"active_downloads": ["a", "b"]} def test_both_views_refuse_a_user_without_a_database_identity(self, main_module, client): - _login(client, user_id="ghost", db_user_id=None) - with _builtin(main_module): + forge_session(client, user_id="ghost", is_admin=False) + with _builtin(main_module), skip_session_check(): order = client.get("/api/queue/order") active = client.get("/api/downloads/active") @@ -454,8 +451,8 @@ class TestQueueViews: class TestStatus: def test_a_user_without_a_database_identity_gets_an_empty_object(self, main_module, client): - _login(client, user_id="ghost", db_user_id=None) - with _builtin(main_module): + forge_session(client, user_id="ghost", is_admin=False) + with _builtin(main_module), skip_session_check(): resp = client.get("/api/status") assert resp.status_code == 200 diff --git a/tests/core/test_release_routes.py b/tests/core/test_release_routes.py index adb96cb2..5984194a 100644 --- a/tests/core/test_release_routes.py +++ b/tests/core/test_release_routes.py @@ -54,6 +54,7 @@ def _login_user(client, main_module, *, is_admin: bool = False) -> dict: sess["user_id"] = user["username"] sess["is_admin"] = is_admin sess["db_user_id"] = user["id"] + sess["session_nonce"] = user["session_nonce"] return user diff --git a/tests/core/test_release_routes_policy.py b/tests/core/test_release_routes_policy.py index df7de73f..90975e98 100644 --- a/tests/core/test_release_routes_policy.py +++ b/tests/core/test_release_routes_policy.py @@ -41,6 +41,7 @@ def _login(client, main_module, *, is_admin: bool = False) -> dict: sess["user_id"] = user["username"] sess["is_admin"] = is_admin sess["db_user_id"] = user["id"] + sess["session_nonce"] = user["session_nonce"] return user diff --git a/tests/core/test_request_routes_api.py b/tests/core/test_request_routes_api.py index 2cb43d7b..87b3a35b 100644 --- a/tests/core/test_request_routes_api.py +++ b/tests/core/test_request_routes_api.py @@ -9,6 +9,7 @@ from unittest.mock import patch import pytest from shelfmark.core.notifications import NotificationEvent +from tests.core.sessions import forge_session, sign_in, skip_session_check @pytest.fixture(scope="module") @@ -27,13 +28,7 @@ def client(main_module): def _set_session(client, *, user_id: str, db_user_id: int | None, is_admin: bool) -> None: - with client.session_transaction() as sess: - sess["user_id"] = user_id - sess["is_admin"] = is_admin - if db_user_id is not None: - sess["db_user_id"] = db_user_id - elif "db_user_id" in sess: - del sess["db_user_id"] + sign_in(client, user_id=user_id, db_user_id=db_user_id, is_admin=is_admin) def _create_user(main_module, *, prefix: str, role: str = "user") -> dict: @@ -108,6 +103,7 @@ class TestDownloadPolicyGuards: with client.session_transaction() as sess: sess["user_id"] = user["username"] sess["db_user_id"] = user["id"] + sess["session_nonce"] = user["session_nonce"] sess.pop("is_admin", None) with patch.object(main_module, "get_auth_mode", return_value="builtin"): @@ -2408,13 +2404,12 @@ class TestRequestCreationEdgeCases: assert resp.json["request_level"] == "release" def test_without_db_user_id_returns_403(self, main_module, client): - with client.session_transaction() as sess: - sess["user_id"] = "some-user" - sess["is_admin"] = False - if "db_user_id" in sess: - del sess["db_user_id"] + forge_session(client, user_id="some-user", is_admin=False) - with patch.object(main_module, "get_auth_mode", return_value="builtin"): + with ( + patch.object(main_module, "get_auth_mode", return_value="builtin"), + skip_session_check(), + ): resp = client.post( "/api/requests", json={ @@ -2954,13 +2949,12 @@ class TestAdminFulfilEdgeCases: assert fulfil_resp.json["release_data"]["source_id"] == "better-r" def test_admin_without_db_user_id_returns_403(self, main_module, client): - with client.session_transaction() as sess: - sess["user_id"] = "admin-user" - sess["is_admin"] = True - if "db_user_id" in sess: - del sess["db_user_id"] + forge_session(client, user_id="admin-user", is_admin=True) - with patch.object(main_module, "get_auth_mode", return_value="builtin"): + with ( + patch.object(main_module, "get_auth_mode", return_value="builtin"), + skip_session_check(), + ): resp = client.post("/api/admin/requests/1/fulfil", json={}) assert resp.status_code == 403 diff --git a/tests/core/test_session_revocation.py b/tests/core/test_session_revocation.py new file mode 100644 index 00000000..a299fbb2 --- /dev/null +++ b/tests/core/test_session_revocation.py @@ -0,0 +1,400 @@ +"""A session cookie stops granting what users.db no longer allows (GHSA-hr9m-646v-8g6w, +GHSA-9gqw-mmp2-pjm8). + +Sign-in copies the user and their admin flag into the signed cookie. These tests sign in +through the real login route, change the user from a second admin's session, and replay +the first cookie: a demotion, a deletion or a password change must apply to it at once. +""" + +from __future__ import annotations + +import importlib +import sqlite3 +import uuid +from contextlib import ExitStack +from unittest.mock import patch + +import pytest +from werkzeug.security import generate_password_hash + +from shelfmark.core.session_auth import SESSION_NONCE_KEY, revalidate_session +from shelfmark.core.user_db import UserDB +from tests.core.sessions import forge_session + +PASSWORD = "fake-password-1" + + +@pytest.fixture(scope="module") +def main_module(): + """Import `shelfmark.main` with background startup disabled.""" + with patch("shelfmark.download.orchestrator.start"): + import shelfmark.main as main + + importlib.reload(main) + return main + + +@pytest.fixture +def auth_mode(main_module): + """Run the app in builtin auth mode; set ``.mode`` to switch it mid-test.""" + + class _Mode: + mode = "builtin" + + current = _Mode() + with ExitStack() as stack: + for target in ( + "shelfmark.core.admin_routes.load_active_auth_mode", + "shelfmark.core.self_user_routes.load_active_auth_mode", + ): + stack.enter_context(patch(target, side_effect=lambda: current.mode)) + stack.enter_context( + patch.object(main_module, "get_auth_mode", side_effect=lambda: current.mode) + ) + main_module.failed_login_attempts.clear() + yield current + main_module.failed_login_attempts.clear() + + +def _user(main_module, *, prefix: str, role: str = "user") -> dict: + return main_module.user_db.create_user( + username=f"{prefix}-{uuid.uuid4().hex[:8]}", + password_hash=generate_password_hash(PASSWORD), + role=role, + ) + + +def _signed_in(main_module, user: dict, password: str = PASSWORD): + client = main_module.app.test_client() + resp = client.post("/api/auth/login", json={"username": user["username"], "password": password}) + assert resp.status_code == 200, resp.get_json() + return client + + +def _check(client) -> dict: + return client.get("/api/auth/check").get_json() + + +class TestDemotedAdmin: + def test_old_session_loses_admin_access_at_once(self, main_module, auth_mode): + admin_a = _user(main_module, prefix="admin-a", role="admin") + admin_b = _user(main_module, prefix="admin-b", role="admin") + a = _signed_in(main_module, admin_a) + b = _signed_in(main_module, admin_b) + assert a.get("/api/admin/users").status_code == 200 + + resp = b.put(f"/api/admin/users/{admin_a['id']}", json={"role": "user"}) + assert resp.status_code == 200 + + assert a.get("/api/admin/users").status_code == 403 + assert _check(a)["is_admin"] is False + assert _check(a)["authenticated"] is True + + def test_old_session_cannot_restore_its_role_or_mint_an_admin(self, main_module, auth_mode): + admin_a = _user(main_module, prefix="admin-a", role="admin") + admin_b = _user(main_module, prefix="admin-b", role="admin") + a = _signed_in(main_module, admin_a) + b = _signed_in(main_module, admin_b) + b.put(f"/api/admin/users/{admin_a['id']}", json={"role": "user"}) + + restore = a.put(f"/api/admin/users/{admin_a['id']}", json={"role": "admin"}) + backdoor = a.post( + "/api/admin/users", + json={"username": f"backdoor-{uuid.uuid4().hex[:8]}", "password": PASSWORD}, + ) + + assert restore.status_code == 403 + assert backdoor.status_code == 403 + assert main_module.user_db.get_user(user_id=admin_a["id"])["role"] == "user" + + def test_admin_only_settings_close_too(self, main_module, auth_mode): + admin_a = _user(main_module, prefix="admin-a", role="admin") + admin_b = _user(main_module, prefix="admin-b", role="admin") + a = _signed_in(main_module, admin_a) + b = _signed_in(main_module, admin_b) + b.put(f"/api/admin/users/{admin_a['id']}", json={"role": "user"}) + + assert a.get("/api/settings/security").status_code == 403 + + def test_a_promotion_applies_without_signing_in_again(self, main_module, auth_mode): + user = _user(main_module, prefix="reader") + admin = _user(main_module, prefix="admin", role="admin") + u = _signed_in(main_module, user) + assert u.get("/api/admin/users").status_code == 403 + + _signed_in(main_module, admin).put(f"/api/admin/users/{user['id']}", json={"role": "admin"}) + + assert u.get("/api/admin/users").status_code == 200 + + +class TestDeletedUser: + def test_old_session_is_signed_out(self, main_module, auth_mode): + victim = _user(main_module, prefix="victim") + admin = _user(main_module, prefix="admin", role="admin") + v = _signed_in(main_module, victim) + assert _check(v)["authenticated"] is True + + assert ( + _signed_in(main_module, admin).delete(f"/api/admin/users/{victim['id']}").status_code + == 200 + ) + + assert _check(v)["authenticated"] is False + assert v.get("/api/status").status_code == 401 + with v.session_transaction() as sess: + assert "user_id" not in sess + + def test_a_deleted_admin_cannot_use_the_admin_api(self, main_module, auth_mode): + admin_a = _user(main_module, prefix="admin-a", role="admin") + admin_b = _user(main_module, prefix="admin-b", role="admin") + a = _signed_in(main_module, admin_a) + _signed_in(main_module, admin_b).delete(f"/api/admin/users/{admin_a['id']}") + + assert a.get("/api/admin/users").status_code == 401 + assert ( + a.post("/api/admin/users", json={"username": "x", "password": PASSWORD}).status_code + == 401 + ) + + +class TestPasswordChange: + def test_an_admin_reset_signs_out_existing_sessions(self, main_module, auth_mode): + victim = _user(main_module, prefix="victim") + admin = _user(main_module, prefix="admin", role="admin") + stolen = _signed_in(main_module, victim) + + resp = _signed_in(main_module, admin).put( + f"/api/admin/users/{victim['id']}", json={"password": "new-fake-password-2"} + ) + assert resp.status_code == 200 + + assert _check(stolen)["authenticated"] is False + fresh = _signed_in(main_module, victim, password="new-fake-password-2") + assert _check(fresh)["authenticated"] is True + + def test_changing_your_own_password_keeps_this_session_and_ends_the_others( + self, main_module, auth_mode + ): + user = _user(main_module, prefix="reader") + here = _signed_in(main_module, user) + elsewhere = _signed_in(main_module, user) + + resp = here.put( + "/api/users/me", + json={"password": "new-fake-password-2", "current_password": PASSWORD}, + ) + assert resp.status_code == 200 + + assert _check(here)["authenticated"] is True + assert _check(elsewhere)["authenticated"] is False + + def test_an_admin_setting_their_own_password_stays_signed_in(self, main_module, auth_mode): + admin = _user(main_module, prefix="admin", role="admin") + other_admin = _user(main_module, prefix="admin-2", role="admin") # keeps a local admin + here = _signed_in(main_module, admin) + elsewhere = _signed_in(main_module, admin) + assert other_admin + + resp = here.put(f"/api/admin/users/{admin['id']}", json={"password": "new-fake-password-2"}) + assert resp.status_code == 200 + + assert here.get("/api/admin/users").status_code == 200 + assert _check(elsewhere)["authenticated"] is False + + def test_user_payloads_never_carry_the_session_nonce(self, main_module, auth_mode): + admin = _user(main_module, prefix="admin", role="admin") + client = _signed_in(main_module, admin) + + listed = client.get("/api/admin/users").get_json() + one = client.get(f"/api/admin/users/{admin['id']}").get_json() + me = client.get("/api/users/me/edit-context").get_json() + + assert all(SESSION_NONCE_KEY not in row for row in listed) + assert SESSION_NONCE_KEY not in one + assert SESSION_NONCE_KEY not in me["user"] + + +class TestStaleCookies: + def test_a_cookie_from_before_session_nonces_is_signed_out(self, main_module, auth_mode): + user = _user(main_module, prefix="reader") + client = main_module.app.test_client() + forge_session(client, user_id=user["username"], db_user_id=user["id"], is_admin=False) + + assert _check(client)["authenticated"] is False + + def test_a_session_without_a_linked_user_is_signed_out(self, main_module, auth_mode): + client = main_module.app.test_client() + forge_session(client, user_id="someone", is_admin=True) + + assert client.get("/api/status").status_code == 401 + + def test_a_builtin_session_ends_when_auth_moves_to_another_source(self, main_module, auth_mode): + user = _user(main_module, prefix="reader") + client = _signed_in(main_module, user) + + auth_mode.mode = "cwa" + + assert _check(client)["authenticated"] is False + + def test_a_database_error_fails_closed(self, main_module, auth_mode): + user = _user(main_module, prefix="reader") + client = _signed_in(main_module, user) + + with patch.object( + main_module.user_db, "get_user_cached", side_effect=sqlite3.OperationalError("locked") + ): + resp = client.get("/api/status") + + assert resp.status_code == 500 + assert resp.get_json() == {"error": "Authentication error"} + + +class TestSocketIO: + @staticmethod + def _connect(main_module, client): + socket = main_module.socketio.test_client(main_module.app, flask_test_client=client) + events = [(item["name"], item["args"][0]) for item in socket.get_received()] + return socket, events + + def test_a_demoted_admins_cookie_joins_only_their_own_room(self, main_module, auth_mode): + admin_a = _user(main_module, prefix="admin-a", role="admin") + admin_b = _user(main_module, prefix="admin-b", role="admin") + a = _signed_in(main_module, admin_a) + _signed_in(main_module, admin_b).put( + f"/api/admin/users/{admin_a['id']}", json={"role": "user"} + ) + + with patch.object(main_module.ws_manager, "join_user_room") as join: + socket, _ = self._connect(main_module, a) + socket.disconnect() + + assert join.call_args.kwargs == {"is_admin": False, "db_user_id": admin_a["id"]} + + def test_a_deleted_users_cookie_gets_no_room_and_no_status(self, main_module, auth_mode): + victim = _user(main_module, prefix="victim") + admin = _user(main_module, prefix="admin", role="admin") + v = _signed_in(main_module, victim) + _signed_in(main_module, admin).delete(f"/api/admin/users/{victim['id']}") + + with patch.object(main_module.ws_manager, "join_user_room") as join: + socket, events = self._connect(main_module, v) + socket.disconnect() + + assert join.call_args.kwargs == {"is_admin": False, "db_user_id": None} + assert events == [("status_update", {})] + + def test_a_demotion_disconnects_the_users_open_sockets(self, main_module, auth_mode): + admin_a = _user(main_module, prefix="admin-a", role="admin") + admin_b = _user(main_module, prefix="admin-b", role="admin") + a = _signed_in(main_module, admin_a) + b = _signed_in(main_module, admin_b) + socket, _ = self._connect(main_module, a) + assert socket.is_connected() + + b.put(f"/api/admin/users/{admin_a['id']}", json={"role": "user"}) + + assert not socket.is_connected() + + def test_a_deletion_disconnects_the_users_open_sockets(self, main_module, auth_mode): + victim = _user(main_module, prefix="victim") + admin = _user(main_module, prefix="admin", role="admin") + socket, _ = self._connect(main_module, _signed_in(main_module, victim)) + assert socket.is_connected() + + _signed_in(main_module, admin).delete(f"/api/admin/users/{victim['id']}") + + assert not socket.is_connected() + + +class TestRevalidateSession: + @pytest.fixture + def user_db(self, tmp_path): + db = UserDB(str(tmp_path / "users.db")) + db.initialize() + return db + + def test_proxy_and_no_auth_sessions_are_left_alone(self, user_db): + for mode in ("none", "proxy"): + sess = {"user_id": "ghost", "is_admin": True} + assert revalidate_session(sess, user_db=user_db, auth_mode=mode) is True + assert sess == {"user_id": "ghost", "is_admin": True} + + def test_cwa_without_a_user_database_keeps_its_session(self): + sess = {"user_id": "cwa-user", "is_admin": False} + assert revalidate_session(sess, user_db=None, auth_mode="cwa") is True + + def test_builtin_without_a_user_database_signs_out(self): + sess = {"user_id": "someone", "db_user_id": 1, "is_admin": True} + assert revalidate_session(sess, user_db=None, auth_mode="builtin") is False + assert sess == {} + + def test_an_unrecognized_auth_mode_signs_out(self, user_db): + user = user_db.create_user(username="alice", role="admin") + sess = { + "user_id": "alice", + "db_user_id": user["id"], + "is_admin": True, + SESSION_NONCE_KEY: user["session_nonce"], + } + assert revalidate_session(sess, user_db=user_db, auth_mode="unavailable") is False + + def test_a_rebuilt_database_does_not_honor_old_cookies(self, tmp_path): + """A fresh users.db hands out id 1 again; the old cookie's nonce cannot match it.""" + old_db = UserDB(str(tmp_path / "old.db")) + old_db.initialize() + old_user = old_db.create_user(username="alice", role="user") + new_db = UserDB(str(tmp_path / "new.db")) + new_db.initialize() + new_admin = new_db.create_user(username="root", role="admin") + assert new_admin["id"] == old_user["id"] + + sess = { + "user_id": "alice", + "db_user_id": old_user["id"], + "is_admin": False, + SESSION_NONCE_KEY: old_user["session_nonce"], + } + assert revalidate_session(sess, user_db=new_db, auth_mode="builtin") is False + + +class TestSessionNonceColumn: + def test_every_user_gets_a_distinct_nonce(self, tmp_path): + db = UserDB(str(tmp_path / "users.db")) + db.initialize() + a = db.create_user(username="a") + b = db.create_user(username="b") + assert a["session_nonce"] + assert b["session_nonce"] + assert a["session_nonce"] != b["session_nonce"] + + def test_a_password_change_rotates_it_and_other_edits_do_not(self, tmp_path): + db = UserDB(str(tmp_path / "users.db")) + db.initialize() + user = db.create_user(username="a", password_hash="old") + nonce = user["session_nonce"] + + db.update_user(user["id"], role="admin", email="a@example.invalid", display_name="A") + assert db.get_user(user_id=user["id"])["session_nonce"] == nonce + + db.update_user(user["id"], password_hash="new") + assert db.get_user(user_id=user["id"])["session_nonce"] != nonce + + def test_an_existing_database_is_migrated_and_backfilled(self, tmp_path): + path = tmp_path / "users.db" + conn = sqlite3.connect(path) + conn.execute( + "CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL," + " email TEXT, display_name TEXT, password_hash TEXT, oidc_subject TEXT UNIQUE," + " role TEXT NOT NULL DEFAULT 'user', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)" + ) + conn.execute("INSERT INTO users (username, role) VALUES ('legacy-a', 'admin')") + conn.execute("INSERT INTO users (username, role) VALUES ('legacy-b', 'user')") + conn.commit() + conn.close() + + db = UserDB(str(path)) + db.initialize() + + nonces = [row["session_nonce"] for row in db.list_users()] + assert all(nonces) + assert len(set(nonces)) == 2 diff --git a/tests/core/test_settings_routes.py b/tests/core/test_settings_routes.py index 5f45f85d..2b610c1f 100644 --- a/tests/core/test_settings_routes.py +++ b/tests/core/test_settings_routes.py @@ -7,6 +7,8 @@ from unittest.mock import patch import pytest +from tests.core.sessions import sign_in + @pytest.fixture(scope="module") def main_module(): @@ -24,10 +26,7 @@ def client(main_module): def _sign_in(client, *, is_admin: bool) -> None: - with client.session_transaction() as sess: - sess["user_id"] = "someone" - sess["db_user_id"] = 7 - sess["is_admin"] = is_admin + sign_in(client, user_id="someone", is_admin=is_admin) @pytest.fixture diff --git a/tests/core/test_socket_handlers.py b/tests/core/test_socket_handlers.py index e3caa1de..7de1b1a8 100644 --- a/tests/core/test_socket_handlers.py +++ b/tests/core/test_socket_handlers.py @@ -11,6 +11,8 @@ from unittest.mock import patch import pytest +from tests.core.sessions import sign_in + @pytest.fixture(scope="module") def main_module(): @@ -27,12 +29,8 @@ def client(main_module): return main_module.app.test_client() -def _login(client, *, user_id="alice", db_user_id: int | None = 7, is_admin=False) -> None: - with client.session_transaction() as sess: - sess["user_id"] = user_id - sess["is_admin"] = is_admin - if db_user_id is not None: - sess["db_user_id"] = db_user_id +def _login(client, *, user_id="alice", db_user_id: int | None = None, is_admin=False) -> dict: + return sign_in(client, user_id=user_id, db_user_id=db_user_id, is_admin=is_admin) def _socket(main_module, client): @@ -74,7 +72,7 @@ class TestConnect: assert join.call_args.kwargs == {"is_admin": True, "db_user_id": None} def test_a_user_gets_their_own_status_with_release_details_hidden(self, main_module, client): - _login(client, user_id="alice", db_user_id=7) + alice = _login(client, user_id="alice") with patch.object(main_module, "get_auth_mode", return_value="builtin"): with patch.object(main_module.backend, "queue_status", return_value=_STATUS) as status: with patch( @@ -86,8 +84,8 @@ class TestConnect: socket.disconnect() assert events == [("status_update", {"redacted": {}})] - status.assert_called_once_with(user_id=7) - assert join.call_args.kwargs == {"is_admin": False, "db_user_id": 7} + status.assert_called_once_with(user_id=alice["id"]) + assert join.call_args.kwargs == {"is_admin": False, "db_user_id": alice["id"]} def test_a_visitor_with_no_session_gets_an_empty_status(self, main_module, client): with patch.object(main_module, "get_auth_mode", return_value="builtin"):