Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(security): cross-user isolation for benchmark runs, research termination, and follow-up (#5600)

LearningCircuitfa466ad13de5
diff --git a/.pre-commit-hooks/check-research-id-type.py b/.pre-commit-hooks/check-research-id-type.py
index 6ff65c0865..83785aba1a 100755
--- a/.pre-commit-hooks/check-research-id-type.py
+++ b/.pre-commit-hooks/check-research-id-type.py
@@ -12,6 +12,62 @@ from pathlib import Path
# Set environment variable for pre-commit hooks to allow unencrypted databases
os.environ["LDR_ALLOW_UNENCRYPTED"] = "true"
+_REPO_ROOT = Path(__file__).resolve().parent.parent
+
+# Patterns to check for, as (id, regex, message). The id is what a file may be
+# sanctioned for below — exemptions are per-pattern, never whole-file, so a
+# sanctioned boundary file still gets every other check.
+_PATTERNS = [
+ # Flask route with int type
+ (
+ "route-int",
+ r"<int:research_id>",
+ "Flask route uses <int:research_id> - should be <string:research_id>",
+ ),
+ # Type hints with int
+ (
+ "int-hint",
+ r"research_id:\s*int",
+ "Type hint uses research_id: int - should be research_id: str",
+ ),
+ # Function parameters with int conversion
+ (
+ "int-cast",
+ r"int\(research_id\)",
+ "Converting research_id to int - research IDs are UUIDs/strings",
+ ),
+ # Integer comparison patterns
+ (
+ "int-compare",
+ r"research_id\s*==\s*\d+",
+ "Comparing research_id to integer - research IDs are UUIDs/strings",
+ ),
+]
+
+# The integer-research-id boundary, as repo-relative POSIX paths mapped to the
+# pattern ids each file is allowed to trip. Research IDs are UUID strings
+# everywhere except at the sanctioned benchmark boundary: ``BenchmarkRun.id``
+# is a per-user autoincrement integer, so the socket subscription key composes
+# the owner with an ``int`` benchmark id (see ``__subscription_key``).
+#
+# Anchored to the FULL repo-relative path, not the basename, so the repo-wide
+# ban cannot be defeated by picking a filename. Exemptions are per-pattern:
+# socket_service.py may cast a numeric benchmark id to int, but a stray
+# ``research_id: int`` hint or ``<int:research_id>`` route there still fails.
+_SANCTIONED_INT_BOUNDARY = {
+ "src/local_deep_research/web/services/socket_service.py": frozenset(
+ {"int-cast"}
+ ),
+}
+
+
+def _repo_rel_posix(filepath):
+ """Repo-relative POSIX path for ``filepath``, or ``None`` if outside repo."""
+ try:
+ return Path(filepath).resolve().relative_to(_REPO_ROOT).as_posix()
+ except ValueError:
+ return None
+
def check_file(filepath):
"""Check a single file for incorrect research_id patterns."""
@@ -20,36 +76,18 @@ def check_file(filepath):
with open(filepath, "r", encoding="utf-8") as f:
lines = f.readlines()
- # Patterns to check for
- patterns = [
- # Flask route with int type
- (
- r"<int:research_id>",
- "Flask route uses <int:research_id> - should be <string:research_id>",
- ),
- # Type hints with int
- (
- r"research_id:\s*int",
- "Type hint uses research_id: int - should be research_id: str",
- ),
- # Function parameters with int conversion
- (
- r"int\(research_id\)",
- "Converting research_id to int - research IDs are UUIDs/strings",
- ),
- # Integer comparison patterns
- (
- r"research_id\s*==\s*\d+",
- "Comparing research_id to integer - research IDs are UUIDs/strings",
- ),
- ]
+ sanctioned = _SANCTIONED_INT_BOUNDARY.get(
+ _repo_rel_posix(filepath), frozenset()
+ )
for line_num, line in enumerate(lines, 1):
# Skip comment and docstring lines — comments like
# "# Flask route: <int:research_id> (old API)" should not fire.
if line.lstrip().startswith(("#", '"""', "'''")):
continue
- for pattern, message in patterns:
+ for pattern_id, pattern, message in _PATTERNS:
+ if pattern_id in sanctioned:
+ continue
if re.search(pattern, line):
errors.append(f"{filepath}:{line_num}: {message}")
errors.append(f" {line.strip()}")
diff --git a/changelog.d/+benchmark-run-cross-user-isolation.security.md b/changelog.d/+benchmark-run-cross-user-isolation.security.md
new file mode 100644
index 0000000000..c7c85e741b
--- /dev/null
+++ b/changelog.d/+benchmark-run-cross-user-isolation.security.md
@@ -0,0 +1,11 @@
+Benchmark runs are now isolated per user in the in-process run registry. That
+registry was keyed by the benchmark run id — a **per-user** autoincrement
+integer, so two different users can each own a run with the same id (both have
+run 1). Because the id was trusted on its own, one signed-in user could cancel
+another user's in-flight benchmark (a denial of service), trigger a
+read/persist of another user's in-memory results, or observe their run state;
+and two users running a benchmark with the same id at the same time would
+**overwrite each other's entry**, crossing their results and — via the run's
+stored password — their credentials. The registry is now keyed by
+`(username, run id)`, so every operation only ever reaches the caller's own run
+and colliding per-user ids can no longer collide.
diff --git a/changelog.d/+followup-parent-ownership.security.md b/changelog.d/+followup-parent-ownership.security.md
new file mode 100644
index 0000000000..40ea70e825
--- /dev/null
+++ b/changelog.d/+followup-parent-ownership.security.md
@@ -0,0 +1,7 @@
+Starting a follow-up research now verifies you own the parent research.
+`POST /api/followup/start` prepared and spawned a follow-up without checking
+that `parent_research_id` belonged to the caller (unlike `/api/followup/prepare`,
+which returns 404). Research ids are per-user, so this could not read another
+user's research data (it lives in a separate encrypted database), but it let a
+user start a research thread referencing a parent that isn't theirs. `start`
+now applies the same 404 ownership check as `prepare`.
diff --git a/changelog.d/+research-terminate-cross-user.security.md b/changelog.d/+research-terminate-cross-user.security.md
new file mode 100644
index 0000000000..7ac9c26c06
--- /dev/null
+++ b/changelog.d/+research-terminate-cross-user.security.md
@@ -0,0 +1,6 @@
+Terminating a research run now verifies you own it. `cancel_research` (reached
+from `POST /research/api/terminate/<id>`) drove the process-global termination
+registry — keyed by research id alone and shared across users — before any
+ownership check, so a signed-in user who knew another user's research id could
+terminate that user's in-progress research. Ownership is now confirmed against
+the caller's own database before any global termination state is touched.
diff --git a/src/local_deep_research/benchmarks/web_api/benchmark_routes.py b/src/local_deep_research/benchmarks/web_api/benchmark_routes.py
index 980d26f284..29c5425af4 100644
--- a/src/local_deep_research/benchmarks/web_api/benchmark_routes.py
+++ b/src/local_deep_research/benchmarks/web_api/benchmark_routes.py
@@ -498,7 +498,7 @@ def get_benchmark_results(benchmark_run_id: int):
# First sync any pending results from active runs
benchmark_service.sync_pending_results(benchmark_run_id, username)
persistence_error = benchmark_service.get_result_persistence_error(
- benchmark_run_id
+ benchmark_run_id, username
)
with get_user_db_session(username) as session:
# Get recent results (limit to last 10)
diff --git a/src/local_deep_research/benchmarks/web_api/benchmark_service.py b/src/local_deep_research/benchmarks/web_api/benchmark_service.py
index 739bb57fa4..fe3d54d991 100644
--- a/src/local_deep_research/benchmarks/web_api/benchmark_service.py
+++ b/src/local_deep_research/benchmarks/web_api/benchmark_service.py
@@ -6,7 +6,7 @@ import threading
import time
from datetime import UTC, datetime
from enum import Enum
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict, List, Optional, Tuple
from loguru import logger
from sqlalchemy.exc import SQLAlchemyError
@@ -165,11 +165,14 @@ class BenchmarkService:
"""Service for managing benchmark runs through the web interface."""
def __init__(self, socket_service=None):
- self.active_runs: Dict[int, Dict] = {}
+ # Keyed by (username, BenchmarkRun.id). BenchmarkRun.id is a PER-USER
+ # autoincrement, so two users can each own run id 1; keying by the
+ # owner as well prevents one user's start_benchmark from clobbering
+ # another's in-memory run (and the cross-user reads that enabled).
+ self.active_runs: Dict[Tuple[str, int], Dict] = {}
self.socket_service = socket_service or self._get_socket_service()
- self.rate_limit_detected: Dict[
- int, bool
- ] = {} # Track rate limiting per benchmark run
+ # Track rate limiting per user benchmark run.
+ self.rate_limit_detected: Dict[Tuple[str, int], bool] = {}
self.queue_tracker = BenchmarkQueueTracker() # Initialize queue tracker
# Serializes benchmark-result persistence. _sync_results_to_database
# runs on the worker thread while sync_pending_results runs on the
@@ -376,23 +379,27 @@ class BenchmarkService:
benchmark_run.start_time = datetime.now(UTC)
session.commit()
- # Store data in memory for the thread
- self.active_runs[benchmark_run_id] = {
+ # Store data in memory for the thread. Key by (username, id) so a
+ # run another user owns under the same per-user id can't overwrite
+ # this entry (see _run_key).
+ run_key = self._run_key(username, benchmark_run_id)
+ self.active_runs[run_key] = {
"data": benchmark_data,
"start_time": datetime.now(UTC),
"status": "running",
"results": [],
}
- # Start background thread
+ # Start background thread. Pass the owner so the thread rebuilds the
+ # same composite key for its own active_runs accesses.
thread = threading.Thread(
target=self._run_benchmark_thread,
- args=(benchmark_run_id,),
+ args=(username, benchmark_run_id),
daemon=True,
)
thread.start()
- self.active_runs[benchmark_run_id]["thread"] = thread
+ self.active_runs[run_key]["thread"] = thread
logger.info(f"Started benchmark run {benchmark_run_id}")
return True
@@ -401,8 +408,11 @@ class BenchmarkService:
logger.exception(f"Error starting benchmark {benchmark_run_id}")
# If we populated active_runs before the spawn failed, drop the
# stale entry — it has no thread and would mislead subsequent
- # cancel_benchmark / get_run_status calls.
- self.active_runs.pop(benchmark_run_id, None)
+ # cancel_benchmark / get_run_status calls. Recompute the key here
+ # (the local run_key may not exist yet if we failed before it).
+ self.active_runs.pop(
+ self._run_key(username, benchmark_run_id), None
+ )
# Update status using user database
with get_user_db_session(username, user_password) as session:
benchmark_run = (
@@ -417,16 +427,20 @@ class BenchmarkService:
return False
@thread_cleanup
- def _run_benchmark_thread(self, benchmark_run_id: int):
+ def _run_benchmark_thread(
+ self, username: Optional[str], benchmark_run_id: int
+ ):
"""Main benchmark execution thread."""
# IMPORTANT: This runs in a background thread, so we cannot access the user database
# Using in-memory queue tracker for benchmark status tracking
task_id = None
+ # Rebuild the same composite key start_benchmark stored this run under.
+ run_key = self._run_key(username, benchmark_run_id)
# Get the benchmark data that was passed to us
# We need to retrieve this from the service database or from memory
- benchmark_data = self.active_runs.get(benchmark_run_id, {}).get("data")
+ benchmark_data = self.active_runs.get(run_key, {}).get("data")
try:
if not benchmark_data:
@@ -487,9 +501,8 @@ class BenchmarkService:
for i, task in enumerate(task_queue):
# Check if benchmark has been cancelled
if (
- benchmark_run_id in self.active_runs
- and self.active_runs[benchmark_run_id].get("status")
- == "cancelled"
+ run_key in self.active_runs
+ and self.active_runs[run_key].get("status") == "cancelled"
):
logger.info(
f"Benchmark {benchmark_run_id} was cancelled, stopping processing"
@@ -518,9 +531,9 @@ class BenchmarkService:
_global_research_semaphore.release()
# Store result in memory for now (will be saved later)
- if "results" not in self.active_runs[benchmark_run_id]:
- self.active_runs[benchmark_run_id]["results"] = []
- self.active_runs[benchmark_run_id]["results"].append(result)
+ if "results" not in self.active_runs[run_key]:
+ self.active_runs[run_key]["results"] = []
+ self.active_runs[run_key]["results"].append(result)
# Update progress
progress_info["completed_examples"] += 1
@@ -535,6 +548,7 @@ class BenchmarkService:
benchmark_run_id,
progress_info["completed_examples"],
progress_info["total_examples"],
+ username=username,
)
except Exception as e:
@@ -552,8 +566,12 @@ class BenchmarkService:
or "rate limit" in error_str
or "forbidden" in error_str
):
- self.rate_limit_detected[benchmark_run_id] = True
- # Send rate limit warning via WebSocket
+ self.rate_limit_detected[run_key] = True
+ # Send rate limit warning via WebSocket. Pass the
+ # run's owner so the socket service files this under
+ # the right per-user subscriber set -- benchmark_run_id
+ # is a per-user integer, so two users can share the
+ # same id (see SocketIOService.__subscription_key).
self.socket_service.emit_to_subscribers(
"research_progress",
benchmark_run_id,
@@ -561,6 +579,7 @@ class BenchmarkService:
"rate_limit_detected": True,
"message": "SearXNG rate limiting detected",
},
+ username=username,
)
# Mark as completed in memory tracker
@@ -568,9 +587,8 @@ class BenchmarkService:
# Check if benchmark was cancelled
was_cancelled = (
- benchmark_run_id in self.active_runs
- and self.active_runs[benchmark_run_id].get("status")
- == "cancelled"
+ run_key in self.active_runs
+ and self.active_runs[run_key].get("status") == "cancelled"
)
if was_cancelled:
@@ -589,14 +607,15 @@ class BenchmarkService:
)
# Store completion info for later database update
- self.active_runs[benchmark_run_id]["completion_info"] = {
+ self.active_runs[run_key]["completion_info"] = {
"status": status,
"end_time": progress_info["end_time"],
"completed_examples": progress_info["completed_examples"],
"failed_examples": progress_info["failed_examples"],
}
- # Send completion notification
+ # Send completion notification. Pass the owner so this reaches
+ # only their subscriber set (see rate-limit emit above for why).
self.socket_service.emit_to_subscribers(
"research_progress",
benchmark_run_id,
@@ -612,6 +631,7 @@ class BenchmarkService:
else 0,
"benchmark_run_id": benchmark_run_id,
},
+ username=username,
)
except Exception as e:
@@ -622,19 +642,19 @@ class BenchmarkService:
task_id, BenchmarkTaskStatus.FAILED
)
# Store failure info for later database update
- if benchmark_run_id in self.active_runs:
- self.active_runs[benchmark_run_id]["completion_info"] = {
+ if run_key in self.active_runs:
+ self.active_runs[run_key]["completion_info"] = {
"status": BenchmarkStatus.FAILED,
"error_message": str(e),
}
finally:
# Clean up active run tracking
- if benchmark_run_id in self.active_runs:
+ if run_key in self.active_runs:
# Mark that thread is done but keep data for database update
- self.active_runs[benchmark_run_id]["thread_complete"] = True
+ self.active_runs[run_key]["thread_complete"] = True
# Try to save results to database immediately if possible
- self._sync_results_to_database(benchmark_run_id)
+ self._sync_results_to_database(username, benchmark_run_id)
def _create_task_queue(
self,
@@ -768,11 +788,16 @@ class BenchmarkService:
), # Array format expected by socket.js
}
- # Emit using research_progress format that the UI expects
+ # Emit using research_progress format that the UI expects.
+ # Pass the owner (set on task before this callback's
+ # enclosing call, see _run_benchmark_thread) so this
+ # reaches only their subscriber set -- benchmark_run_id
+ # is a per-user integer and can collide across users.
self.socket_service.emit_to_subscribers(
"research_progress",
task["benchmark_run_id"],
progress_data,
+ username=task.get("username"),
)
except Exception:
@@ -1040,22 +1065,54 @@ class BenchmarkService:
return staged_indices
+ @staticmethod
+ def _run_key(
+ username: Optional[str], benchmark_run_id: int
+ ) -> Tuple[str, int]:
+ """Composite ``active_runs`` key: ``(username, BenchmarkRun.id)``.
+
+ ``active_runs`` is a process-global map, but ``BenchmarkRun.id`` is a
+ PER-USER autoincrement integer -- so two different users can each own a
+ run with the same id (e.g. both have id == 1). Keying by the owner too
+ means a request can only ever reach the caller's own in-flight run:
+ one user's ``start_benchmark`` cannot clobber another's entry, and no
+ user-facing lookup can name another user's run. ``username`` is
+ normalized the same way ``start_benchmark`` records it so the key a run
+ is stored under matches the key every later lookup computes.
+ """
+ return (username or "benchmark_user", benchmark_run_id)
+
+ @staticmethod
+ def _run_owner(run_data: Optional[Dict]) -> Optional[str]:
+ """Username that started the given in-memory run entry, if any."""
+ if not run_data:
+ return None
+ return run_data.get("data", {}).get("username")
+
def sync_pending_results(
self, benchmark_run_id: int, username: Optional[str] = None
):
"""Sync any pending results to database. Can be called from main thread."""
# Read outside _results_sync_lock, so the worker thread's
- # ``del self.active_runs[benchmark_run_id]`` (in _sync_results_to_database,
+ # ``del self.active_runs[run_key]`` (in _sync_results_to_database,
# also unlocked) can land between the membership check and the subscript.
- # A plain ``active_runs[id]`` would then raise KeyError, which escapes
+ # A plain ``active_runs[key]`` would then raise KeyError, which escapes
# before the try below and surfaces as a spurious 500 on /api/results.
# Fetch once so the check and the read see the same state. See #4859.
- run_data = self.active_runs.get(benchmark_run_id)
+ # active_runs is keyed by (username, id) (see _run_key), so this lookup
+ # can only ever return the caller's own run -- a caller naming another
+ # user's per-user id simply misses. That keeps one user's results (and,
+ # via the run's stored password, their credentials) unreachable here.
+ run_data = self.active_runs.get(
+ self._run_key(username, benchmark_run_id)
+ )
if run_data is None:
return 0
+ # For an anonymous/internal caller (username None) fall back to the
+ # owner recorded on the run for the DB session below.
if not username:
- username = run_data.get("data", {}).get("username")
+ username = self._run_owner(run_data)
user_password = run_data.get("data", {}).get("user_password")
saved_count = 0
@@ -1103,21 +1160,28 @@ class BenchmarkService:
return saved_count
def get_result_persistence_error(
- self, benchmark_run_id: int
+ self, benchmark_run_id: int, username: Optional[str] = None
) -> Optional[Dict[str, str]]:
"""Return a safe client-facing result persistence error, if active."""
- run_data = self.active_runs.get(benchmark_run_id)
+ # Keyed by (username, id) (see _run_key): a caller can only ever read
+ # the state of their own run, never one that belongs to someone else.
+ run_data = self.active_runs.get(
+ self._run_key(username, benchmark_run_id)
+ )
if not run_data or not run_data.get("result_persistence_failed"):
return None
# Return a copy so callers cannot mutate the shared constant.
return dict(_RESULT_PERSISTENCE_ERROR)
- def _sync_results_to_database(self, benchmark_run_id: int):
+ def _sync_results_to_database(
+ self, username: Optional[str], benchmark_run_id: int
+ ):
"""Sync benchmark results from memory to database after thread completes."""
- if benchmark_run_id not in self.active_runs:
+ run_key = self._run_key(username, benchmark_run_id)
+ if run_key not in self.active_runs:
return
- run_data = self.active_runs[benchmark_run_id]
+ run_data = self.active_runs[run_key]
if not run_data.get("thread_complete"):
return
@@ -1205,7 +1269,7 @@ class BenchmarkService:
)
# Clean up memory
- del self.active_runs[benchmark_run_id]
+ del self.active_runs[run_key]
except Exception:
logger.exception("Error syncing benchmark results to database")
@@ -1216,9 +1280,20 @@ class BenchmarkService:
run_data["result_persistence_failed"] = True
def _send_progress_update(
- self, benchmark_run_id: int, completed: int, total: int
+ self,
+ benchmark_run_id: int,
+ completed: int,
+ total: int,
+ username: Optional[str] = None,
):
- """Send real-time progress update via websocket."""
+ """Send real-time progress update via websocket.
+
+ ``username`` is the run's owner and is passed through to
+ ``emit_to_subscribers`` so the event reaches only that user's
+ socket subscriber set -- ``benchmark_run_id`` is a per-user integer
+ and can collide across users (see
+ ``SocketIOService.__subscription_key``).
+ """
try:
percentage = (completed / total * 100) if total > 0 else 0
@@ -1248,7 +1323,10 @@ class BenchmarkService:
}
self.socket_service.emit_to_subscribers(
- "research_progress", benchmark_run_id, progress_data
+ "research_progress",
+ benchmark_run_id,
+ progress_data,
+ username=username,
)
except Exception:
@@ -1520,8 +1598,16 @@ class BenchmarkService:
) -> bool:
"""Cancel a running benchmark."""
try:
- if benchmark_run_id in self.active_runs:
- self.active_runs[benchmark_run_id]["status"] = "cancelled"
+ # active_runs is keyed by (username, id) (see _run_key), so this
+ # lookup only ever finds the requester's own run -- one user can no
+ # longer set another user's in-flight run to "cancelled" and stop
+ # it (cross-user DoS). The DB update below is already scoped to the
+ # caller's own database.
+ run = self.active_runs.get(
+ self._run_key(username, benchmark_run_id)
+ )
+ if run is not None:
+ run["status"] = "cancelled"
self.update_benchmark_status(
benchmark_run_id, BenchmarkStatus.CANCELLED, username=username
diff --git a/src/local_deep_research/followup_research/routes.py b/src/local_deep_research/followup_research/routes.py
index a45d0da0d8..cb07c95995 100644
--- a/src/local_deep_research/followup_research/routes.py
+++ b/src/local_deep_research/followup_research/routes.py
@@ -179,6 +179,32 @@ def start_followup():
# Initialize service
service = FollowUpResearchService(username=username)
+ # Resolve the user's password (needed for metrics DB access later) and
+ # decide authentication FIRST. An expired encrypted-DB session is a 401,
+ # and it must be settled BEFORE the parent-ownership check below so an
+ # unauthenticated caller sees "session expired" (401), not the
+ # authorization outcome "parent not found" (404). Auth precedes authz.
+ user_password, session_expired = resolve_user_password(username)
+ if session_expired:
+ return jsonify(
+ {
+ "success": False,
+ "error": "Your session has expired. Please log out and log back in to start research.",
+ }
+ ), 401
+
+ # Reject a follow-up naming a parent research the caller does not own,
+ # mirroring /api/followup/prepare's 404 contract. Research ids are
+ # per-user (a different physical encrypted DB per user), so a parent id
+ # that isn't in the caller's DB is not theirs; without this a user could
+ # spawn a follow-up referencing another user's research_id (the parent
+ # context comes back empty, but a research thread would still start).
+ parent_id = data.get("parent_research_id")
+ if not parent_id or not service.load_parent_research(parent_id):
+ return jsonify(
+ {"success": False, "error": "Parent research not found"}
+ ), 404
+
# Prepare research parameters
research_params = service.perform_followup(followup_request)
@@ -193,21 +219,8 @@ def start_followup():
f"Query type: {type(research_params.get('query')) if isinstance(research_params, dict) else 'N/A'}"
)
- # Get user password for metrics database access.
- # Shared helper (password_utils) so every research entry point makes
- # the same encryption-aware decision and logs it the same way.
- # Must check BEFORE creating ResearchHistory to avoid orphaned records.
- user_password, session_expired = resolve_user_password(username)
-
- if session_expired:
- # Use success/error keys to match followup API convention
- # (the followup frontend checks data.success and data.error)
- return jsonify(
- {
- "success": False,
- "error": "Your session has expired. Please log out and log back in to start research.",
- }
- ), 401
+ # (user_password / session-expired 401 are resolved above, before the
+ # parent-ownership check, so auth precedes authz.)
# Pre-flight: refuse to spawn a research thread (and create an
# orphan ResearchHistory row) when llm.model is empty. Mirrors the
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 304a55ea3c..2365c514e5 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -3159,6 +3159,27 @@ def cancel_research(research_id, username):
try:
from ..routes.globals import is_research_active, set_termination_flag
+ # Ownership gate. research ids are per-user, but the global termination
+ # registry (_termination_flags / _active_research, keyed by id alone) is
+ # shared across all users. Without this check any signed-in user could
+ # terminate ANOTHER user's active research by id: the active branch
+ # below sets the flag and calls handle_termination before the only
+ # pre-existing ownership query (which lives in the not-active branch).
+ # Confirm the caller owns this research in their OWN database first.
+ with get_user_db_session(username) as _owner_check_session:
+ owns_research = (
+ _owner_check_session.query(ResearchHistory.id)
+ .filter_by(id=research_id)
+ .first()
+ is not None
+ )
+ if not owns_research:
+ logger.info(
+ f"Research {research_id} not found for this user; "
+ "refusing to cancel."
+ )
+ return False
+
# Set termination flag
set_termination_flag(research_id)
diff --git a/src/local_deep_research/web/services/socket_service.py b/src/local_deep_research/web/services/socket_service.py
index 9d3484abc9..e323f015a3 100644
--- a/src/local_deep_research/web/services/socket_service.py
+++ b/src/local_deep_research/web/services/socket_service.py
@@ -138,8 +138,10 @@ class SocketIOService:
if socketio_cors != "*":
_install_origin_rejection_logging(self.__socketio)
- # Socket subscription tracking.
- self.__socket_subscriptions: dict[str, Any] = {}
+ # Socket subscription tracking. Keyed by __subscription_key(...): a
+ # plain research_id for UUID-keyed research, or a (username, id)
+ # composite for numeric benchmark ids (see __subscription_key).
+ self.__socket_subscriptions: dict[Any, set[str]] = {}
# Set to false to disable logging in the event handlers. This can
# be necessary because it will sometimes run the handlers directly
# during a call to `emit` that was made in a logging handler.
@@ -226,6 +228,42 @@ class SocketIOService:
"""
return f"session:{session_id}"
+ @staticmethod
+ def __subscription_key(research_id: Any, username: str | None) -> Any:
+ """Key under which ``research_id``'s socket subscriptions are stored.
+
+ ``ResearchHistory.id`` is a globally-unique UUID string, so a plain
+ ``research_id`` is enough to key it -- no two users' research can
+ ever collide. ``BenchmarkRun.id`` is, by contrast, a PER-USER
+ autoincrement integer (see ``BenchmarkService._run_key``), so two
+ different users can each legitimately own a benchmark run with the
+ same id (e.g. both have id == 1). Keying subscriptions by bare
+ ``research_id`` alone would then file both users' sockets under the
+ same subscriber set, so each user's browser would receive the
+ other's ``research_progress_<id>`` events -- live queries, partial
+ results, rate-limit warnings.
+
+ Only numeric ids get the composite treatment: this mirrors the
+ ``str(research_id).isdigit()`` test ``_user_owns_research`` already
+ uses to decide whether an id might name a benchmark run instead of a
+ UUID research id, so subscribe-time authorization and subscription
+ storage agree on what counts as "a benchmark id". ``username`` is
+ normalized the same way ``BenchmarkService._run_key`` normalizes the
+ owner of an ``active_runs`` entry (``username or "benchmark_user"``)
+ so the two independent per-user-collision fixes share one key
+ convention instead of inventing a second.
+
+ The id is normalized to ``int`` inside the composite. Subscribe-time
+ ids arrive from a JSON socket payload and emit-time ids come from the
+ database, so the same run can present as ``"1"`` on one side and ``1``
+ on the other -- which would be two different dict keys and a silently
+ missed delivery. ``isdigit()`` has already guaranteed the conversion
+ is safe here.
+ """
+ if str(research_id).isdigit():
+ return (username or "benchmark_user", int(research_id))
+ return research_id
+
def emit_socket_event(self, event, data, room=None):
"""
Emit a socket event to clients.
@@ -251,7 +289,12 @@ class SocketIOService:
return False
def emit_to_subscribers(
- self, event_base, research_id, data, enable_logging: bool = True
+ self,
+ event_base,
+ research_id,
+ data,
+ enable_logging: bool = True,
+ username: str | None = None,
):
"""
Emit an event to all subscribers of a specific research.
@@ -263,6 +306,16 @@ class SocketIOService:
enable_logging: If set to false, this will disable all logging,
which is useful if we are calling this inside of a logging
handler.
+ username: Owner of ``research_id``. Required to reach the right
+ subscriber set when ``research_id`` is a numeric benchmark
+ id, since ``BenchmarkRun.id`` is a per-user integer and two
+ different users can own a run with the same id (see
+ ``__subscription_key``). Ignored for UUID-keyed research
+ ids, which have no collision surface. Callers that emit for
+ a benchmark run MUST pass the run's actual owner -- never a
+ guessed/default value -- or the event is filed under the
+ wrong subscriber set and either leaks to a different user's
+ socket or fails to reach the real owner.
Returns:
bool: True if emission was successful, False otherwise
@@ -273,11 +326,12 @@ class SocketIOService:
try:
full_event = f"{event_base}_{research_id}"
+ key = self.__subscription_key(research_id, username)
# Emit only to specific subscribers (no broadcast) to avoid
# duplicate messages and reduce server load under concurrency
with self.__lock:
- subscriptions = self.__socket_subscriptions.get(research_id)
+ subscriptions = self.__socket_subscriptions.get(key)
if subscriptions:
subscriptions = (
subscriptions.copy()
@@ -321,10 +375,20 @@ class SocketIOService:
finally:
self.__logging_enabled = True
- def remove_subscriptions_for_research(self, research_id: str) -> None:
- """Remove all socket subscriptions for a completed research."""
+ def remove_subscriptions_for_research(
+ self, research_id: str, username: str | None = None
+ ) -> None:
+ """Remove all socket subscriptions for a completed research.
+
+ ``username`` is only consulted when ``research_id`` is numeric (a
+ benchmark id) -- see ``__subscription_key``. Every current caller
+ passes a UUID research id, so omitting it is safe today, but a
+ future benchmark-completion caller must pass the run's owner or it
+ will pop the wrong (or a fabricated pseudo-owner's) subscriber set.
+ """
+ key = self.__subscription_key(research_id, username)
with self.__lock:
- removed = self.__socket_subscriptions.pop(research_id, None)
+ removed = self.__socket_subscriptions.pop(key, None)
if removed is not None:
self.__log_info(
f"Removed {len(removed)} subscription(s) for research {research_id}"
@@ -388,10 +452,10 @@ class SocketIOService:
# (which also takes the lock) never contends with us.
with self.__lock:
empty_keys = []
- for research_id, subscribed in self.__socket_subscriptions.items():
+ for key, subscribed in self.__socket_subscriptions.items():
subscribed.difference_update(sids)
if not subscribed:
- empty_keys.append(research_id)
+ empty_keys.append(key)
for key in empty_keys:
del self.__socket_subscriptions[key]
@@ -649,15 +713,18 @@ class SocketIOService:
f"Client {request.sid} disconnected because: {reason}"
)
# Clean up subscriptions for this client.
- # __socket_subscriptions is keyed by research_id → set of sids,
- # so we iterate all entries and discard the disconnecting sid.
+ # __socket_subscriptions is keyed by __subscription_key(...) →
+ # set of sids (plain research_id, or a (username, id) composite
+ # for benchmark ids -- see __subscription_key), so we iterate
+ # all entries and discard the disconnecting sid regardless of
+ # key shape.
with self.__lock:
self.__sid_sessions.pop(request.sid, None)
empty_keys = []
- for research_id, sids in self.__socket_subscriptions.items():
+ for key, sids in self.__socket_subscriptions.items():
sids.discard(request.sid)
if not sids:
- empty_keys.append(research_id)
+ empty_keys.append(key)
for key in empty_keys:
del self.__socket_subscriptions[key]
self.__log_info(f"Removed subscription for client {request.sid}")
@@ -712,10 +779,11 @@ class SocketIOService:
)
return
+ key = self.__subscription_key(research_id, username)
with self.__lock:
- if research_id not in self.__socket_subscriptions:
- self.__socket_subscriptions[research_id] = set()
- self.__socket_subscriptions[research_id].add(request.sid)
+ if key not in self.__socket_subscriptions:
+ self.__socket_subscriptions[key] = set()
+ self.__socket_subscriptions[key].add(request.sid)
self.__log_info(
f"Client {request.sid} subscribed to research {research_id}"
)
@@ -822,14 +890,15 @@ class SocketIOService:
)
return
+ key = self.__subscription_key(research_id, username)
with self.__lock:
- subs = self.__socket_subscriptions.get(research_id)
+ subs = self.__socket_subscriptions.get(key)
if subs:
subs.discard(request.sid)
# Prune empty sets so the dict doesn't grow unbounded with
# stale research_ids over long server runtimes.
if not subs:
- self.__socket_subscriptions.pop(research_id, None)
+ self.__socket_subscriptions.pop(key, None)
self.__log_info(
f"Client {request.sid} unsubscribed from research {research_id}"
)
diff --git a/tests/benchmarks/test_benchmark_service.py b/tests/benchmarks/test_benchmark_service.py
index 6b3105a68c..3c7512f3a6 100644
--- a/tests/benchmarks/test_benchmark_service.py
+++ b/tests/benchmarks/test_benchmark_service.py
@@ -261,14 +261,14 @@ class TestBenchmarkServiceActiveRuns:
mock_socket.return_value = Mock()
service = BenchmarkService()
- service.active_runs[1] = {
+ service.active_runs[("testuser", 1)] = {
"run_id": 1,
"status": "running",
"progress": 50,
}
- assert 1 in service.active_runs
- assert service.active_runs[1]["progress"] == 50
+ assert ("testuser", 1) in service.active_runs
+ assert service.active_runs[("testuser", 1)]["progress"] == 50
def test_rate_limit_tracking(self):
"""Test rate limit tracking per run."""
@@ -282,11 +282,11 @@ class TestBenchmarkServiceActiveRuns:
mock_socket.return_value = Mock()
service = BenchmarkService()
- service.rate_limit_detected[1] = True
- service.rate_limit_detected[2] = False
+ service.rate_limit_detected[("alice", 1)] = True
+ service.rate_limit_detected[("bob", 1)] = False
- assert service.rate_limit_detected[1] is True
- assert service.rate_limit_detected[2] is False
+ assert service.rate_limit_detected[("alice", 1)] is True
+ assert service.rate_limit_detected[("bob", 1)] is False
class TestBenchmarkQueueTrackerThreadSafety:
@@ -615,13 +615,18 @@ class TestBenchmarkServiceCancelBenchmark:
mock_socket = Mock()
service = BenchmarkService(socket_service=mock_socket)
- # Add an active run
- service.active_runs[1] = {"status": "running"}
+ # Add an active run owned by the cancelling user. active_runs is keyed
+ # by (username, id), so cancel only ever finds — and stops — the
+ # in-memory run belonging to the requesting user.
+ service.active_runs[("testuser", 1)] = {
+ "status": "running",
+ "data": {"username": "testuser"},
+ }
with patch.object(service, "update_benchmark_status"):
service.cancel_benchmark(1, username="testuser")
- assert service.active_runs[1]["status"] == "cancelled"
+ assert service.active_runs[("testuser", 1)]["status"] == "cancelled"
def test_cancel_returns_true_on_success(self):
"""Test that cancel returns True on success."""
@@ -632,7 +637,7 @@ class TestBenchmarkServiceCancelBenchmark:
mock_socket = Mock()
service = BenchmarkService(socket_service=mock_socket)
- service.active_runs[1] = {"status": "running"}
+ service.active_runs[("testuser", 1)] = {"status": "running"}
with patch.object(service, "update_benchmark_status"):
result = service.cancel_benchmark(1, username="testuser")
@@ -855,8 +860,11 @@ class TestBenchmarkServiceStartBenchmark:
)
assert result is True
- assert 1 in service.active_runs
- assert service.active_runs[1]["status"] == "running"
+ assert ("testuser", 1) in service.active_runs
+ assert (
+ service.active_runs[("testuser", 1)]["status"]
+ == "running"
+ )
def test_start_benchmark_stores_data_in_memory(self):
"""Test that start_benchmark stores benchmark data in memory."""
@@ -904,18 +912,69 @@ class TestBenchmarkServiceStartBenchmark:
):
service.start_benchmark(1, username="testuser")
- assert "data" in service.active_runs[1]
assert (
- service.active_runs[1]["data"][
+ "data" in service.active_runs[("testuser", 1)]
+ )
+ assert (
+ service.active_runs[("testuser", 1)]["data"][
"benchmark_run_id"
]
== 1
)
assert (
- service.active_runs[1]["data"]["username"]
+ service.active_runs[("testuser", 1)]["data"][
+ "username"
+ ]
== "testuser"
)
+ def test_start_benchmark_two_users_same_id_coexist(self):
+ """Two different users starting a run with the SAME per-user id must not
+ clobber each other in the process-global active_runs -- the exact write
+ collision the composite (username, id) key prevents. Drives the real
+ start_benchmark write path for both users (thread spawn mocked)."""
+ from local_deep_research.benchmarks.web_api.benchmark_service import (
+ BenchmarkService,
+ )
+
+ service = BenchmarkService(socket_service=Mock())
+
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session"
+ ) as mock_get_session:
+ mock_session = Mock()
+ mock_session.__enter__ = Mock(return_value=mock_session)
+ mock_session.__exit__ = Mock(return_value=False)
+ mock_get_session.return_value = mock_session
+
+ mock_run = Mock()
+ mock_run.id = 1 # the same per-user id for both users
+ mock_run.config_hash = "abc12345"
+ mock_run.datasets_config = {"simpleqa": {"count": 1}}
+ mock_run.search_config = {"iterations": 1}
+ mock_run.evaluation_config = {"model_name": "test"}
+ mock_session.query.return_value.filter.return_value.first.return_value = mock_run
+
+ with patch(
+ "local_deep_research.settings.SettingsManager"
+ ) as mock_settings_mgr:
+ mock_settings_mgr.return_value.get_all_settings.return_value = {}
+ with patch("flask.session", {"session_id": "sid"}):
+ with patch(
+ "local_deep_research.database.session_passwords.session_password_store"
+ ):
+ with patch.object(
+ service, "_run_benchmark_thread", return_value=None
+ ):
+ assert service.start_benchmark(1, username="alice")
+ assert service.start_benchmark(1, username="bob")
+
+ # Both users' id-1 runs live under distinct composite keys; the second
+ # start did not overwrite the first.
+ assert len(service.active_runs) == 2
+ assert service.active_runs[("alice", 1)]["data"]["username"] == "alice"
+ assert service.active_runs[("bob", 1)]["data"]["username"] == "bob"
+
def test_start_benchmark_handles_not_found(self):
"""Test that start_benchmark handles benchmark not found."""
from local_deep_research.benchmarks.web_api.benchmark_service import (
@@ -989,7 +1048,7 @@ class TestBenchmarkServiceStartBenchmark:
assert result is False
# active_runs must not retain the zombie entry.
- assert 42 not in service.active_runs
+ assert ("testuser", 42) not in service.active_runs
# BenchmarkRun.status was flipped to FAILED by the error handler.
assert mock_run.status == BenchmarkStatus.FAILED
diff --git a/tests/benchmarks/test_benchmark_service_snapshot.py b/tests/benchmarks/test_benchmark_service_snapshot.py
index cf9771e99f..525bc7aa33 100644
--- a/tests/benchmarks/test_benchmark_service_snapshot.py
+++ b/tests/benchmarks/test_benchmark_service_snapshot.py
@@ -130,7 +130,7 @@ def test_start_benchmark_does_not_mutate_in_memory_snapshot():
# The active_runs in-memory copy keeps the unredacted snapshot for the
# background thread (which needs the real keys to call providers).
assert (
- service.active_runs[1]["data"]["settings_snapshot"][
+ service.active_runs[("testuser", 1)]["data"]["settings_snapshot"][
"llm.openai.api_key"
]["value"]
== "sk-real-secret"
diff --git a/tests/benchmarks/web_api/test_benchmark_result_dedup.py b/tests/benchmarks/web_api/test_benchmark_result_dedup.py
index 03b8c1a1f4..962daccd1d 100644
--- a/tests/benchmarks/web_api/test_benchmark_result_dedup.py
+++ b/tests/benchmarks/web_api/test_benchmark_result_dedup.py
@@ -432,7 +432,7 @@ def test_real_sync_methods_acquire_the_lock():
target = "local_deep_research.database.session_context.get_user_db_session"
# sync_pending_results (request-thread path)
- svc.active_runs[1] = {
+ svc.active_runs[("u", 1)] = {
"data": {"username": "u", "user_password": None},
"results": [_result("a", "h1")],
}
@@ -444,7 +444,7 @@ def test_real_sync_methods_acquire_the_lock():
mock_session.query.return_value.filter.return_value.first.return_value = (
MagicMock(status=BenchmarkStatus.COMPLETED)
)
- svc.active_runs[2] = {
+ svc.active_runs[("u", 2)] = {
"data": {"username": "u", "user_password": None},
"results": [_result("b", "h2")],
"thread_complete": True,
@@ -455,7 +455,7 @@ def test_real_sync_methods_acquire_the_lock():
},
}
with patch(target, _mock_session_cm(mock_session)):
- svc._sync_results_to_database(2)
+ svc._sync_results_to_database("u", 2)
assert len(entries) == 2, "_sync_results_to_database did not enter the lock"
@@ -490,14 +490,14 @@ def test_real_sync_methods_commit_inside_the_lock():
target = "local_deep_research.database.session_context.get_user_db_session"
- svc.active_runs[1] = {
+ svc.active_runs[("u", 1)] = {
"data": {"username": "u", "user_password": None},
"results": [_result("a", "h1")],
}
with patch(target, _mock_session_cm(mock_session)):
svc.sync_pending_results(1, "u")
- svc.active_runs[2] = {
+ svc.active_runs[("u", 2)] = {
"data": {"username": "u", "user_password": None},
"results": [_result("b", "h2")],
"thread_complete": True,
@@ -508,7 +508,7 @@ def test_real_sync_methods_commit_inside_the_lock():
},
}
with patch(target, _mock_session_cm(mock_session)):
- svc._sync_results_to_database(2)
+ svc._sync_results_to_database("u", 2)
# Both methods committed, and the lock was held at each commit.
assert commit_held == [True, True], commit_held
@@ -535,7 +535,7 @@ def test_callers_do_not_mark_saved_on_commit_failure():
"data": {"username": "u", "user_password": None},
"results": [_result("a", "h1")],
}
- svc.active_runs[1] = run1
+ svc.active_runs[("u", 1)] = run1
with patch(target, _mock_session_cm(mock_session)):
svc.sync_pending_results(1, "u")
assert "saved_indices" not in run1, run1.get("saved_indices")
@@ -551,9 +551,9 @@ def test_callers_do_not_mark_saved_on_commit_failure():
"failed_examples": 0,
},
}
- svc.active_runs[2] = run2
+ svc.active_runs[("u", 2)] = run2
with patch(target, _mock_session_cm(mock_session)):
- svc._sync_results_to_database(2)
+ svc._sync_results_to_database("u", 2)
assert "saved_indices" not in run2, run2.get("saved_indices")
diff --git a/tests/benchmarks/web_api/test_benchmark_service_coverage.py b/tests/benchmarks/web_api/test_benchmark_service_coverage.py
index c484fe2976..8db0666dce 100644
--- a/tests/benchmarks/web_api/test_benchmark_service_coverage.py
+++ b/tests/benchmarks/web_api/test_benchmark_service_coverage.py
@@ -700,7 +700,7 @@ class TestSyncPendingResults:
assert svc.sync_pending_results(999) == 0
def test_returns_zero_when_entry_deleted_during_toctou_window(self):
- """The worker thread's ``del self.active_runs[id]`` can land between
+ """The worker thread's ``del self.active_runs[run_key]`` can land between
the membership check and the subscript in ``sync_pending_results``.
The read must not raise KeyError (which surfaces as a spurious 500 on
/api/results); a run that vanished has nothing pending. See #4859.
@@ -720,7 +720,7 @@ class TestSyncPendingResults:
def test_saves_new_results(self):
svc = _make_service()
- svc.active_runs[1] = {
+ svc.active_runs[("user1", 1)] = {
"data": {"username": "user1", "user_password": None},
"results": [
{
@@ -752,11 +752,11 @@ class TestSyncPendingResults:
assert count == 1
mock_session.add.assert_called_once()
mock_session.commit.assert_called_once()
- assert svc.get_result_persistence_error(1) is None
+ assert svc.get_result_persistence_error(1, "user1") is None
def test_skips_already_saved_indices(self):
svc = _make_service()
- svc.active_runs[1] = {
+ svc.active_runs[("user1", 1)] = {
"data": {"username": "user1", "user_password": None},
"results": [
{
@@ -783,13 +783,13 @@ class TestSyncPendingResults:
)
mock_get_session.return_value.__exit__ = Mock(return_value=False)
- count = svc.sync_pending_results(1)
+ count = svc.sync_pending_results(1, "user1")
assert count == 0
def test_skips_existing_db_result(self):
svc = _make_service()
- svc.active_runs[1] = {
+ svc.active_runs[("user1", 1)] = {
"data": {"username": "user1", "user_password": None},
"results": [
{
@@ -817,14 +817,14 @@ class TestSyncPendingResults:
)
mock_get_session.return_value.__exit__ = Mock(return_value=False)
- count = svc.sync_pending_results(1)
+ count = svc.sync_pending_results(1, "user1")
assert count == 0
mock_session.add.assert_not_called()
def test_handles_db_error(self):
svc = _make_service()
- svc.active_runs[1] = {
+ svc.active_runs[("user1", 1)] = {
"data": {"username": "user1", "user_password": None},
"results": [
{
@@ -849,17 +849,17 @@ class TestSyncPendingResults:
)
mock_get_session.return_value.__exit__ = Mock(return_value=False)
- count = svc.sync_pending_results(1)
+ count = svc.sync_pending_results(1, "user1")
assert count == 0
- error = svc.get_result_persistence_error(1)
+ error = svc.get_result_persistence_error(1, "user1")
assert error is not None
assert error["code"] == "database_write_failed"
assert "db error" not in error["message"]
def test_uses_username_from_run_data(self):
svc = _make_service()
- svc.active_runs[1] = {
+ svc.active_runs[("fromdata", 1)] = {
"data": {"username": "fromdata", "user_password": "pw"},
"results": [],
}
@@ -874,10 +874,43 @@ class TestSyncPendingResults:
)
mock_get_session.return_value.__exit__ = Mock(return_value=False)
- svc.sync_pending_results(1)
+ # active_runs is keyed by (username, id): an internal caller must
+ # name the owner to reach the run; the stored password still comes
+ # from run_data.
+ svc.sync_pending_results(1, "fromdata")
mock_get_session.assert_called_once_with("fromdata", "pw")
+ def test_anonymous_caller_falls_back_to_recorded_owner(self):
+ """When no username is passed (anonymous/internal caller), the run stored
+ under the normalized ``benchmark_user`` key is found and its recorded
+ owner drives the DB session -- exercising the ``if not username`` owner
+ fallback that the composite key otherwise makes unnecessary."""
+ svc = _make_service()
+ # An anonymous run is stored under the normalized owner "benchmark_user".
+ svc.active_runs[("benchmark_user", 1)] = {
+ "data": {"username": "benchmark_user", "user_password": "anon-pw"},
+ "results": [],
+ }
+
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session"
+ ) as mock_get_session:
+ mock_session = MagicMock()
+ mock_session.query.return_value.filter.return_value.all.return_value = []
+ mock_get_session.return_value.__enter__ = Mock(
+ return_value=mock_session
+ )
+ mock_get_session.return_value.__exit__ = Mock(return_value=False)
+
+ # No username -> _run_key(None, 1) == ("benchmark_user", 1) hits the
+ # anonymous run, then the fallback derives the owner for the session.
+ svc.sync_pending_results(1)
+
+ mock_get_session.assert_called_once_with(
+ "benchmark_user", "anon-pw"
+ )
+
# ============================================================
# _sync_results_to_database
@@ -888,12 +921,12 @@ class TestSyncResultsToDatabase:
def test_returns_early_if_no_active_run(self):
svc = _make_service()
# Should not raise
- svc._sync_results_to_database(999)
+ svc._sync_results_to_database("user1", 999)
def test_returns_early_if_thread_not_complete(self):
svc = _make_service()
- svc.active_runs[1] = {"thread_complete": False}
- svc._sync_results_to_database(1)
+ svc.active_runs[("user1", 1)] = {"thread_complete": False}
+ svc._sync_results_to_database("user1", 1)
# No DB calls expected
def test_syncs_completed_run(self):
@@ -902,7 +935,7 @@ class TestSyncResultsToDatabase:
)
svc = _make_service()
- svc.active_runs[1] = {
+ svc.active_runs[("user1", 1)] = {
"thread_complete": True,
"data": {"username": "user1", "user_password": None},
"completion_info": {
@@ -950,11 +983,11 @@ class TestSyncResultsToDatabase:
)
mock_get_session.return_value.__exit__ = Mock(return_value=False)
- svc._sync_results_to_database(1)
+ svc._sync_results_to_database("user1", 1)
mock_session.commit.assert_called_once()
# Active run should be cleaned up
- assert 1 not in svc.active_runs
+ assert ("user1", 1) not in svc.active_runs
def test_calculates_accuracy_correctly(self):
from local_deep_research.benchmarks.web_api.benchmark_service import (
@@ -962,7 +995,7 @@ class TestSyncResultsToDatabase:
)
svc = _make_service()
- svc.active_runs[1] = {
+ svc.active_runs[("user1", 1)] = {
"thread_complete": True,
"data": {"username": "user1", "user_password": None},
"completion_info": {
@@ -1009,7 +1042,7 @@ class TestSyncResultsToDatabase:
)
mock_get_session.return_value.__exit__ = Mock(return_value=False)
- svc._sync_results_to_database(1)
+ svc._sync_results_to_database("user1", 1)
# 2 correct out of 2 = 100%
assert mock_benchmark_run.overall_accuracy == 100.0
@@ -1020,7 +1053,7 @@ class TestSyncResultsToDatabase:
)
svc = _make_service()
- svc.active_runs[1] = {
+ svc.active_runs[("user1", 1)] = {
"thread_complete": True,
"data": {"username": "user1", "user_password": None},
"completion_info": {
@@ -1054,7 +1087,7 @@ class TestSyncResultsToDatabase:
)
mock_get_session.return_value.__exit__ = Mock(return_value=False)
- svc._sync_results_to_database(1)
+ svc._sync_results_to_database("user1", 1)
# Only the run status update, no result adds
assert mock_session.add.call_count == 0
@@ -1065,7 +1098,7 @@ class TestSyncResultsToDatabase:
)
svc = _make_service()
- svc.active_runs[1] = {
+ svc.active_runs[("user1", 1)] = {
"thread_complete": True,
"data": {"username": "user1", "user_password": None},
"completion_info": {
@@ -1083,9 +1116,9 @@ class TestSyncResultsToDatabase:
mock_get_session.return_value.__exit__ = Mock(return_value=False)
# Should not raise
- svc._sync_results_to_database(1)
+ svc._sync_results_to_database("user1", 1)
- error = svc.get_result_persistence_error(1)
+ error = svc.get_result_persistence_error(1, "user1")
assert error is not None
assert error["code"] == "database_write_failed"
@@ -1095,7 +1128,7 @@ class TestSyncResultsToDatabase:
)
svc = _make_service()
- svc.active_runs[1] = {
+ svc.active_runs[("user1", 1)] = {
"thread_complete": True,
"data": {"username": "user1", "user_password": None},
"completion_info": {
@@ -1131,7 +1164,7 @@ class TestSyncResultsToDatabase:
)
mock_get_session.return_value.__exit__ = Mock(return_value=False)
- svc._sync_results_to_database(1)
+ svc._sync_results_to_database("user1", 1)
# Should NOT set overall_accuracy for failed runs
# (the code only calculates accuracy when status == COMPLETED)
@@ -1344,13 +1377,19 @@ class TestUpdateBenchmarkStatus:
class TestCancelBenchmark:
def test_cancel_active_run(self):
svc = _make_service()
- svc.active_runs[1] = {"status": "running"}
+ # Owned by the cancelling user: active_runs is keyed by (username, id),
+ # so cancel only ever finds — and stops — the in-memory run for the
+ # requesting owner.
+ svc.active_runs[("user1", 1)] = {
+ "status": "running",
+ "data": {"username": "user1"},
+ }
with patch.object(svc, "update_benchmark_status"):
result = svc.cancel_benchmark(1, "user1")
assert result is True
- assert svc.active_runs[1]["status"] == "cancelled"
+ assert svc.active_runs[("user1", 1)]["status"] == "cancelled"
def test_cancel_nonexistent_run(self):
svc = _make_service()
@@ -1492,7 +1531,7 @@ class TestRunBenchmarkThread:
@patch(f"{SETTINGS_CTX_MODULE}.set_settings_context")
def test_thread_runs_tasks(self, mock_set_ctx, mock_semaphore):
svc = _make_service()
- svc.active_runs[1] = {
+ svc.active_runs[("user1", 1)] = {
"data": {
"username": "user1",
"user_password": None,
@@ -1525,16 +1564,16 @@ class TestRunBenchmarkThread:
patch.object(svc, "_send_progress_update"),
patch.object(svc, "_sync_results_to_database"),
):
- svc._run_benchmark_thread(1)
+ svc._run_benchmark_thread("user1", 1)
- assert len(svc.active_runs[1]["results"]) == 1
- assert svc.active_runs[1]["thread_complete"] is True
+ assert len(svc.active_runs[("user1", 1)]["results"]) == 1
+ assert svc.active_runs[("user1", 1)]["thread_complete"] is True
@patch(f"{MODULE}._global_research_semaphore")
@patch(f"{SETTINGS_CTX_MODULE}.set_settings_context")
def test_thread_handles_cancelled_run(self, mock_set_ctx, mock_semaphore):
svc = _make_service()
- svc.active_runs[1] = {
+ svc.active_runs[("user1", 1)] = {
"data": {
"username": "user1",
"user_password": None,
@@ -1562,9 +1601,9 @@ class TestRunBenchmarkThread:
),
patch.object(svc, "_sync_results_to_database"),
):
- svc._run_benchmark_thread(1)
+ svc._run_benchmark_thread("user1", 1)
- info = svc.active_runs[1]["completion_info"]
+ info = svc.active_runs[("user1", 1)]["completion_info"]
from local_deep_research.benchmarks.web_api.benchmark_service import (
BenchmarkStatus,
)
@@ -1577,7 +1616,7 @@ class TestRunBenchmarkThread:
self, mock_set_ctx, mock_semaphore
):
svc = _make_service()
- svc.active_runs[1] = {
+ svc.active_runs[("user1", 1)] = {
"data": {
"username": "user1",
"user_password": None,
@@ -1609,20 +1648,20 @@ class TestRunBenchmarkThread:
),
patch.object(svc, "_sync_results_to_database"),
):
- svc._run_benchmark_thread(1)
+ svc._run_benchmark_thread("user1", 1)
- assert svc.rate_limit_detected.get(1) is True
+ assert svc.rate_limit_detected == {("user1", 1): True}
@patch(f"{MODULE}._global_research_semaphore")
@patch(f"{SETTINGS_CTX_MODULE}.set_settings_context")
def test_thread_handles_missing_data(self, mock_set_ctx, mock_semaphore):
svc = _make_service()
- svc.active_runs[1] = {} # No "data" key
+ svc.active_runs[("user1", 1)] = {} # No "data" key
with patch.object(svc, "_sync_results_to_database"):
- svc._run_benchmark_thread(1)
+ svc._run_benchmark_thread("user1", 1)
- info = svc.active_runs[1]["completion_info"]
+ info = svc.active_runs[("user1", 1)]["completion_info"]
from local_deep_research.benchmarks.web_api.benchmark_service import (
BenchmarkStatus,
)
@@ -1634,7 +1673,7 @@ class TestRunBenchmarkThread:
def test_thread_settings_context_values(self, mock_set_ctx, mock_semaphore):
"""Test that SettingsContext correctly extracts values from setting objects."""
svc = _make_service()
- svc.active_runs[1] = {
+ svc.active_runs[("user1", 1)] = {
"data": {
"username": "user1",
"user_password": None,
@@ -1661,7 +1700,7 @@ class TestRunBenchmarkThread:
patch.object(svc, "_create_task_queue", return_value=[]),
patch.object(svc, "_sync_results_to_database"),
):
- svc._run_benchmark_thread(1)
+ svc._run_benchmark_thread("user1", 1)
ctx = captured_ctx["ctx"]
assert ctx.get_setting("key1") == "val1"
@@ -1675,7 +1714,7 @@ class TestRunBenchmarkThread:
):
"""Cover branch where total_examples is 0 for progress calculation."""
svc = _make_service()
- svc.active_runs[1] = {
+ svc.active_runs[("user1", 1)] = {
"data": {
"username": "user1",
"user_password": None,
@@ -1692,10 +1731,10 @@ class TestRunBenchmarkThread:
patch.object(svc, "_create_task_queue", return_value=[]),
patch.object(svc, "_sync_results_to_database"),
):
- svc._run_benchmark_thread(1)
+ svc._run_benchmark_thread("user1", 1)
# Completion should still happen (progress = 0 since total = 0)
- assert svc.active_runs[1]["thread_complete"] is True
+ assert svc.active_runs[("user1", 1)]["thread_complete"] is True
# ============================================================
diff --git a/tests/followup_research/test_routes_coverage.py b/tests/followup_research/test_routes_coverage.py
index ac7aae9a73..3abdf359bb 100644
--- a/tests/followup_research/test_routes_coverage.py
+++ b/tests/followup_research/test_routes_coverage.py
@@ -757,6 +757,13 @@ class TestStartFollowupException:
patch(AUTH_DB_MANAGER, _mock_auth()),
patch(SETTINGS_MANAGER, return_value=_make_settings_mock()),
_mock_db_session_ctx(),
+ # Auth precedes authz/business logic: give the caller a valid
+ # password so the 401 session-expired guard passes and the flow
+ # reaches perform_followup (which raises → the 500 under test).
+ patch(
+ f"{MODULE}.resolve_user_password",
+ return_value=("secret-password", False),
+ ),
patch(
f"{MODULE}.FollowUpResearchService", return_value=mock_service
),
diff --git a/tests/security/test_benchmark_cross_user_isolation.py b/tests/security/test_benchmark_cross_user_isolation.py
new file mode 100644
index 0000000000..f0d8b86d31
--- /dev/null
+++ b/tests/security/test_benchmark_cross_user_isolation.py
@@ -0,0 +1,208 @@
+"""Cross-user isolation for the in-memory benchmark run registry.
+
+``BenchmarkService.active_runs`` is process-global, but ``BenchmarkRun.id`` is a
+PER-USER autoincrement integer -- so two different users can each own a run with
+the same id (both have id == 1). The registry is therefore keyed by
+``(username, BenchmarkRun.id)``: a user-facing lookup can only ever reach the
+caller's OWN run, so a request that names another user's per-user id simply
+misses. Without that binding one user could:
+
+ * set another user's in-flight run to "cancelled" and stop it (cross-user DoS);
+ * trigger a read/persist of another user's in-memory results (disclosure, and
+ -- via the run's stored password -- a credential crossover between DBs);
+ * observe another user's run persistence-error state;
+ * clobber another user's live run by starting their own colliding id.
+
+This is the same bug class as the cached-connection auth bypass: an identifier
+(here the per-user integer id) trusted for authorization without being bound to
+the authenticated principal -- fixed here by binding the id to its owner in the
+key itself. These tests exercise the isolation directly on ``active_runs``
+state, mocking the database layer so only the in-memory logic is under test.
+"""
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from local_deep_research.benchmarks.web_api.benchmark_service import (
+ BenchmarkService,
+)
+
+
+def service():
+ """A fresh BenchmarkService with an empty in-memory registry."""
+ return BenchmarkService()
+
+
+def _seed_run(
+ service, run_id, owner, *, results=None, persistence_failed=False
+):
+ """Put an in-memory run owned by ``owner`` under the ``(owner, run_id)`` key
+ start_benchmark would use (the owner also lives at
+ run['data']['username'])."""
+ key = service._run_key(owner, run_id)
+ service.active_runs[key] = {
+ "data": {"username": owner, "user_password": f"{owner}-pw"},
+ "status": "running",
+ "results": list(results or []),
+ }
+ if persistence_failed:
+ service.active_runs[key]["result_persistence_failed"] = True
+ return service.active_runs[key]
+
+
+# --------------------------------------------------------------------------- #
+# cancel_benchmark
+# --------------------------------------------------------------------------- #
+def test_cancel_does_not_stop_another_users_run(service):
+ """A different user's cancel must NOT flip the in-memory run to cancelled.
+
+ The colliding-id scenario: alice owns the in-memory run at id 1; bob (who
+ also has his own id 1 in his own DB) POSTs /benchmark/api/cancel/1.
+ """
+ run = _seed_run(service, 1, "alice")
+
+ with patch.object(service, "update_benchmark_status") as upd:
+ # update_benchmark_status is DB-scoped to the caller (bob) and is
+ # irrelevant to the in-memory DoS -- mock it away.
+ assert service.cancel_benchmark(1, "bob") is True
+
+ assert run["status"] == "running", (
+ "bob's cancel must not stop alice's in-flight benchmark run"
+ )
+ # The DB update still runs, scoped to the caller's own database.
+ upd.assert_called_once()
+
+
+def test_cancel_stops_your_own_run(service):
+ run = _seed_run(service, 1, "alice")
+ with patch.object(service, "update_benchmark_status"):
+ assert service.cancel_benchmark(1, "alice") is True
+ assert run["status"] == "cancelled", (
+ "the owner's cancel must stop their own run"
+ )
+
+
+def test_cancel_unknown_run_is_harmless(service):
+ with patch.object(service, "update_benchmark_status"):
+ assert service.cancel_benchmark(999, "alice") is True
+ assert service._run_key("alice", 999) not in service.active_runs
+
+
+# --------------------------------------------------------------------------- #
+# sync_pending_results
+# --------------------------------------------------------------------------- #
+def test_sync_pending_results_refuses_cross_user(service):
+ """bob syncing alice's run must be refused (0) and must NOT open any DB or
+ read alice's results."""
+ _seed_run(service, 1, "alice", results=[{"secret": "alice-only"}])
+
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session"
+ ) as gud:
+ saved = service.sync_pending_results(1, "bob")
+
+ assert saved == 0, "a cross-user result sync must persist nothing"
+ # A refused cross-user sync must never open a database session -- no read of
+ # alice's results, and no credential crossover via the run's stored password.
+ gud.assert_not_called()
+
+
+def test_sync_pending_results_owner_passes_the_gate(service):
+ """The owner is allowed past the gate and opens THEIR OWN db session."""
+ _seed_run(service, 1, "alice", results=[])
+
+ ctx = MagicMock()
+ ctx.__enter__.return_value = MagicMock()
+ ctx.__exit__.return_value = False
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ return_value=ctx,
+ ) as gud:
+ with patch.object(service, "_persist_unsaved_results", return_value=[]):
+ service.sync_pending_results(1, "alice")
+
+ gud.assert_called_once()
+ # Opened as alice, with alice's stored password -- never crossed.
+ args, kwargs = gud.call_args
+ called_with = list(args) + list(kwargs.values())
+ assert "alice" in called_with and "alice-pw" in called_with
+
+
+def test_sync_pending_results_unknown_run_returns_zero(service):
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session"
+ ) as gud:
+ assert service.sync_pending_results(1234, "alice") == 0
+ gud.assert_not_called()
+
+
+# --------------------------------------------------------------------------- #
+# get_result_persistence_error
+# --------------------------------------------------------------------------- #
+def test_persistence_error_not_disclosed_cross_user(service):
+ _seed_run(service, 1, "alice", persistence_failed=True)
+
+ assert service.get_result_persistence_error(1, "bob") is None, (
+ "bob must not observe alice's run persistence-error state"
+ )
+ # The owner still sees their own error.
+ assert service.get_result_persistence_error(1, "alice") is not None
+
+
+def test_persistence_error_none_when_not_failed(service):
+ _seed_run(service, 1, "alice", persistence_failed=False)
+ assert service.get_result_persistence_error(1, "alice") is None
+
+
+# --------------------------------------------------------------------------- #
+# write-collision: colliding per-user ids must not clobber each other
+# --------------------------------------------------------------------------- #
+def test_two_users_colliding_ids_coexist(service):
+ """The core write-collision fix. alice and bob can each own run id 1 at the
+ same time; keying by (username, id) keeps both entries distinct instead of
+ the second start_benchmark overwriting the first -- an overwrite that would
+ cross the two users' results (and, via the run's stored password, their
+ credentials)."""
+ alice_run = _seed_run(service, 1, "alice", results=[{"r": "alice-1"}])
+ bob_run = _seed_run(service, 1, "bob", results=[{"r": "bob-1"}])
+
+ # Neither seed overwrote the other: two distinct entries remain. Assert
+ # against the REGISTRY (re-fetched by key), never the captured references --
+ # a captured ref survives even if its entry was evicted, so reading it back
+ # would pass under a regression that collapsed both users onto one key.
+ # `len == 2` and the identity re-fetch both fail if the keys collapse.
+ assert len(service.active_runs) == 2
+ stored_alice = service.active_runs[service._run_key("alice", 1)]
+ stored_bob = service.active_runs[service._run_key("bob", 1)]
+ assert stored_alice is alice_run
+ assert stored_bob is bob_run
+ assert alice_run is not bob_run
+
+ # Each key holds its own owner's results and password -- never crossed.
+ assert stored_alice["results"] == [{"r": "alice-1"}]
+ assert stored_bob["results"] == [{"r": "bob-1"}]
+ assert stored_alice["data"]["user_password"] == "alice-pw"
+ assert stored_bob["data"]["user_password"] == "bob-pw"
+
+
+def test_cancel_with_colliding_ids_targets_only_the_caller(service):
+ """With both users holding id 1, bob's cancel stops only bob's run."""
+ _seed_run(service, 1, "alice")
+ _seed_run(service, 1, "bob")
+ # Two distinct entries to begin with -- guards against a collapsed key that
+ # would make the assertions below vacuous.
+ assert len(service.active_runs) == 2
+
+ with patch.object(service, "update_benchmark_status"):
+ assert service.cancel_benchmark(1, "bob") is True
+
+ # Re-fetch each entry by key (not a captured reference): bob's is cancelled,
+ # alice's is untouched.
+ assert (
+ service.active_runs[service._run_key("bob", 1)]["status"] == "cancelled"
+ )
+ assert (
+ service.active_runs[service._run_key("alice", 1)]["status"] == "running"
+ ), "cancelling bob's id-1 run must not touch alice's id-1 run"
diff --git a/tests/security/test_notes_chat_followup_cross_user.py b/tests/security/test_notes_chat_followup_cross_user.py
new file mode 100644
index 0000000000..99dcd027ba
--- /dev/null
+++ b/tests/security/test_notes_chat_followup_cross_user.py
@@ -0,0 +1,574 @@
+"""Cross-user IDOR regression suite for the Notes, Chat, and Follow-up-Research
+HTTP APIs.
+
+Same bug class as the fixed cross-user issues (cached-connection auth bypass
+#5596, benchmark active_runs cross-user leak, research cancel_research missing
+ownership check): an authenticated user must never be able to read, list,
+create-on, or mutate ANOTHER user's objects by supplying that object's id.
+
+Architecture recap (see notes/chat/followup route + service source):
+ * Every user has their OWN encrypted SQLCipher database, opened via
+ ``get_user_db_session(username)`` where ``username`` always comes from
+ ``session["username"]`` (never from client-supplied request data) in
+ every route touched below.
+ * NoteService(username), ChatService(username), and
+ FollowUpResearchService(username=username) all resolve *every* query
+ through that per-user database, so an id belonging to another user's
+ database simply does not exist in the caller's database.
+ * The invariant under test: supplying another user's object id (note_id,
+ chat session_id, research_id) must 404 / be excluded from listings /
+ fail to attach, never return or mutate that user's data.
+
+Fixture pattern mirrors ``tests/security/test_login_cached_connection_password_route.py``
+and the sibling ``newtests2_crossuser_isolation.py``: the module-level
+``db_manager`` singleton is shared by every blueprint, so the fixture uses the
+real singleton and only isolates + restores its data dir. Data is seeded
+through the REAL authenticated HTTP endpoints (not raw ORM pokes) so the
+tests exercise the exact same code path an attacker would.
+"""
+
+import uuid
+from contextlib import contextmanager
+from datetime import datetime, timezone
+from unittest.mock import patch
+
+import pytest
+
+
+# ---------------------------------------------------------------------------
+# App fixture (real singleton db_manager, isolated data dir)
+# ---------------------------------------------------------------------------
+def app_client(tmp_path, monkeypatch):
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+ monkeypatch.setenv("LDR_TESTING_WITH_MOCKS", "true")
+ monkeypatch.setenv("LDR_DISABLE_RATE_LIMITING", "true")
+ monkeypatch.setenv("LDR_RATE_LIMITING_ENABLED", "false")
+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")
+
+ from local_deep_research.database.auth_db import init_auth_database
+ from local_deep_research.database.encrypted_db import db_manager
+ from local_deep_research.web.app_factory import create_app
+ import local_deep_research.web.auth.routes as auth_routes
+
+ if not db_manager.has_encryption:
+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")
+
+ original_data_dir = db_manager.data_dir
+ try:
+ db_manager.data_dir = tmp_path / "encrypted_databases"
+ init_auth_database()
+
+ app, _ = create_app()
+ app.config["TESTING"] = True
+ app.config["WTF_CSRF_ENABLED"] = False
+ app.config["WTF_CSRF_CHECK_DEFAULT"] = False
+ app.config["SESSION_COOKIE_SECURE"] = False
+ app.config["PREFERRED_URL_SCHEME"] = "http"
+
+ # Keep the synchronous test off the real post-login worker threads.
+ monkeypatch.setattr(
+ auth_routes, "_perform_post_login_tasks", lambda _u, _p: None
+ )
+
+ yield app, db_manager
+ finally:
+ try:
+ from local_deep_research.security.account_lockout import (
+ get_account_lockout_manager,
+ )
+
+ get_account_lockout_manager()._state.clear()
+ except Exception:
+ pass
+ db_manager.close_all_databases()
+ db_manager.data_dir = original_data_dir
+
+
+# ---------------------------------------------------------------------------
+# Registration / login / seeding helpers
+# ---------------------------------------------------------------------------
+def _register(client, username, password):
+ return client.post(
+ "/auth/register",
+ data={
+ "username": username,
+ "password": password,
+ "confirm_password": password,
+ "acknowledge": "true",
+ },
+ follow_redirects=False,
+ )
+
+
+def _login(client, username, password):
+ return client.post(
+ "/auth/login",
+ data={"username": username, "password": password},
+ follow_redirects=False,
+ )
+
+
+class _User:
+ """A registered + logged-in user with a live authenticated test client."""
+
+ def __init__(self, app, tag):
+ self.username = f"{tag}_{uuid.uuid4().hex[:10]}"
+ self.password = f"P@ss-{tag}-{uuid.uuid4().hex[:8]}"
+ reg = _register(app.test_client(), self.username, self.password)
+ assert reg.status_code in (200, 302), (
+ f"registration failed for {self.username}: {reg.status_code}"
+ )
+ self.client = app.test_client()
+ login = _login(self.client, self.username, self.password)
+ assert login.status_code == 302, (
+ f"login failed for {self.username}: {login.status_code}"
+ )
+
+ def seed_llm_model_setting(self, model_name="test-model"):
+ """Give this user a non-empty llm.model setting so
+ /api/followup/start's pre-flight model check doesn't 400 before
+ reaching the code path under test."""
+ from local_deep_research.database.session_context import (
+ get_user_db_session,
+ )
+ from local_deep_research.database.models.settings import (
+ Setting,
+ SettingType,
+ )
+
+ with get_user_db_session(self.username, self.password) as s:
+ existing = (
+ s.query(Setting).filter(Setting.key == "llm.model").first()
+ )
+ if existing:
+ existing.value = model_name
+ else:
+ s.add(
+ Setting(
+ key="llm.model",
+ value=model_name,
+ type=SettingType.LLM,
+ name="llm.model",
+ ui_element="text",
+ category="llm",
+ visible=True,
+ editable=True,
+ )
+ )
+ s.commit()
+
+ def seed_research(self, research_id, query, title, report="body"):
+ """Directly write a completed ResearchHistory row into THIS user's
+ own encrypted DB (bypasses the real research pipeline; used as the
+ the "parent"/"linked" research object for notes/followup tests)."""
+ from local_deep_research.database.session_context import (
+ get_user_db_session,
+ )
+ from local_deep_research.database.models import ResearchHistory
+
+ now = datetime.now(timezone.utc).isoformat()
+ with get_user_db_session(self.username, self.password) as s:
+ s.add(
+ ResearchHistory(
+ id=research_id,
+ query=query,
+ mode="quick_summary",
+ status="completed",
+ created_at=now,
+ completed_at=now,
+ duration_seconds=1,
+ progress=100,
+ title=title,
+ report_content=report,
+ )
+ )
+ s.commit()
+
+ # --- Notes, via the real API ---
+ def create_note(self, title, content):
+ resp = self.client.post(
+ "/notes/api/notes",
+ json={"title": title, "content": content},
+ )
+ assert resp.status_code == 201, resp.get_data(as_text=True)
+ return resp.get_json()["id"]
+
+ # --- Chat, via the real API ---
+ def create_chat_session(self, title):
+ resp = self.client.post(
+ "/api/chat/sessions",
+ json={"title": title},
+ )
+ assert resp.status_code == 200, resp.get_data(as_text=True)
+ return resp.get_json()["session_id"]
+
+ def send_chat_message(self, session_id, content):
+ """Send a message WITHOUT triggering research (keeps the test
+ hermetic — no search/LLM stack needed)."""
+ resp = self.client.post(
+ f"/api/chat/sessions/{session_id}/messages",
+ json={"content": content, "trigger_research": False},
+ )
+ assert resp.status_code == 200, resp.get_data(as_text=True)
+ return resp.get_json()["message_id"]
+
+
+def two_users(app_client):
+ """Two fully-provisioned users A and B, each with distinguishable
+ notes, chat sessions/messages, and a seeded "completed" research run."""
+ app, db_manager = app_client
+ a = _User(app, "alice")
+ b = _User(app, "bob")
+
+ a.marker = f"ALICE_MARKER_{uuid.uuid4().hex[:8]}"
+ b.marker = f"BOB_MARKER_{uuid.uuid4().hex[:8]}"
+
+ # Research (used both standalone and as the notes "linked research" /
+ # followup "parent research" target).
+ a.research_id = str(uuid.uuid4())
+ b.research_id = str(uuid.uuid4())
+ a.seed_research(a.research_id, f"query {a.marker}", f"title {a.marker}")
+ b.seed_research(b.research_id, f"query {b.marker}", f"title {b.marker}")
+
+ # Needed so /api/followup/start's pre-flight "llm.model configured"
+ # check doesn't 400 before reaching the ownership-scoping code path.
+ a.seed_llm_model_setting()
+ b.seed_llm_model_setting()
+
+ # Notes.
+ a.note_id = a.create_note(f"Note {a.marker}", f"content {a.marker}")
+ b.note_id = b.create_note(f"Note {b.marker}", f"content {b.marker}")
+
+ # Chat sessions + one message each.
+ a.session_id = a.create_chat_session(f"Chat {a.marker}")
+ b.session_id = b.create_chat_session(f"Chat {b.marker}")
+ a.message_id = a.send_chat_message(a.session_id, f"hello {a.marker}")
+ b.message_id = b.send_chat_message(b.session_id, f"hello {b.marker}")
+
+ return app, a, b
+
+
+@contextmanager
+def _no_spawn():
+ """Patch out the actual research-thread spawn so /api/followup/start can
+ be exercised without a real search/LLM stack. We only care whether the
+ route/service layer rejects (or accepts) a cross-user parent_research_id
+ BEFORE any thread would be spawned.
+
+ ``start_followup`` imports ``start_research_process`` INSIDE the view
+ function body (``from ..web.services.research_service import
+ start_research_process, ...``), so the name to patch is the real
+ definition site, not an attribute of the routes module.
+ """
+ with patch(
+ "local_deep_research.web.services.research_service.start_research_process"
+ ) as mock_start:
+ mock_start.return_value = None
+ yield mock_start
+
+
+# ===========================================================================
+# Notes blueprint (/notes/api/...)
+# ===========================================================================
+def test_notes_list_scoped_to_session_user(two_users):
+ app, a, b = two_users
+ resp = a.client.get("/notes/api/notes")
+ assert resp.status_code == 200
+ body = resp.get_data(as_text=True)
+ assert a.marker in body, "A must see its own notes"
+ assert b.marker not in body, "A must NOT see B's notes in the list"
+
+
+def test_notes_get_idor_blocked(two_users):
+ app, a, b = two_users
+ ok = a.client.get(f"/notes/api/notes/{a.note_id}")
+ assert ok.status_code == 200
+ leaked = a.client.get(f"/notes/api/notes/{b.note_id}")
+ assert leaked.status_code == 404, (
+ "A must not read B's note via /notes/api/notes/<id> IDOR"
+ )
+ assert b.marker not in leaked.get_data(as_text=True)
+
+
+def test_notes_update_idor_blocked(two_users):
+ app, a, b = two_users
+ resp = a.client.put(
+ f"/notes/api/notes/{b.note_id}",
+ json={"title": "PWNED", "content": "PWNED"},
+ )
+ assert resp.status_code == 404, (
+ "A must not be able to update B's note by id"
+ )
+ # B's note must be unchanged.
+ still_b = b.client.get(f"/notes/api/notes/{b.note_id}")
+ assert still_b.status_code == 200
+ assert "PWNED" not in still_b.get_data(as_text=True)
+ assert b.marker in still_b.get_data(as_text=True)
+
+
+def test_notes_delete_idor_blocked(two_users):
+ app, a, b = two_users
+ resp = a.client.delete(f"/notes/api/notes/{b.note_id}")
+ assert resp.status_code == 404, (
+ "A must not be able to delete B's note by id"
+ )
+ still_b = b.client.get(f"/notes/api/notes/{b.note_id}")
+ assert still_b.status_code == 200, (
+ "B's note must survive A's delete attempt"
+ )
+
+
+def test_notes_collections_idor_blocked(two_users):
+ app, a, b = two_users
+ resp = a.client.get(f"/notes/api/notes/{b.note_id}/collections")
+ assert resp.status_code == 404
+
+
+def test_notes_link_research_no_cross_user_row_persisted(two_users):
+ """A cannot end up with a persisted NoteResearch link from A's note to
+ B's research_id.
+
+ NOTE: this only asserts the underlying DATA-ISOLATION invariant (no
+ cross-user row is ever committed) -- it deliberately does NOT assert on
+ the HTTP status code here. As of this run, POST
+ /notes/api/notes/<note_id>/research with a foreign research_id returns
+ HTTP 500 instead of the intended 404 ("Research run not found") --
+ tracked in #5721 (notes_routes.py's IntegrityError handler never
+ matches on the encrypted DB backend). No B data is returned and no link
+ is created either way, so isolation holds even though the error-status
+ contract is broken. Narrow this to ``== 404`` when #5721 lands.
+ """
+ app, a, b = two_users
+ resp = a.client.post(
+ f"/notes/api/notes/{a.note_id}/research",
+ json={"research_id": b.research_id},
+ )
+ assert resp.status_code in (404, 500), resp.get_data(as_text=True)
+ assert b.marker not in resp.get_data(as_text=True)
+
+ # No NoteResearch row was persisted linking A's note to B's research,
+ # from either A's or B's point of view.
+ linked = a.client.get(f"/notes/api/notes/{a.note_id}/research")
+ assert linked.status_code == 200
+ assert b.research_id not in linked.get_data(as_text=True)
+
+ # A's own research_id links fine (positive control) -- the endpoint
+ # works correctly for a same-user, valid research_id.
+ ok = a.client.post(
+ f"/notes/api/notes/{a.note_id}/research",
+ json={"research_id": a.research_id},
+ )
+ assert ok.status_code == 201, ok.get_data(as_text=True)
+
+
+def test_research_notes_panel_idor_blocked(two_users):
+ """GET/POST /api/research/<research_id>/notes scoped to caller's own
+ research."""
+ app, a, b = two_users
+ leaked = a.client.get(f"/notes/api/research/{b.research_id}/notes")
+ assert leaked.status_code == 404
+
+ created = a.client.post(
+ f"/notes/api/research/{b.research_id}/notes",
+ json={"title": "x", "content": "y"},
+ )
+ assert created.status_code == 404, (
+ "A must not be able to create a note pre-linked to B's research"
+ )
+
+
+def test_research_save_as_note_idor_blocked(two_users):
+ app, a, b = two_users
+ resp = a.client.post(f"/notes/api/research/{b.research_id}/save-as-note")
+ assert resp.status_code == 404
+
+
+def test_research_annotations_idor_blocked(two_users):
+ app, a, b = two_users
+ leaked = a.client.get(f"/notes/api/research/{b.research_id}/annotations")
+ assert leaked.status_code == 404
+
+ created = a.client.post(
+ f"/notes/api/research/{b.research_id}/annotations",
+ json={"quote": "q", "comment": "c"},
+ )
+ assert created.status_code == 404, (
+ "A must not be able to annotate B's research report"
+ )
+
+
+# ===========================================================================
+# Chat blueprint (/api/chat/...)
+# ===========================================================================
+def test_chat_sessions_list_scoped_to_session_user(two_users):
+ app, a, b = two_users
+ resp = a.client.get("/api/chat/sessions")
+ assert resp.status_code == 200
+ body = resp.get_data(as_text=True)
+ assert a.marker in body, "A must see its own chat sessions"
+ assert b.marker not in body, "A must NOT see B's chat sessions in the list"
+
+
+def test_chat_get_session_idor_blocked(two_users):
+ app, a, b = two_users
+ ok = a.client.get(f"/api/chat/sessions/{a.session_id}")
+ assert ok.status_code == 200
+ leaked = a.client.get(f"/api/chat/sessions/{b.session_id}")
+ assert leaked.status_code == 404, (
+ "A must not read B's chat session via IDOR"
+ )
+ assert b.marker not in leaked.get_data(as_text=True)
+
+
+def test_chat_get_messages_idor_blocked(two_users):
+ app, a, b = two_users
+ ok = a.client.get(f"/api/chat/sessions/{a.session_id}/messages")
+ assert ok.status_code == 200
+ leaked = a.client.get(f"/api/chat/sessions/{b.session_id}/messages")
+ assert leaked.status_code == 404, (
+ "A must not read B's chat messages via IDOR"
+ )
+ assert b.marker not in leaked.get_data(as_text=True)
+
+
+def test_chat_post_message_idor_blocked(two_users):
+ """A cannot post a message ONTO B's chat session by id."""
+ app, a, b = two_users
+ resp = a.client.post(
+ f"/api/chat/sessions/{b.session_id}/messages",
+ json={"content": "injected", "trigger_research": False},
+ )
+ assert resp.status_code == 404, (
+ "A must not be able to send a message into B's chat session"
+ )
+ # B's session must show no trace of A's message.
+ still_b = b.client.get(f"/api/chat/sessions/{b.session_id}/messages")
+ assert still_b.status_code == 200
+ assert "injected" not in still_b.get_data(as_text=True)
+
+
+def test_chat_update_session_idor_blocked(two_users):
+ app, a, b = two_users
+ resp = a.client.patch(
+ f"/api/chat/sessions/{b.session_id}",
+ json={"title": "PWNED"},
+ )
+ assert resp.status_code == 404, (
+ "A must not be able to rename/archive B's chat session"
+ )
+ still_b = b.client.get(f"/api/chat/sessions/{b.session_id}")
+ assert still_b.status_code == 200
+ assert "PWNED" not in still_b.get_data(as_text=True)
+
+
+def test_chat_delete_session_idor_blocked(two_users):
+ app, a, b = two_users
+ resp = a.client.delete(f"/api/chat/sessions/{b.session_id}")
+ assert resp.status_code == 404, (
+ "A must not be able to delete B's chat session"
+ )
+ still_b = b.client.get(f"/api/chat/sessions/{b.session_id}")
+ assert still_b.status_code == 200, (
+ "B's session must survive A's delete attempt"
+ )
+
+
+def test_chat_generate_title_idor_blocked(two_users):
+ app, a, b = two_users
+ resp = a.client.post(
+ f"/api/chat/sessions/{b.session_id}/generate-title",
+ json={"query": "what is this about"},
+ )
+ assert resp.status_code == 404
+
+
+def test_chat_delete_attempt_idor_blocked(two_users):
+ """A cannot delete a chat "attempt" (message+research turn) scoped to
+ B's session, even when supplying A's OWN research_id as the attempt id
+ (the session_id ownership check must fire first)."""
+ app, a, b = two_users
+ resp = a.client.delete(
+ f"/api/chat/sessions/{b.session_id}/attempts/{a.research_id}"
+ )
+ assert resp.status_code == 404
+
+
+# ===========================================================================
+# Follow-up research blueprint (/api/followup/...)
+# ===========================================================================
+def test_followup_prepare_idor_blocked(two_users):
+ app, a, b = two_users
+ resp = a.client.post(
+ "/api/followup/prepare",
+ json={
+ "parent_research_id": b.research_id,
+ "question": "tell me more",
+ },
+ )
+ assert resp.status_code == 404, (
+ "A must not be able to prepare a follow-up against B's research"
+ )
+ assert b.marker not in resp.get_data(as_text=True)
+
+
+def test_followup_prepare_own_research_succeeds(two_users):
+ """Positive control: A can prepare a follow-up against A's own research."""
+ app, a, b = two_users
+ resp = a.client.post(
+ "/api/followup/prepare",
+ json={
+ "parent_research_id": a.research_id,
+ "question": "tell me more",
+ },
+ )
+ assert resp.status_code == 200, resp.get_data(as_text=True)
+ body = resp.get_json()
+ assert body["success"] is True
+ assert body["parent_research"]["id"] == a.research_id
+
+
+def test_followup_start_idor_blocked(two_users):
+ """A must not be able to start a follow-up research "on" B's
+ research_id. Mirrors /api/followup/prepare's 404 contract for the same
+ cross-user id.
+
+ See notes/newtests3_notes_chat_followup_isolation.py module docstring
+ for context; this is the assertion the task explicitly calls out
+ ("A cannot start a followup on B's research id").
+ """
+ app, a, b = two_users
+ with _no_spawn() as mock_start:
+ resp = a.client.post(
+ "/api/followup/start",
+ json={
+ "parent_research_id": b.research_id,
+ "question": "tell me more",
+ },
+ )
+ assert resp.status_code == 404, (
+ "A must not be able to start a follow-up referencing B's "
+ f"research_id (got {resp.status_code}: "
+ f"{resp.get_data(as_text=True)})"
+ )
+ assert mock_start.called is False, (
+ "no research thread should ever be spawned for a rejected "
+ "cross-user follow-up"
+ )
+
+
+def test_followup_start_own_research_succeeds(two_users):
+ app, a, b = two_users
+ with _no_spawn() as mock_start:
+ resp = a.client.post(
+ "/api/followup/start",
+ json={
+ "parent_research_id": a.research_id,
+ "question": "tell me more",
+ },
+ )
+
+ assert resp.status_code == 200, resp.get_data(as_text=True)
+ assert resp.get_json()["success"] is True
+ mock_start.assert_called_once()
diff --git a/tests/security/test_research_terminate_cross_user.py b/tests/security/test_research_terminate_cross_user.py
new file mode 100644
index 0000000000..b482598d10
--- /dev/null
+++ b/tests/security/test_research_terminate_cross_user.py
@@ -0,0 +1,104 @@
+"""Cross-user isolation for research termination.
+
+``cancel_research`` (reached from ``POST /research/api/terminate/<id>`` via
+``api_terminate_research``) drives the PROCESS-GLOBAL termination registry
+(``_termination_flags`` / ``_active_research`` in ``web/routes/globals.py``),
+which is keyed by ``research_id`` alone and shared across all users. Before the
+fix it called ``set_termination_flag`` and, for an active run,
+``handle_termination`` *before* any ownership check (the only pre-existing DB
+ownership query lived in the not-active branch). So a signed-in user who knew
+another user's research id could terminate that user's in-progress research
+(cross-user denial of service).
+
+Same bug class as the cached-connection auth bypass (#5596): an identifier
+acted on against shared global state without being bound to the authenticated
+principal. The fix confirms the caller owns the research in their OWN database
+before touching any global termination state.
+
+These tests exercise the ownership gate directly, mocking the DB and the global
+registry so only the authorization ordering is under test.
+"""
+
+from unittest.mock import MagicMock
+
+import pytest
+
+from local_deep_research.web.services import research_service as rs
+import local_deep_research.web.routes.globals as gl
+
+
+def _db_ctx(first_return):
+ """A ``with get_user_db_session(...) as session`` mock whose
+ ``session.query(...).filter_by(...).first()`` yields ``first_return``."""
+ session = MagicMock()
+ session.query.return_value.filter_by.return_value.first.return_value = (
+ first_return
+ )
+ ctx = MagicMock()
+ ctx.__enter__.return_value = session
+ ctx.__exit__.return_value = False
+ return ctx
+
+
+def patched(monkeypatch):
+ """Patch the global termination registry + handle_termination and return
+ the mocks so tests can assert whether they were touched."""
+ set_flag = MagicMock()
+ is_active = MagicMock(return_value=True)
+ handle = MagicMock()
+ monkeypatch.setattr(gl, "set_termination_flag", set_flag)
+ monkeypatch.setattr(gl, "is_research_active", is_active)
+ monkeypatch.setattr(rs, "handle_termination", handle)
+ return set_flag, is_active, handle
+
+
+def test_cancel_research_refuses_when_caller_does_not_own_it(
+ monkeypatch, patched
+):
+ """The security fix: a research id not in the caller's own database must be
+ refused BEFORE any global termination state is touched -- otherwise a user
+ could terminate another user's active research by id."""
+ set_flag, is_active, handle = patched
+ # research id is NOT in alice's database.
+ monkeypatch.setattr(
+ rs, "get_user_db_session", MagicMock(return_value=_db_ctx(None))
+ )
+
+ result = rs.cancel_research("bob-research-uuid", "alice")
+
+ assert result is False
+ set_flag.assert_not_called() # never sets the global termination flag
+ is_active.assert_not_called() # never even consults the shared registry
+ handle.assert_not_called()
+
+
+def test_cancel_research_terminates_your_own_active_research(
+ monkeypatch, patched
+):
+ """The owner's terminate still works: an owned, active research sets the
+ flag and calls handle_termination."""
+ set_flag, is_active, handle = patched
+ # research id IS in alice's database (truthy row).
+ monkeypatch.setattr(
+ rs,
+ "get_user_db_session",
+ MagicMock(return_value=_db_ctx(MagicMock())),
+ )
+
+ result = rs.cancel_research("alice-research-uuid", "alice")
+
+ assert result is True
+ set_flag.assert_called_once_with("alice-research-uuid")
+ handle.assert_called_once()
+
+
+def test_cancel_research_fails_closed_on_db_error(monkeypatch, patched):
+ """If the caller's ownership lookup cannot even be performed, refuse --
+ never fall through to touching the global registry."""
+ set_flag, _is_active, _handle = patched
+ boom = MagicMock(side_effect=RuntimeError("db down"))
+ monkeypatch.setattr(rs, "get_user_db_session", boom)
+
+ assert rs.cancel_research("some-uuid", "alice") is False
+ set_flag.assert_not_called()
diff --git a/tests/web/queue/test_queued_research_lifecycle_races.py b/tests/web/queue/test_queued_research_lifecycle_races.py
index d685313d83..79bf9996de 100644
--- a/tests/web/queue/test_queued_research_lifecycle_races.py
+++ b/tests/web/queue/test_queued_research_lifecycle_races.py
@@ -220,8 +220,11 @@ def test_cancel_does_not_cleanup_queued_research_after_claim(
patch(f"{GLOBALS_MODULE}.set_termination_flag"),
patch(f"{GLOBALS_MODULE}.is_research_active", return_value=False),
patch(
+ # Fresh CM per call: cancel_research's ownership gate opens the
+ # session once before the cancel path re-opens it, so a single-use
+ # return_value CM would be exhausted on the second enter.
f"{SERVICE_MODULE}.get_user_db_session",
- return_value=user_db_session(db_session),
+ side_effect=lambda *a, **k: user_db_session(db_session),
),
):
result = cancel_research("claimed", "alice")
diff --git a/tests/web/services/test_research_service.py b/tests/web/services/test_research_service.py
index 85c88be0b1..bcbf29649e 100644
--- a/tests/web/services/test_research_service.py
+++ b/tests/web/services/test_research_service.py
@@ -497,6 +497,10 @@ class TestCleanupResearchResources:
class TestCancelResearch:
"""Tests for cancel_research function."""
+ @patch(
+ "local_deep_research.web.services.research_service.get_user_db_session",
+ MagicMock(),
+ )
@patch(
"local_deep_research.web.routes.globals.is_research_active",
return_value=True,
@@ -508,6 +512,8 @@ class TestCancelResearch:
def test_cancel_research_sets_termination_flag(
self, mock_handle_termination, mock_set_flag, mock_is_active
):
+ # Ownership gate now reads the caller's DB first; a MagicMock session
+ # makes the ownership query return a row so the owner is authorized.
"""cancel_research sets termination flag."""
from local_deep_research.web.services.research_service import (
cancel_research,
diff --git a/tests/web/services/test_research_service_coverage.py b/tests/web/services/test_research_service_coverage.py
index 70276f79e5..e5237f0972 100644
--- a/tests/web/services/test_research_service_coverage.py
+++ b/tests/web/services/test_research_service_coverage.py
@@ -451,6 +451,9 @@ class TestCancelResearch:
@patch(f"{RS}.handle_termination")
def test_active_research_cancelled(self, mock_handle):
with (
+ # Ownership gate reads the caller's DB first; a mock session makes
+ # the ownership query return a row so the owner is authorized.
+ patch(f"{RS}.get_user_db_session", _fake_session_ctx(MagicMock())),
patch(
"local_deep_research.web.routes.globals.set_termination_flag"
) as mock_flag,
diff --git a/tests/web/services/test_research_service_coverage_gaps.py b/tests/web/services/test_research_service_coverage_gaps.py
index c975791d59..e3d6b805d1 100644
--- a/tests/web/services/test_research_service_coverage_gaps.py
+++ b/tests/web/services/test_research_service_coverage_gaps.py
@@ -1066,7 +1066,12 @@ class TestCancelResearchOuterException:
mock_handle = MagicMock()
- with patch(f"{GLOBALS_MOD}.set_termination_flag"):
+ with (
+ # Ownership gate reads the caller's DB first; a mock session makes
+ # the ownership query return a row so the owner is authorized.
+ patch(f"{MODULE}.get_user_db_session", _fake_session_ctx()),
+ patch(f"{GLOBALS_MOD}.set_termination_flag"),
+ ):
with patch(f"{GLOBALS_MOD}.is_research_active", return_value=True):
with patch(f"{MODULE}.handle_termination", mock_handle):
result = cancel_research(10, username="user1")
diff --git a/tests/web/services/test_research_service_extra_coverage.py b/tests/web/services/test_research_service_extra_coverage.py
index 47d3c92079..ec357fe12a 100644
--- a/tests/web/services/test_research_service_extra_coverage.py
+++ b/tests/web/services/test_research_service_extra_coverage.py
@@ -66,6 +66,9 @@ class TestCancelResearch:
)
with (
+ # Ownership gate reads the caller's DB first; a mock session makes
+ # the ownership query return a row so the owner is authorized.
+ patch(f"{MODULE}.get_user_db_session", _fake_session_ctx()),
patch(f"{GLOBALS_MOD}.set_termination_flag") as mock_flag,
patch(f"{GLOBALS_MOD}.is_research_active", return_value=True),
patch(f"{MODULE}.handle_termination") as mock_term,
diff --git a/tests/web_services/test_socket_service.py b/tests/web_services/test_socket_service.py
index b4dd655832..075843c10c 100644
--- a/tests/web_services/test_socket_service.py
+++ b/tests/web_services/test_socket_service.py
@@ -1023,3 +1023,159 @@ class TestSocketIOServiceLogging:
service._SocketIOService__log_exception("Exception message")
mock_logger.exception.assert_not_called()
+
+
+class TestSocketIOServiceBenchmarkSubscriptionIsolation:
+ """Two users can each own a benchmark run with the same integer id.
+
+ ``BenchmarkRun.id`` is a per-user autoincrement integer (unlike
+ ``ResearchHistory.id``, a globally-unique UUID), so two different
+ users' first benchmark run both have id == 1. ``_user_owns_research``
+ correctly confirms each of them owns *a* run with that id, but unless
+ the subscription registry itself is scoped per user, both sockets are
+ filed under the same subscriber set and each user's browser receives
+ the other's ``research_progress_1`` events (live queries, partial
+ results, rate-limit warnings).
+
+ Note: Singleton reset is handled by the global reset_all_singletons
+ fixture in tests/conftest.py.
+ """
+
+ @pytest.fixture
+ def service_with_mocks(self, mock_flask_app):
+ """Create service with accessible internal state."""
+ from local_deep_research.web.services.socket_service import (
+ SocketIOService,
+ )
+
+ mock_socketio = MagicMock()
+
+ with patch(
+ "local_deep_research.web.services.socket_service.SocketIO",
+ return_value=mock_socketio,
+ ):
+ service = SocketIOService(app=mock_flask_app)
+ service._SocketIOService__socketio = mock_socketio
+ return service, mock_socketio
+
+ @staticmethod
+ def _subscribe_as(svc, sid, username, research_id):
+ """Drive __handle_subscribe as if ``username`` owns the socket.
+
+ Overrides (for the duration of this call only) the module-level
+ ``session`` and ``validate_session`` the directory's autouse
+ ``_allow_socket_subscribe`` fixture already patches, so each call
+ can simulate a *different* logged-in user rather than the fixed
+ "test-owner" every other test in this file relies on.
+ """
+ module_path = "local_deep_research.web.services.socket_service"
+ mock_request = Mock()
+ mock_request.sid = sid
+ with (
+ patch(
+ f"{module_path}.session",
+ {"username": username, "session_id": f"sess-{username}"},
+ ),
+ patch(
+ "local_deep_research.web.auth.session_manager."
+ "session_manager.validate_session",
+ return_value=username,
+ ),
+ ):
+ svc._SocketIOService__handle_subscribe(
+ {"research_id": research_id}, mock_request
+ )
+
+ def test_same_id_benchmark_runs_do_not_cross_deliver(
+ self, service_with_mocks
+ ):
+ """Alice's and Bob's id-1 runs must not leak into each other."""
+ svc, mock_socketio = service_with_mocks
+
+ self._subscribe_as(svc, "sid-alice", "alice", 1)
+ self._subscribe_as(svc, "sid-bob", "bob", 1)
+ mock_socketio.emit.reset_mock()
+
+ result = svc.emit_to_subscribers(
+ "research_progress", 1, {"progress": 42}, username="alice"
+ )
+
+ assert result is True
+ emitted_rooms = {
+ call.kwargs.get("room")
+ for call in mock_socketio.emit.call_args_list
+ }
+ # Bob's socket must never appear here.
+ assert emitted_rooms == {"sid-alice"}
+
+ def test_string_and_int_benchmark_ids_are_one_subscription(
+ self, service_with_mocks
+ ):
+ """Subscribing with "1" must receive an emit made with 1.
+
+ Subscribe-time ids arrive from a JSON socket payload; emit-time ids
+ come from the database. Without normalizing the id inside the
+ composite key those are two distinct dict keys, so the legitimate
+ owner silently receives nothing -- a missed delivery rather than a
+ leak, but invisible either way.
+ """
+ svc, mock_socketio = service_with_mocks
+
+ self._subscribe_as(svc, "sid-alice", "alice", "1")
+ mock_socketio.emit.reset_mock()
+
+ result = svc.emit_to_subscribers(
+ "research_progress", 1, {"progress": 42}, username="alice"
+ )
+
+ assert result is True
+ emitted_rooms = {
+ call.kwargs.get("room")
+ for call in mock_socketio.emit.call_args_list
+ }
+ assert emitted_rooms == {"sid-alice"}
+
+ def test_legitimate_owner_still_receives_own_benchmark_events(
+ self, service_with_mocks
+ ):
+ """The real owner must still get their own benchmark's events."""
+ svc, mock_socketio = service_with_mocks
+
+ self._subscribe_as(svc, "sid-alice", "alice", 1)
+ self._subscribe_as(svc, "sid-bob", "bob", 1)
+ mock_socketio.emit.reset_mock()
+
+ result = svc.emit_to_subscribers(
+ "research_progress", 1, {"progress": 99}, username="bob"
+ )
+
+ assert result is True
+ mock_socketio.emit.assert_any_call(
+ "research_progress_1", {"progress": 99}, room="sid-bob"
+ )
+ emitted_rooms = {
+ call.kwargs.get("room")
+ for call in mock_socketio.emit.call_args_list
+ }
+ assert emitted_rooms == {"sid-bob"}
+
+ def test_uuid_research_subscriptions_unaffected_by_username(
+ self, service_with_mocks
+ ):
+ """UUID-keyed research ids have no per-user collision surface, so
+ emit_to_subscribers must reach the subscriber regardless of which
+ (or whether any) username is passed.
+ """
+ svc, mock_socketio = service_with_mocks
+
+ self._subscribe_as(svc, "sid-alice", "alice", "research-abc-123")
+ mock_socketio.emit.reset_mock()
+
+ result = svc.emit_to_subscribers(
+ "progress", "research-abc-123", {"progress": 10}
+ )
+
+ assert result is True
+ mock_socketio.emit.assert_any_call(
+ "progress_research-abc-123", {"progress": 10}, room="sid-alice"
+ )