~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
test(security): deep DB-connection security tests for the #5596 incident class (#5654)
LearningCircuita2218172eb9a
diff --git a/.github/workflows/docker-tests.yml b/.github/workflows/docker-tests.ymlindex 9d880df901..3a3f279e75 100644--- a/.github/workflows/docker-tests.yml+++ b/.github/workflows/docker-tests.yml@@ -219,8 +219,8 @@ jobs:id: main_pytest# Tests are always blocking - failures should not be silently ignored.# Emits the final coverage xml + html reports and enforces the 50%- # fail-under gate. (fd_canary tests are still split into a dedicated- # serial step below — see that step's comment.)+ # fail-under gate. (fd_canary, serial, and nonroot tests are split+ # into dedicated steps below — see each step's comment.)## Historical note (#4402): the deleted Flask file# tests/web/routes/test_settings_routes_coverage.py had 94@@ -270,7 +270,7 @@ jobs:-v \--durations=20 \-n auto \- -m 'not integration and not fd_canary' \+ -m 'not integration and not fd_canary and not serial and not nonroot' \--ignore=tests/ui_tests \--ignore=tests/infrastructure_tests \--ignore=tests/api_tests_with_login \@@ -282,24 +282,126 @@ jobs:# destabilized xdist workers.# Run them in a dedicated SERIAL step with NO coverage and NO '-n auto'# so the FD-count signal stays deterministic (~10s) without flaking.+ #+ # Scoped to the SAME tree (tests/, minus the same --ignore list) as+ # the '-m not fd_canary' exclusion in the main step above, not to a+ # single hardcoded file. A hardcoded-file scope silently drops any+ # future fd_canary-marked test added outside that one file: excluded+ # from the parallel lane by the tree-wide marker, but never picked up+ # here -- it would vanish from CI entirely. The four --ignore'd+ # directories are skipped for the same reason the main step skips+ # them (ui_tests/infrastructure_tests need browsers/node harnesses+ # not set up in this step; api_tests_with_login and fuzz have their+ # own dedicated runners).+ #+ # Modules this lane collects at the time of writing:+ # fd_canary tests/utilities/test_close_base_llm.py+ # DELETING THEM ALL EMPTIES THE LANE: pytest exits 5 ("no tests+ # collected") and this step fails hard (cf. #4411). If the last+ # marked module goes away, delete this step in the same change.- name: Run fd_canary FD-leak tests (serial, no coverage)if: always()run: |- docker run --rm \+ docker run --rm -t \-v "$PWD":/app \-e CI=true \-e GITHUB_ACTIONS=true \-e LDR_TESTING_WITH_MOCKS=true \-e LDR_DISABLE_RATE_LIMITING=true \+ -e PYTHONUNBUFFERED=1 \+ -e LDR_NEWS_SCHEDULER_ENABLED=false \-e PYTHONPATH=/app/src \-w /app \${{ env.TEST_IMAGE }} \- sh -c "python -m pytest tests/utilities/test_close_base_llm.py \+ sh -c "python -m pytest tests/ \-m fd_canary \-p no:cov \--tb=short \--no-header \- -q"+ -v \+ --color=no \+ --ignore=tests/ui_tests \+ --ignore=tests/infrastructure_tests \+ --ignore=tests/api_tests_with_login \+ --ignore=tests/fuzz"++ # 'serial' and 'nonroot' tests share one step because they need the+ # same runner: no '-n auto' (serial mutates process-global state --+ # os.umask -- for the duration of an assertion, so a concurrently+ # running test in the same xdist worker would inherit it) and a+ # genuinely unprivileged uid (permission bits are not enforced for+ # root, so a nonroot test self-skips as root). Selector is+ # '-m serial or nonroot', so a module carrying BOTH markers runs here+ # exactly once. They stay two DISTINCT markers -- see their docstrings+ # in pyproject.toml -- because tagging a non-mutating permission test+ # 'serial' would be a false claim about what it does; only the CI lane+ # is shared.+ #+ # Modules this lane collects at the time of writing:+ # serial tests/security/test_db_connection_umask_perms.py+ # nonroot tests/security/test_db_connection_umask_perms.py+ # tests/security/test_db_connection_create_hostile_dir.py+ # tests/security/test_db_connection_readonly_hostile_fs.py+ # DELETING ALL OF THEM EMPTIES THE LANE: pytest exits 5 ("no tests+ # collected") and this step fails hard -- the same class of breakage+ # as #4411, which is why the security-tests.yml comment stopped+ # enumerating files. If the last marked module goes away, delete this+ # step (and the markers) in the same change.+ #+ # Scoped to the SAME tree (tests/, minus the SAME four --ignore paths)+ # as the '-m not serial and not nonroot' exclusion in the main step+ # above, not to tests/security. A tests/security-only scope would+ # silently drop any future serial/nonroot test added elsewhere:+ # excluded from the parallel lane by the tree-wide marker, but never+ # picked up here -- it would vanish from CI entirely (same class of+ # gap as the fd_canary step above).+ #+ # '--user ldruser' doesn't need write access to the bind-mounted /app+ # checkout -- this step writes no coverage/junit output and pytest's+ # test artifacts (tmp_path, the DB files under test) live under the+ # container-local /tmp via pytest's own tmp_path fixture, not /app.+ # '-p no:cacheprovider' avoids pytest trying (and silently failing) to+ # write its .pytest_cache dir into the root-owned /app mount.+ # '-e HOME=/home/ldruser': cheap insurance, not a known failure --+ # 'docker run --user ldruser' does not itself export HOME, and this+ # Dockerfile's own entrypoint (scripts/ldr_entrypoint.sh) explicitly+ # sets HOME=/home/ldruser before switching to ldruser via setpriv, so+ # an unset/root-owned $HOME under an equivalent uid-switch here is a+ # plausible failure mode worth pre-empting.+ # '-t', 'PYTHONUNBUFFERED=1' and '-v' are the live-progress trio the+ # main step's own comment documents: without them a hang in this lane+ # is invisible until the timeout-minutes backstop kills the job.+ # '-e LDR_NEWS_SCHEDULER_ENABLED=false' matches the main step for+ # parity; the news scheduler is only read in the FastAPI lifespan,+ # which a pytest lane never enters, so this is a no-op here today.+ - name: Run serial + nonroot (process-global state, permission-bit) tests+ if: always()+ run: |+ docker run --rm -t \+ --user ldruser \+ -v "$PWD":/app \+ -e CI=true \+ -e GITHUB_ACTIONS=true \+ -e LDR_TESTING_WITH_MOCKS=true \+ -e LDR_DISABLE_RATE_LIMITING=true \+ -e PYTHONUNBUFFERED=1 \+ -e LDR_NEWS_SCHEDULER_ENABLED=false \+ -e PYTHONPATH=/app/src \+ -e HOME=/home/ldruser \+ -w /app \+ ${{ env.TEST_IMAGE }} \+ sh -c "python -m pytest tests/ \+ -m 'serial or nonroot' \+ -p no:cov \+ -p no:cacheprovider \+ --tb=short \+ --no-header \+ -v \+ --color=no \+ --ignore=tests/ui_tests \+ --ignore=tests/infrastructure_tests \+ --ignore=tests/api_tests_with_login \+ --ignore=tests/fuzz"- name: Run JavaScript infrastructure testsif: always()diff --git a/.github/workflows/security-tests.yml b/.github/workflows/security-tests.ymlindex 2d8700b529..a7bda741b1 100644--- a/.github/workflows/security-tests.yml+++ b/.github/workflows/security-tests.yml@@ -105,7 +105,34 @@ jobs:# code 5 ("no tests collected") and failed this gate (#4411).# Running the directory picks up new security tests automatically and# never rots when files move.- pdm run python -m pytest tests/security/ -v --tb=short -n auto+ #+ # 'serial' tests mutate PROCESS-GLOBAL state (os.umask) for the+ # duration of an assertion, so a concurrently-running test in this+ # same '-n auto' worker process would inherit it (see the 'serial'+ # marker in pyproject.toml, and the same split in+ # docker-tests.yml). Excluded here and run in the dedicated serial+ # step below instead.+ pdm run python -m pytest tests/security/ -v --tb=short -n auto -m 'not serial'++ - name: Run serial (process-global state) security tests+ if: always()+ env:+ DATABASE_URL: postgresql://postgres:postgres@localhost:5432/test_security_db+ run: |+ # No '-n auto' here -- see the comment on the step above.+ #+ # Modules this lane collects at the time of writing:+ # serial tests/security/test_db_connection_umask_perms.py+ # DELETING THEM ALL EMPTIES THE LANE: pytest exits 5 ("no tests+ # collected") and this step fails hard -- the same #4411 breakage+ # the step above's comment describes. If the last serial-marked+ # module under tests/security/ goes away, delete this step in the+ # same change.+ #+ # There is no 'nonroot' counterpart here (unlike docker-tests.yml):+ # this job's runner is already an unprivileged user, so nonroot+ # tests run in the parallel step above without special handling.+ pdm run python -m pytest tests/security/ -m serial -p no:cov --tb=short -v- name: Check for hardcoded secretsrun: |diff --git a/Dockerfile b/Dockerfileindex bedab957dc..44165dfa02 100644--- a/Dockerfile+++ b/Dockerfile@@ -270,9 +270,22 @@ RUN find /install/.venv -type d -path '*/local_deep_research/database/migrations# Configure path to default to the venv python.ENV PATH="/install/.venv/bin:$PATH"-# Note: Test container runs as root because CI workflows mount source code-# volumes that are owned by root. The production container (ldr) runs as-# non-root user for security.+# Non-root user available for individual CI steps that need to run+# permission-sensitive tests as a real unprivileged user (e.g. the+# tests/security 'serial' battery -- every os.geteuid() == 0 check in+# that suite short-circuits to a skip under root, so those assertions+# are meaningless unless something in the container actually isn't+# root). Deliberately NOT set as this stage's default USER -- see the+# note below.+RUN groupadd -r ldruser && useradd -r -g ldruser -u 1000 -m -d /home/ldruser ldruser++# Note: Test container runs as root by default because CI workflows mount+# source code volumes that are owned by root, and most of the suite+# (coverage/junit output, npm/playwright caches, etc.) writes into that+# mount. The production container (ldr) runs as non-root user for+# security. Steps that don't need to write to the mount (e.g. the serial+# permission tests above) opt into `--user ldruser` individually instead+# of flipping the whole stage non-root.##### Runs the LDR service.diff --git a/changelog.d/5654.bugfix.md b/changelog.d/5654.bugfix.mdnew file mode 100644index 0000000000..0e62b9c70c--- /dev/null+++ b/changelog.d/5654.bugfix.md@@ -0,0 +1,16 @@+Two password changes running at the same time for one account can no longer+both report success. `DatabaseManager.change_password` was assembled from+public pieces — close the connection, reopen with the old password, issue+`PRAGMA rekey`, evict — and held no lock across that sequence, so two+concurrent calls for the same user could interleave: both opened with the old+key, both rekeyed, and both returned success while the database file ended up+encrypted with whichever new password happened to be written last. The caller+whose rekey lost the race was told the change had taken effect, and their new+password would not open the database. The sequence now runs under a per-user+lock, so at most one rekey per account succeeds; a concurrent second call+fails its reopen against the already-rekeyed file and returns failure, which+the change-password route surfaces as a rejected current password. The web+route already serialised its own calls behind the per-user research gate, so+the change matters for direct callers of the manager. The lock is per user,+process-local (the server runs a single worker), and is not held while other+users open or close their databases, so unrelated logins are unaffected.diff --git a/pyproject.toml b/pyproject.tomlindex b961ae7f1d..4f6cad564a 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -282,7 +282,9 @@ markers = ["fd_canary: heavy file-descriptor-leak regression tests (#3816). CPU-bound real-event-loop spins that exceeded the legacy 60s timeout under coverage + '-n auto' contention, and whose FD-count assertions are noisy under parallel execution; run in a dedicated serial, no-coverage CI step instead of the parallel suite.","lifespan: enters the app's real lifespan (startup/shutdown). At most ONE such test may run per process: socketio_asgi.init_lock() only assigns when _lock is None, so a second cycle would leave the asyncio.Lock bound to a dead loop. Do not add a second one or convert it into a fixture.","real_session_check: opt out of the autouse _legacy_bare_username_auth shim so the real server-side session-id check is exercised. For tests that must prove a destroyed/invalid session is rejected.",+ "serial: tests that mutate PROCESS-GLOBAL state (os.umask, os.chdir, signal handlers) for the duration of an assertion. Correct on their own, but under '-n auto' any other file creation happening concurrently in the same worker process inherits the hostile global -- so they run in a dedicated serial CI step instead of the parallel suite. This marker says NOTHING about privilege by itself: if a serial test's assertions also require a genuinely unprivileged process (e.g. it self-skips with `if os.geteuid() == 0: pytest.skip(...)`), it MUST also carry the 'nonroot' marker explicitly -- do not rely on a CI step happening to invoke pytest under an unprivileged user (docker-tests.yml's serial step uses '--user ldruser', but that is CI wiring, not a property of the marker, and a lane that ran '-m serial' as root would silently no-op every assertion in such a test). docker-tests.yml runs 'serial' and 'nonroot' together in one step selecting '-m serial or nonroot' under '--user ldruser', so a module carrying both markers runs exactly once.","connected: marks the connected pytest suite (real per-user encrypted SQLCipher DBs; heavier scenarios run out of the default unit suite).",+ "nonroot: tests whose assertions require a genuinely unprivileged process -- they start with `if os.geteuid() == 0: pytest.skip(...)` because permission bits (chmod/O_CREAT denial, read-only dirs, etc.) are not enforced for root. A test may carry 'nonroot' alone (does not mutate process-global state, e.g. tests/security/test_db_connection_create_hostile_dir.py, tests/security/test_db_connection_readonly_hostile_fs.py) or 'nonroot' together with 'serial' (also mutates process-global state, e.g. tests/security/test_db_connection_umask_perms.py). docker-tests.yml runs both markers together in one step, '-m serial or nonroot' under '--user ldruser', so a module carrying both runs exactly once regardless of which marker it also carries. The distinction matters because docker-tests.yml's default (main) container runs as root (it needs write access to the bind-mounted checkout for coverage/junit output), so nonroot-marked tests would silently no-op there unless excluded from the main step ('not serial and not nonroot') and run in that dedicated '--user ldruser' step instead. No exclusion is needed in security-tests.yml, which already executes as the non-root Actions runner user for every step (main and serial alike), so a serial+nonroot module's non-root requirement is satisfied there without a dedicated nonroot step or selector.",]# Global timeout for all tests - fail fast instead of hanging.# "thread" (not "signal") because SIGALRM was firing inside weakref/GC ondiff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.pyindex 5f32a73bc4..a7adc4c237 100644--- a/src/local_deep_research/database/encrypted_db.py+++ b/src/local_deep_research/database/encrypted_db.py@@ -183,6 +183,13 @@ class DatabaseManager:# the same database file at once. Created lazily under# _connections_lock; see open_user_database / _get_init_lock.self._init_locks: Dict[str, threading.Lock] = {}+ # Per-user locks serializing the whole change_password sequence+ # (close -> open(old) -> PRAGMA rekey -> evict). Deliberately NOT+ # _init_locks: change_password calls open_user_database, which+ # acquires the init lock itself, so sharing that non-reentrant lock+ # would self-deadlock. Created lazily; see+ # _get_password_change_lock.+ self._password_change_locks: Dict[str, threading.Lock] = {}self._data_dir_override: Optional[Path] = Noneself._initialized_data_dirs: set[Path] = set()@@ -907,6 +914,34 @@ class DatabaseManager:self._init_locks[username] = lockreturn lock+ def _get_password_change_lock(self, username: str) -> threading.Lock:+ """Return the per-user rekey lock, creating it on first use.++ Serializes the whole of :meth:`change_password` for one user. Per-user+ (not the global ``_connections_lock``) so a rekey for one user never+ stalls another user's opens, and so the lock can be held across the+ multi-second PBKDF2 + ``PRAGMA rekey`` without freezing the manager.++ Deliberately a SEPARATE registry from ``_init_locks``:+ ``change_password`` calls ``open_user_database``, which acquires this+ user's init lock itself, so sharing that non-reentrant lock would+ self-deadlock on every password change.++ The backing dict is reached through ``getattr`` because several tests+ build a ``DatabaseManager`` via ``__new__`` and set only the attributes+ the method under test touches, so it can legitimately be absent.+ """+ with self._connections_lock:+ locks = getattr(self, "_password_change_locks", None)+ if locks is None:+ locks = {}+ self._password_change_locks = locks+ lock = locks.get(username)+ if lock is None:+ lock = threading.Lock()+ locks[username] = lock+ return lock+def open_user_database(self, username: str, password: str) -> Optional[Engine]:@@ -1309,6 +1344,13 @@ class DatabaseManager:self.connections.clear()self._password_verifiers.clear()self._init_locks.clear()+ # _password_change_locks is deliberately NOT cleared. An entry may+ # be held by a change_password still in flight, and dropping it+ # would let the next caller build a SECOND gate for that user and+ # rekey the same file concurrently -- the exact race the lock+ # exists to stop. Bounded by the number of distinct usernames+ # whose database file exists (change_password looks the lock up+ # only after the path check), one small Lock each.def check_database_integrity(self, username: str) -> bool:"""Check integrity of a user's encrypted database."""@@ -1379,53 +1421,67 @@ class DatabaseManager:if not db_path.exists():return False- try:- # Close existing connection if any- self.close_user_database(username)+ # Serialize the whole close -> open(old) -> rekey -> evict+ # sequence for this user. Built from public pieces, two concurrent+ # change_password calls for one user could otherwise interleave --+ # A opens with the old key, B disposes A's engine and opens with the+ # old key too, then both rekey -- leaving the file owned by whichever+ # rekey landed last while BOTH callers were told True, and the loser's+ # new password silently does not work. The lock makes at most one+ # rekey per user succeed; the loser's open(old) then fails against the+ # already-rekeyed file and it returns False. Per-user, and acquired+ # WITHOUT holding _connections_lock (open_user_database /+ # close_user_database take that themselves), so it neither blocks+ # other users nor inverts the lock order.+ with self._get_password_change_lock(username):+ try:+ # Close existing connection if any+ self.close_user_database(username)- # Open with old password- engine = self.open_user_database(username, old_password)- if not engine:- return False+ # Open with old password+ engine = self.open_user_database(username, old_password)+ if not engine:+ return False- # Rekey the database (only works with SQLCipher)- with engine.connect() as conn:- # Use centralized rekey function- set_sqlcipher_rekey(conn, new_password, db_path=db_path)-- # Evict the cached engine and its verifier NOW, while still inside- # the try. open_user_database() above cold-opened with old_password- # and cached that engine together with a verifier for old_password.- # The rekey just invalidated that engine's key (its creator closure- # still derives the OLD hex key, so any freshly pooled connection is- # mis-keyed) yet the cached verifier still matches old_password -- so- # until this eviction a concurrent open_user_database(old_password)- # would pass the verifier check and be handed the stale-key engine.- # change_password holds no lock across the rekey, so evict here- # rather than waiting for the finally. close_user_database is- # idempotent (no-ops when the user is not cached), so the- # finally-close below stays a backstop and is a no-op once this ran.- self.close_user_database(username)-- logger.info(f"Password changed for user {username}")- return True+ # Rekey the database (only works with SQLCipher)+ with engine.connect() as conn:+ # Use centralized rekey function+ set_sqlcipher_rekey(conn, new_password, db_path=db_path)++ # Evict the cached engine and its verifier NOW, while still inside+ # the try. open_user_database() above cold-opened with old_password+ # and cached that engine together with a verifier for old_password.+ # The rekey just invalidated that engine's key (its creator closure+ # still derives the OLD hex key, so any freshly pooled connection is+ # mis-keyed) yet the cached verifier still matches old_password -- so+ # until this eviction a concurrent open_user_database(old_password)+ # would pass the verifier check and be handed the stale-key engine.+ # The per-user lock above only excludes another change_password --+ # plain opens run concurrently throughout -- so evict here rather+ # than waiting for the finally. close_user_database is idempotent+ # (no-ops when the user is not cached), so the finally-close below+ # stays a backstop and is a no-op once this ran.+ self.close_user_database(username)++ logger.info(f"Password changed for user {username}")+ return True- except Exception as e:- # Both ``old_password`` and ``new_password`` are in lexical- # scope. ``open_user_database`` / ``set_sqlcipher_rekey``- # carry these into nested frames — a traceback rendered- # with ``diagnose=True`` would leak them. Redact both and- # drop the traceback chain.- from ..security.log_sanitizer import redact_secrets+ except Exception as e:+ # Both ``old_password`` and ``new_password`` are in lexical+ # scope. ``open_user_database`` / ``set_sqlcipher_rekey``+ # carry these into nested frames — a traceback rendered+ # with ``diagnose=True`` would leak them. Redact both and+ # drop the traceback chain.+ from ..security.log_sanitizer import redact_secrets- safe_msg = redact_secrets(str(e), old_password, new_password)- logger.warning(- f"Failed to change password for user: {username}: {safe_msg}"- )- return False- finally:- # Close the connection- self.close_user_database(username)+ safe_msg = redact_secrets(str(e), old_password, new_password)+ logger.warning(+ f"Failed to change password for user: {username}: {safe_msg}"+ )+ return False+ finally:+ # Close the connection+ self.close_user_database(username)def user_exists(self, username: str) -> bool:"""Check if a user exists in the auth database."""diff --git a/src/local_deep_research/database/sqlcipher_utils.py b/src/local_deep_research/database/sqlcipher_utils.pyindex 167b3fdc6d..b237461661 100644--- a/src/local_deep_research/database/sqlcipher_utils.py+++ b/src/local_deep_research/database/sqlcipher_utils.py@@ -230,6 +230,15 @@ def set_sqlcipher_key_from_hex(cursor_or_conn: Any, hex_key: str) -> None:cursor_or_conn.execute(f"PRAGMA key = \"x'{hex_key}'\"") # gitleaks:allow+class SQLCipherRekeyError(RuntimeError):+ """Raised when ``PRAGMA rekey`` fails.++ Deliberately carries no detail beyond the failing exception's type: the+ underlying error text embeds the rekey statement, which embeds the+ derived master key in hex.+ """++def set_sqlcipher_rekey(cursor_or_conn: Any,new_password: str,@@ -253,14 +262,33 @@ def set_sqlcipher_rekey(# The hex encoding already prevents injection since it only contains [0-9a-f]safe_sql = f"PRAGMA rekey = \"x'{key.hex()}'\""+ # Any failure here must not carry ``safe_sql`` outwards. SQLAlchemy wraps+ # DBAPI errors in ``StatementError``, whose ``_sql_message`` appends+ # ``"[SQL: %s]" % self.statement`` -- so the raw exception's ``str()``,+ # its ``.statement`` attribute and its rendered traceback all contain the+ # derived master key in hex. ``change_password``'s handler only redacts+ # the two plaintext passwords, so an unwrapped error would put the key in+ # the log. Capture the failure, then raise a key-free error *outside* the+ # ``except`` block: ``from None`` clears ``__cause__`` and raising after+ # the handler has exited leaves ``__context__`` unset, so no surface of+ # the propagated exception references the key.+ failure: Optional[BaseException] = Nonetry:- # Try SQLAlchemy connection (needs text() wrapper)- from sqlalchemy import text-- cursor_or_conn.execute(text(safe_sql))- except TypeError:- # Raw SQLCipher connection - use string directly- cursor_or_conn.execute(safe_sql)+ try:+ # Try SQLAlchemy connection (needs text() wrapper)+ from sqlalchemy import text++ cursor_or_conn.execute(text(safe_sql))+ except TypeError:+ # Raw SQLCipher connection - use string directly+ cursor_or_conn.execute(safe_sql)+ except Exception as exc: # noqa: BLE001 - re-raised below as a key-free error+ failure = exc++ if failure is not None:+ raise SQLCipherRekeyError(+ f"PRAGMA rekey failed ({type(failure).__name__})"+ ) from None# Default SQLCipher configuration (can be overridden by settings)diff --git a/tests/deployment/test_deployment_surface_contracts.py b/tests/deployment/test_deployment_surface_contracts.pyindex b3d498c177..b50d9be8a7 100644--- a/tests/deployment/test_deployment_surface_contracts.py+++ b/tests/deployment/test_deployment_surface_contracts.py@@ -43,6 +43,7 @@ COMPOSE_BASE = REPO_ROOT / "docker-compose.yml"COMPOSE_UNRAID = REPO_ROOT / "docker-compose.unraid.yml"COMPOSE_GPU = REPO_ROOT / "docker-compose.gpu.override.yml"ENTRYPOINT = REPO_ROOT / "scripts" / "ldr_entrypoint.sh"+DOCKER_TESTS_YML = REPO_ROOT / ".github" / "workflows" / "docker-tests.yml"ZIPFILE_PATCH_SCRIPT_REL = "scripts/patch_cpython_zipfile_cve_2026_15310.py"ZIPFILE_PATCH_SCRIPT = REPO_ROOT / ZIPFILE_PATCH_SCRIPT_RELCOOKIECUTTER_DIR = REPO_ROOT / "cookiecutter-docker"@@ -376,6 +377,11 @@ def unraid_xml():return DefusedET.parse(UNRAID_TEMPLATE).getroot()[email protected](scope="module")+def docker_tests_workflow() -> dict:+ return yaml.safe_load(DOCKER_TESTS_YML.read_text(encoding="utf-8"))++# ---------------------------------------------------------------------------# Parser floors -- a parser that finds nothing must not silently pass# ---------------------------------------------------------------------------@@ -1554,3 +1560,58 @@ class TestCPythonZipfileBackportWiring:f"{destination} but never RUNs it, so the stdlib is left ""unpatched")+++# ---------------------------------------------------------------------------+# CI marker-lane wiring -- the nonroot battery's teeth hang on one flag+# ---------------------------------------------------------------------------+++class TestCIMarkerLaneWiring:+ """The 'serial'/'nonroot' CI step actually runs unprivileged and+ selects the markers it claims to.++ ``pyproject.toml``'s ``nonroot`` marker docstring says every+ 'nonroot'-marked test self-skips with+ ``if os.geteuid() == 0: pytest.skip(...)`` rather than+ ``allow_module_level=True`` -- so if this step's own ``--user ldruser``+ or its ``-m 'serial or nonroot'`` selector is ever dropped, none of+ that shows up as a failure: pytest still exits 0, the modules report+ "N skipped" instead of running, and the CI summary looks identical to+ a green permission-bit battery that actually executed. This is the+ only thing in the suite that would catch that class of regression.++ Revert that must turn this red: in+ ``.github/workflows/docker-tests.yml``, drop ``--user ldruser`` from+ the "Run serial + nonroot (process-global state, permission-bit)+ tests" step's ``docker run`` invocation (or change its ``-m`` selector+ away from ``'serial or nonroot'``).+ """++ def test_merged_marker_step_runs_unprivileged_with_both_markers(+ self, docker_tests_workflow+ ):+ steps = docker_tests_workflow["jobs"]["pytest-tests"]["steps"]+ matches = [+ step+ for step in steps+ if step.get("name")+ == "Run serial + nonroot (process-global state, permission-bit) "+ "tests"+ ]+ assert len(matches) == 1, (+ "expected exactly one 'serial + nonroot' step in "+ f"docker-tests.yml's pytest-tests job, found {len(matches)}"+ )+ run = matches[0]["run"]+ assert "--user ldruser" in run, (+ "the merged serial/nonroot step no longer runs as 'ldruser' -- "+ "every nonroot-marked test self-skips as root instead of "+ "failing, so this lane would report green having tested "+ "nothing"+ )+ assert re.search(r"-m\s+'serial or nonroot'", run), (+ "the merged serial/nonroot step's marker selector changed -- "+ "it must select both markers so a module carrying either one "+ "still runs"+ )diff --git a/tests/security/test_change_password_evicts_stale_engine.py b/tests/security/test_change_password_evicts_stale_engine.pyindex 18e289f121..34b7978138 100644--- a/tests/security/test_change_password_evicts_stale_engine.py+++ b/tests/security/test_change_password_evicts_stale_engine.py@@ -7,8 +7,10 @@ connection. Before the fix the close happened ONLY in the ``finally`` block, sobetween the rekey and the finally the cache held an engine whose creator closurestill derives the now-invalid OLD key while its verifier still matched the OLDpassword. In that window a concurrent ``open_user_database(username, old)`` would-pass the verifier check and be handed the stale-key engine, and ``change_password``-holds no lock across the rekey.+pass the verifier check and be handed the stale-key engine. ``change_password``+now runs under a per-user lock, but that lock only excludes a second+``change_password``; a concurrent ``open_user_database`` is not held back by it,+so the eviction is still what closes this window.The fix evicts the connection (and its verifier) immediately AFTER the rekey,INSIDE the ``try``, keeping the finally-close as an idempotent backstop.diff --git a/tests/security/test_db_connection_change_password_edges.py b/tests/security/test_db_connection_change_password_edges.pynew file mode 100644index 0000000000..5c67d575d6--- /dev/null+++ b/tests/security/test_db_connection_change_password_edges.py@@ -0,0 +1,195 @@+"""``change_password`` edge cases: same-password, empty-new, wrong-old.++Incident context (PR #5596): change_password is a credential-taking+write path built from public pieces (close -> open(old) -> PRAGMA rekey+-> evict). Its guards decide whether a bad request can hurt the file.+Round-4 P pinned the rekey's effect on held credentials; this file pins+the INPUT-validation edges:++* AB1 rekey to the SAME password: succeeds (True), the single password+ keeps working cold, data survives, exactly one cache entry after+ reopen (no double caching);+* AB2 empty NEW password -- DATA-DESTRUCTION BUG, asserted as an+ ``xfail(strict)`` on the correct behavior. ``change_password``+ performs NO ``_is_valid_encryption_key`` check on ``new_password``+ (the guard exists on create/open only -- ``create_user_database``+ and ``open_user_database`` both call it).+ The rekey derives a key from the empty string and SUCCEEDS, so the+ call returns True -- and the database is then permanently UNOPENABLE:+ the old password no longer matches the rekeyed file, and opening with+ "" is refused by ``_is_valid_encryption_key`` on the open path. The+ test asserts what MUST happen (refuse with False, leave the database+ openable with the old password), so it flips to passing the moment the+ guard lands.+* AB3 wrong OLD password: clean False (the open(old) inside fails), no+ rekey (old password still opens, the would-be new one still fails),+ canary intact, salt bytes unchanged, nothing cached afterwards.+"""++import hashlib+import uuid++import pytest+from sqlalchemy import text++from local_deep_research.database.encrypted_db import DatabaseManager+from local_deep_research.database.sqlcipher_utils import get_salt_file_path++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager writing to an isolated data directory.++ Same self-contained pattern as the round-1..5 files, with the+ sanctioned test-mode KDF knob.+ """+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ mgr = DatabaseManager()+ mgr.data_dir = tmp_path+ yield mgr+ mgr.close_all_databases()+++def _make_user(manager, note):+ username = f"chgpwedge_{uuid.uuid4().hex[:8]}"+ password = "EdgeOldPw1!" # noqa: S105+ engine = manager.create_user_database(username, password)+ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE gap_ab_canary (id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO gap_ab_canary (id, note) VALUES (1, :note)"),+ {"note": note},+ )+ manager.close_user_database(username)+ return username, password+++def _salt_digest(manager, username) -> str:+ salt_path = get_salt_file_path(manager._get_user_db_path(username))+ return hashlib.sha256(salt_path.read_bytes()).hexdigest()+++def test_change_password_to_same_password_is_a_clean_no_op_rekey(manager):+ """AB1: old == new. Returns True, the password keeps working cold,+ data survives, and exactly one engine/verifier entry exists after+ reopen."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username, password = _make_user(manager, "gap-AB1")+ salt_before = _salt_digest(manager, username)++ assert manager.change_password(username, password, password) is True++ # change_password evicts; the (single) password reopens cold.+ assert username not in manager.connections+ reopened = manager.open_user_database(username, password)+ assert reopened is not None+ with reopened.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_ab_canary WHERE id = 1")+ ).scalar()+ == "gap-AB1"+ )+ assert manager._password_matches_cached(username, password) is True+ with manager._connections_lock:+ assert set(manager.connections) == set(manager._password_verifiers)+ assert set(manager.connections) == {username}+ # Rekeying to the same key material leaves the salt untouched.+ assert _salt_digest(manager, username) == salt_before+++ strict=True,+ reason=(+ "change_password must validate new_password with "+ "_is_valid_encryption_key before rekeying; today it rekeys to a "+ 'key derived from "" and returns True, permanently bricking the '+ 'database because the open path refuses "". Fix: add the guard at '+ "the top of encrypted_db.py::change_password, mirroring the "+ "_is_valid_encryption_key calls in encrypted_db.py::"+ "create_user_database and encrypted_db.py::open_user_database."+ ),+)+def test_change_password_refuses_an_empty_new_password(manager):+ """AB2 (CORRECT behavior, currently unimplemented): an empty new+ password must be refused BEFORE the rekey, leaving the database fully+ intact and openable with the existing password. Anything else is+ silent, unrecoverable data destruction: the rekey succeeds against a+ key the open path will never accept again."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username, password = _make_user(manager, "gap-AB2")+ salt_before = _salt_digest(manager, username)++ assert manager.change_password(username, password, "") is False, (+ "change_password accepted an empty new password -- the rekey has "+ "already bricked the database at this point"+ )++ # The existing credential must still open the database and read data.+ reopened = manager.open_user_database(username, password)+ assert reopened is not None, (+ "the old password no longer opens the database -- the refused "+ "change_password rekeyed anyway"+ )+ with reopened.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_ab_canary WHERE id = 1")+ ).scalar()+ == "gap-AB2"+ )+ # The empty password is refused on the open path (this part holds+ # today and must keep holding).+ with pytest.raises(ValueError, match="Invalid encryption key"):+ manager.open_user_database(username, "")+ assert _salt_digest(manager, username) == salt_before+++def test_change_password_with_wrong_old_password_fails_without_rekey(manager):+ """AB3: wrong current password -> False, no rekey (old still opens,+ would-be new fails), canary intact, salt bytes unchanged, nothing+ cached afterwards."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username, password = _make_user(manager, "gap-AB3")+ new_password = "WouldBeNewPw2!" # noqa: S105+ salt_before = _salt_digest(manager, username)++ assert (+ manager.change_password(username, "definitely-wrong", new_password)+ is False+ )++ # No rekey happened.+ assert manager.open_user_database(username, new_password) is None+ reopened = manager.open_user_database(username, password)+ assert reopened is not None, "the real password must still open"+ with reopened.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_ab_canary WHERE id = 1")+ ).scalar()+ == "gap-AB3"+ )+ assert manager._password_matches_cached(username, password) is True+ assert manager._password_matches_cached(username, new_password) is False+ assert _salt_digest(manager, username) == salt_before+ with manager._connections_lock:+ assert set(manager.connections) == set(manager._password_verifiers)diff --git a/tests/security/test_db_connection_change_password_race.py b/tests/security/test_db_connection_change_password_race.pynew file mode 100644index 0000000000..9072279951--- /dev/null+++ b/tests/security/test_db_connection_change_password_race.py@@ -0,0 +1,463 @@+"""change_password rekey racing concurrent open_user_database(old_password).++Incident context (PR #5596): the fix's eviction comment in ``change_password``+warns about the exact race these tests drive at the real-database level:++ open_user_database() above cold-opened with old_password and cached that+ engine together with a verifier for old_password. The rekey just+ invalidated that engine's key [...] yet the cached verifier still matches+ old_password -- so until this eviction a concurrent+ open_user_database(old_password) would pass the verifier check and be+ handed the stale-key engine.++``change_password`` now runs under a per-user lock, but that lock excludes+only a second ``change_password``: a concurrent ``open_user_database`` still+runs alongside the rekey, so the window above is still closed by the+eviction alone.++``test_change_password_evicts_stale_engine.py`` pins that the eviction runs+inside the try (via monkeypatched spies on close/rekey/log); it never runs+the race with real threads. ``test_login_cached_connection_password_extra.+py::test_password_change_invalidates_old_verifier_and_arms_new`` pins only+the sequential after-state. Neither proves the end-to-end concurrent+property against a real SQLCipher file:++* WHILE change_password runs, threads calling open_user_database(old) may+ receive engines (legitimately -- the old key is still valid until the+ rekey lands), but every such engine must be DEAD once the rekey+ completes: it must never yield a queryable session afterward.+* AFTER change_password returns: the old key must fail (and cache nothing),+ the new key must open and read data written under previous passwords.+* Under a stress loop of chained rekeys, no snapshot of the manager may+ ever show an engine without its verifier or vice versa (atomic+ publication), and no stale password may ever produce a usable engine.++All tests use the real DatabaseManager with real SQLCipher files under+tmp_path; no mocks on the crypto or cache layer.+"""++import threading+import time+import uuid+import warnings++import pytest+from sqlalchemy import text++from local_deep_research.database.encrypted_db import DatabaseManager++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")++# Bounded concurrency: explicit thread counts, explicit iteration caps, a+# barrier for synchronized starts and a wall-clock budget well under 30s.+MAX_HAMMER_ITERATIONS = 25+JOIN_TIMEOUT_S = 60+BARRIER_TIMEOUT_S = 30+# Race witness floor: the hammer thread must have made at least this many+# open attempts. Below it the run raced nothing and the stale-engine+# assertions are vacuous, so it is a hard failure rather than a silent pass.+MIN_HAMMER_ATTEMPTS = 1+++def _join_all(threads):+ """Join every thread against ONE shared deadline.++ A per-thread ``join(timeout=JOIN_TIMEOUT_S)`` inside a loop costs+ ``len(threads) * JOIN_TIMEOUT_S`` in the worst case. ``pyproject.toml``+ sets ``timeout = 180`` with ``timeout_method = "thread"``, and+ pytest-timeout's thread handler ends in ``os._exit(1)`` -- so when these+ tests actually find the deadlock they exist to find, a per-thread budget+ would kill the whole xdist worker (losing its coverage, then tripping+ ``--cov-fail-under``) instead of failing on the named "deadlocked"+ assertion at the call site. One shared deadline bounds the entire join at+ JOIN_TIMEOUT_S regardless of thread count, which keeps that assertion+ reachable well inside the global timeout. Each thread still gets the full+ remaining budget in wall-clock terms, because the threads run+ concurrently.+ """+ deadline = time.monotonic() + JOIN_TIMEOUT_S+ for t in threads:+ t.join(timeout=max(0.0, deadline - time.monotonic()))+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager writing to an isolated data directory.++ Same self-contained pattern as the incident tests; KDF iterations are+ lowered via the sanctioned test-mode knob (see tests/conftest.py's+ ``app`` fixture) because the stress tests below perform dozens of key+ derivations (one per open/rekey attempt).+ """+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ mgr = DatabaseManager()+ mgr.data_dir = tmp_path+ yield mgr+ mgr.close_all_databases()+++def _write_canary(engine, note: str) -> None:+ """Write a marker row through a real engine so rekey/data-survival is+ asserted on actual readable data, not on engine non-None-ness."""+ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE IF NOT EXISTS gap_b_canary "+ "(id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO gap_b_canary (id, note) VALUES (1, :note)"),+ {"note": note},+ )+++def _engine_usable(engine) -> tuple[bool, str]:+ """Is this engine able to run a SELECT right now?++ Returns (usable, detail); detail carries the failure repr so a failed+ invariant prints WHY the engine was (or was not) usable.+ """+ try:+ with engine.connect() as conn:+ value = conn.execute(text("SELECT 1")).scalar()+ return value == 1, "select ok"+ except Exception as exc: # noqa: BLE001 - converted into a loud assert below+ return False, repr(exc)+++def test_post_change_password_old_key_dead_new_key_reads_data(manager):+ """Sequential baseline at real-DB level: after change_password, the old+ key is dead (and its failed attempt caches NOTHING), the new key opens+ and reads the canary row written under the old key (rekey preserved+ data), and no cache pollution is left behind.++ Goes beyond test_password_change_invalidates_old_verifier_and_arms_new+ (which checks open-None/engine-identity only) by asserting data+ readability through a real session and the no-residue property of the+ failed old-key open.+ """+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"chgpw_seq_{uuid.uuid4().hex[:8]}"+ old = "OldCorrectHorse1!" # noqa: S105+ new = "NewCorrectHorse2!" # noqa: S105+ engine = manager.create_user_database(username, old)+ _write_canary(engine, "gap-B-seq")+ manager.close_user_database(username)++ assert manager.change_password(username, old, new) is True++ # change_password evicted everything; nothing half-cached.+ assert username not in manager.connections+ assert username not in manager._password_verifiers++ # Old key: rejected, and the rejection must not populate any cache+ # entry (a cached engine or verifier from a FAILED open would arm a+ # future bypass).+ assert manager.open_user_database(username, old) is None, (+ "the old password must not open the re-keyed database"+ )+ assert username not in manager.connections, (+ "a failed old-password open must not cache an engine"+ )+ assert username not in manager._password_verifiers, (+ "a failed old-password open must not arm a verifier"+ )++ # New key: opens, and the data written under the old key is readable.+ reopened = manager.open_user_database(username, new)+ assert reopened is not None+ with reopened.connect() as conn:+ note = conn.execute(+ text("SELECT note FROM gap_b_canary WHERE id = 1")+ ).scalar()+ assert note == "gap-B-seq", "rekey must preserve existing data"+ assert manager._password_matches_cached(username, new) is True+++def test_old_password_open_racing_change_password_never_usable_after_rekey(+ manager,+):+ """The single-shot race: one thread runs change_password(old -> new)+ while another hammers open_user_database(old).++ Any engine the old-password thread manages to grab (legal only before+ the rekey lands -- the old key is genuinely valid until then) must be+ DEAD once change_password returns: a SELECT on it must fail.++ STRICTLY WEAKER than the spy test it complements, and deliberately so.+ Delete ``encrypted_db.py::change_password``'s IN-TRY eviction and keep+ only the ``finally`` close, and every assertion here still passes: the+ grabbed engine is dead after the rekey either way, because the rekey+ invalidated the key its creator closure derives. That is a property of+ SQLCipher rekey, not of where the eviction sits.++ What this test does pin, under real threads rather than spies: no+ engine handed out under the OLD password survives a completed+ change_password, the old password no longer opens afterwards, and the+ new one reads the pre-change data. The PLACEMENT of the eviction --+ inside the try, closing the window a concurrent old-password open could+ otherwise use -- is pinned by+ ``tests/security/test_change_password_evicts_stale_engine.py``, which+ fails when that in-try close is removed.+ """+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"chgpw_race_{uuid.uuid4().hex[:8]}"+ old = "OldCorrectHorse1!" # noqa: S105+ new = "NewCorrectHorse2!" # noqa: S105+ engine = manager.create_user_database(username, old)+ _write_canary(engine, "gap-B-race")+ manager.close_user_database(username)++ barrier = threading.Barrier(2)+ done = threading.Event()+ outcome = {}+ grabbed_engines = []+ errors = {}++ def rekeyer():+ try:+ barrier.wait(timeout=BARRIER_TIMEOUT_S)+ outcome["changed"] = manager.change_password(username, old, new)+ except Exception as exc: # noqa: BLE001 - surfaced via `errors` below+ errors["rekeyer"] = exc+ finally:+ done.set()++ def old_password_hammer():+ try:+ barrier.wait(timeout=BARRIER_TIMEOUT_S)+ attempts = 0+ while not done.is_set() and attempts < MAX_HAMMER_ITERATIONS:+ attempts += 1+ engine = manager.open_user_database(username, old)+ if engine is not None:+ grabbed_engines.append(engine)+ time.sleep(0.005)+ outcome["attempts"] = attempts+ except Exception as exc: # noqa: BLE001 - surfaced via `errors` below+ errors["hammer"] = exc++ threads = [+ threading.Thread(target=rekeyer, name="gap-b-rekeyer"),+ threading.Thread(target=old_password_hammer, name="gap-b-hammer-old"),+ ]+ for t in threads:+ t.start()+ _join_all(threads)+ assert not any(t.is_alive() for t in threads), (+ "change_password / open_user_database deadlocked under the race"+ )+ assert not errors, f"a racing thread raised: {errors}"+ assert outcome.get("changed") is True, f"change_password outcome: {outcome}"++ # Race witness. Without it a scheduler that never gave the hammer a+ # slice leaves `grabbed_engines` empty and the core loop below asserts+ # nothing, while the test still reports green.+ attempts = outcome.get("attempts", 0)+ assert attempts >= MIN_HAMMER_ATTEMPTS, (+ f"the old-password hammer made {attempts} attempt(s) (minimum "+ f"{MIN_HAMMER_ATTEMPTS}) -- nothing was raced on this runner"+ )+ if not grabbed_engines:+ warnings.warn(+ f"stale-engine invariant not exercised: all {attempts} "+ "old-password attempts lost the pre-rekey window, so no engine "+ "was grabbed to check. The post-conditions below still ran.",+ stacklevel=1,+ )++ # Core invariant: every engine handed to the OLD password during the+ # race must be unusable now that the rekey completed.+ for index, engine in enumerate(grabbed_engines):+ usable, detail = _engine_usable(engine)+ assert not usable, (+ f"engine #{index} grabbed with the OLD password is still "+ f"usable after the rekey completed ({detail}) -- a stale-key "+ "engine escaped the eviction"+ )++ # Post-conditions: old dead, new alive and reading pre-change data.+ assert manager.open_user_database(username, old) is None+ reopened = manager.open_user_database(username, new)+ assert reopened is not None+ with reopened.connect() as conn:+ note = conn.execute(+ text("SELECT note FROM gap_b_canary WHERE id = 1")+ ).scalar()+ assert note == "gap-B-race"+++def test_stress_change_password_chain_vs_open_hammers(manager):+ """Chained rekeys (pw0 -> pw1 -> ... -> pw4) racing two open-hammer+ threads: one stuck on the ORIGINAL password, one on the FINAL password.++ Invariants after stabilization:+ * every engine obtained with the ORIGINAL password during the run is+ dead (its key was rekeyed away and can never return);+ * every engine obtained with the FINAL password is exactly the one+ surviving current-key engine -- it can only have been handed out+ AFTER the final rekey landed, never a mis-keyed duplicate;+ * no intermediate or original password can open at the end;+ * the final password opens and reads the canary written at creation;+ * the engine/verifier PAIRING invariant, sampled under the connections+ lock after each change: the set of usernames in ``connections``+ always equals the set in ``_password_verifiers``. Either map CAN+ legitimately be (re-)populated between the change_password eviction+ and the snapshot by a concurrent open_user_database republishing+ engine+verifier atomically via _cache_connection -- that is not a+ publication gap. The engine-without-verifier / verifier-without-+ engine state the product guarantees cannot occur is what is+ asserted (same invariant as round 1's gap-C storm test).+ """+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"chgpw_stress_{uuid.uuid4().hex[:8]}"+ passwords = [f"StressPass{i}!A" for i in range(5)] # noqa: S105+ final_password = passwords[-1]+ engine = manager.create_user_database(username, passwords[0])+ _write_canary(engine, "gap-B-stress")+ manager.close_user_database(username)++ barrier = threading.Barrier(3) # rekeyer + 2 hammers+ done = threading.Event()+ errors = {}+ grabbed = [] # (password_label, engine) pairs recorded by hammers+ grabbed_lock = threading.Lock()+ pair_violations = [] # engine/verifier pairing snapshots that broke+ hammer_attempts = {} # race witness: per-hammer open attempt counts++ def rekeyer():+ try:+ barrier.wait(timeout=BARRIER_TIMEOUT_S)+ for i in range(len(passwords) - 1):+ changed = manager.change_password(+ username, passwords[i], passwords[i + 1]+ )+ assert changed is True, f"change_password #{i} failed mid-chain"+ # Pairing-invariant sample: after a change returns, the+ # username sets of connections and _password_verifiers+ # must agree. A hammer thread may have legitimately+ # republished BOTH maps via _cache_connection (atomic+ # under _connections_lock), so emptiness is NOT the+ # invariant -- only the pairing is. Both maps are mutated+ # only under _connections_lock, so this snapshot cannot+ # observe a torn state.+ with manager._connections_lock:+ engines = set(manager.connections)+ verifiers = set(manager._password_verifiers)+ if engines != verifiers:+ pair_violations.append((i, engines, verifiers))+ except Exception as exc: # noqa: BLE001 - surfaced via `errors` below+ errors["rekeyer"] = exc+ finally:+ done.set()++ def hammer(label: str, password: str):+ try:+ barrier.wait(timeout=BARRIER_TIMEOUT_S)+ attempts = 0+ while not done.is_set() and attempts < MAX_HAMMER_ITERATIONS:+ attempts += 1+ engine = manager.open_user_database(username, password)+ if engine is not None:+ with grabbed_lock:+ grabbed.append((label, engine))+ time.sleep(0.005)+ hammer_attempts[label] = attempts+ except Exception as exc: # noqa: BLE001 - surfaced via `errors` below+ errors[f"hammer-{label}"] = exc++ threads = [+ threading.Thread(target=rekeyer, name="gap-b-chain"),+ threading.Thread(+ target=hammer, args=("original", passwords[0]), name="gap-b-h0"+ ),+ threading.Thread(+ target=hammer, args=("final", final_password), name="gap-b-hf"+ ),+ ]+ for t in threads:+ t.start()+ _join_all(threads)+ assert not any(t.is_alive() for t in threads), "stress race deadlocked"+ assert not errors, f"a stress thread raised: {errors}"+ assert not pair_violations, (+ f"engine/verifier pairing broken: {pair_violations}"+ )++ # Race witness: both hammers must have run. Without it a scheduler that+ # starves them leaves `grabbed` empty and the engine-verdict loop below+ # iterates over nothing while the test reports green.+ assert set(hammer_attempts) == {"original", "final"}, (+ f"a hammer thread recorded no attempts: {hammer_attempts}"+ )+ assert all(n >= MIN_HAMMER_ATTEMPTS for n in hammer_attempts.values()), (+ f"hammer attempt counts below the {MIN_HAMMER_ATTEMPTS} floor: "+ f"{hammer_attempts} -- nothing was raced on this runner"+ )+ if not grabbed:+ warnings.warn(+ "engine-verdict loop not exercised: neither hammer grabbed an "+ f"engine across {hammer_attempts} attempts, so no stale/surviving "+ "engine verdict was checked. The end-state assertions still ran.",+ stacklevel=1,+ )++ # Stabilized end-state, part 1: every STALE password (original + all+ # intermediates) is dead from the manager's point of view.+ for stale in passwords[:-1]:+ assert manager.open_user_database(username, stale) is None, (+ f"stale password {stale!r} still opens after the rekey chain"+ )++ # Stabilized end-state, part 2: the final password opens and reads the+ # data written before any rekey happened. The engine it gets back is+ # the one surviving current-key engine (or, if no hammer grabbed one+ # after the last rekey, the freshly cold-opened one we just created).+ reopened = manager.open_user_database(username, final_password)+ assert reopened is not None+ surviving = manager.connections.get(username)+ assert surviving is reopened, "the final-password engine must be cached"+ with reopened.connect() as conn:+ note = conn.execute(+ text("SELECT note FROM gap_b_canary WHERE id = 1")+ ).scalar()+ assert note == "gap-B-stress", "rekey chain must preserve data"++ # Engine verdicts, computed AFTER stabilization so the surviving+ # current-key engine is known:+ # * 'original': every engine handed out for the ORIGINAL password+ # must be dead -- its key was rekeyed away and can never return.+ # * 'final': a final-password engine is legitimate ONLY once the+ # final rekey has landed, and there is exactly one such engine:+ # the surviving cached engine. Anything else -- a second engine+ # object, or one handed out before the final rekey completed --+ # would mean a mis-keyed engine escaped. (A final-password open+ # cannot succeed before the final rekey: the file is keyed with+ # an earlier password and SQLCipher verification fails.)+ for index, (label, engine) in enumerate(grabbed):+ if label == "original":+ usable, detail = _engine_usable(engine)+ assert not usable, (+ f"engine #{index} (hammer={label}) is still usable after "+ f"the rekey chain completed ({detail}) -- a stale-key "+ "engine escaped the eviction"+ )+ else:+ assert engine is surviving, (+ f"engine #{index} (hammer={label}) is not the surviving "+ f"current-key engine -- a mis-keyed engine was handed out "+ "for the final password"+ )diff --git a/tests/security/test_db_connection_close_all_race.py b/tests/security/test_db_connection_close_all_race.pynew file mode 100644index 0000000000..b761ce877e--- /dev/null+++ b/tests/security/test_db_connection_close_all_race.py@@ -0,0 +1,312 @@+"""``close_all_databases`` racing concurrent opens.++Incident context (PR #5596): the trust model of the connection cache is+"an entry exists only together with its verifier, and only while a+credential-verified open put it there". ``close_all_databases`` is the+shutdown-scale eviction: it clears ``connections``,+``_password_verifiers`` AND ``_init_locks`` wholesale, all under+``_connections_lock``. Racing it against open/close churn must never tear+that model:++* O1 single user: a churn thread cycling open(correct)+close while a+ teardown thread repeatedly calls close_all_databases. At every sampled+ instant (under ``_connections_lock``) the engine/verifier PAIRING+ invariant holds; after both threads join and a final close_all, the+ cache is empty; the next open yields a fresh working engine that reads+ the canary (no engine handle reachable from cached state survived).+* O2 multi-user: three users churned round-robin against the same+ teardown; after stabilization every user reopens and reads its OWN+ canary (no cross-user bleed), and the pairing invariant held throughout.++Note on engine handles: per round 3's session-lifetime finding, an Engine+OBJECT handed out before a close_all can keep reconnecting via its+creator closure (by design; secured by the verifier on the next+credential-taking open). What close_all guarantees -- and what is pinned+here -- is the CACHE-level property: nothing remains reachable from+``connections``/``_password_verifiers``, and the next open publishes a+fresh, working engine.+"""++import threading+import time+import uuid++import pytest+from sqlalchemy import text++from local_deep_research.database.encrypted_db import DatabaseManager++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")++CHURN_ITERATIONS = 12+TEARDOWN_ITERATIONS = 6+# Cap on the extra teardown passes taken while the churn thread is still+# running. The fixed TEARDOWN_ITERATIONS at 0.02s is only ~0.12s against+# 12 real SQLCipher cold opens, so without this the teardown thread+# routinely finishes first and the race is never actually raced.+TEARDOWN_MAX_ITERATIONS = 200+JOIN_TIMEOUT_S = 60+BARRIER_TIMEOUT_S = 30+# Backoff before the single retry of a legitimate open. A transient+# SQLITE_BUSY under close_all contention is not the property under test,+# and reddening on it turns a loaded runner into a security-gate failure.+RETRY_BACKOFF_S = 0.1+# Sanity floor, not the race witness (that's ``overlaps >= 1`` in+# ``_run_and_assert_raced``): the teardown thread must have completed at+# least this many close_all passes, otherwise it never ran at all.+MIN_TEARDOWN_PASSES = 1+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager writing to an isolated data directory.++ Same self-contained pattern as the round-1/2 files, with the sanctioned+ test-mode KDF knob (each churn iteration cold-opens through PBKDF2).+ """+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ mgr = DatabaseManager()+ mgr.data_dir = tmp_path+ yield mgr+ mgr.close_all_databases()+++def _sample_pairing(manager, violations, label):+ with manager._connections_lock:+ engines = set(manager.connections)+ verifiers = set(manager._password_verifiers)+ if engines != verifiers:+ violations.append(f"{label}: engines={engines} verifiers={verifiers}")+++def _run_churn_vs_teardown(manager, usernames, password_for):+ """Shared driver: churn thread opens/closes users round-robin; teardown+ thread hammers close_all_databases until the churn finishes.++ Returns ``(errors, pairing_violations, open_failures, overlaps,+ teardown_passes)``. ``overlaps`` counts the teardown passes that ran+ while the churn thread was demonstrably still working -- without it the+ two threads can run end to end without ever meeting and the test passes+ having raced nothing. ``teardown_passes`` is the total, used as the+ minimum-progress witness.+ """+ barrier = threading.Barrier(2)+ errors = {}+ pairing_violations = []+ open_failures = []+ churn_done = threading.Event()+ overlaps = 0+ teardown_passes = 0++ def churn():+ try:+ barrier.wait(timeout=BARRIER_TIMEOUT_S)+ for i in range(CHURN_ITERATIONS):+ username = usernames[i % len(usernames)]+ engine = manager.open_user_database(+ username, password_for[username]+ )+ if engine is None:+ # Retry once (see RETRY_BACKOFF_S): absorb a transient+ # busy-database under contention, keep a repeatable+ # refusal red.+ time.sleep(RETRY_BACKOFF_S)+ engine = manager.open_user_database(+ username, password_for[username]+ )+ if engine is None:+ open_failures.append(f"iteration {i}: {username} (twice)")+ continue+ manager.close_user_database(username)+ _sample_pairing(manager, pairing_violations, f"churn#{i}")+ except Exception as exc: # noqa: BLE001 - surfaced via `errors` below+ errors["churn"] = exc+ finally:+ churn_done.set()++ def teardown():+ nonlocal overlaps, teardown_passes+ try:+ barrier.wait(timeout=BARRIER_TIMEOUT_S)+ for i in range(TEARDOWN_MAX_ITERATIONS):+ still_churning = not churn_done.is_set()+ manager.close_all_databases()+ teardown_passes += 1+ _sample_pairing(manager, pairing_violations, f"teardown#{i}")+ if still_churning:+ overlaps += 1+ if i + 1 >= TEARDOWN_ITERATIONS and churn_done.is_set():+ break+ time.sleep(0.02)+ except Exception as exc: # noqa: BLE001 - surfaced via `errors` below+ errors["teardown"] = exc++ threads = [+ threading.Thread(target=churn, name="gap-o-churn"),+ threading.Thread(target=teardown, name="gap-o-teardown"),+ ]+ for t in threads:+ t.start()+ for t in threads:+ t.join(timeout=JOIN_TIMEOUT_S)+ assert not any(t.is_alive() for t in threads), "churn/teardown deadlocked"+ return (+ errors,+ pairing_violations,+ open_failures,+ overlaps,+ teardown_passes,+ )+++def _run_and_assert_raced(manager, usernames, password_for, max_attempts=5):+ """Run the churn/teardown race, retrying the racing phase (never the+ correctness assertions) until an overlap is actually witnessed, then+ binds ``overlaps >= 1``.++ A pass with zero interleaving proves nothing about the race -- so+ unlike a plain single-shot assertion, "we didn't overlap" gets a+ bounded number of fresh attempts (each a full barrier-synchronized+ churn/teardown run) before this fails. This used to be a+ ``pytest.skip``, which was worse than useless here: in the CI summary+ a skip from a loaded runner is indistinguishable from "no SQLCipher+ build", so the lane reported green having raced nothing and nobody+ could tell. Now a run that never overlaps is a hard failure, not a+ warning that survives unexamined.++ Every attempt's correctness invariants (errors, pairing, opens) are+ checked immediately and unconditionally: a real invariant violation+ fails the test on the attempt where it happened -- it is never+ absorbed by a later retry, because only the "did we overlap" outcome+ is retried.+ """+ for attempt in range(1, max_attempts + 1):+ (+ errors,+ pairing_violations,+ open_failures,+ overlaps,+ teardown_passes,+ ) = _run_churn_vs_teardown(manager, usernames, password_for)+ assert not errors, (+ f"a racing thread raised (attempt {attempt}): {errors}"+ )+ assert not open_failures, (+ f"legitimate opens failed during close_all churn "+ f"(attempt {attempt}): {open_failures}"+ )+ assert not pairing_violations, (+ f"engine/verifier pairing broke (attempt {attempt}): "+ f"{pairing_violations}"+ )+ # Sanity check only, not the race witness: a wedged runner that+ # never even started the teardown thread would fail here first.+ assert teardown_passes >= MIN_TEARDOWN_PASSES, (+ f"the teardown thread completed {teardown_passes} close_all "+ f"passes (minimum {MIN_TEARDOWN_PASSES}, attempt {attempt}) -- "+ "the race driver did not run"+ )+ if overlaps >= 1:+ return+ pytest.fail(+ f"close_all race not witnessed after {max_attempts} attempts: the "+ "teardown thread never ran while the churn thread was still "+ "active on any attempt, so the pairing invariant above was "+ "checked but nothing was actually raced"+ )+++def test_close_all_racing_single_user_open_close_churn(manager):+ """O1: one user's open/close churn vs repeated close_all_databases."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"churnone_{uuid.uuid4().hex[:8]}"+ password = "ChurnOnePassword1!" # noqa: S105+ engine = manager.create_user_database(username, password)+ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE gap_o_canary (id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO gap_o_canary (id, note) VALUES (1, :note)"),+ {"note": "gap-O1"},+ )+ manager.close_user_database(username)++ _run_and_assert_raced(manager, [username], {username: password})++ # Stabilize: final close_all empties every map.+ manager.close_all_databases()+ with manager._connections_lock:+ assert manager.connections == {}+ assert manager._password_verifiers == {}++ # The next open publishes a fresh working engine with the canary.+ fresh = manager.open_user_database(username, password)+ assert fresh is not None+ with fresh.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_o_canary WHERE id = 1")+ ).scalar()+ == "gap-O1"+ )+ assert manager.connections[username] is fresh+++def test_close_all_racing_multi_user_churn(manager):+ """O2: three users churned round-robin vs the same teardown; every user+ reopens afterwards and reads its OWN canary (no cross-user bleed)."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ users = []+ for name, password, note in [+ ("churnu1", "ChurnUserPw1!", "gap-O2-one"),+ ("churnu2", "ChurnUserPw2!", "gap-O2-two"),+ ("churnu3", "ChurnUserPw3!", "gap-O2-three"),+ ]:+ username = f"{name}_{uuid.uuid4().hex[:8]}"+ engine = manager.create_user_database(username, password)+ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE gap_o_canary "+ "(id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO gap_o_canary (id, note) VALUES (1, :note)"),+ {"note": note},+ )+ users.append((username, password, note))+ manager.close_all_databases()++ usernames = [u for u, _, _ in users]+ password_for = {u: p for u, p, _ in users}+ _run_and_assert_raced(manager, usernames, password_for)++ manager.close_all_databases()+ with manager._connections_lock:+ assert manager.connections == {}+ assert manager._password_verifiers == {}++ for username, password, note in users:+ fresh = manager.open_user_database(username, password)+ assert fresh is not None, f"{username} failed to reopen after churn"+ with fresh.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_o_canary WHERE id = 1")+ ).scalar()+ == note+ ), f"{username} read the wrong user's canary"diff --git a/tests/security/test_db_connection_close_and_salt_lifecycle.py b/tests/security/test_db_connection_close_and_salt_lifecycle.pynew file mode 100644index 0000000000..e64dc36810--- /dev/null+++ b/tests/security/test_db_connection_close_and_salt_lifecycle.py@@ -0,0 +1,293 @@+"""Close idempotency and salt stability across the rekey lifecycle.++Incident context (PR #5596): eviction correctness is what keeps the+cache trustworthy -- ``close_user_database`` pops engine AND verifier+together under the lock, and ``change_password``'s rekey must not+disturb the on-disk key-derivation inputs. This file pins the two+remaining lifecycle edges:++* AE1 double-close is a no-op (the ``if username in connections`` guard+ makes the second close silently skip) -- single-threaded and for a+ user never opened; no raise, maps stay clean;+* AE2 concurrent double-close: 2 threads x 6 iterations racing closes+ of the same warm user -- no unhandled exception, the pairing invariant+ holds under ``_connections_lock`` at every sample, maps empty after,+ reopen works (round-4 O's pairing discipline applied to the close+ path);+* AF1 salt stability across rekey: the .salt bytes (sha256), its 0o600+ mode, and the absence of .salt.new/.salt.tmp leftovers are identical+ before and after change_password -- the rekey changes the FILE key,+ never the salt (set_sqlcipher_rekey reads the same salt);+* AF2 sidecars after rekey + final close: none left (the close-time WAL+ checkpoint removes them, mirroring round-4 S on the rekey path).+"""++import hashlib+import os+import stat+import threading+import uuid+from pathlib import Path++import pytest+from sqlalchemy import text++from local_deep_research.database.encrypted_db import DatabaseManager+from local_deep_research.database.sqlcipher_utils import get_salt_file_path++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")++CLOSE_ITERATIONS = 6+JOIN_TIMEOUT_S = 60+BARRIER_TIMEOUT_S = 30+# Race witness floor for AE2: at least this many of the racing closes must+# have found a live cached entry. Below it the "race" degenerated to AE1's+# no-op double-close shape and pins nothing new.+MIN_EFFECTIVE_CLOSES = 1+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager writing to an isolated data directory.++ Same self-contained pattern as the round-1..5 files, with the+ sanctioned test-mode KDF knob.+ """+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ mgr = DatabaseManager()+ mgr.data_dir = tmp_path+ yield mgr+ mgr.close_all_databases()+++def _write_canary(engine, note: str) -> None:+ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE gap_ae_canary (id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO gap_ae_canary (id, note) VALUES (1, :note)"),+ {"note": note},+ )+++def _salt_state(db_path: Path) -> tuple:+ salt_path = get_salt_file_path(db_path)+ data = salt_path.read_bytes()+ return (+ hashlib.sha256(data).hexdigest(),+ stat.S_IMODE(os.stat(salt_path).st_mode),+ )+++def test_double_close_is_an_idempotent_noop(manager):+ """AE1: closing twice in a row, and closing a user who was never+ opened, neither raise nor disturb the maps."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"dblclose_{uuid.uuid4().hex[:8]}"+ password = "DoubleClosePw1!" # noqa: S105+ engine = manager.create_user_database(username, password)+ _write_canary(engine, "gap-AE1")++ manager.close_user_database(username)+ # Second close on the just-closed user: silent no-op.+ manager.close_user_database(username)+ # Close for a user never opened on this manager: same shape.+ manager.close_user_database(f"never-opened-{uuid.uuid4().hex[:8]}")++ with manager._connections_lock:+ assert manager.connections == {}+ assert manager._password_verifiers == {}+ # Reopen still works -- the no-op closes hurt nothing.+ reopened = manager.open_user_database(username, password)+ assert reopened is not None+ with reopened.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_ae_canary WHERE id = 1")+ ).scalar()+ == "gap-AE1"+ )+++def test_concurrent_double_close_races_stay_clean(manager):+ """AE2: two threads race closes of the same warm user. No unhandled+ exception, pairing invariant at every sample, empty maps after,+ reopen works."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"raceclose_{uuid.uuid4().hex[:8]}"+ password = "RaceClosePw1!" # noqa: S105+ engine = manager.create_user_database(username, password)+ _write_canary(engine, "gap-AE2")++ barrier = threading.Barrier(2)+ errors = {}+ pairing_violations = []+ rounds = {} # race witness: completed iterations per closer+ effective_closes = [] # closes that actually evicted a cached engine++ def closer(label):+ try:+ barrier.wait(timeout=BARRIER_TIMEOUT_S)+ completed = 0+ for i in range(CLOSE_ITERATIONS):+ # Reopen between closes so both threads usually find+ # something to close -- otherwise the race collapses to+ # AE1's no-op shape and proves nothing.+ if manager.open_user_database(username, password) is None:+ manager.open_user_database(username, password)+ with manager._connections_lock:+ was_cached = username in manager.connections+ manager.close_user_database(username)+ if was_cached:+ effective_closes.append(f"{label}#{i}")+ completed += 1+ with manager._connections_lock:+ engines = set(manager.connections)+ verifiers = set(manager._password_verifiers)+ if engines != verifiers:+ pairing_violations.append(+ f"{label} #{i}: {engines} vs {verifiers}"+ )+ rounds[label] = completed+ except Exception as exc: # noqa: BLE001 - surfaced via `errors` below+ errors[label] = exc++ threads = [+ threading.Thread(target=closer, args=("a",), name="gap-ae2-a"),+ threading.Thread(target=closer, args=("b",), name="gap-ae2-b"),+ ]+ for t in threads:+ t.start()+ for t in threads:+ t.join(timeout=JOIN_TIMEOUT_S)+ assert not any(t.is_alive() for t in threads), "close race deadlocked"+ assert not errors, f"a racing closer raised: {errors}"+ assert not pairing_violations, (+ f"engine/verifier pairing broke: {pairing_violations}"+ )++ # Race witnesses: both closers ran every iteration, and the closes were+ # not all no-ops. `outcome recorded but never asserted` is how a loaded+ # runner reports green having raced nothing.+ assert rounds == {"a": CLOSE_ITERATIONS, "b": CLOSE_ITERATIONS}, (+ f"a closer did not complete its iterations: {rounds}"+ )+ assert len(effective_closes) >= MIN_EFFECTIVE_CLOSES, (+ f"only {len(effective_closes)} of the racing closes found a cached "+ f"engine (minimum {MIN_EFFECTIVE_CLOSES}) -- every close was a no-op, "+ "so this run degenerated to AE1's shape"+ )++ manager.close_user_database(username) # final drain+ with manager._connections_lock:+ assert username not in manager.connections+ assert username not in manager._password_verifiers++ reopened = manager.open_user_database(username, password)+ assert reopened is not None+ with reopened.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_ae_canary WHERE id = 1")+ ).scalar()+ == "gap-AE2"+ )+++def test_salt_bytes_and_mode_survive_rekey_untouched(manager):+ """AF1: change_password rekeys the file, not the salt: sha256 and+ 0o600 mode identical before/after, and no .salt.new/.salt.tmp (or+ any other unexpected sibling) is left behind."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"saltrekey_{uuid.uuid4().hex[:8]}"+ old = "SaltRekeyOldPw1!" # noqa: S105+ new = "SaltRekeyNewPw2!" # noqa: S105+ engine = manager.create_user_database(username, old)+ _write_canary(engine, "gap-AF1")+ manager.close_user_database(username)++ db_path = manager._get_user_db_path(username)+ before = _salt_state(db_path)+ files_before = {p.name for p in manager.data_dir.iterdir()}++ assert manager.change_password(username, old, new) is True++ after = _salt_state(db_path)+ assert after[0] == before[0], "the salt BYTES changed across the rekey"+ assert after[1] == before[1] == 0o600, (+ "the salt MODE changed across the rekey"+ )++ files_after = {p.name for p in manager.data_dir.iterdir()}+ unexpected = {+ name+ for name in files_after - files_before+ if ".salt.new" in name or ".salt.tmp" in name+ }+ assert not unexpected, (+ f"rekey left salt work-in-progress files: {unexpected}"+ )++ # And the rekeyed database serves its data under the new password.+ reopened = manager.open_user_database(username, new)+ assert reopened is not None+ with reopened.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_ae_canary WHERE id = 1")+ ).scalar()+ == "gap-AF1"+ )+++def test_no_sidecars_left_after_rekey_and_final_close(manager):+ """AF2: warm with a fresh write, rekey, close -> the close-time WAL+ checkpoint leaves no -wal/-shm behind (round-4 S's property, pinned+ on the rekey path)."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"rekeywal_{uuid.uuid4().hex[:8]}"+ old = "RekeyWalOldPw1!" # noqa: S105+ new = "RekeyWalNewPw2!" # noqa: S105+ engine = manager.create_user_database(username, old)+ _write_canary(engine, "gap-AF2")++ # WAL mode is genuinely on while warm (round-4 S pinned this; here we+ # only need the sidecars to be plausible mid-open).+ assert manager.change_password(username, old, new) is True+ manager.close_user_database(username)++ leftovers = [+ p.name+ for p in manager.data_dir.iterdir()+ if p.name.endswith(("-wal", "-shm"))+ ]+ assert leftovers == [], (+ f"rekey + close left WAL sidecars behind: {leftovers}"+ )++ reopened = manager.open_user_database(username, new)+ assert reopened is not None+ with reopened.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_ae_canary WHERE id = 1")+ ).scalar()+ == "gap-AF2"+ )diff --git a/tests/security/test_db_connection_cold_open_artifacts.py b/tests/security/test_db_connection_cold_open_artifacts.pynew file mode 100644index 0000000000..1e368eeb6b--- /dev/null+++ b/tests/security/test_db_connection_cold_open_artifacts.py@@ -0,0 +1,253 @@+"""Cold-path artifact hygiene and edge-password depth at real SQLCipher level.++Incident context (PR #5596): the fix made every cache hit fall through to a+key-validating cold open when the verifier does not match. That moves the+cold open onto the hot path of every WRONG-password attempt (an attacker's+guess is now a full PBKDF2 derivation + SQLCipher verify every time), so+the cold path's on-disk hygiene is now part of the security boundary:++* a rejected cold attempt must leave the filesystem exactly as it found it+ (no -wal/-shm/-journal droppings, no byte changes, no permission drift,+ nothing a forensic or a subsequent open could trip over);+* it must leave the manager exactly as it found it (no engine, no verifier+ cached from a FAILED attempt -- a cached verifier matching a wrong+ password would re-arm the original incident);+* repeated failures must not poison the next CORRECT open;+* passwords that are byte-distinct but "look equivalent" (NFC vs NFD+ unicode, embedded NUL, 4096 chars) must be treated as fully distinct+ keys, cold AND warm.++``test_login_cached_connection_password.py::test_wrong_password_rejected_+when_connection_is_cold`` pins only the None return value.+``test_password_verifier_primitive.py`` pins unicode/case/whitespace+distinctness of the verifier DIGEST; this file pins the same distinctness+against real PBKDF2+SQLCipher keys and real files. ``test_db_file_+permissions.py`` pins 0600 on the unencrypted CREATE path only.+"""++import hashlib+import os+import unicodedata+import uuid+from pathlib import Path++import pytest+from sqlalchemy import text++from local_deep_research.database.encrypted_db import DatabaseManager++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager writing to an isolated data directory.++ Same self-contained pattern as the incident tests; KDF iterations are+ lowered via the sanctioned test-mode knob (see tests/conftest.py's+ ``app`` fixture) so the many wrong-password derivations below stay fast.+ """+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ mgr = DatabaseManager()+ mgr.data_dir = tmp_path+ yield mgr+ mgr.close_all_databases()+++def _dir_fingerprint(root: Path) -> dict:+ """name -> (size, sha256, mode) for every file under root."""+ fingerprint = {}+ for path in sorted(root.rglob("*")):+ if path.is_file():+ data = path.read_bytes()+ fingerprint[path.name] = (+ len(data),+ hashlib.sha256(data).hexdigest(),+ os.stat(path).st_mode,+ )+ return fingerprint+++def _dir_mode(root: Path) -> int:+ return os.stat(root).st_mode+++def test_wrong_password_cold_open_leaves_no_new_artifacts(manager):+ """A rejected cold attempt must not create or mutate ANY file.++ Snapshot (names, sizes, digests, modes) before vs after must be+ identical: no new -wal/-shm/-journal sidecars, no touched header bytes,+ no permission drift. The DB directory must stay owner-only (0o700 --+ the defense that covers any sidecar SQLite would recreate with umask+ perms, see ``_ensure_data_dir``).+ """+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"cold_artifact_{uuid.uuid4().hex[:8]}"+ password = "ColdArtifactPassword1!" # noqa: S105+ manager.create_user_database(username, password)+ manager.close_user_database(username)++ before = _dir_fingerprint(manager.data_dir)+ dir_mode_before = _dir_mode(manager.data_dir)+ db_path = manager._get_user_db_path(username)+ assert db_path.exists(), "setup: the closed DB file must exist"++ for wrong in ("totally-wrong", "ColdArtifactPassword1! ", "x" * 4096):+ assert manager.open_user_database(username, wrong) is None, (+ f"wrong password {wrong[:16]!r}... opened the cold database"+ )++ after = _dir_fingerprint(manager.data_dir)+ assert set(after) == set(before), (+ f"failed cold attempts changed the file set: "+ f"new={sorted(set(after) - set(before))} "+ f"gone={sorted(set(before) - set(after))}"+ )+ changed = [name for name in before if before[name] != after[name]]+ assert not changed, (+ f"failed cold attempts mutated artifacts: {changed} "+ f"(before={ {n: before[n] for n in changed} }, "+ f"after={ {n: after[n] for n in changed} })"+ )+ assert _dir_mode(manager.data_dir) == dir_mode_before++ # The owner-only directory must still be owner-only, and the two files+ # that exist since creation must still be owner-only (0o600).+ assert os.stat(manager.data_dir).st_mode & 0o777 == 0o700+ assert os.stat(db_path).st_mode & 0o777 == 0o600++ # And the manager kept no trace of the failed attempts.+ assert manager.connections == {}+ assert manager._password_verifiers == {}+++def test_failed_wrong_attempts_do_not_poison_subsequent_correct_open(manager):+ """Several wrong cold attempts (varied shapes) must not poison the next+ correct open: the engine opens, reads real data, arms the verifier for+ the CORRECT password only, and a subsequent wrong attempt against the+ now-warm cache still fails."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"poison_{uuid.uuid4().hex[:8]}"+ password = "PoisonProofPassword1!" # noqa: S105+ engine = manager.create_user_database(username, password)+ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE gap_d_canary (id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO gap_d_canary (id, note) VALUES (1, :note)"),+ {"note": "gap-D"},+ )+ manager.close_user_database(username)++ for wrong in ("nope-1", "PoisonProofPassword1!x", "\x00embedded-nul"):+ assert manager.open_user_database(username, wrong) is None++ reopened = manager.open_user_database(username, password)+ assert reopened is not None, "correct open poisoned by earlier failures"+ with reopened.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_d_canary WHERE id = 1")+ ).scalar()+ == "gap-D"+ )+ assert manager._password_matches_cached(username, password) is True+ assert manager._password_matches_cached(username, "nope-1") is False++ # Warm-cache control after the recovery: still fail-closed.+ assert manager.open_user_database(username, "still-wrong") is None+ assert manager.connections[username] is reopened+++def test_edge_passwords_rejected_cold_and_warm(manager):+ """Byte-distinct but confusable passwords must behave as fully distinct+ keys against the real SQLCipher file, both cold and warm:++ * NFC vs NFD unicode forms of the same visible string;+ * a password with an embedded NUL byte;+ * a 4096-character password;+ * the empty string is rejected upstream with ValueError and must leave+ the filesystem untouched.++ Complements test_password_verifier_primitive.py (digest-level+ distinctness) by proving the end-to-end key path agrees: PBKDF2 over+ the UTF-8 bytes, so any normalization/truncation regression anywhere in+ the chain shows up here as an unexpected engine.+ """+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ nfc = unicodedata.normalize("NFC", "Cafe\u0301-Contrasenya-1!")+ nfd = unicodedata.normalize("NFD", "Cafe\u0301-Contrasenya-1!")+ assert nfc != nfd, "setup: NFC and NFD forms must be byte-distinct"+ nul_password = "Pass\x00w0rd-With-Nul!"+ long_password = "L" * 4096++ families = [+ (+ f"edge_nfc_{uuid.uuid4().hex[:8]}",+ nfc,+ [nfd, nul_password, long_password],+ ),+ (+ f"edge_nfd_{uuid.uuid4().hex[:8]}",+ nfd,+ [nfc, nul_password, long_password],+ ),+ ]++ for username, canonical, wrongs in families:+ engine = manager.create_user_database(username, canonical)+ assert engine is not None++ # Warm phase: cache holds an engine opened with the canonical form.+ warm_engine = manager.open_user_database(username, canonical)+ assert warm_engine is engine+ for wrong in wrongs:+ assert manager.open_user_database(username, wrong) is None, (+ f"warm cache accepted a byte-distinct variant for "+ f"{username}: {wrong[:20]!r}..."+ )+ # The rejections must not have disturbed the legitimate entry.+ assert manager.connections[username] is engine+ assert manager._password_matches_cached(username, canonical) is True++ # Cold phase: no cache, real key validation each time.+ manager.close_user_database(username)+ for wrong in wrongs:+ assert manager.open_user_database(username, wrong) is None, (+ f"cold open accepted a byte-distinct variant for "+ f"{username}: {wrong[:20]!r}..."+ )+ assert username not in manager.connections, (+ "a rejected variant left an engine cached"+ )+ assert username not in manager._password_verifiers, (+ "a rejected variant left a verifier cached"+ )++ # Recovery: the canonical form still works after all the rejects.+ recovered = manager.open_user_database(username, canonical)+ assert recovered is not None++ # Empty password: rejected by the key-validity guard with ValueError,+ # BEFORE any path resolution or file access.+ fingerprint_before = _dir_fingerprint(manager.data_dir)+ with pytest.raises(ValueError, match="Invalid encryption key"):+ manager.open_user_database(f"edge_empty_{uuid.uuid4().hex[:8]}", "")+ assert _dir_fingerprint(manager.data_dir) == fingerprint_before, (+ "the empty-password rejection must not touch the filesystem"+ )diff --git a/tests/security/test_db_connection_create_hostile_dir.py b/tests/security/test_db_connection_create_hostile_dir.pynew file mode 100644index 0000000000..1d22d8cad0--- /dev/null+++ b/tests/security/test_db_connection_create_hostile_dir.py@@ -0,0 +1,119 @@+"""``create_user_database`` in a read-only data directory.++Incident context (PR #5596): the cache only ever publishes engines for+creates that fully succeeded; a create that dies mid-way must leave the+filesystem in a state that cannot be mistaken for a usable (or+half-usable) account. A non-writable data directory is the simplest+hostile state that kills a create at its FIRST write -- before any+ciphertext exists.++AA1 (ACTUAL, probed): with the data dir at 0o500, the salt's+``os.open(..., O_CREAT)`` raises PermissionError out of+``create_user_database``; NO partial ``.db`` and NO partial ``.salt``+are left behind (the failure precedes every on-disk write); existing+users' files are untouched; restoring 0o700 lets the same username+create successfully. Complements round-2 H (duplicate/concurrent create+safety) by adding the permission-hostile dimension.+"""++import os+import stat+import uuid++import pytest+from sqlalchemy import text++from local_deep_research.database.encrypted_db import DatabaseManager++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")++# Every test below starts with `if os.geteuid() == 0: pytest.skip(...)`+# because permission bits are not enforced for root -- under the+# root-default docker-tests.yml container this whole module would+# silently no-op. Unlike ``serial`` this does NOT mutate process-global+# state (no shared state to race), it just needs a genuinely unprivileged+# process, so it opts into the dedicated non-root CI step instead of the+# parallel lane (see the ``nonroot`` marker in pyproject.toml and the+# dedicated step in .github/workflows/docker-tests.yml).+pytestmark = pytest.mark.nonroot+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager writing to an isolated data directory.++ Same self-contained pattern as the round-1..5 files, with the+ sanctioned test-mode KDF knob. One seed user is created and closed so+ the data dir is fully initialized (and its files give the "existing+ artifacts must be untouched" assertion something to protect).+ """+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ mgr = DatabaseManager()+ mgr.data_dir = tmp_path+ seed = f"roseed_{uuid.uuid4().hex[:8]}"+ mgr.create_user_database(seed, "SeedPw1!") # noqa: S105+ mgr.close_user_database(seed)+ yield mgr+ # Belt and suspenders: restore writability so the fixture teardown+ # (close_all_databases -> WAL checkpoints) and tmp_path cleanup work.+ os.chmod(mgr.data_dir, 0o700)+ mgr.close_all_databases()+++def test_create_in_readonly_data_dir_fails_cleanly_with_no_orphans(manager):+ """AA1: 0o500 data dir -> PermissionError, zero partial artifacts,+ existing files untouched, cache untouched; 0o700 restore -> the same+ username creates successfully."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")+ if os.geteuid() == 0:+ pytest.skip("permission bits are not enforced for root")++ data_dir = manager.data_dir+ before = sorted(p.name for p in data_dir.iterdir())+ assert before, "setup: the seed user's artifacts must exist"++ username = f"rocreate_{uuid.uuid4().hex[:8]}"+ os.chmod(data_dir, 0o500)+ try:+ assert stat.S_IMODE(os.stat(data_dir).st_mode) == 0o500+ with pytest.raises(PermissionError):+ manager.create_user_database(username, "RoCreatePw1!") # noqa: S105+ finally:+ os.chmod(data_dir, 0o700)++ # Zero orphans from the failed create; seed artifacts untouched.+ after = sorted(p.name for p in data_dir.iterdir())+ assert after == before, (+ f"the read-only-dir create left orphans or touched existing "+ f"files: new={set(after) - set(before)} gone={set(before) - set(after)}"+ )+ for name in after:+ assert username.split("_")[0] not in name # none belong to the new user+ assert username not in manager.connections+ assert username not in manager._password_verifiers++ # Restore proven: the same username now creates cleanly.+ engine = manager.create_user_database(username, "RoCreatePw1!") # noqa: S105+ assert engine is not None+ with engine.begin() as conn:+ conn.execute(+ text("CREATE TABLE gap_aa_canary (id INTEGER PRIMARY KEY, v TEXT)")+ )+ conn.execute(text("INSERT INTO gap_aa_canary VALUES (1, 'gap-AA')"))+ manager.close_user_database(username)+ reopened = manager.open_user_database(username, "RoCreatePw1!") # noqa: S105+ assert reopened is not None+ with reopened.connect() as conn:+ assert (+ conn.execute(+ text("SELECT v FROM gap_aa_canary WHERE id = 1")+ ).scalar()+ == "gap-AA"+ )diff --git a/tests/security/test_db_connection_create_safety.py b/tests/security/test_db_connection_create_safety.pynew file mode 100644index 0000000000..7b227f321f--- /dev/null+++ b/tests/security/test_db_connection_create_safety.py@@ -0,0 +1,251 @@+"""``create_user_database`` duplicate / concurrent / orphaned-salt safety.++Incident context (PR #5596): the connection cache is only as trustworthy as+the code paths that publish into it. ``_cache_connection`` (engine ++verifier, atomically) runs at the END of a successful create; the guards+in front of it decide who may get there:++* the ``db_path.exists()`` guard rejects a second create for an existing+ database (line ~526);+* the orphaned-salt recovery branch (lines ~560-568) removes a+ salt-without-db left by a dead create and retries, keeping usernames+ reusable.++Round 1 and the incident files covered the OPEN path deeply; the CREATE+path has no real-SQLCipher security coverage beyond happy-path fixtures.+This file pins:++* H1 duplicate create (same AND different password): ValueError, no+ rekey side effect (old password still opens, new still fails), on-disk+ artifacts byte/mode-identical, cache and verifier untouched;+* H2 a create racing an already-materialized DB file: the late create+ fails cleanly with the exists-ValueError and the in-flight winner+ survives intact (see the module FINDING note in the test docstring for+ why the simultaneous barrier variant is deliberately NOT asserted);+* H3 the orphaned-salt recovery branch: a salt without a .db is recovered+ from, the created DB opens with the chosen password, and only the+ documented artifacts remain.+"""++import hashlib+import threading+import time+import uuid++import pytest+from sqlalchemy import text++from local_deep_research.database.encrypted_db import DatabaseManager+from local_deep_research.database.sqlcipher_utils import create_database_salt++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager writing to an isolated data directory.++ Same self-contained pattern as the round-1 files, with the sanctioned+ test-mode KDF knob.+ """+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ mgr = DatabaseManager()+ mgr.data_dir = tmp_path+ yield mgr+ mgr.close_all_databases()+++def _dir_fingerprint(root) -> dict:+ """name -> (size, sha256, mode) for every file under root."""+ fingerprint = {}+ for path in sorted(root.rglob("*")):+ if path.is_file():+ data = path.read_bytes()+ fingerprint[path.name] = (+ len(data),+ hashlib.sha256(data).hexdigest(),+ path.stat().st_mode,+ )+ return fingerprint+++def test_duplicate_create_raises_and_changes_nothing(manager):+ """H1: a second create -- same or different password -- must be a clean+ no-op that changes nothing on disk or in the caches, and must NOT rekey+ (the original password keeps working, the impostor password keeps+ failing)."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"dup_{uuid.uuid4().hex[:8]}"+ password = "DuplicateCreatePw1!" # noqa: S105+ other_password = "ImpostorPassword2!" # noqa: S105+ engine = manager.create_user_database(username, password)+ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE gap_h_canary (id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO gap_h_canary (id, note) VALUES (1, :note)"),+ {"note": "gap-H"},+ )++ before = _dir_fingerprint(manager.data_dir)++ with pytest.raises(ValueError, match="already exists"):+ manager.create_user_database(username, password)+ with pytest.raises(ValueError, match="already exists"):+ manager.create_user_database(username, other_password)++ # Nothing on disk moved: same files, same bytes, same modes.+ assert _dir_fingerprint(manager.data_dir) == before, (+ "a rejected duplicate create mutated on-disk artifacts"+ )++ # Cache untouched: same engine object, verifier still for the ORIGINAL+ # password only.+ assert manager.connections[username] is engine+ assert manager._password_matches_cached(username, password) is True+ assert manager._password_matches_cached(username, other_password) is False++ # No rekey happened: the original password still opens (warm AND after+ # a close), the impostor still fails, and the data survived.+ assert manager.open_user_database(username, password) is engine+ manager.close_user_database(username)+ assert manager.open_user_database(username, other_password) is None+ reopened = manager.open_user_database(username, password)+ assert reopened is not None+ with reopened.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_h_canary WHERE id = 1")+ ).scalar()+ == "gap-H"+ )+++def test_create_racing_materialized_file_fails_cleanly_and_winner_survives(+ manager,+):+ """H2: thread T1 runs a full create; once its DB file has MATERIALIZED+ on disk (but while T1 may still be mid-migration), a second create for+ the same user must fail with the exists-ValueError, touch nothing, and+ leave T1's outcome intact: one shared cached engine, verifier armed,+ data readable.++ FINDING (documented, deliberately not asserted as a test):+ ``create_user_database`` does NOT acquire the per-user init lock (only+ ``open_user_database`` does). Two creates that both pass the+ ``db_path.exists()`` check before either materializes the file can+ interleave through the orphaned-salt recovery branch, whose+ ``_remove_partial_user_db_files`` may delete the other thread's+ partial DB. This test pins the contract that HOLDS today (a create+ racing an already-existing file fails cleanly); the+ both-past-the-guard interleaving is reported as a finding rather than+ shipped as a test.+ """+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"conccreate_{uuid.uuid4().hex[:8]}"+ password = "ConcurrentCreatePw1!" # noqa: S105+ db_path = manager._get_user_db_path(username)+ outcome = {}+ errors = {}++ def creator():+ try:+ outcome["engine"] = manager.create_user_database(username, password)+ except Exception as exc: # noqa: BLE001 - surfaced via `errors` below+ errors["creator"] = exc++ t1 = threading.Thread(target=creator, name="gap-h-creator")+ t1.start()+ try:+ # Wait until the winner's DB file exists but do NOT wait for the+ # create to finish -- the loser must fail cleanly even mid-create.+ deadline = time.monotonic() + 30+ while not db_path.exists():+ if time.monotonic() > deadline or not t1.is_alive():+ break+ time.sleep(0.005)+ assert db_path.exists(), (+ "setup: the creator thread never materialized the DB file"+ )++ with pytest.raises(ValueError, match="already exists"):+ manager.create_user_database(username, password)+ finally:+ t1.join(timeout=60)+ assert not t1.is_alive(), "creator thread hung"+ assert not errors, f"creator thread raised: {errors}"+ assert outcome["engine"] is not None++ # Exactly one engine published, verifier armed for the password, and+ # the engine genuinely works.+ assert manager.connections[username] is outcome["engine"]+ assert manager._password_matches_cached(username, password) is True+ with outcome["engine"].connect() as conn:+ assert conn.execute(text("SELECT 1")).scalar() == 1+++def test_orphaned_salt_recovery_creates_usable_database(manager):+ """H3: a .salt without a .db (a create killed mid-way, or pre-#4934+ cleanup that removed only the .db) must NOT brick the username: the+ recovery branch removes the orphan and the create succeeds. Without+ the branch, ``create_database_salt``'s FileExistsError would propagate+ and the username would stay permanently un-registerable -- so SUCCESS+ here is direct evidence the recovery branch ran. The resulting DB must+ open with the chosen password and leave only documented artifacts.+ """+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"orphan_{uuid.uuid4().hex[:8]}"+ password = "OrphanSaltRecoveryPw1!" # noqa: S105+ db_path = manager._get_user_db_path(username)++ # The orphan: exactly the state the recovery branch exists for. Import+ # and call the same salt creator encrypted_db.py itself uses.+ create_database_salt(db_path)+ assert db_path.with_suffix(db_path.suffix + ".salt").exists()+ assert not db_path.exists()++ engine = manager.create_user_database(username, password)+ assert engine is not None, (+ "orphaned-salt recovery failed (username bricked)"+ )+ with engine.connect() as conn:+ assert conn.execute(text("SELECT 1")).scalar() == 1++ # Post-conditions: the .db exists, a 32-byte salt sits beside it, and+ # nothing beyond the documented artifact family is present.+ assert db_path.exists()+ artifacts = {p.name for p in manager.data_dir.iterdir()}+ stem = db_path.name+ allowed = {+ stem,+ stem + ".salt",+ stem + "-wal",+ stem + "-shm",+ stem + "-journal",+ }+ assert artifacts <= allowed, (+ f"unexpected artifacts after recovery: {artifacts}"+ )++ # And the database reopens with the chosen password after a close.+ manager.close_user_database(username)+ reopened = manager.open_user_database(username, password)+ assert reopened is not None+ with reopened.connect() as conn:+ assert conn.execute(text("SELECT 1")).scalar() == 1+ assert manager._password_matches_cached(username, password) is Truediff --git a/tests/security/test_db_connection_cross_process.py b/tests/security/test_db_connection_cross_process.pynew file mode 100644index 0000000000..fe43965e8d--- /dev/null+++ b/tests/security/test_db_connection_cross_process.py@@ -0,0 +1,360 @@+"""Cross-process cache isolation: a warm in-process cache gives a separate+OS process nothing.++Incident context (PR #5596): the verifier is a per-PROCESS keyed HMAC --+``self._verifier_key = secrets.token_bytes(32)`` in ``DatabaseManager.+__init__`` -- and both ``connections`` and ``_password_verifiers`` are+plain in-process dicts. The realistic deployment shape is the web app+plus a second process (CLI / tooling / research worker) over the same+data directory. ``test_password_verifier_primitive.py`` pinned the+cross-KEY digest property; ``test_db_connection_multi_manager_isolation.+py`` (round 1) pinned cross-INSTANCE isolation within one process. This+file pins the actual multi-PROCESS property with real spawned children:++* Q1 a child process with its OWN DatabaseManager over the parent's data+ dir: wrong password -> None with nothing cached; correct password ->+ a working engine that reads the canary; the parent's warm cache,+ engine identity and verifier are completely undisturbed by the child's+ activity;+* Q2 the cross-process echo of round 4's gap P: the child holds a warm+ correct-password engine; the PARENT then rekeys the file via+ change_password; the child's next table read must die on the stale key,+ and the parent's new password reads the canary.+"""++import multiprocessing+import queue+import re+import time+import uuid+from pathlib import Path++import pytest+from sqlalchemy import text++from local_deep_research.database.encrypted_db import DatabaseManager++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")++# Deliberately short. The global pytest timeout is 180s (pyproject.toml),+# and a child that dies before its first put() -- or one left blocked+# because an assertion escaped the parent's try -- otherwise burns a full+# timeout per queue get AND another on the join, which can approach the+# global budget on its own. Children do one cold SQLCipher open at+# LDR_DB_CONFIG_KDF_ITERATIONS=1000, so 20s is a very generous ceiling.+CHILD_TIMEOUT_S = 20+# Granularity of the liveness poll while waiting on a child's queue.+CHILD_POLL_S = 0.25++# What a read through a STALE SQLCipher key looks like once the file has+# been rekeyed underneath it. Deliberately excludes contention errors+# ("database is locked"), which would otherwise satisfy a bare+# `select_ok is False` while proving nothing about the key.+STALE_KEY_ERROR_RE = re.compile(+ r"file is not a database|not a database|decrypt|HMAC|hmac|"+ r"malformed|encrypted",+ re.IGNORECASE,+)+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager writing to an isolated data directory.++ Same self-contained pattern as the round-1/2/3 files, with the+ sanctioned test-mode KDF knob (passed explicitly to the children --+ spawn inherits the environment, but the children set it themselves+ for determinism).+ """+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ mgr = DatabaseManager()+ mgr.data_dir = tmp_path+ yield mgr+ mgr.close_all_databases()+++def _child_env(data_dir: str) -> None:+ """Point THIS (child) process's environment at the parent's data dir+ with the same KDF knob, before any DatabaseManager is built."""+ import os++ os.environ["LDR_DATA_DIR"] = data_dir+ os.environ["LDR_DB_CONFIG_KDF_ITERATIONS"] = "1000"+++def _child_open_probe(data_dir, username, wrong_pw, correct_pw, result_q):+ """Q1 child: builds its own manager, tries wrong then correct."""+ try:+ _child_env(data_dir)+ from local_deep_research.database.encrypted_db import (+ DatabaseManager as ChildManager,+ )++ mgr = ChildManager()+ mgr.data_dir = Path(data_dir)+ try:+ wrong_engine = mgr.open_user_database(username, wrong_pw)+ result_q.put(+ {+ "wrong_engine": wrong_engine is not None,+ "wrong_cached": (+ username in mgr.connections+ or username in mgr._password_verifiers+ ),+ }+ )+ engine = mgr.open_user_database(username, correct_pw)+ canary = None+ if engine is not None:+ with engine.connect() as conn:+ canary = conn.execute(+ text("SELECT note FROM gap_q_canary WHERE id = 1")+ ).scalar()+ result_q.put(+ {+ "correct_engine": engine is not None,+ "canary": canary,+ }+ )+ finally:+ mgr.close_all_databases()+ except Exception as exc: # noqa: BLE001 - reported to the parent loudly+ result_q.put({"child_error": repr(exc)})+++def _child_holds_engine_then_reads(data_dir, username, pw, cmd_q, result_q):+ """Q2 child: opens (correct pw), signals, then SELECTs on command."""+ try:+ _child_env(data_dir)+ from pathlib import Path++ from local_deep_research.database.encrypted_db import (+ DatabaseManager as ChildManager,+ )++ mgr = ChildManager()+ mgr.data_dir = Path(data_dir)+ try:+ engine = mgr.open_user_database(username, pw)+ if engine is None:+ result_q.put({"child_error": "child cold-open failed"})+ return+ with engine.connect() as conn:+ note = conn.execute(+ text("SELECT note FROM gap_q_canary WHERE id = 1")+ ).scalar()+ result_q.put({"opened": True, "canary_before": note})+ while True:+ cmd = cmd_q.get(timeout=CHILD_TIMEOUT_S)+ if cmd == "done":+ break+ if cmd == "select":+ try:+ with engine.connect() as conn:+ note = conn.execute(+ text(+ "SELECT note FROM gap_q_canary WHERE id = 1"+ )+ ).scalar()+ result_q.put({"select_ok": True, "canary": note})+ except Exception as exc: # noqa: BLE001 - reported out+ result_q.put({"select_ok": False, "error": repr(exc)})+ finally:+ mgr.close_all_databases()+ except Exception as exc: # noqa: BLE001 - reported to the parent loudly+ result_q.put({"child_error": repr(exc)})+++def _get_result(result_q, what, child):+ """Fetch one result dict from a child, failing loudly on death.++ Polls ``child.is_alive()`` between short queue waits so a child that+ dies before its first ``put`` fails in seconds instead of stalling for+ the whole ``CHILD_TIMEOUT_S``.+ """+ deadline = time.monotonic() + CHILD_TIMEOUT_S+ while True:+ try:+ result = result_q.get(timeout=CHILD_POLL_S)+ break+ except queue.Empty:+ if not child.is_alive():+ # A child that already exited may still have results in+ # flight (the Queue feeder thread flushes on exit), so+ # give the pipe one last, generous chance before calling+ # it a death.+ try:+ result = result_q.get(timeout=CHILD_POLL_S * 8)+ break+ except queue.Empty:+ raise AssertionError(+ f"child died during {what} without reporting "+ f"(exitcode {child.exitcode})"+ ) from None+ if time.monotonic() >= deadline:+ raise AssertionError(+ f"child produced no result for {what} within "+ f"{CHILD_TIMEOUT_S}s"+ ) from None+ assert "child_error" not in result, (+ f"child failed during {what}: {result.get('child_error')}"+ )+ return result+++def _reap(child):+ """Join a child, killing it if it is wedged, so a failed assertion in+ the parent cannot cost a second full timeout in ``finally``."""+ child.join(timeout=CHILD_TIMEOUT_S)+ if child.is_alive():+ child.terminate()+ child.join(timeout=CHILD_POLL_S * 4)+++def test_separate_process_gets_nothing_from_parent_cache(manager, tmp_path):+ """Q1: parent cache is warm; a spawned child with its own manager gets+ no benefit from it (wrong pw refused, correct pw re-proven against+ SQLCipher) and the parent's state is untouched."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"xproc_{uuid.uuid4().hex[:8]}"+ password = "CrossProcessPw1!" # noqa: S105+ parent_engine = manager.create_user_database(username, password)+ with parent_engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE gap_q_canary (id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO gap_q_canary (id, note) VALUES (1, :note)"),+ {"note": "gap-Q"},+ )+ assert manager.is_user_connected(username), "parent cache must be warm"++ ctx = multiprocessing.get_context("spawn")+ result_q = ctx.Queue()+ child = ctx.Process(+ target=_child_open_probe,+ args=(+ str(manager.data_dir),+ username,+ "xproc-wrong",+ password,+ result_q,+ ),+ name="gap-q1-child",+ )+ child.start()+ try:+ wrong = _get_result(result_q, "wrong-password probe", child)+ assert wrong["wrong_engine"] is False, (+ "the child process opened the database with a wrong password"+ )+ assert wrong["wrong_cached"] is False, (+ "the child's refused attempt cached engine or verifier state"+ )+ correct = _get_result(result_q, "correct-password probe", child)+ assert correct["correct_engine"] is True, (+ "the child could not open with the correct password"+ )+ assert correct["canary"] == "gap-Q", (+ "the child's engine could not read the canary"+ )+ finally:+ _reap(child)+ assert not child.is_alive(), "Q1 child did not exit"+ assert child.exitcode == 0, f"Q1 child exitcode {child.exitcode}"++ # The child's activity must not have disturbed the parent at all.+ assert manager.connections[username] is parent_engine, (+ "the child replaced or evicted the parent's cached engine"+ )+ assert manager._password_matches_cached(username, password) is True+ with parent_engine.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_q_canary WHERE id = 1")+ ).scalar()+ == "gap-Q"+ )+++def test_parent_rekey_kills_child_held_engine(manager, tmp_path):+ """Q2: the child holds a warm correct-password engine; the parent+ rekeys the file; the child's next table read dies on the stale key+ (gap P's cross-process echo), and the parent's new password reads the+ canary."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"xprockey_{uuid.uuid4().hex[:8]}"+ old = "CrossProcOldPw1!" # noqa: S105+ new = "CrossProcNewPw2!" # noqa: S105+ engine = manager.create_user_database(username, old)+ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE gap_q_canary (id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO gap_q_canary (id, note) VALUES (1, :note)"),+ {"note": "gap-Q2"},+ )+ manager.close_user_database(username)++ ctx = multiprocessing.get_context("spawn")+ result_q = ctx.Queue()+ cmd_q = ctx.Queue()+ child = ctx.Process(+ target=_child_holds_engine_then_reads,+ args=(str(manager.data_dir), username, old, cmd_q, result_q),+ name="gap-q2-child",+ )+ child.start()+ try:+ opened = _get_result(result_q, "child warm-open", child)+ assert opened["opened"] is True+ assert opened["canary_before"] == "gap-Q2"++ # Parent-side rekey while the child holds its warm engine.+ assert manager.change_password(username, old, new) is True++ cmd_q.put("select")+ after = _get_result(result_q, "post-rekey child read", child)+ assert after["select_ok"] is False, (+ "the child's pre-rekey engine still reads data after the "+ "parent rekeyed the file -- the stale key outlived the rekey"+ )+ # The failure must be a KEY failure, not incidental contention:+ # "database is locked" would satisfy select_ok is False while+ # proving nothing about the stale key.+ assert STALE_KEY_ERROR_RE.search(after["error"]), (+ "the child's post-rekey read failed for the wrong reason -- "+ f"expected a key/HMAC/decrypt failure, got {after['error']!r}"+ )+ cmd_q.put("done")+ finally:+ _reap(child)+ assert not child.is_alive(), "Q2 child did not exit"+ assert child.exitcode == 0, f"Q2 child exitcode {child.exitcode}"++ # Parent-side recovery with the new password.+ reopened = manager.open_user_database(username, new)+ assert reopened is not None+ with reopened.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_q_canary WHERE id = 1")+ ).scalar()+ == "gap-Q2"+ )+ assert manager.open_user_database(username, old) is Nonediff --git a/tests/security/test_db_connection_get_session_no_open.py b/tests/security/test_db_connection_get_session_no_open.pynew file mode 100644index 0000000000..1ec7beb2a8--- /dev/null+++ b/tests/security/test_db_connection_get_session_no_open.py@@ -0,0 +1,233 @@+"""``get_session`` never-open-on-miss, proven against real SQLCipher files.++Incident context (PR #5596, cached-connection login auth bypass):+``DatabaseManager.connections`` was keyed by username alone and a cache hit+returned the engine without verifying the password. The fix's docstring for+``get_session`` documents the load-bearing guarantee that keeps this+passwordless accessor safe:++ It NEVER opens a database -- a cache miss returns ``None``. [...]++That property has no dedicated real-DB coverage today:+``tests/database/test_encrypted_db_manager.py::TestSessionManagement`` pins+``get_session`` only against ``MagicMock`` engines injected straight into+``connections``, so a regression that made ``get_session`` lazily open the+database (the exact "DO NOT add a lazy open-on-miss here" warning in the+fix) would pass every existing test and turn this post-auth accessor back+into an unauthenticated engine dispenser: any caller holding a username+would get a working engine for the on-disk database with no credential at+all -- a bypass strictly stronger than the original incident's, which at+least required a live cached connection.++These tests drive the real ``DatabaseManager`` with real SQLCipher files in+``tmp_path`` and assert the three shapes of the invariant:++* DB file exists on disk but the connection was closed -> ``None``, forever+ (no revival), and the file is not touched (content digest unchanged);+* user never opened -> ``None`` with NO side effects (no file creation, no+ cache pollution, not even a per-user init lock);+* many repeated calls -> a pure no-op, not a slow leak into any cache.+"""++import hashlib+import os+import uuid+from pathlib import Path++import pytest+from sqlalchemy import text++from local_deep_research.database.encrypted_db import DatabaseManager+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager writing to an isolated data directory.++ Mirrors the incident-test fixture pattern (self-contained per file --+ ``test_login_cached_connection_password.py``), with the low test-mode+ PBKDF2 iteration knob that ``tests/conftest.py``'s own ``app`` fixture+ uses (``MIN_KDF_ITERATIONS_TESTING`` exists precisely for this); it+ speeds key derivation without weakening any distinctness property these+ tests assert on.+ """+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ mgr = DatabaseManager()+ mgr.data_dir = tmp_path+ yield mgr+ # Dispose the real SQLCipher engines these tests open (a leaked+ # StaticPool/QueuePool engine holds live connections and FDs otherwise).+ mgr.close_all_databases()+++def _dir_fingerprint(root: Path) -> dict:+ """Map every file under ``root`` to (size, sha256, mode).++ Used to prove ``get_session`` is a pure no-op: not only must it not+ create files, it must not touch, truncate, chmod or checkpoint anything+ already on disk either.+ """+ fingerprint = {}+ for path in sorted(root.rglob("*")):+ if path.is_file():+ data = path.read_bytes()+ fingerprint[path.name] = (+ len(data),+ hashlib.sha256(data).hexdigest(),+ os.stat(path).st_mode,+ )+ return fingerprint+++def test_get_session_none_when_db_file_exists_but_connection_closed(manager):+ """A closed connection must stay closed: ``get_session`` returns ``None``+ even though the encrypted DB file (with real data in it) sits on disk.++ This is the "browser closed but DB idle" resting state from the+ incident. A lazy-open regression here would revive the engine with no+ credential, making the username alone sufficient again.+ """+ username = f"closed_db_{uuid.uuid4().hex[:8]}"+ password = "CorrectHorseBattery1!" # noqa: S105+ engine = manager.create_user_database(username, password)+ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE gap_a_canary (id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO gap_a_canary (id, note) VALUES (1, :note)"),+ {"note": "gap-A"},+ )+ manager.close_user_database(username)++ db_path = manager._get_user_db_path(username)+ assert db_path.exists(), "setup: the closed DB file must still exist"+ before = _dir_fingerprint(manager.data_dir)++ # Repeated asks: no revival on the first call, the second, or the tenth.+ for _ in range(10):+ assert manager.get_session(username) is None, (+ "get_session revived/opened a database whose connection was "+ "closed -- the never-open-on-miss guarantee is the reason this "+ "passwordless accessor is safe (see the #5596 fix docstring)"+ )++ # No half-revival state either: nothing cached, no verifier armed, and+ # the on-disk artifacts byte-identical (no checkpoint/write/chmod).+ assert username not in manager.connections+ assert username not in manager._password_verifiers+ assert manager._init_locks.get(username) is None, (+ "get_session must not even run the open-path machinery (init lock)"+ )+ assert _dir_fingerprint(manager.data_dir) == before, (+ "get_session modified on-disk artifacts for a closed user"+ )++ # Control: the file is genuinely still openable -- with the credential,+ # through open_user_database, the credential-taking entry point.+ reopened = manager.open_user_database(username, password)+ assert reopened is not None+ with reopened.connect() as conn:+ note = conn.execute(+ text("SELECT note FROM gap_a_canary WHERE id = 1")+ ).scalar()+ assert note == "gap-A", "canary row must survive the close/reopen cycle"+++def test_get_session_for_never_opened_user_creates_no_file(manager):+ """A username with no database anywhere must return ``None`` with zero+ side effects -- most importantly NO implicit file creation.++ If ``get_session`` ever materialized an empty database for an unknown+ username, it would become an oracle/enrollment primitive for arbitrary+ usernames and could shadow a later legitimate registration.+ """+ username = f"never_opened_{uuid.uuid4().hex[:8]}"++ assert manager.get_session(username) is None+ assert manager.get_session(username.upper()) is None # near-miss name++ # The data directory must be exactly as it was: no DB, no salt, no+ # sidecar files, nothing.+ assert list(manager.data_dir.rglob("*")) == [], (+ "get_session created on-disk artifacts for a user that never existed"+ )+ assert manager.connections == {}+ assert manager._password_verifiers == {}+ assert manager._init_locks == {}+++def test_get_session_is_not_an_auth_bypass_for_closed_db(manager):+ """Attacker shape from the incident: the caller controls only the+ username argument. While the victim's DB is closed, ``get_session`` must+ refuse; while a genuinely-connected user exists, it must work -- proving+ the refusals are policy, not a broken accessor.++ Complements test_login_cached_connection_password_route.py (which pins+ the login route end-to-end) by pinning the accessor itself at the+ connection layer against the lazy-open regression the fix explicitly+ warns about.+ """+ victim = f"victim_{uuid.uuid4().hex[:8]}"+ victim_password = "VictimSecretPassword1!" # noqa: S105+ manager.create_user_database(victim, victim_password)+ manager.close_user_database(victim)++ friend = f"friend_{uuid.uuid4().hex[:8]}"+ friend_password = "FriendOtherPassword2!" # noqa: S105+ friend_engine = manager.create_user_database(friend, friend_password)++ try:+ # The attacker "knows" the victim's username only.+ assert manager.get_session(victim) is None, (+ "get_session returned an engine for a closed database -- with no "+ "password argument this is an unauthenticated bypass"+ )+ assert victim not in manager.connections++ # Positive control on the same manager: the connected user DOES get+ # a usable session, bound to the cached engine.+ session = manager.get_session(friend)+ assert session is not None+ try:+ assert session.bind is friend_engine+ assert session.execute(text("SELECT 1")).scalar() == 1+ finally:+ session.close()++ # And the attacker's asks changed nothing about either user.+ assert manager.get_session(victim) is None+ assert victim not in manager.connections+ assert friend in manager.connections+ finally:+ manager.close_all_databases()+++def test_get_session_repeated_calls_are_pure_noop(manager):+ """Hammering ``get_session`` for an uncached user must be a pure no-op:+ no temp files, no cache entries, no init locks -- nothing that a later+ call could mistake for state.++ Guards against a "harmless-looking" regression where a miss spawns a+ throwaway engine, session, or lock per call (FD/resource leak that also+ widens the attack surface the incident exploited).+ """+ username = f"noop_hammer_{uuid.uuid4().hex[:8]}"+ password = "NoOpPassword3!" # noqa: S105+ manager.create_user_database(username, password)+ manager.close_user_database(username)+ before = _dir_fingerprint(manager.data_dir)++ for _ in range(50):+ assert manager.get_session(username) is None++ assert _dir_fingerprint(manager.data_dir) == before, (+ "50 get_session calls changed on-disk state for an uncached user"+ )+ assert manager.connections == {}+ assert manager._password_verifiers == {}+ assert manager._init_locks == {}+ assert manager.get_connected_usernames() == set()diff --git a/tests/security/test_db_connection_hostile_passwords.py b/tests/security/test_db_connection_hostile_passwords.pynew file mode 100644index 0000000000..e5f033da79--- /dev/null+++ b/tests/security/test_db_connection_hostile_passwords.py@@ -0,0 +1,106 @@+"""PRAGMA- and SQL-hostile passwords through the real key path.++Incident context (PR #5596): the connection layer never interpolates a+password into SQL. ``get_key_from_password``+(sqlcipher_utils.py::get_key_from_password) derives raw bytes with+PBKDF2 and the key reaches SQLCipher as a hex literal+(``PRAGMA key = "x'...'"`` / ``PRAGMA rekey``), so a password+that LOOKS like SQL or a PRAGMA is just key material. This file pins that+end-to-end for a battery of hostile strings, each as a REAL database:++* create with the hostile password -> canary write;+* warm open with the SAME hostile password reuses the cached engine+ (verifier matches -- the HMAC covers the exact bytes);+* a wrong-password sibling fails closed, warm and cold;+* close + cold reopen with the hostile password works and reads the+ canary.++Complements test_password_verifier_primitive.py (digest-level+distinctness for unusual strings): this is the full create/open/verify+cycle against real SQLCipher files. The KDF-1000 knob keeps the battery+fast.+"""++import uuid++import pytest+from sqlalchemy import text++from local_deep_research.database.encrypted_db import DatabaseManager++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")++HOSTILE_PASSWORDS = [+ "sqlite_master",+ "key='x'",+ "x'; DROP TABLE users;--",+ "PRAGMA cipher_integrity_check",+ "M\\' OR 1=1--",+ "%s%s%s%s",+ '{"n":1}',+]+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager writing to an isolated data directory.++ Same self-contained pattern as the round-1/2/3/4 files, with the+ sanctioned test-mode KDF knob.+ """+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ mgr = DatabaseManager()+ mgr.data_dir = tmp_path+ yield mgr+ mgr.close_all_databases()++[email protected]("password", HOSTILE_PASSWORDS)+def test_hostile_password_is_pure_key_material(manager, password):+ """A password that reads as SQL / a PRAGMA / a format string must+ behave as ordinary key material: create, warm reuse, fail-closed+ sibling, cold reopen -- no interpretation anywhere in the chain."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"hostile_{uuid.uuid4().hex[:8]}"+ wrong = password + "-wrong"++ engine = manager.create_user_database(username, password)+ assert engine is not None+ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE gap_y_canary (id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO gap_y_canary (id, note) VALUES (1, :note)"),+ {"note": password}, # the hostile string round-trips as data too+ )++ # Warm: the same hostile password hits the verifier and reuses the+ # engine (verifier-mismatch fail-closure for wrong passwords is+ # pinned extensively in rounds 1-4; Y's unique surface is the hostile+ # string surviving the full key path, checked cold below).+ assert manager.open_user_database(username, password) is engine+ assert manager._password_matches_cached(username, password) is True++ # Cold: close, then the hostile password reopens and the sibling fails.+ manager.close_user_database(username)+ assert manager.open_user_database(username, wrong) is None+ reopened = manager.open_user_database(username, password)+ assert reopened is not None+ with reopened.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_y_canary WHERE id = 1")+ ).scalar()+ == password+ ), "the hostile password must round-trip as plain data"diff --git a/tests/security/test_db_connection_integrity_swap.py b/tests/security/test_db_connection_integrity_swap.pynew file mode 100644index 0000000000..daa9df4984--- /dev/null+++ b/tests/security/test_db_connection_integrity_swap.py@@ -0,0 +1,122 @@+"""Integrity-check control and file-swap under a warm cache.++Incident context (PR #5596): the verifier protects the CONTROL plane+(which password may use the cached engine). It deliberately does not --+and cannot -- attest the DATA plane (which bytes are in the file). This+file pins both halves of that distinction at the real-file level:++* X1 ``check_database_integrity`` as the tamper control: with the engine+ warm and page-1 bytes flipped (round-3 K1's tamper shape), the+ quick_check read HMAC-fails inside the method and it returns False --+ WITHOUT evicting or polluting the engine/verifier pair (integrity+ checking must not mutate trust state); restoring the file makes the+ same warm engine report True again.++A companion file-swap-under-a-warm-cache test was dropped: it asserted on+SQLite page-cache internals (which stale page a held session happens to+still hold), which is neither an LDR contract nor stable across SQLite+builds. The underlying exposure -- control-plane trust outliving+data-plane integrity -- is out of scope for this battery.+"""++import shutil+import uuid+from pathlib import Path++import pytest+from sqlalchemy import text++from local_deep_research.database.encrypted_db import DatabaseManager++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager writing to an isolated data directory.++ Same self-contained pattern as the round-1/2/3/4 files, with the+ sanctioned test-mode KDF knob.+ """+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ mgr = DatabaseManager()+ mgr.data_dir = tmp_path+ yield mgr+ mgr.close_all_databases()+++def _tamper_page_one(db_path: Path) -> None:+ """Flip a few bytes inside page 1 (sqlite_master's page)."""+ size = db_path.stat().st_size+ offsets = [off for off in (100, 5000, 15000) if 0 < off < size]+ assert offsets, f"setup: db too small to tamper ({size} bytes)"+ with open(db_path, "r+b") as handle:+ for off in offsets:+ handle.seek(off)+ byte = handle.read(1)+ handle.seek(off)+ handle.write(bytes([byte[0] ^ 0xFF]))+++def test_integrity_check_detects_tamper_without_polluting_cache(manager):+ """X1: warm engine + page-1 tamper -> check_database_integrity False+ (the quick_check read fails the page HMAC inside the method); the+ engine/verifier pair is untouched by the check; restore -> True again+ on the SAME warm engine."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"integrityx_{uuid.uuid4().hex[:8]}"+ password = "IntegrityXPw1!" # noqa: S105+ engine = manager.create_user_database(username, password)+ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE gap_x_canary (id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO gap_x_canary (id, note) VALUES (1, :note)"),+ {"note": "gap-X1"},+ )+ assert manager.check_database_integrity(username) is True++ # Checkpoint the canary into the main file so on-disk tamper is what+ # the next fresh read sees, then back the pristine file up.+ manager.close_user_database(username)+ db_path = manager._get_user_db_path(username)+ backup = db_path.with_name(db_path.name + ".bak")+ shutil.copy2(db_path, backup)+ engine = manager.open_user_database(username, password)+ assert engine is not None # warm again++ _tamper_page_one(db_path)++ assert manager.check_database_integrity(username) is False, (+ "the integrity check did not detect a page-1 tamper"+ )+ # The check must not have evicted or polluted the trust state.+ with manager._connections_lock:+ assert set(manager.connections) == set(manager._password_verifiers)+ assert manager.connections[username] is engine+ assert manager._password_matches_cached(username, password) is True++ # Restore: the SAME warm engine reports healthy again (the pooled+ # connection's next read goes back to the restored bytes).+ shutil.copy2(backup, db_path)+ assert manager.check_database_integrity(username) is True, (+ "the integrity check did not recover after the file was restored"+ )+ with engine.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_x_canary WHERE id = 1")+ ).scalar()+ == "gap-X1"+ )diff --git a/tests/security/test_db_connection_kdf_downgrade.py b/tests/security/test_db_connection_kdf_downgrade.pynew file mode 100644index 0000000000..0cddcc442f--- /dev/null+++ b/tests/security/test_db_connection_kdf_downgrade.py@@ -0,0 +1,171 @@+"""KDF-iteration configuration drift resistance at open time.++Incident context (PR #5596): the fail-closed cache means every open is+ultimately backed by a real key validation. LDR derives SQLCipher keys+PYTHON-side (``get_key_from_password`` -> ``pbkdf2_hmac`` with+``get_sqlcipher_settings()["kdf_iterations"]``) and passes raw hex keys to+``PRAGMA key``, so the iteration count is part of the effective key+material even though it is NOT stored with the database (see+``warn_if_weak_kdf_with_existing_databases``'s docstring -- the+KDF-mismatch symptom class behind PR #4775).++If the environment's iteration count drifts between create and open, the+derived key changes and SQLCipher's HMAC check must fail. This file pins+that the manager does NOT silently absorb the drift -- no engine, no+verifier, no fallback -- in either direction, and that restoring the+creation-time count reopens the data:++* L1 downgrade (1000 -> 2000 between create and open): clean refusal,+ nothing published; restore -> opens, canary reads;+* L2 upgrade (1000 -> 4000): same clean refusal (direction-independence);+* L3 no residue / no silent fallback: repeated wrong-iter opens publish+ nothing and leave no state that could poison the later correct open.++``tests/database/test_kdf_iterations.py`` covers the settings-level floor+logic only (production vs test-mode minimums); the cross-OPEN behavior+here is new. Settings are read live per access (env_settings.py reads+``os.environ`` on every ``get``; no caching), which is what makes the+in-test env dance a faithful model of a drifted deployment.+"""++import uuid++import pytest+from sqlalchemy import text++from local_deep_research.database.encrypted_db import DatabaseManager+from local_deep_research.database.sqlcipher_utils import get_sqlcipher_settings++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager writing to an isolated data directory (KDF 1000).++ Same self-contained pattern as the round-1/2 files; the iteration+ count is the sanctioned test-mode knob.+ """+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ mgr = DatabaseManager()+ mgr.data_dir = tmp_path+ yield mgr+ mgr.close_all_databases()+++def _assert_nothing_published(manager, username):+ assert username not in manager.connections, (+ "a wrong-iteration open published an engine"+ )+ assert username not in manager._password_verifiers, (+ "a wrong-iteration open published a verifier"+ )+ assert manager.is_user_connected(username) is False+++def _make_user_with_canary(manager, note):+ username = f"kdfdrift_{uuid.uuid4().hex[:8]}"+ password = "KdfDriftPassword1!" # noqa: S105+ engine = manager.create_user_database(username, password)+ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE gap_l_canary (id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO gap_l_canary (id, note) VALUES (1, :note)"),+ {"note": note},+ )+ manager.close_user_database(username)+ return username, password+++ ("drift_iterations", "direction"),+ [("2000", "downgrade"), ("4000", "upgrade")],+)+def test_kdf_iteration_drift_refuses_open_and_restore_reopens(+ manager, monkeypatch, drift_iterations, direction+):+ """L1 + L2: changing the effective KDF iterations between create and+ open changes the derived key, so the open must fail cleanly (None,+ nothing published) regardless of direction; restoring the creation-time+ count reopens and reads the canary."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username, password = _make_user_with_canary(manager, f"gap-L-{direction}")++ # Sanity: the env knob genuinely reaches the live settings read that+ # open_user_database's key derivation uses.+ assert get_sqlcipher_settings()["kdf_iterations"] == 1000+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", drift_iterations)+ assert get_sqlcipher_settings()["kdf_iterations"] == int(drift_iterations)++ assert manager.open_user_database(username, password) is None, (+ f"a {direction} of KDF iterations (1000 -> {drift_iterations}) "+ "still opened the database -- the differently-derived key was "+ "accepted without a fallback"+ )+ _assert_nothing_published(manager, username)++ # Restore the creation-time count: the original key is derived again,+ # the open succeeds, and the data survived the whole drift window.+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ reopened = manager.open_user_database(username, password)+ assert reopened is not None, (+ "restore of the creation-time KDF count failed to reopen"+ )+ with reopened.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_l_canary WHERE id = 1")+ ).scalar()+ == f"gap-L-{direction}"+ )+ assert manager._password_matches_cached(username, password) is True+++def test_repeated_wrong_iteration_opens_leave_no_residue(manager, monkeypatch):+ """L3: no silent fallback and no poisoning. Repeated opens under the+ wrong iteration count each refuse and publish NOTHING (an engine that+ 'worked' via a hardcoded fallback would defeat the at-rest work factor+ -- the weak-KDF class PR #4816/#4775 warns about); afterwards the+ correct count opens cleanly, and a wrong password still fails closed+ through the verifier."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username, password = _make_user_with_canary(manager, "gap-L3")++ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "3000")+ for i in range(3):+ assert manager.open_user_database(username, password) is None, (+ f"wrong-iteration attempt #{i} opened the database"+ )+ _assert_nothing_published(manager, username)++ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ reopened = manager.open_user_database(username, password)+ assert reopened is not None, (+ "residue from failed drift opens poisoned recovery"+ )+ with reopened.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_l_canary WHERE id = 1")+ ).scalar()+ == "gap-L3"+ )++ # The recovered cache is still fail-closed for a wrong password.+ assert manager.open_user_database(username, "kdf-wrong") is None+ assert manager.connections[username] is reopened+ assert manager._password_matches_cached(username, password) is Truediff --git a/tests/security/test_db_connection_legacy_salt.py b/tests/security/test_db_connection_legacy_salt.pynew file mode 100644index 0000000000..0566c4d324--- /dev/null+++ b/tests/security/test_db_connection_legacy_salt.py@@ -0,0 +1,247 @@+"""Legacy v1 (shared-salt) databases on the post-#5596 connection layer.++Incident context (PR #5596): the fix's verifier is keyed by the password+alone (``_cache_connection`` publishes engine+verifier together on every+credential-proving open) -- it does not care HOW the SQLCipher key was+derived. LDR's v1 format derives keys with the shared+``LEGACY_PBKDF2_SALT`` when no per-database ``.salt`` file exists+(``get_salt_for_database``, sqlcipher_utils.py:42); v2 uses a random+per-DB salt written at creation (``create_database_salt``, line 77). The+open path warns when it sees a v1 database+(encrypted_db.py::_open_user_database_cold).++A genuine v1 database is built here by neutering the single+``create_database_salt`` call inside ``create_user_database`` (monkeypatch+to a no-op): with no ``.salt`` file, every key derivation -- creation,+open, rekey -- takes the legacy-salt-by-omission path. This file pins:++* V1 cold open of a v1 DB: succeeds, caches the engine, ARMS the verifier+ (the fix covers all opens regardless of salt format), and logs the+ legacy-salt warning naming the user; wrong password fails cleanly;+ correct password works warm and cold;+* V2 change_password on a v1 DB (ACTUAL behavior, read from+ ``change_password`` + ``set_sqlcipher_rekey``): the rekey itself also+ derives via ``get_key_from_password(new, db_path)`` -- salt-by-omission+ -- so it SUCCEEDS and the database STAYS v1 (no ``.salt`` file is ever+ created); old key dead, new key opens, data survives;+* V3 a v1 user and a v2 user coexist on one manager: both open, verifiers+ independent, cross-user passwords fail, close_all clears both.+"""++import uuid++import pytest+from sqlalchemy import text++import local_deep_research.database.encrypted_db as encrypted_db_module+from local_deep_research.database.encrypted_db import DatabaseManager+from local_deep_research.database.sqlcipher_utils import get_salt_file_path++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")++# The real salt writer, captured at import time so the v1-construction+# helper can restore it after neutering it for one creation.+_REAL_CREATE_DATABASE_SALT = encrypted_db_module.create_database_salt+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager writing to an isolated data directory.++ Same self-contained pattern as the round-1/2/3/4 files, with the+ sanctioned test-mode KDF knob.+ """+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ mgr = DatabaseManager()+ mgr.data_dir = tmp_path+ yield mgr+ mgr.close_all_databases()+++def _create_v1_user(manager, monkeypatch, note):+ """Create a GENUINE v1 user: no .salt file is written, so every key+ derivation (creation included) uses LEGACY_PBKDF2_SALT by omission."""+ username = f"legacyv1_{uuid.uuid4().hex[:8]}"+ password = "LegacyV1Password1!" # noqa: S105+ monkeypatch.setattr(+ encrypted_db_module, "create_database_salt", lambda _path: None+ )+ try:+ engine = manager.create_user_database(username, password)+ finally:+ # Restore immediately: later creates in the same test (v2 users)+ # must go through the real salt writer.+ monkeypatch.setattr(+ encrypted_db_module,+ "create_database_salt",+ _REAL_CREATE_DATABASE_SALT,+ )+ assert engine is not None+ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE gap_v_canary (id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO gap_v_canary (id, note) VALUES (1, :note)"),+ {"note": note},+ )+ manager.close_user_database(username)+ db_path = manager._get_user_db_path(username)+ assert not get_salt_file_path(db_path).exists(), (+ "setup: the v1 user must NOT have a .salt file"+ )+ return username, password+++def test_v1_legacy_db_opens_and_arms_verifier_with_warning(+ manager, monkeypatch, loguru_caplog_full+):+ """V1: cold open of a legacy shared-salt database succeeds, caches the+ engine, arms the verifier, and logs the legacy warning; wrong+ password fails cleanly; correct password works warm and cold."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username, password = _create_v1_user(manager, monkeypatch, "gap-V1")++ with loguru_caplog_full.at_level("DEBUG"):+ engine = manager.open_user_database(username, password)+ assert engine is not None, "a v1 database failed to open with its password"+ assert manager.connections[username] is engine+ assert manager._password_matches_cached(username, password) is True, (+ "the verifier must be armed for a v1 open exactly as for v2 -- "+ "the fix's cache contract is salt-format independent"+ )+ assert username in loguru_caplog_full.text, (+ "the legacy-salt warning must name the user when opening a v1 DB"+ )+ assert "legacy shared salt" in loguru_caplog_full.text++ # Warm: the correct password reuses the cached engine.+ assert manager.open_user_database(username, password) is engine++ # Wrong password: clean refusal on the warm cache, nothing published.+ assert manager.open_user_database(username, "legacy-v1-wrong") is None+ assert manager.connections[username] is engine++ # Cold: same story after a close.+ manager.close_user_database(username)+ assert manager.open_user_database(username, "legacy-v1-wrong") is None+ reopened = manager.open_user_database(username, password)+ assert reopened is not None+ with reopened.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_v_canary WHERE id = 1")+ ).scalar()+ == "gap-V1"+ )+++def test_change_password_on_v1_db_succeeds_and_stays_v1(manager, monkeypatch):+ """V2 (ACTUAL, read from the code): change_password rekeys through+ set_sqlcipher_rekey -> get_key_from_password(new, db_path), which+ ALSO derives by salt-omission for this user -- so the rekey succeeds,+ the old key dies, the new key opens with data intact, and the+ database REMAINS v1 (no .salt file is created; no migration to v2+ happens on the rekey path)."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username, old = _create_v1_user(manager, monkeypatch, "gap-V2")+ new = "LegacyV1NewPw2!" # noqa: S105+ db_path = manager._get_user_db_path(username)++ assert manager.change_password(username, old, new) is True++ # Old key dead, new key alive, data survived.+ assert manager.open_user_database(username, old) is None+ reopened = manager.open_user_database(username, new)+ assert reopened is not None+ with reopened.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_v_canary WHERE id = 1")+ ).scalar()+ == "gap-V2"+ )+ assert manager._password_matches_cached(username, new) is True++ # Format pin: still v1 -- no .salt file materialized anywhere.+ assert not get_salt_file_path(db_path).exists(), (+ "change_password created a per-database salt for a v1 user -- "+ "the rekey path was expected to stay salt-by-omission (pin "+ "updated if this intentionally changed)"+ )+++def test_v1_and_v2_users_coexist_with_independent_verifiers(+ manager, monkeypatch+):+ """V3: a legacy user and a fresh per-salt user on one manager: both+ open with their own passwords, verifiers stay independent, cross-user+ passwords fail, close_all clears both."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ v1_user, v1_pw = _create_v1_user(manager, monkeypatch, "gap-V3-v1")++ v2_user = f"freshv2_{uuid.uuid4().hex[:8]}"+ v2_pw = "FreshV2Password2!" # noqa: S105+ v2_engine = manager.create_user_database(v2_user, v2_pw)+ with v2_engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE gap_v_canary (id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO gap_v_canary (id, note) VALUES (1, :note)"),+ {"note": "gap-V3-v2"},+ )+ manager.close_user_database(v2_user)+ assert get_salt_file_path(manager._get_user_db_path(v2_user)).exists()++ # Both open; each keeps its own verifier.+ e1 = manager.open_user_database(v1_user, v1_pw)+ e2 = manager.open_user_database(v2_user, v2_pw)+ assert e1 is not None and e2 is not None and e1 is not e2+ assert manager._password_matches_cached(v1_user, v1_pw) is True+ assert manager._password_matches_cached(v2_user, v2_pw) is True+ with manager._connections_lock:+ assert set(manager.connections) == set(manager._password_verifiers)++ # Cross-user passwords fail against both the warm cache and the file.+ assert manager.open_user_database(v1_user, v2_pw) is None+ assert manager.open_user_database(v2_user, v1_pw) is None+ assert manager.connections[v1_user] is e1+ assert manager.connections[v2_user] is e2++ # Each engine reads only its own canary.+ with e1.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_v_canary WHERE id = 1")+ ).scalar()+ == "gap-V3-v1"+ )+ with e2.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_v_canary WHERE id = 1")+ ).scalar()+ == "gap-V3-v2"+ )++ manager.close_all_databases()+ with manager._connections_lock:+ assert manager.connections == {}+ assert manager._password_verifiers == {}diff --git a/tests/security/test_db_connection_log_hygiene.py b/tests/security/test_db_connection_log_hygiene.pynew file mode 100644index 0000000000..6830a3e124--- /dev/null+++ b/tests/security/test_db_connection_log_hygiene.py@@ -0,0 +1,217 @@+"""Log hygiene and auditability of failed credential attempts.++Incident context (PR #5596): the original cached-connection bypass was+invisible -- every attack "succeeded", so it cleared the lockout counter,+matched nothing anomalous in the logs, and left no trace. Two opposite+requirements follow for the fixed failure paths, both pinned here at the+real-SQLCipher level using the repo's canonical ``loguru_caplog_full``+fixture (the package disables its own loguru logging by default; the+fixture re-enables it and captures message + rendered exception block):++* I1 SECRECY -- a NEGATIVE property, deliberately scoped: no presented+ password, no derived hex key and no verifier salt/digest appears in any+ record captured while running (a) warm wrong-password opens, (b) cold+ wrong-password opens, (c) failed metrics sessions and (d) a failed+ change_password. It pins the observable outcome of those four paths and+ nothing more. In particular it is NOT a test of ``redact_secrets``: on+ all four paths the plaintext password never reaches ``str(e)`` in the+ first place (the engine creator closure is handed only the pre-derived+ ``hex_key``), and the traceback half is unobservable here because+ ``loguru_caplog_full`` fixes ``diagnose=False`` to match production. I1+ would therefore still hold with the redaction call deleted -- the+ redaction helpers are covered by ``test_password_leakage.py`` /+ ``test_credential_leak_followup.py``, and the rekey statement's own+ scrubbing by ``test_sqlcipher_rekey_key_not_leaked.py``. Path (d) is+ kept for the credential-bearing frames it drives under capture, NOT as+ coverage of ``change_password``'s handler, which it cannot reach: with+ a wrong old password ``open_user_database`` returns None and+ ``change_password`` returns False before the ``try`` body can raise.+ A positive control asserts that a package-originated record --+ ``_open_user_database_cold``'s own failure warning, which names the+ target username, the same shape I2 below pins -- IS present in the+ capture block, so the "not in captured" assertions cannot pass against+ a capture that recorded nothing at all.+* I2 AUDITABILITY: a failed attempt must not be SILENT either -- the+ cold-open failure path logs ``Failed to open database for user+ {username} ...`` at warning level, so every failed warm-cache+ wrong-password attempt leaves at least one record naming the target+ account. (Anti-invisibility regression guard: the incident's attacks+ produced zero failure records.)++The password-leakage unit tests in test_password_leakage.py /+test_credential_leak_followup.py cover the redaction helpers with mocked+databases; this file exercises the real database paths end to end and also+asserts the derived-key and verifier-material never reach the capture.+"""++import uuid++import pytest+from sqlalchemy import text++from local_deep_research.database.encrypted_db import DatabaseManager+from local_deep_research.database.sqlcipher_utils import get_key_from_password++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager writing to an isolated data directory.++ Same self-contained pattern as the round-1 files, with the sanctioned+ test-mode KDF knob (so in-test key derivation for the hex-leak oracle+ is cheap).+ """+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ mgr = DatabaseManager()+ mgr.data_dir = tmp_path+ yield mgr+ mgr.close_all_databases()+++def test_failed_credential_attempts_never_leak_secrets_into_logs(+ manager, loguru_caplog_full+):+ """I1: across warm opens, cold opens, metrics sessions and a failed+ change_password, no captured record contains any presented password,+ any derived hex key, or the verifier salt/digest.++ Negative property only -- see the module docstring for what this does+ and does not pin. The positive control below is what keeps it from+ passing vacuously.+ """+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"leakcheck_{uuid.uuid4().hex[:8]}"+ correct = f"R2Correct-Zebra-{uuid.uuid4().hex[:10]}" # noqa: S105+ wrong_warm = f"R2WarmWrong-Tiger-{uuid.uuid4().hex[:10]}" # noqa: S105+ wrong_cold = f"R2ColdWrong-Puma-{uuid.uuid4().hex[:10]}" # noqa: S105+ wrong_metrics = f"R2MetricsWrong-Lynx-{uuid.uuid4().hex[:10]}" # noqa: S105+ wrong_old = f"R2OldWrong-Bear-{uuid.uuid4().hex[:10]}" # noqa: S105+ new_password = f"R2New-Panda-{uuid.uuid4().hex[:10]}" # noqa: S105++ engine = manager.create_user_database(username, correct)+ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE gap_i_canary (id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO gap_i_canary (id, note) VALUES (1, :note)"),+ {"note": "gap-I"},+ )+ # Capture the verifier material while the engine is warm; it must never+ # surface in any captured record later.+ salt, digest = manager._password_verifiers[username]+ db_path = manager._get_user_db_path(username)+ hex_keys = [+ get_key_from_password(pw, db_path=db_path).hex()+ for pw in (correct, wrong_warm, wrong_cold, new_password)+ ]++ with loguru_caplog_full.at_level("DEBUG"):+ # (a) warm-cache wrong-password open+ assert manager.open_user_database(username, wrong_warm) is None+ # (b) cold wrong-password open+ manager.close_user_database(username)+ assert manager.open_user_database(username, wrong_cold) is None+ # (c) failed metrics session (cache is cold; falls through to open)+ with pytest.raises(ValueError):+ manager.create_thread_safe_session_for_metrics(+ username, wrong_metrics+ )+ # (d) failed change_password (wrong current password). This+ # returns False from the early `if not engine` inside the try --+ # it never reaches change_password's own except handler. It is+ # here for the credential-bearing frames it drives under capture,+ # not as coverage of that handler.+ assert (+ manager.change_password(username, wrong_old, new_password) is False+ )++ captured = loguru_caplog_full.text+ assert captured, "capture sanity: no records captured at all"+ assert username in captured, (+ "positive control missing: `_open_user_database_cold`'s own "+ "failure warning (which names the target username) did not reach "+ "`captured`, so the absence assertions below prove nothing"+ )++ for secret in (+ correct,+ wrong_warm,+ wrong_cold,+ wrong_metrics,+ wrong_old,+ new_password,+ ):+ assert secret not in captured, (+ f"presented password leaked into a log record: {secret!r}"+ )+ for hex_key in hex_keys:+ assert hex_key not in captured, (+ "a derived SQLCipher hex key leaked into logs"+ )+ assert salt.hex() not in captured, "verifier salt leaked into logs"+ assert digest.hex() not in captured, "verifier digest leaked into logs"++ # Control: the account still works after all the failed attempts.+ reopened = manager.open_user_database(username, correct)+ assert reopened is not None+ with reopened.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_i_canary WHERE id = 1")+ ).scalar()+ == "gap-I"+ )+++def test_failed_warm_wrong_password_attempt_is_logged_with_username(+ manager, loguru_caplog_full+):+ """I2 (anti-invisibility): the incident's attacks produced NO failure+ records (they counted as successes). Today every failed warm-cache+ wrong-password attempt falls through to a real cold open whose failure+ is logged naming the target username -- pin that, so a regression back+ to silent acceptance cannot hide.++ Verified against the current code first: ``_open_user_database_cold``'s+ failure handler emits ``logger.warning(f"Failed to open database for+ user {username} after ...")``, and the no-file path emits+ ``logger.error(f"No database found for user {username}")`` -- both+ name the account, so the assertion below holds today.+ """+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"audit_{uuid.uuid4().hex[:8]}"+ password = f"AuditOwl-{uuid.uuid4().hex[:10]}" # noqa: S105+ manager.create_user_database(username, password)++ with loguru_caplog_full.at_level("DEBUG"):+ for i in range(3):+ loguru_caplog_full.clear()+ assert (+ manager.open_user_database(username, f"audit-wrong-{i}") is None+ )+ captured = loguru_caplog_full.text+ assert username in captured, (+ f"failed warm-cache attempt #{i} left no log record naming "+ "the target account -- a silent-acceptance regression would "+ "be invisible again (the exact property that made the "+ "original incident undetectable)"+ )+ # And the records it did leave must not carry the credential.+ assert f"audit-wrong-{i}" not in captured, (+ f"attempt #{i}'s wrong password appears in a log record"+ )diff --git a/tests/security/test_db_connection_many_users.py b/tests/security/test_db_connection_many_users.pynew file mode 100644index 0000000000..4a4ac049f0--- /dev/null+++ b/tests/security/test_db_connection_many_users.py@@ -0,0 +1,292 @@+"""Many-user cache hygiene under sequential and concurrent churn.++Incident context (PR #5596): the cache maps (``connections``,+``_password_verifiers``, ``_init_locks``) are the entire trust state of+the connection layer. At scale -- many accounts churning through one+process -- two operational security properties must hold:++* W1 after 30 sequential create/write/close cycles and a final+ ``close_all_databases``, every map is empty (close_all clears all+ three, encrypted_db.py::close_all_databases) and the liveness+ accessors read zero;+* W2 the same 30 users created and churned CONCURRENTLY across 4 threads+ (each owning a subset, barrier-start, EVERY user with its own distinct+ password), with the engine/verifier pairing invariant sampled under+ ``_connections_lock`` throughout, no failed opens, and every user+ reopening afterwards reading its OWN canary.++FD-count deltas are deliberately NOT asserted here: pyproject.toml's+``fd_canary`` marker documents that ``/proc/self/fd`` assertions are+noisy under parallel execution, and this file belongs in the parallel+lane for the cache-hygiene coverage above. ``tests/utilities/+test_close_base_llm.py`` owns the FD-leak canaries.++Per-user schema migration is neutered for these tests ONLY (monkeypatch+of ``initialize.initialize_database`` to a no-op) -- the exact isolation+pattern of ``tests/database/test_concurrent_user_db_open.py`` -- because+30 full migrations would blow the run-time budget while exercising+nothing this file asserts on (the cache, the open/close lifecycle, and+descriptors are all fully real, backed by real SQLCipher files).+"""++import threading+import time+import uuid++import pytest+from sqlalchemy import text++import local_deep_research.database.initialize as init_mod+from local_deep_research.database.encrypted_db import DatabaseManager++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")++USER_COUNT = 30+THREAD_COUNT = 4+CHURN_ITERATIONS = 8+# 120s, not the 60s the other shared-deadline modules use: this module does+# 4 threads x 30 real SQLCipher users (create + write + churn + reopen),+# more work than the 3-thread modules the 60s budget was sized for, and+# unlike the per-thread-join modules (2 threads, 120s worst case each) it+# has no headroom to trade away -- there is only one shared deadline here.+# 120s join budget + pytest's own setup/call/teardown overhead (this+# fixture's ``close_all_databases`` teardown included) must still land+# under ``pyproject.toml``'s global ``timeout = 180``; 60s of headroom is+# the same margin the per-thread modules get.+JOIN_TIMEOUT_S = 120+BARRIER_TIMEOUT_S = 30+++def _join_all(threads):+ """Join every thread against ONE shared deadline.++ A per-thread ``join(timeout=JOIN_TIMEOUT_S)`` inside a loop costs+ ``len(threads) * JOIN_TIMEOUT_S`` in the worst case. ``pyproject.toml``+ sets ``timeout = 180`` with ``timeout_method = "thread"``, and+ pytest-timeout's thread handler ends in ``os._exit(1)`` -- so when these+ tests actually find the deadlock they exist to find, a per-thread budget+ would kill the whole xdist worker (losing its coverage, then tripping+ ``--cov-fail-under``) instead of failing on the named "deadlocked"+ assertion at the call site. One shared deadline bounds the entire join at+ JOIN_TIMEOUT_S regardless of thread count, which keeps that assertion+ reachable well inside the global timeout. Each thread still gets the full+ remaining budget in wall-clock terms, because the threads run+ concurrently.+ """+ deadline = time.monotonic() + JOIN_TIMEOUT_S+ for t in threads:+ t.join(timeout=max(0.0, deadline - time.monotonic()))+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager writing to an isolated data directory.++ Same self-contained pattern as the round-1/2/3/4 files, with the+ sanctioned test-mode KDF knob. ``initialize_database`` is additionally+ neutered for this file (see module docstring) to keep 30-user tests+ inside the run-time budget.+ """+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ monkeypatch.setattr(init_mod, "initialize_database", lambda *a, **k: None)+ # With migrations neutered the databases stay unstamped, which would+ # make every cold open attempt a pre-migration BACKUP. W asserts on+ # cache/FD lifecycle, not backups -- the same isolation class as the+ # initialize_database patch above.+ monkeypatch.setattr(+ "local_deep_research.database.alembic_runner.needs_migration",+ lambda *a, **k: False,+ )+ mgr = DatabaseManager()+ # The phase-2 RAG index re-key re-enters through vector-store imports+ # and dominates cold-open time; tests/database/test_concurrent_user_db+ # _open.py already isolates it the same way for cache-lifecycle tests.+ monkeypatch.setattr(mgr, "_run_phase2_rekey", lambda *a, **k: None)+ mgr.data_dir = tmp_path+ yield mgr+ mgr.close_all_databases()+++def _write_canary(engine, note: str) -> None:+ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE gap_w_canary (id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO gap_w_canary (id, note) VALUES (1, :note)"),+ {"note": note},+ )+++def _make_user(manager, index):+ username = f"many_{index}_{uuid.uuid4().hex[:8]}"+ password = f"ManyUsersPw{index % 10}!" # noqa: S105+ engine = manager.create_user_database(username, password)+ _write_canary(engine, f"gap-W-{index}")+ manager.close_user_database(username)+ return username, password+++def _assert_fully_drained(manager):+ with manager._connections_lock:+ assert manager.connections == {}, "close_all left cached engines"+ assert manager._password_verifiers == {}, "close_all left verifiers"+ assert manager._init_locks == {}, "close_all left init locks"+ assert manager.get_connected_usernames() == set()+ assert manager.get_memory_usage()["active_connections"] == 0+++def test_thirty_sequential_users_drain_all_state(manager):+ """W1: 30 sequential create+canary+close cycles, then close_all:+ all three maps empty, liveness accessors zero."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ users = [_make_user(manager, i) for i in range(USER_COUNT)]+ assert len(users) == USER_COUNT++ # Mid-state sanity: 30 engines came and went; nothing is live now+ # (each cycle closed its own engine), and the maps are paired-empty.+ with manager._connections_lock:+ assert set(manager.connections) == set(manager._password_verifiers)++ manager.close_all_databases()+ _assert_fully_drained(manager)++ # A sample of the users still opens and reads its canary afterwards.+ for username, password in users[:3]:+ engine = manager.open_user_database(username, password)+ assert engine is not None+ with engine.connect() as conn:+ note = conn.execute(+ text("SELECT note FROM gap_w_canary WHERE id = 1")+ ).scalar()+ assert note.startswith("gap-W-")+ manager.close_user_database(username)+ # close_user_database deliberately RETAINS per-user init locks (see+ # tests/database/test_concurrent_user_db_open.py); only close_all+ # clears them, so drain via close_all before asserting emptiness.+ manager.close_all_databases()+ _assert_fully_drained(manager)+++def test_thirty_users_concurrent_churn_stays_paired(manager):+ """W2: 30 users created and churned by 4 barrier-synced threads (each+ owning a subset, each user with its OWN password): no open failures,+ pairing invariant at every sample, every user reopen+canary at the+ end, all maps drained after close_all."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ barrier = threading.Barrier(THREAD_COUNT)+ errors = {}+ open_failures = []+ pairing_violations = []+ canary_failures = []+ subset_sizes = {}++ def worker(tid: int):+ try:+ # Each thread owns a DISJOINT subset of the USER_COUNT users and+ # creates them itself (parallel creation, distinct files). The+ # split is round-robin (`range(tid, USER_COUNT, THREAD_COUNT)`)+ # so the subsets together cover every user: a plain+ # `range(USER_COUNT // THREAD_COUNT)` silently dropped the+ # remainder and churned 28 of the 30 this test is named for.+ # Every user gets a DISTINCT password: a shared per-thread+ # password would make cross-user bleed WITHIN a thread's own+ # subset invisible (any of its users would open any other).+ own = [+ (+ f"many_c_{tid}_{i}_{uuid.uuid4().hex[:6]}",+ f"ConcPw{tid}_{i}_{uuid.uuid4().hex[:6]}!",+ )+ for i in range(tid, USER_COUNT, THREAD_COUNT)+ ]+ subset_sizes[tid] = len(own)+ notes = {}+ for index, (username, password) in enumerate(own):+ engine = manager.create_user_database(username, password)+ notes[username] = f"gap-W2-{tid}-{index}"+ _write_canary(engine, notes[username])++ barrier.wait(timeout=BARRIER_TIMEOUT_S)++ # Churn: cycle the subset, open + canary read + close.+ for i in range(CHURN_ITERATIONS):+ username, password = own[i % len(own)]+ engine = manager.open_user_database(username, password)+ if engine is None:+ open_failures.append(f"t{tid} churn#{i}: {username}")+ continue+ try:+ with engine.connect() as conn:+ note = conn.execute(+ text("SELECT note FROM gap_w_canary WHERE id = 1")+ ).scalar()+ if note != notes[username]:+ canary_failures.append(+ f"t{tid} churn#{i} {username}: read {note!r}, "+ f"expected {notes[username]!r}"+ )+ finally:+ manager.close_user_database(username)+ with manager._connections_lock:+ engines = set(manager.connections)+ verifiers = set(manager._password_verifiers)+ if engines != verifiers:+ pairing_violations.append(+ f"t{tid} churn#{i}: {engines} vs {verifiers}"+ )++ # Final pass: EVERY user in this thread's subset reopens and+ # reads its own canary.+ for username, password in own:+ engine = manager.open_user_database(username, password)+ if engine is None:+ open_failures.append(f"t{tid} final: {username}")+ continue+ try:+ with engine.connect() as conn:+ note = conn.execute(+ text("SELECT note FROM gap_w_canary WHERE id = 1")+ ).scalar()+ if note != notes[username]:+ canary_failures.append(+ f"t{tid} final {username}: read {note!r}, "+ f"expected {notes[username]!r}"+ )+ finally:+ manager.close_user_database(username)+ except Exception as exc: # noqa: BLE001 - surfaced via `errors` below+ errors[tid] = exc++ threads = [+ threading.Thread(target=worker, args=(i,), name=f"gap-w2-t{i}")+ for i in range(THREAD_COUNT)+ ]+ for t in threads:+ t.start()+ _join_all(threads)+ assert not any(t.is_alive() for t in threads), "many-user churn deadlocked"+ assert not errors, f"a churn thread raised: {errors}"+ assert sum(subset_sizes.values()) == USER_COUNT, (+ f"the thread subsets covered {sum(subset_sizes.values())} users, not "+ f"the {USER_COUNT} this test is named for: {subset_sizes}"+ )+ assert not open_failures, f"legitimate opens failed: {open_failures}"+ assert not canary_failures, f"cross-user canary reads: {canary_failures}"+ assert not pairing_violations, (+ f"engine/verifier pairing broke: {pairing_violations}"+ )++ manager.close_all_databases()+ _assert_fully_drained(manager)diff --git a/tests/security/test_db_connection_metrics_entry.py b/tests/security/test_db_connection_metrics_entry.pynew file mode 100644index 0000000000..d9ef485e6e--- /dev/null+++ b/tests/security/test_db_connection_metrics_entry.py@@ -0,0 +1,268 @@+"""``create_thread_safe_session_for_metrics`` under attack.++Incident context (PR #5596): this method is the SECOND credential-taking+entry point the fix closed. Pre-fix, its cache hit handed a Session bound+to the cached engine to ANY caller presenting the right username with any+password -- the same shape as the login bypass (see its docstring: "a+second instance of exactly the cached-connection password bypass"). The+fix routes a rejected cache hit through ``open_user_database`` so the wrong+password must survive a real key-validating cold open, ending in+``ValueError``.++Existing coverage is single-threaded only:+``test_login_cached_connection_password_extra.py::test_metrics_session_is_+fail_closed_on_wrong_password`` pins one warm wrong attempt and one warm+correct bind. This file adds the incident-shaped depth:++* G1 a storm race through THIS entry point (round 1's gap-C storm hammered+ ``open_user_database`` directly): attacker thread hammering the metrics+ entry with wrong passwords (every call must raise ValueError and never+ return a Session) while the owner thread cycles open(correct) + SELECT ++ close, with the engine/verifier pairing invariant sampled under+ ``_connections_lock`` throughout;+* G2 engine identity + thread affinity + recovery: the metrics Session+ binds to the ONE cached engine (no second engine is built), is genuinely+ usable from a NON-main thread (``check_same_thread=False``), keeps the+ verifier armed; after a close it cold-opens fresh through the same entry+ point, and a wrong password afterwards raises without disturbing the+ cached engine.+"""++import threading+import uuid++import pytest+from sqlalchemy import text++from local_deep_research.database.encrypted_db import DatabaseManager++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")++# Bounded concurrency: 2 threads, explicit iteration caps, one barrier.+HAMMER_ITERATIONS = 12+JOIN_TIMEOUT_S = 60+BARRIER_TIMEOUT_S = 30+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager writing to an isolated data directory.++ Same self-contained pattern as the round-1 files, with the sanctioned+ test-mode KDF knob (each wrong-password attempt performs a full PBKDF2+ derivation + verify cycle).+ """+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ mgr = DatabaseManager()+ mgr.data_dir = tmp_path+ yield mgr+ mgr.close_all_databases()+++def test_metrics_entry_wrong_password_storm_racing_close_and_reopen(manager):+ """G1: attacker hammers the metrics entry with wrong passwords while+ the owner tears down and rebuilds the real engine.++ Invariants:+ * the attacker NEVER receives a Session (every call raises ValueError;+ any other outcome or exception type is recorded and fails the test);+ * the owner's open(correct) always returns an engine whose SELECT reads+ the canary row written at setup;+ * every lock-consistent snapshot shows ``connections`` and+ ``_password_verifiers`` keyed identically (atomic publication /+ eviction);+ * quiesced: neither engine nor verifier remains after the final close.+ """+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"metrics_storm_{uuid.uuid4().hex[:8]}"+ password = "MetricsStormPassword1!" # noqa: S105+ engine = manager.create_user_database(username, password)+ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE gap_g_canary (id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO gap_g_canary (id, note) VALUES (1, :note)"),+ {"note": "gap-G"},+ )++ barrier = threading.Barrier(2)+ errors = {}+ attacker_violations = []+ owner_failures = []+ pairing_violations = []++ def attacker():+ try:+ barrier.wait(timeout=BARRIER_TIMEOUT_S)+ for i in range(HAMMER_ITERATIONS):+ try:+ session = manager.create_thread_safe_session_for_metrics(+ username, f"metrics-wrong-{i}"+ )+ except ValueError:+ continue # the documented fail-closed contract+ attacker_violations.append(+ f"iteration {i}: metrics entry returned {session!r} "+ "for a wrong password"+ )+ session.close()+ except Exception as exc: # noqa: BLE001 - surfaced via `errors` below+ errors["attacker"] = exc++ def owner():+ try:+ barrier.wait(timeout=BARRIER_TIMEOUT_S)+ for i in range(HAMMER_ITERATIONS):+ engine = manager.open_user_database(username, password)+ if engine is None:+ owner_failures.append(+ f"iteration {i}: open(correct) returned None"+ )+ continue+ try:+ with engine.connect() as conn:+ note = conn.execute(+ text("SELECT note FROM gap_g_canary WHERE id = 1")+ ).scalar()+ if note != "gap-G":+ owner_failures.append(+ f"iteration {i}: canary read {note!r}"+ )+ except Exception as exc: # noqa: BLE001 - loud assert below+ owner_failures.append(+ f"iteration {i}: SELECT failed: {exc!r}"+ )+ manager.close_user_database(username)+ with manager._connections_lock:+ engines = set(manager.connections)+ verifiers = set(manager._password_verifiers)+ if engines != verifiers:+ pairing_violations.append(+ f"iteration {i}: engines={engines} "+ f"verifiers={verifiers}"+ )+ except Exception as exc: # noqa: BLE001 - surfaced via `errors` below+ errors["owner"] = exc++ threads = [+ threading.Thread(target=attacker, name="gap-g-attacker"),+ threading.Thread(target=owner, name="gap-g-owner"),+ ]+ for t in threads:+ t.start()+ for t in threads:+ t.join(timeout=JOIN_TIMEOUT_S)+ assert not any(t.is_alive() for t in threads), "storm deadlocked"+ assert not errors, f"a storm thread raised: {errors}"+ assert not attacker_violations, (+ f"metrics entry handed out sessions for wrong passwords: "+ f"{attacker_violations}"+ )+ assert not owner_failures, (+ f"legitimate metrics-path opens failed: {owner_failures}"+ )+ assert not pairing_violations, (+ f"engine/verifier pairing broke: {pairing_violations}"+ )++ with manager._connections_lock:+ assert username not in manager.connections+ assert username not in manager._password_verifiers+++def test_metrics_session_identity_thread_affinity_and_recovery(manager):+ """G2: warm cache -- the metrics Session binds to the cached engine+ object (no second engine), used from a NON-main thread; the verifier+ still matches afterwards. After a close, the same entry point+ cold-opens a fresh engine that works; a wrong password then raises+ ValueError and leaves the cached engine and verifier intact.+ """+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"metrics_id_{uuid.uuid4().hex[:8]}"+ password = "MetricsIdentityPw1!" # noqa: S105+ warm_engine = manager.create_user_database(username, password)+ with warm_engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE gap_g2_canary (id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO gap_g2_canary (id, note) VALUES (1, :note)"),+ {"note": "gap-G2"},+ )++ outcome = {}+ errors = {}++ def background_user():+ # The whole point of this entry point: background threads. The+ # engine is built with check_same_thread=False, so a Session bound+ # to it must be usable off the main thread.+ try:+ session = manager.create_thread_safe_session_for_metrics(+ username, password+ )+ cached = manager.connections.get(username)+ outcome["bind_is_cached_engine"] = session.bind is cached+ outcome["cached_is_warm_engine"] = cached is warm_engine+ outcome["select"] = session.execute(text("SELECT 1")).scalar()+ outcome["canary"] = session.execute(+ text("SELECT note FROM gap_g2_canary WHERE id = 1")+ ).scalar()+ session.close()+ except Exception as exc: # noqa: BLE001 - surfaced via `errors` below+ errors["background"] = exc++ worker = threading.Thread(target=background_user, name="gap-g2-worker")+ worker.start()+ worker.join(timeout=JOIN_TIMEOUT_S)+ assert not worker.is_alive(), "metrics background thread hung"+ assert not errors, f"background thread raised: {errors}"+ assert outcome["bind_is_cached_engine"] is True, (+ "the metrics Session must bind to the cached engine, not a second one"+ )+ assert outcome["cached_is_warm_engine"] is True+ assert outcome["select"] == 1+ assert outcome["canary"] == "gap-G2"+ assert manager._password_matches_cached(username, password) is True++ # Close, then cold-open through the SAME entry point.+ manager.close_user_database(username)+ cold_session = manager.create_thread_safe_session_for_metrics(+ username, password+ )+ try:+ assert cold_session.bind is manager.connections[username]+ assert cold_session.execute(text("SELECT 1")).scalar() == 1+ finally:+ cold_session.close()++ # Wrong password through the metrics entry: ValueError, and the cached+ # engine/verifier for the correct password survive undisturbed.+ cached_engine = manager.connections[username]+ with pytest.raises(ValueError):+ manager.create_thread_safe_session_for_metrics(+ username, "metrics-wrong-after-cold"+ )+ assert manager.connections[username] is cached_engine, (+ "a rejected metrics attempt must not disturb the cached engine"+ )+ assert manager._password_matches_cached(username, password) is True+ assert (+ manager._password_matches_cached(username, "metrics-wrong-after-cold")+ is False+ )diff --git a/tests/security/test_db_connection_multi_manager_isolation.py b/tests/security/test_db_connection_multi_manager_isolation.pynew file mode 100644index 0000000000..adcad1febe--- /dev/null+++ b/tests/security/test_db_connection_multi_manager_isolation.py@@ -0,0 +1,100 @@+"""Per-instance trust: two DatabaseManagers never share cache trust.++Incident context (PR #5596): the verifier is keyed by a per-process random+``_verifier_key`` (``secrets.token_bytes(32)`` in ``__init__``), and both+``connections`` and ``_password_verifiers`` are plain instance attributes.+``test_password_verifier_primitive.py::test_fresh_managers_do_not_share_+verifier_keys`` pins the digest-level consequence (manager B cannot+validate manager A's verifier tuple). This file pins the real-database+consequence at the ``open_user_database`` / ``get_session`` layer:++* manager A's warm cache gives manager B nothing: B's wrong-password open+ fails at SQLCipher and B's correct-password open builds B's OWN engine;+* closing A's engine cannot invalidate or disturb B's live engine (a+ cross-instance eviction would be an availability bug; the reverse -- A's+ trust leaking into B -- would be the bypass);+* B fails closed on its own warm cache exactly like A does.++Two live managers over one data directory is a real deployment shape (e.g.+a tooling process plus the web app before per-user DB locking, or tests+constructing managers against a shared temp dir).+"""++import uuid++import pytest+from sqlalchemy import text++from local_deep_research.database.encrypted_db import DatabaseManager++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")+++def manager_pair(tmp_path, monkeypatch):+ """Two independent DatabaseManagers sharing one data directory."""+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ manager_a = DatabaseManager()+ manager_a.data_dir = tmp_path+ manager_b = DatabaseManager()+ manager_b.data_dir = tmp_path+ assert manager_a._verifier_key != manager_b._verifier_key, (+ "setup: the two managers must not share a verifier key"+ )+ yield manager_a, manager_b+ manager_a.close_all_databases()+ manager_b.close_all_databases()+++def test_manager_a_cache_gives_manager_b_nothing(manager_pair):+ """A's cached engine is invisible to B; B re-proves the credential+ against SQLCipher, fails closed on a wrong password, and A's later+ close does not disturb B's live engine."""+ manager_a, manager_b = manager_pair+ if not manager_a.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"multimgr_{uuid.uuid4().hex[:8]}"+ password = "MultiManagerPassword1!" # noqa: S105+ engine_a = manager_a.create_user_database(username, password)+ assert manager_a.is_user_connected(username), "A holds the warm cache"++ # B, wrong password: cold attempt against the real file -> rejected,+ # and B caches nothing from the failure.+ assert manager_b.open_user_database(username, "wrong-for-B") is None+ assert username not in manager_b.connections+ assert username not in manager_b._password_verifiers++ # B, correct password: B builds and caches its OWN engine (distinct+ # object from A's), with B's own verifier.+ engine_b = manager_b.open_user_database(username, password)+ assert engine_b is not None+ assert engine_b is not engine_a+ assert manager_b.connections[username] is engine_b+ assert manager_b._password_matches_cached(username, password) is True++ # B fails closed on its own warm cache, exactly like A would.+ assert manager_b.open_user_database(username, "wrong-for-B") is None++ # A tears its engine down; B's engine and sessions must be unaffected.+ manager_a.close_user_database(username)+ assert not manager_a.is_user_connected(username)+ session_b = manager_b.get_session(username)+ assert session_b is not None, (+ "A's close invalidated B's live engine -- cache trust and engine "+ "lifetime must be per-instance"+ )+ with session_b:+ assert session_b.execute(text("SELECT 1")).scalar() == 1+ assert manager_b.connections[username] is engine_b++ # And the teardown symmetry: B closing leaves A exactly as A was.+ manager_b.close_user_database(username)+ assert manager_a.connections == {}+ assert manager_a._password_verifiers == {}diff --git a/tests/security/test_db_connection_passwordless_accessors.py b/tests/security/test_db_connection_passwordless_accessors.pynew file mode 100644index 0000000000..bd9f3c2e37--- /dev/null+++ b/tests/security/test_db_connection_passwordless_accessors.py@@ -0,0 +1,121 @@+"""Passwordless accessor surface: post-auth-only, side-effect-free.++Incident context (PR #5596): the fix's safety argument for methods that+take NO password (``get_session``, ``check_database_integrity``,+``get_connected_usernames``, ``get_memory_usage``) is that they are purely+POST-AUTH accessors over already-verified state -- they must never open,+create, or revive anything (the same never-open principle round 1 pinned+for ``get_session``). This file pins the remaining passwordless surface:++* J1 ``check_database_integrity``: for a closed-but-on-disk user it+ returns False WITHOUT opening (code: the ``username not in+ self.connections`` early-return happens before any engine work) and+ with zero side effects -- no file mutation, no cache/verifier entries,+ not even a new init lock; for a warm encrypted user it returns True via+ a real quick_check + cipher_integrity_check; for an unknown user,+ False with zero side effects.+(A J2 companion covering ``get_memory_usage`` /+``get_connected_usernames`` liveness was dropped: it duplicated+``test_login_cached_connection_password_lifecycle.py``'s+``test_is_user_connected_reflects_liveness_only`` and+``test_close_all_databases_clears_connections_and_verifiers``.)+"""++import hashlib+import uuid++import pytest++from local_deep_research.database.encrypted_db import DatabaseManager++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager writing to an isolated data directory.++ Same self-contained pattern as the round-1 files, with the sanctioned+ test-mode KDF knob.+ """+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ mgr = DatabaseManager()+ mgr.data_dir = tmp_path+ yield mgr+ mgr.close_all_databases()+++def _dir_fingerprint(root) -> dict:+ """name -> (size, sha256, mode) for every file under root."""+ fingerprint = {}+ for path in sorted(root.rglob("*")):+ if path.is_file():+ data = path.read_bytes()+ fingerprint[path.name] = (+ len(data),+ hashlib.sha256(data).hexdigest(),+ path.stat().st_mode,+ )+ return fingerprint+++def test_check_database_integrity_is_post_auth_only(manager):+ """J1: integrity checking must be a read over LIVE state, never an+ open-on-miss."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ def maps_snapshot():+ return (+ dict(manager.connections),+ dict(manager._password_verifiers),+ dict(manager._init_locks),+ )++ # --- Unknown user: False, zero side effects of any kind.+ unknown = f"never_existed_{uuid.uuid4().hex[:8]}"+ files_before = _dir_fingerprint(manager.data_dir)+ maps_before = maps_snapshot()+ assert manager.check_database_integrity(unknown) is False+ assert _dir_fingerprint(manager.data_dir) == files_before, (+ "integrity check created or mutated files for an unknown user"+ )+ assert maps_snapshot() == maps_before, (+ "integrity check added cache/verifier/init-lock state for an "+ "unknown user"+ )++ # --- Closed-but-on-disk user: False WITHOUT opening the database+ # (the never-open principle for this accessor), zero side effects.+ username = f"integrity_{uuid.uuid4().hex[:8]}"+ password = "IntegrityAccessorPw1!" # noqa: S105+ manager.create_user_database(username, password)+ manager.close_user_database(username)+ assert manager._get_user_db_path(username).exists()++ files_before = _dir_fingerprint(manager.data_dir)+ maps_before = maps_snapshot()+ for _ in range(3):+ assert manager.check_database_integrity(username) is False, (+ "integrity check returned True for a CLOSED database -- it must "+ "not have opened it"+ )+ assert _dir_fingerprint(manager.data_dir) == files_before, (+ "integrity check touched the on-disk database of a closed user"+ )+ assert maps_snapshot() == maps_before, (+ "integrity check changed manager state for a closed user"+ )++ # --- Warm user: a real quick_check + cipher_integrity_check over the+ # live engine returns True.+ engine = manager.open_user_database(username, password)+ assert engine is not None+ assert manager.check_database_integrity(username) is True+ assert manager.connections[username] is enginediff --git a/tests/security/test_db_connection_path_and_accessors.py b/tests/security/test_db_connection_path_and_accessors.pynew file mode 100644index 0000000000..13b343150f--- /dev/null+++ b/tests/security/test_db_connection_path_and_accessors.py@@ -0,0 +1,182 @@+"""Passwordless accessors and hostile data-dir paths.++Incident context (PR #5596): the never-open / no-side-effect discipline+(round-1 A, round-2 J) extends to every passwordless surface, and the+data-dir path itself is deployer-controlled input. This file pins:++* AC1 ``user_exists`` -- a pure AUTH-database lookup+ (encrypted_db.py::user_exists: it queries ``auth_db``, never the+ user's encrypted DB): unknown user -> False with NO ``ldr_user_*``+ file created and no cache state; a known-on-disk-but-never-opened+ user -> False as well (no DB open+ happens as a side effect). NOTE the one real side effect, pinned as+ actual: the FIRST call bootstraps ``ldr_auth.db`` inside the data dir+ (the auth store itself) -- expected infrastructure, distinct from any+ user-database artifact;+* AG1 a regular FILE where the data dir should be: assignment through+ the ``data_dir`` setter raises FileExistsError cleanly (the setter's+ ``mkdir(exist_ok=True)`` only tolerates an existing DIRECTORY), the+ file is undamaged, and a valid dir assignment still works afterwards;+* AG2 spaces + unicode in the data-dir path: full create/canary/warm/+ cold/close_all cycle works, and the DB artifacts land inside the+ unicode directory verbatim.+"""++import uuid++import pytest+from sqlalchemy import text++from local_deep_research.database.encrypted_db import DatabaseManager++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager writing to an isolated data directory.++ Same self-contained pattern as the round-1..5 files, with the+ sanctioned test-mode KDF knob.+ """+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ mgr = DatabaseManager()+ mgr.data_dir = tmp_path+ yield mgr+ mgr.close_all_databases()+++def test_user_exists_is_a_pure_auth_lookup(manager):+ """AC1: unknown user -> False with no ldr_user_* artifacts and no+ cache touch; a user whose DB file exists but was never opened ->+ False too (the user DB is never opened by this call). The auth-store+ bootstrap (ldr_auth.db) is the one allowed side effect, pinned."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ unknown = f"no_such_user_{uuid.uuid4().hex[:8]}"+ assert manager.user_exists(unknown) is False++ # No USER-database artifact appeared (ldr_auth.db may -- that is the+ # auth store bootstrapping, not a user DB).+ user_artifacts = [+ p.name+ for p in manager.data_dir.iterdir()+ if p.name.startswith("ldr_user_")+ ]+ assert user_artifacts == [], (+ f"user_exists created user-database artifacts: {user_artifacts}"+ )+ assert manager.connections == {}+ assert manager._password_verifiers == {}+ assert manager.get_connected_usernames() == set()++ # A real user DB that exists on disk but was never opened: still+ # False (registration lives in the auth DB, not the file system),+ # and the call must not have OPENED the file either.+ username = f"on_disk_never_opened_{uuid.uuid4().hex[:8]}"+ password = "OnDiskPw1!" # noqa: S105+ manager.create_user_database(username, password)+ manager.close_user_database(username)+ assert manager._get_user_db_path(username).exists()++ assert manager.user_exists(username) is False, (+ "a filesystem-only user (created directly through the manager, "+ "never registered in the auth DB) must not count as existing"+ )+ assert username not in manager.connections, (+ "user_exists opened the user's database as a side effect"+ )+ assert username not in manager._password_verifiers+++def test_regular_file_as_data_dir_fails_cleanly(manager, tmp_path):+ """AG1: assigning a regular file as the data dir raises+ FileExistsError from the setter's mkdir; the file's content is+ undamaged; a subsequent valid assignment works."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ impostor = tmp_path / "iamfile_not_a_dir"+ impostor.write_text("precious-content")++ with pytest.raises(FileExistsError):+ manager.data_dir = impostor++ assert impostor.read_text() == "precious-content", (+ "the failed data_dir assignment damaged the impostor file"+ )++ # The manager still accepts a real directory afterwards.+ good_dir = tmp_path / "real_dir"+ manager.data_dir = good_dir+ username = f"after impostor fix, user_{uuid.uuid4().hex[:8]}"[:40].replace(+ " ", "_"+ )+ password = "RecoverPw1!" # noqa: S105+ engine = manager.create_user_database(username, password)+ assert engine is not None+ with engine.connect() as conn:+ assert conn.execute(text("SELECT 1")).scalar() == 1+++def test_unicode_and_spaces_data_dir_full_cycle(tmp_path, monkeypatch):+ """AG2: a data dir whose name carries spaces, CJK, and an em-dash:+ create, canary, warm reuse, cold reopen, close_all -- all clean, with+ the artifacts landing inside the verbatim unicode path."""+ # Set the sanctioned test-mode KDF knob BEFORE any DatabaseManager is+ # constructed: `has_encryption` is decided by a probe that derives a key,+ # so building one first makes that probe run at the 256,000-iteration+ # production default instead of 1,000 -- out of line with the other+ # modules in this battery, and hundreds of milliseconds per test.+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")++ if not DatabaseManager().has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ fancy = tmp_path / "with spaces and 漢字 and —émphasis—"+ mgr = DatabaseManager()+ mgr.data_dir = fancy+ try:+ username = f"unicode_dir_{uuid.uuid4().hex[:8]}"+ password = "UnicodeDirPw1!" # noqa: S105+ engine = mgr.create_user_database(username, password)+ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE gap_ag_canary "+ "(id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO gap_ag_canary (id, note) VALUES (1, :n)"),+ {"n": "gap-AG2"},+ )++ # Warm reuse, then cold reopen, inside the verbatim path.+ assert mgr.open_user_database(username, password) is engine+ mgr.close_user_database(username)+ reopened = mgr.open_user_database(username, password)+ assert reopened is not None+ with reopened.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_ag_canary WHERE id = 1")+ ).scalar()+ == "gap-AG2"+ )++ # The artifacts live inside the unicode directory itself.+ db_path = mgr._get_user_db_path(username)+ assert db_path.exists()+ assert "漢字" in str(db_path.parent.name)+ assert db_path.parent.parent == tmp_path+ finally:+ mgr.close_all_databases()diff --git a/tests/security/test_db_connection_planted_journal_artifacts.py b/tests/security/test_db_connection_planted_journal_artifacts.pynew file mode 100644index 0000000000..d8375eba2d--- /dev/null+++ b/tests/security/test_db_connection_planted_journal_artifacts.py@@ -0,0 +1,234 @@+"""Planted journal artifacts and the crafted super-journal unlink class.++Research context (SQLite bug forum 2026 disclosure; sqlite.org/fileformat+§rollback journal): a crafted hot ``-journal`` whose header names a+"super-journal" (master journal) pathname can make a read-write opener+UNLINK that pathname during journal finalization -- i.e., an attacker+with data-directory write access can aim an arbitrary-file deletion at+any path the process may unlink. Related class from sqlite.org/+howtocorrupt.html: planting journal/WAL artifacts belonging to a+DIFFERENT database.++Probed and pinned against the real manager (all HOLD on this build):++* AI1 crafted super-journal: a journal carrying the real magic + a+ plausible header + an out-of-directory super-journal name is consumed+ harmlessly on open -- the SENTINEL file at the named path survives,+ the open succeeds, and no engine/verifier anomalies occur. (The+ crafted header's checksum is invalid, so SQLite discards it as a stale+ journal; a fully checksum-valid super-journal header would be needed+ to exercise the deletion path itself -- see the summary's scope+ note.)+* AI2 a REAL hot journal stolen from another user's database (captured+ mid-transaction in journal_mode=DELETE) and planted next to a closed+ target: the databases are persistent WAL-mode (journal_mode lives in+ the db header), so the rollback journal is not consulted at all --+ the target opens, reads ONLY its own canary, and the other user's+ secret is nowhere.+* AI3 garbage ``-wal`` bytes planted before open: SQLite's WAL-header+ checksum fails, the file is treated as invalid and reset -- the open+ succeeds, the target reads its own canary, nothing else appears.+"""++import shutil+import struct+import tempfile+import uuid+from pathlib import Path++import pytest+from sqlalchemy import text++from local_deep_research.database.encrypted_db import DatabaseManager++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager writing to an isolated data directory.++ Same self-contained pattern as the round-1..6 files, with the+ sanctioned test-mode KDF knob.+ """+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ mgr = DatabaseManager()+ mgr.data_dir = tmp_path+ yield mgr+ mgr.close_all_databases()+++def _write_row(engine, value: str) -> None:+ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE IF NOT EXISTS gap_ai (id INTEGER PRIMARY KEY, v TEXT)"+ )+ )+ conn.execute(text("INSERT INTO gap_ai (v) VALUES (:v)"), {"v": value})+++def _run_crafted_super_journal_probe(manager, sentinel):+ """Body of AI1; split out so the sentinel cleanup can wrap it."""+ username = f"ai1_{uuid.uuid4().hex[:8]}"+ password = "CraftedJournalPw1!" # noqa: S105+ engine = manager.create_user_database(username, password)+ _write_row(engine, "gap-AI1")+ manager.close_user_database(username)++ db_path = manager._get_user_db_path(username)+ journal = db_path.with_name(db_path.name + "-journal")+ # Real journal magic + structurally plausible header (per the+ # rollback-journal file-format doc), an intentionally INVALID+ # checksum, and the super-journal pathname field pointing at the+ # sentinel. SQLite validates the header checksum before playback and+ # discards what fails -- the resist posture for crafted input.+ payload = b"\xd9\xd5\x05\xf9\x20\xa1\x63\xd7"+ payload += struct.pack(">I", 1) # file format version+ payload += struct.pack(">I", 0) # page record count (0 = all)+ payload += struct.pack(">I", 0) # checksum nonce+ payload += struct.pack(">I", 1) # initial database size (pages)+ payload += struct.pack(">I", 512) # sector size+ payload += struct.pack(">I", 4096) # page size+ payload += struct.pack(">I", 0xDEADBEEF) # header checksum (invalid)+ payload += str(sentinel).encode() + b"\x00" # "super-journal" name+ payload += b"\x00" * 256+ journal.write_bytes(payload)++ opened = manager.open_user_database(username, password)+ assert opened is not None, (+ "the crafted journal broke the open itself (unexpected)"+ )+ # THE assertion of this test: no arbitrary-file deletion happened.+ assert sentinel.exists(), (+ "the crafted super-journal pathname was UNLINKED during open -- "+ "this SQLite build is vulnerable to the 2026 super-journal "+ "deletion class"+ )+ assert sentinel.read_text() == "precious"+ with opened.connect() as conn:+ assert conn.execute(text("SELECT v FROM gap_ai")).scalar() == "gap-AI1"+ manager.close_user_database(username)+++def test_crafted_super_journal_does_not_unlink_arbitrary_files(manager):+ """AI1 (HOLD on this build): a planted hot journal whose payload+ names an out-of-directory "super-journal" is consumed harmlessly;+ the sentinel at that path survives; the open succeeds cleanly."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ # The sentinel lives OUTSIDE the data directory (the attack's target).+ sentinel = manager.data_dir.parent / f"r7_victim_{uuid.uuid4().hex[:8]}.txt"+ sentinel.write_text("precious")++ # The sentinel is in the per-worker basetemp (tmp_path.parent), which+ # pytest only reclaims on its 3-run rotation, so the unlink has to run+ # on the failure path too -- and on the very failure this test exists to+ # catch, the sentinel is gone, hence missing_ok.+ try:+ _run_crafted_super_journal_probe(manager, sentinel)+ finally:+ sentinel.unlink(missing_ok=True)+++def test_real_foreign_journal_planted_is_ignored_entirely(manager):+ """AI2 (HOLD): a genuine hot journal captured from ANOTHER user's+ database, planted next to a closed target, is never consulted --+ these databases are persistent WAL-mode, so rollback journals do not+ participate. The target opens and serves ONLY its own data."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ target = f"ai2t_{uuid.uuid4().hex[:8]}"+ other = f"ai2o_{uuid.uuid4().hex[:8]}"+ password = "ForeignJournalPw1!" # noqa: S105+ engine_t = manager.create_user_database(target, password)+ _write_row(engine_t, "target-secret")+ engine_o = manager.create_user_database(other, password)+ _write_row(engine_o, "OTHER-USER-SECRET")++ # Capture a REAL hot journal: flip the other user into journal_mode+ # DELETE and hold a transaction open across the copy.+ other_db = manager._get_user_db_path(other)+ other_journal = other_db.with_name(other_db.name + "-journal")+ with tempfile.TemporaryDirectory() as stash:+ stolen = Path(stash) / "stolen.journal"+ conn = engine_o.connect()+ try:+ conn.execute(text("PRAGMA journal_mode=DELETE"))+ conn.execute(text("INSERT INTO gap_ai (v) VALUES ('mid-txn')"))+ assert other_journal.exists(), (+ "setup: DELETE-mode journal expected mid-transaction"+ )+ shutil.copy2(other_journal, stolen)+ conn.rollback() # release the hot journal+ finally:+ conn.close()++ manager.close_all_databases()+ target_db = manager._get_user_db_path(target)+ planted = target_db.with_name(target_db.name + "-journal")+ shutil.copy2(stolen, planted)++ opened = manager.open_user_database(target, password)+ assert opened is not None, (+ "the planted real journal broke the target's open (unexpected: "+ "WAL-mode databases should not consult rollback journals)"+ )+ with opened.connect() as conn:+ values = sorted(+ row[0]+ for row in conn.execute(text("SELECT v FROM gap_ai")).fetchall()+ )+ assert values == ["target-secret"], (+ f"cross-user data served through a planted journal: {values}"+ )+ # Still WAL-mode; the planted journal was irrelevant.+ with opened.connect() as conn:+ mode = conn.execute(text("PRAGMA journal_mode")).scalar()+ assert str(mode).lower() == "wal"+ manager.close_user_database(target)+++def test_garbage_wal_planted_is_discarded_not_served(manager):+ """AI3 (HOLD): random bytes as -wal fail SQLite's WAL-header+ checksum and are discarded/reset -- the open succeeds and the target+ reads only its own canary."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"ai3_{uuid.uuid4().hex[:8]}"+ password = "GarbageWalPw1!" # noqa: S105+ engine = manager.create_user_database(username, password)+ _write_row(engine, "gap-AI3")+ manager.close_user_database(username)++ db_path = manager._get_user_db_path(username)+ planted = db_path.with_name(db_path.name + "-wal")+ planted.write_bytes(b"\xde\xad\xbe\xef" * 1024) # garbage++ opened = manager.open_user_database(username, password)+ assert opened is not None, (+ "garbage -wal bytes broke the open (unexpected: invalid WAL "+ "headers are supposed to be discarded)"+ )+ with opened.connect() as conn:+ values = [+ row[0]+ for row in conn.execute(text("SELECT v FROM gap_ai")).fetchall()+ ]+ assert values == ["gap-AI3"], (+ f"garbage WAL served wrong or duplicated data: {values}"+ )+ manager.close_user_database(username)++ # And a clean reopen cycle still works afterwards.+ reopened = manager.open_user_database(username, password)+ assert reopened is not Nonediff --git a/tests/security/test_db_connection_pool_bounds.py b/tests/security/test_db_connection_pool_bounds.pynew file mode 100644index 0000000000..db71f8d36a--- /dev/null+++ b/tests/security/test_db_connection_pool_bounds.py@@ -0,0 +1,316 @@+"""Pool bounds under concurrency and get_session racing close.++Incident context (PR #5596): the shared per-user engine is the trust+boundary -- every Session handed out by ``get_session`` /+``create_thread_safe_session_for_metrics`` binds to the ONE+credential-verified engine (ADR-0004: QueuePool, pool_size=20,+max_overflow=40). Two behavioral properties complete the picture the+incident tests left open:++* T1 concurrent readers through the shared engine: many threads reading+ simultaneously never exceed the pool's configured bounds+ (checked-out <= pool_size + max_overflow, parsed from+ ``engine.pool.status()`` snapshots taken INSIDE the threads) and never+ fail;+* T2 ``get_session`` racing ``close_user_database``: get_session is a+ pure cache lookup under ``_connections_lock``; when it wins the race it+ binds a Session to the live engine, and when the close wins first the+ round-3 resurrection contract covers the Session (the creator closure+ reconnects with the same key) -- so every session the racer obtains+ must still execute real table reads successfully, never raise, and the+ engine/verifier pairing must hold at every sampled instant.++FD-count deltas are deliberately NOT asserted here: pyproject.toml's+``fd_canary`` marker documents that ``/proc/self/fd`` assertions are+noisy under parallel execution (and ``/proc`` is Linux-only), while this+file belongs in the parallel lane for the pool/pairing coverage above.+"""++import re+import threading+import time+import uuid+import warnings++import pytest+from sqlalchemy import text++from local_deep_research.database.encrypted_db import DatabaseManager++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")++READER_THREADS = 4+READS_PER_THREAD = 8+GET_SESSION_ITERATIONS = 30+OPEN_CLOSE_ITERATIONS = 15+JOIN_TIMEOUT_S = 60+BARRIER_TIMEOUT_S = 30+# Backoff before the single retry of a legitimate operation (see the+# `open(correct)` churn below): absorbs a transient SQLITE_BUSY without+# hiding a repeatable refusal.+RETRY_BACKOFF_S = 0.1+++def _join_all(threads):+ """Join every thread against ONE shared deadline.++ A per-thread ``join(timeout=JOIN_TIMEOUT_S)`` inside a loop costs+ ``len(threads) * JOIN_TIMEOUT_S`` in the worst case. ``pyproject.toml``+ sets ``timeout = 180`` with ``timeout_method = "thread"``, and+ pytest-timeout's thread handler ends in ``os._exit(1)`` -- so when these+ tests actually find the deadlock they exist to find, a per-thread budget+ would kill the whole xdist worker (losing its coverage, then tripping+ ``--cov-fail-under``) instead of failing on the named "deadlocked"+ assertion at the call site. One shared deadline bounds the entire join at+ JOIN_TIMEOUT_S regardless of thread count, which keeps that assertion+ reachable well inside the global timeout. Each thread still gets the full+ remaining budget in wall-clock terms, because the threads run+ concurrently.+ """+ deadline = time.monotonic() + JOIN_TIMEOUT_S+ for t in threads:+ t.join(timeout=max(0.0, deadline - time.monotonic()))+++STATUS_RE = re.compile(r"Pool size: (\d+).*?Checked out connections: (\d+)")+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager writing to an isolated data directory.++ Same self-contained pattern as the round-1/2/3 files, with the+ sanctioned test-mode KDF knob. TESTING is deliberately NOT set, so+ the engine uses the production QueuePool (pool_size=20,+ max_overflow=40) the bounds assertions parse from the live pool.+ Explicitly unset rather than just "never set here": several other+ test modules do a bare ``os.environ.setdefault("TESTING", "1")`` at+ import time (not ``monkeypatch``), which never reverts for the rest+ of the xdist worker process once any of them has been collected --+ so ambient absence cannot be assumed.+ """+ monkeypatch.delenv("TESTING", raising=False)+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ mgr = DatabaseManager()+ mgr.data_dir = tmp_path+ yield mgr+ mgr.close_all_databases()+++def _write_canary(engine, note: str) -> None:+ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE gap_t_canary (id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO gap_t_canary (id, note) VALUES (1, :note)"),+ {"note": note},+ )+++def test_concurrent_readers_stay_within_pool_bounds(manager):+ """T1: 4 threads x 8 reads through one warm QueuePool engine; zero+ failures; every in-thread pool.status() snapshot shows checked-out+ connections within pool_size + max_overflow (and trivially <= the+ thread count)."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"poolbounds_{uuid.uuid4().hex[:8]}"+ password = "PoolBoundsPassword1!" # noqa: S105+ engine = manager.create_user_database(username, password)+ _write_canary(engine, "gap-T1")+ # The engine must really be the production-shape pooled engine for+ # the bounds assertions to be meaningful.+ assert hasattr(engine.pool, "size"), (+ "expected a QueuePool-backed engine (TESTING env must be unset)"+ )+ pool_size = engine.pool.size()+ max_overflow = engine.pool._max_overflow+ assert pool_size + max_overflow >= READER_THREADS++ barrier = threading.Barrier(READER_THREADS)+ errors = {}+ failures = []+ statuses = []++ def reader(tid):+ try:+ barrier.wait(timeout=BARRIER_TIMEOUT_S)+ for i in range(READS_PER_THREAD):+ try:+ with engine.connect() as conn:+ note = conn.execute(+ text("SELECT note FROM gap_t_canary WHERE id = 1")+ ).scalar()+ if note != "gap-T1":+ failures.append(f"t{tid}#{i}: canary read {note!r}")+ except Exception as exc: # noqa: BLE001 - loud assert below+ failures.append(f"t{tid}#{i}: {exc!r}")+ statuses.append(engine.pool.status())+ except Exception as exc: # noqa: BLE001 - surfaced via `errors` below+ errors[tid] = exc++ threads = [+ threading.Thread(target=reader, args=(i,), name=f"gap-t1-r{i}")+ for i in range(READER_THREADS)+ ]+ for t in threads:+ t.start()+ _join_all(threads)+ assert not any(t.is_alive() for t in threads), "reader pool deadlocked"+ assert not errors, f"a reader thread raised: {errors}"+ assert not failures, f"concurrent reads failed: {failures}"++ assert statuses, "no pool status snapshots captured"+ worst = 0+ for snapshot in statuses:+ match = STATUS_RE.search(snapshot)+ assert match, f"unparseable pool status: {snapshot!r}"+ checked_out = int(match.group(2))+ assert checked_out <= pool_size + max_overflow, (+ f"pool bounds exceeded: checked-out {checked_out} > "+ f"{pool_size}+{max_overflow} ({snapshot!r})"+ )+ worst = max(worst, checked_out)+ if worst < 1:+ # Four threads doing sub-millisecond SELECTs can serialise+ # completely under '-n auto' plus coverage tracing, so every+ # pool.status() snapshot legitimately reads zero checked-out+ # connections. That makes the run uninformative, not wrong -- but+ # a ``pytest.skip`` here is indistinguishable in the CI summary+ # from "no SQLCipher build", so the lane would report green+ # having bounded nothing. Warn instead: the bounds assertion+ # above still ran (vacuously), and the no-overlap case survives+ # into the run report rather than passing silently.+ warnings.warn(+ "pool-bounds race not witnessed: no snapshot observed a "+ "checked-out connection -- the readers never overlapped on "+ "this runner, so the bounds assertion had nothing to bound",+ stacklevel=2,+ )+++def test_get_session_racing_close_never_raises_and_sessions_work(manager):+ """T2: thread A hammers get_session; thread B hammers open+close.+ Every session A obtains must execute a real table read (resurrection+ contract) or, when the cache is momentarily empty, get_session+ returns None -- but NOTHING may raise, the pairing invariant holds at+ every sample, and the post-close_all state is clean."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"getsessionrace_{uuid.uuid4().hex[:8]}"+ password = "GetSessionRacePw1!" # noqa: S105+ engine = manager.create_user_database(username, password)+ _write_canary(engine, "gap-T2")++ barrier = threading.Barrier(2)+ churn_done = threading.Event()+ errors = {}+ violations = []+ pairing_violations = []+ stats = {"sessions": 0, "nones": 0}++ def session_racer():+ try:+ barrier.wait(timeout=BARRIER_TIMEOUT_S)+ iterations = 0+ # Spin until the churn finishes (a fixed count can complete+ # entirely inside one cold-open window and make this test+ # vacuous), bounded by a generous cap.+ while not churn_done.is_set() and iterations < 3000:+ iterations += 1+ session = manager.get_session(username)+ if session is None:+ stats["nones"] += 1+ continue+ stats["sessions"] += 1+ try:+ note = session.execute(+ text("SELECT note FROM gap_t_canary WHERE id = 1")+ ).scalar()+ if note != "gap-T2":+ violations.append(f"bad canary read: {note!r}")+ except Exception as exc: # noqa: BLE001 - loud assert below+ violations.append(f"session execute failed: {exc!r}")+ finally:+ session.close()+ except Exception as exc: # noqa: BLE001 - surfaced via `errors` below+ errors["racer"] = exc++ def open_close_churn():+ try:+ barrier.wait(timeout=BARRIER_TIMEOUT_S)+ for i in range(OPEN_CLOSE_ITERATIONS):+ opened = manager.open_user_database(username, password)+ if opened is None:+ # Retry once after a short backoff. A transient+ # SQLITE_BUSY on a LEGITIMATE open under contention is+ # not the property under test, and reddening on it turns+ # a loaded runner into a security-gate failure. A real,+ # repeatable refusal still fails on the retry.+ time.sleep(RETRY_BACKOFF_S)+ opened = manager.open_user_database(username, password)+ if opened is None:+ violations.append(f"churn #{i}: open(correct) failed twice")+ continue+ # Hold the engine briefly before closing: open_user_database+ # returns only AFTER caching, so without this pause the+ # populated window is sub-millisecond and the get_session+ # racer could legitimately never observe it (vacuous test).+ time.sleep(0.01)+ manager.close_user_database(username)+ with manager._connections_lock:+ engines = set(manager.connections)+ verifiers = set(manager._password_verifiers)+ if engines != verifiers:+ pairing_violations.append(+ f"churn #{i}: {engines} vs {verifiers}"+ )+ except Exception as exc: # noqa: BLE001 - surfaced via `errors` below+ errors["churn"] = exc+ finally:+ churn_done.set()++ threads = [+ threading.Thread(target=session_racer, name="gap-t2-a"),+ threading.Thread(target=open_close_churn, name="gap-t2-b"),+ ]+ for t in threads:+ t.start()+ _join_all(threads)+ assert not any(t.is_alive() for t in threads), "get_session race deadlocked"+ assert not errors, f"a racing thread raised: {errors}"+ assert not violations, f"get_session racing close misbehaved: {violations}"+ assert not pairing_violations, (+ f"engine/verifier pairing broke: {pairing_violations}"+ )+ assert stats["sessions"] >= 1, (+ "the racer never obtained a single session -- test is vacuous"+ )++ # Final state is clean after close_all.+ manager.close_all_databases()+ with manager._connections_lock:+ assert manager.connections == {}+ assert manager._password_verifiers == {}++ # And the user still works end-to-end.+ reopened = manager.open_user_database(username, password)+ assert reopened is not None+ with reopened.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_t_canary WHERE id = 1")+ ).scalar()+ == "gap-T2"+ )diff --git a/tests/security/test_db_connection_readonly_hostile_fs.py b/tests/security/test_db_connection_readonly_hostile_fs.pynew file mode 100644index 0000000000..42cdf77019--- /dev/null+++ b/tests/security/test_db_connection_readonly_hostile_fs.py@@ -0,0 +1,257 @@+"""Read-only / permission-hostile filesystem behavior at open time.++Incident context (PR #5596): the fail-closed cache means every open is+backed by a real SQLCipher open, so hostile filesystem states surface on+the cold path. Two states matter for the at-rest threat model (a local+attacker who can chmod, or a read-only mount):++* R1 the .db file itself made owner-read-only (0o400): ACTUAL pinned+ behavior -- SQLite falls back to a read-only connection and the cold+ open SUCCEEDS with the correct password, publishing a read-only engine+ whose reads work and whose writes fail loudly; restoring 0o600 and+ reopening regains full read/write function;+* R2 the data directory made non-writable (0o500): WAL sidecars cannot be+ created next to the database, the creator fails, and the open refuses+ cleanly (None, nothing published); restoring 0o700 reopens.++Both tests pin the ACTUAL current behavior (verified empirically, not+assumed). Both restore permissions+in ``finally`` blocks so tmp_path cleanup never breaks, and both skip+when running as root (root ignores file modes).+"""++import os+import stat+import uuid++import pytest+from sqlalchemy import text++from local_deep_research.database.encrypted_db import DatabaseManager++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")++# Both tests skip under root because permission bits are not enforced for+# root -- under the root-default docker-tests.yml container this whole+# module would silently no-op. Unlike ``serial`` this does NOT mutate+# process-global state (no shared state to race), it just needs a+# genuinely unprivileged process, so it opts into the dedicated non-root+# CI step instead of the parallel lane (see the ``nonroot`` marker in+# pyproject.toml and the dedicated step in+# .github/workflows/docker-tests.yml).+pytestmark = pytest.mark.nonroot+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager writing to an isolated data directory.++ Same self-contained pattern as the round-1/2/3 files, with the+ sanctioned test-mode KDF knob.+ """+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ mgr = DatabaseManager()+ mgr.data_dir = tmp_path+ yield mgr+ mgr.close_all_databases()+++def _require_non_root():+ if os.geteuid() == 0:+ pytest.skip("permission tests are meaningless when running as root")+++def _make_user(manager, note):+ username = f"rohost_{uuid.uuid4().hex[:8]}"+ password = "ReadOnlyHostilePw1!" # noqa: S105+ engine = manager.create_user_database(username, password)+ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE gap_r_canary (id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO gap_r_canary (id, note) VALUES (1, :note)"),+ {"note": note},+ )+ manager.close_user_database(username)+ return username, password+++def _assert_nothing_published(manager, username):+ assert username not in manager.connections, (+ "a refused read-only open published an engine"+ )+ assert username not in manager._password_verifiers, (+ "a refused read-only open published a verifier"+ )+++def test_readonly_db_file_opens_readonly_writes_fail_restore_reopens(+ manager,+):+ """R1 (ACTUAL behavior, pinned empirically): with the .db at 0o400 the+ cold open SUCCEEDS -- SQLite falls back to a read-only connection and+ the already-WAL file verifies with the correct key -- so the manager+ publishes a working read-only engine. Pinned: reads work, WRITES fail+ loudly, nothing is corrupted; restoring only the .db restores reads+ but NOT writes (SQLite inherits the db mode for the -wal/-shm+ sidecars it creates during the read-only era, and the stale 0o400+ sidecars keep blocking writers); restoring the sidecars too brings+ full function back."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")+ _require_non_root()++ username, password = _make_user(manager, "gap-R1")+ db_path = manager._get_user_db_path(username)+ original_mode = stat.S_IMODE(os.stat(db_path).st_mode)++ os.chmod(db_path, 0o400)+ try:+ assert stat.S_IMODE(os.stat(db_path).st_mode) == 0o400+ readonly_engine = manager.open_user_database(username, password)+ assert readonly_engine is not None, (+ "expected the empirically-pinned read-only open to succeed"+ )+ assert manager.connections[username] is readonly_engine+ assert manager._password_matches_cached(username, password) is True++ # Reads work through the read-only engine.+ with readonly_engine.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_r_canary WHERE id = 1")+ ).scalar()+ == "gap-R1"+ )++ # Writes fail loudly -- an attacker who chmod-ed the file read-only+ # cannot use the manager to mutate the data either.+ with pytest.raises(Exception, match="readonly|read-only"):+ with readonly_engine.begin() as conn:+ conn.execute(+ text(+ "INSERT INTO gap_r_canary (id, note) "+ "VALUES (2, 'must-not-exist')"+ )+ )+ with readonly_engine.connect() as conn:+ rows = conn.execute(+ text("SELECT COUNT(*) FROM gap_r_canary")+ ).scalar()+ assert rows == 1, "a failed write on the read-only engine mutated data"+ finally:+ os.chmod(db_path, original_mode)++ # Partial recovery (ACTUAL, pinned): restoring only the .db to 0o600+ # brings READS back, but WRITES keep failing: SQLite created the+ # -wal/-shm sidecars during the read-only era INHERITING the db's+ # 0o400 mode, and a writer needs to write the (still 0o400) -wal.+ # The manager surfaces only the generic "attempt to write a readonly+ # database" -- nothing identifies the stale sidecars. See the FINDING+ # in the round-4 summary.+ stale_sidecars = []+ for suffix in ("-wal", "-shm"):+ sidecar = db_path.with_name(db_path.name + suffix)+ if sidecar.exists():+ stale_sidecars.append(sidecar)+ assert stat.S_IMODE(os.stat(sidecar).st_mode) == 0o400, (+ f"setup assumption wrong: {sidecar.name} is not 0o400"+ )+ manager.close_user_database(username)+ reopened = manager.open_user_database(username, password)+ assert reopened is not None, "restore of 0o600 failed to reopen"+ with reopened.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_r_canary WHERE id = 1")+ ).scalar()+ == "gap-R1"+ ), "reads must work again once the .db itself is restored"+ with pytest.raises(Exception, match="readonly|read-only"):+ with reopened.begin() as conn:+ conn.execute(+ text(+ "INSERT INTO gap_r_canary (id, note) "+ "VALUES (2, 'blocked-by-sidecar')"+ )+ )++ # Full recovery (ACTUAL): once the stale sidecars are restored too,+ # a fresh open regains full write function and the data is intact.+ try:+ for sidecar in stale_sidecars:+ os.chmod(sidecar, 0o600)+ manager.close_user_database(username)+ writable = manager.open_user_database(username, password)+ assert writable is not None, "full restore failed to reopen"+ with writable.begin() as conn:+ conn.execute(+ text("INSERT INTO gap_r_canary (id, note) VALUES (2, :note)"),+ {"note": "gap-R1-after-full-restore"},+ )+ with writable.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_r_canary WHERE id = 2")+ ).scalar()+ == "gap-R1-after-full-restore"+ )+ assert (+ conn.execute(+ text("SELECT note FROM gap_r_canary WHERE id = 1")+ ).scalar()+ == "gap-R1"+ )+ finally:+ for sidecar in stale_sidecars:+ if sidecar.exists():+ os.chmod(sidecar, 0o600)+ assert manager._password_matches_cached(username, password) is True+++def test_nonwritable_data_dir_refuses_open_and_restore_reopens(manager):+ """R2: data dir at 0o500 (no write) -- WAL sidecars cannot be created,+ the creator fails, the open refuses cleanly; restoring 0o700 reopens.++ Permissions are restored in ``finally`` so pytest's tmp_path cleanup+ (which must delete files inside this dir) never breaks."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")+ _require_non_root()++ username, password = _make_user(manager, "gap-R2")+ db_path = manager._get_user_db_path(username)+ data_dir = db_path.parent+ original_mode = stat.S_IMODE(os.stat(data_dir).st_mode)++ os.chmod(data_dir, 0o500)+ try:+ assert stat.S_IMODE(os.stat(data_dir).st_mode) == 0o500+ result = manager.open_user_database(username, password)+ assert result is None, (+ "open succeeded with a non-writable data directory -- WAL "+ "sidecar creation should have failed the creator"+ )+ _assert_nothing_published(manager, username)+ finally:+ os.chmod(data_dir, original_mode)++ reopened = manager.open_user_database(username, password)+ assert reopened is not None, "restore of 0o700 failed to reopen"+ with reopened.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_r_canary WHERE id = 1")+ ).scalar()+ == "gap-R2"+ )+ assert manager._password_matches_cached(username, password) is Truediff --git a/tests/security/test_db_connection_rekey_duel.py b/tests/security/test_db_connection_rekey_duel.pynew file mode 100644index 0000000000..36aebb9324--- /dev/null+++ b/tests/security/test_db_connection_rekey_duel.py@@ -0,0 +1,194 @@+"""Racing double-rekey: two concurrent change_password calls, one DB.++Incident context (PR #5596): ``change_password`` originally held NO lock+across the rekey, because it is built from the public pieces -- close,+open(old), PRAGMA rekey, evict. Two threads calling+``change_password(user, old, new_A)`` and ``change_password(user, old,+new_B)`` at a barrier therefore interleaved freely, and CI showed both+reporting success. A per-user lock now serialises the two calls; which+one wins is still scheduler-dependent. What must NOT be+scheduler-dependent is the existential shape afterwards:++* the file ends up keyed by exactly ONE of {old, new_A, new_B} -- a file+ corrupted by interleaved rekeys would leave NO password working;+* the winning password opens, and its engine reads the canary written+ before the race (data survival);+* the losing passwords fail cleanly (None), never a broken engine;+* after a final close_all_databases the manager holds nothing, and the+ engine/verifier pairing invariant holds at every sampled instant.++Round 1's test_db_connection_change_password_race.py pinned the+old-vs-rekey race (hammer threads READ while one rekey chain runs). This+file is the two-WRITERS duel: both threads rekey. It is parametrised over+a single run id: the identifier is kept so the credentials stay unique+per run and a maintainer chasing a flake can widen the range locally, but+repeating a byte-identical duel in CI buys no schedule diversity.+"""++import threading+import uuid++import pytest+from sqlalchemy import text++from local_deep_research.database.encrypted_db import DatabaseManager++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")++JOIN_TIMEOUT_S = 60+BARRIER_TIMEOUT_S = 30+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager writing to an isolated data directory.++ Same self-contained pattern as the round-1/2 files, with the sanctioned+ test-mode KDF knob (each duel performs several derivations/rekeys).+ """+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ mgr = DatabaseManager()+ mgr.data_dir = tmp_path+ yield mgr+ mgr.close_all_databases()+++# One run, not five. The five parametrised repetitions were+# byte-identical -- same users, same passwords, same barrier -- so+# they added no coverage while costing five creates and ten full+# SQLCipher rekeys per CI run. Genuine schedule diversity would need+# different interleavings, not the same duel repeated.[email protected]("run_id", range(1))+def test_double_rekey_duel_existential_invariants(manager, run_id):+ """Two barrier-synchronized change_password races: old->new_A vs+ old->new_B. Afterwards exactly one password owns the file, the winner+ reads the pre-race canary, the losers fail cleanly, and the manager+ quiesces to an empty, pairing-consistent cache."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"duel_{uuid.uuid4().hex[:8]}"+ old = f"DuelOld-{run_id}-CorrectHorse1!" # noqa: S105+ new_a = f"DuelNewA-{run_id}-CorrectHorse2!" # noqa: S105+ new_b = f"DuelNewB-{run_id}-CorrectHorse3!" # noqa: S105+ engine = manager.create_user_database(username, old)+ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE gap_m_canary (id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO gap_m_canary (id, note) VALUES (1, :note)"),+ {"note": "gap-M"},+ )+ manager.close_user_database(username)++ barrier = threading.Barrier(2)+ errors = {}+ outcomes = {}+ pairing_violations = []++ def dueler(label, new_password):+ try:+ barrier.wait(timeout=BARRIER_TIMEOUT_S)+ outcomes[label] = manager.change_password(+ username, old, new_password+ )+ with manager._connections_lock:+ engines = set(manager.connections)+ verifiers = set(manager._password_verifiers)+ if engines != verifiers:+ pairing_violations.append(f"{label}: {engines} vs {verifiers}")+ except Exception as exc: # noqa: BLE001 - surfaced via `errors` below+ errors[label] = exc++ threads = [+ threading.Thread(target=dueler, args=("A", new_a), name="gap-m-a"),+ threading.Thread(target=dueler, args=("B", new_b), name="gap-m-b"),+ ]+ for t in threads:+ t.start()+ for t in threads:+ t.join(timeout=JOIN_TIMEOUT_S)+ assert not any(t.is_alive() for t in threads), "rekey duel deadlocked"+ assert not errors, f"a dueling thread raised: {errors}"+ assert not pairing_violations, (+ f"engine/verifier pairing broke mid-duel: {pairing_violations}"+ )+ # Race witness: both duelers must have recorded an outcome. The former+ # assertion here was `set(outcomes.values()) <= {True, False}`, which+ # holds for ANY bool-returning function and for an empty dict -- it did+ # not distinguish "the duel ran" from "neither thread got a slice".+ assert set(outcomes) == {"A", "B"}, (+ f"a dueling thread recorded no outcome: {outcomes} -- the duel did "+ "not actually run"+ )+ reported_true = {label for label, changed in outcomes.items() if changed}+ assert len(reported_true) <= 1, (+ f"both change_password calls reported success ({outcomes}) -- at "+ "most one rekey can own the file"+ )++ # Quiesce: no cached state survives a close_all_databases.+ manager.close_all_databases()+ with manager._connections_lock:+ assert manager.connections == {}+ assert manager._password_verifiers == {}++ # Existential probe: exactly one of the three passwords opens the file.+ winners = []+ for label, pw in (("old", old), ("new_a", new_a), ("new_b", new_b)):+ if manager.open_user_database(username, pw) is not None:+ winners.append((label, pw))+ assert winners, (+ "no password can open the database after the duel -- the racing "+ "rekeys corrupted the file"+ )+ assert len(winners) == 1, (+ f"multiple passwords open the file after the duel: "+ f"{[label for label, _ in winners]} -- the file must end up keyed "+ "by exactly one of them"+ )++ # Outcome distribution, cross-checked against who actually owns the+ # file: a dueler that reported success MUST be the owner. (The reverse+ # is not asserted -- a rekey can land and still return False if the+ # eviction that follows it raises -- so this stays one-directional.)+ owner_label = {"new_a": "A", "new_b": "B"}.get(winners[0][0])+ expected_true = {owner_label} if owner_label else set()+ assert reported_true <= expected_true, (+ f"change_password returned True for {reported_true} but the file is "+ f"keyed by {winners[0][0]!r} -- a reported success must own the file"+ )++ # The winner reads the canary written before the race.+ winning_label, winning_pw = winners[0]+ engine = manager.open_user_database(username, winning_pw)+ assert engine is not None+ with engine.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_m_canary WHERE id = 1")+ ).scalar()+ == "gap-M"+ ), "the winning password's engine cannot read pre-race data"+ assert manager._password_matches_cached(username, winning_pw) is True++ # The losers fail cleanly -- None, never a broken engine -- and leave+ # the winner's cache entry undisturbed.+ for label, pw in (("old", old), ("new_a", new_a), ("new_b", new_b)):+ if label == winning_label:+ continue+ assert manager.open_user_database(username, pw) is None, (+ f"losing password {label!r} still opens the file"+ )+ assert manager.connections[username] is engine, (+ f"a losing attempt ({label!r}) disturbed the winner's engine"+ )diff --git a/tests/security/test_db_connection_rekey_kills_held_sessions.py b/tests/security/test_db_connection_rekey_kills_held_sessions.pynew file mode 100644index 0000000000..c896cf8898--- /dev/null+++ b/tests/security/test_db_connection_rekey_kills_held_sessions.py@@ -0,0 +1,244 @@+"""Rekey kills held credentials: stale engines and sessions die at REKEY.++Incident context (PR #5596): the fix's ``change_password`` comment+explains why it evicts the cached engine inside the try -- the engine's+creator closure "still derives the OLD hex key, so any freshly pooled+connection is mis-keyed" (encrypted_db.py::change_password). Round 3+pinned the+inverse property (an engine survives its own ``close_user_database``+because the creator closure reconnects with the SAME pre-derived hex key+-- "resurrection", by design). This file pins the complement the incident+threat model needs:++ resurrection-after-CLOSE works (same key material, file unchanged);+ resurrection-after-REKEY dies (same OLD key material, file REKEYED).++* P1 a live engine E1 and a Session S obtained with the old password die+ on use after ``change_password(old -> new)`` (HMAC failure), while the+ file stays readable with the NEW password and ``open(old)`` is None;+* P2 ordering: a session that already survived a close (round 3's+ resurrection) must still die once a rekey lands -- the closure's stale+ key is not healed by close/reconnect cycles, only by a rekey-aware+ reopen;+* P3 a lingering dead session does not poison the manager: caches stay+ clean and paired, new-password opens work, wrong-password opens fail+ closed, and close_all + reopen still reads the canary.+"""++import uuid++import pytest+from sqlalchemy import text++from local_deep_research.database.encrypted_db import DatabaseManager++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager writing to an isolated data directory.++ Same self-contained pattern as the round-1/2/3 files, with the+ sanctioned test-mode KDF knob (each rekey performs several PBKDF2+ derivations).+ """+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ mgr = DatabaseManager()+ mgr.data_dir = tmp_path+ yield mgr+ mgr.close_all_databases()+++def _write_canary(engine, note: str) -> None:+ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE gap_p_canary (id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO gap_p_canary (id, note) VALUES (1, :note)"),+ {"note": note},+ )+++def _make_user(manager, note):+ username = f"rekeyheld_{uuid.uuid4().hex[:8]}"+ old = "RekeyHeldOldPw1!" # noqa: S105+ engine = manager.create_user_database(username, old)+ _write_canary(engine, note)+ return username, old, engine+++def test_rekey_kills_live_engine_and_session(manager):+ """P1: engine + session obtained pre-rekey must fail on use after the+ rekey (old hex key vs rekeyed file -> HMAC failure); the new password+ reads the canary; the old password no longer opens."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username, old, engine = _make_user(manager, "gap-P1")+ session = manager.get_session(username)+ assert session is not None and session.bind is engine+ # Sanity: the session works BEFORE the rekey (reading real table+ # data, so the post-rekey contrast below cannot be satisfied from+ # the connection's page cache).+ assert (+ session.execute(+ text("SELECT note FROM gap_p_canary WHERE id = 1")+ ).scalar()+ == "gap-P1"+ )++ assert manager.change_password(username, old, "RekeyHeldNewPw2!") is True # noqa: S105++ # The live engine now carries a dead key: any new checkout reconnects+ # through the creator closure with the OLD pre-derived hex key and the+ # first page read HMAC-fails.+ with pytest.raises(+ Exception, match="file is not a database|decrypt|operational|HMAC"+ ):+ with engine.connect() as conn:+ conn.execute(text("SELECT 1"))+ # ... and the already-bound session dies too, though by a different+ # mechanism: change_password's in-try eviction+ # (encrypted_db.py::change_password) calls+ # close_user_database, which disposes the cached engine's pool -- and+ # dispose() closes a checked-out DBAPI connection outright rather than+ # merely marking it stale, so the session's held connection is already+ # closed by the time this query runs (sqlcipher3 raises "Cannot+ # operate on a closed database", not an HMAC/decrypt error). Either+ # failure mode proves the same security property: a session obtained+ # before the rekey cannot read a single row after it.+ with pytest.raises(+ Exception,+ match="file is not a database|decrypt|operational|HMAC|closed database",+ ):+ session.execute(text("SELECT note FROM gap_p_canary WHERE id = 1"))+ # The connection underneath is already closed (see above), so+ # Session.close()'s own internal rollback can raise the same+ # DBAPI error instead of no-op'ing -- swallow it here, the way any+ # caller of a session it knows is dead already has to.+ try:+ session.close()+ except Exception: # noqa: BLE001 - cleanup of an already-dead session+ pass++ # The FILE is fine for the NEW password; the OLD password is dead.+ new = "RekeyHeldNewPw2!" # noqa: S105+ assert manager.open_user_database(username, old) is None+ reopened = manager.open_user_database(username, new)+ assert reopened is not None+ with reopened.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_p_canary WHERE id = 1")+ ).scalar()+ == "gap-P1"+ )+ assert manager._password_matches_cached(username, new) is True+++def test_rekey_kills_session_that_survived_a_close(manager):+ """P2: ordering matters. close_user_database alone leaves the held+ session working (round 3's pinned resurrection); the rekey that+ follows must kill it anyway -- the closure's key is stale forever+ until a credential-verified reopen with the new password."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username, old, engine = _make_user(manager, "gap-P2")+ session = manager.get_session(username)+ assert session is not None++ # Step 1: close. The session survives via creator-closure reconnect+ # (round-3 finding; used here as setup, not re-pinned in depth) --+ # proven with a real table read so the contrast with step 2 is+ # meaningful.+ manager.close_user_database(username)+ assert username not in manager.connections+ assert (+ session.execute(+ text("SELECT note FROM gap_p_canary WHERE id = 1")+ ).scalar()+ == "gap-P2"+ )++ # Step 2: rekey. The resurrecting connection now derives the OLD key+ # against a rekeyed file -- it must die on the same table read.+ assert manager.change_password(username, old, "RekeyHeldNewB3!") is True # noqa: S105+ with pytest.raises(+ Exception, match="file is not a database|decrypt|operational|HMAC"+ ):+ session.execute(text("SELECT note FROM gap_p_canary WHERE id = 1"))+ session.close()++ # Recovery: the new password opens and reads the pre-rekey data.+ new = "RekeyHeldNewB3!" # noqa: S105+ reopened = manager.open_user_database(username, new)+ assert reopened is not None+ with reopened.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_p_canary WHERE id = 1")+ ).scalar()+ == "gap-P2"+ )+++def test_dead_session_does_not_poison_the_manager(manager):+ """P3: a lingering dead session (and dead pre-rekey engine) leaves the+ manager exactly as healthy as change_password's contract promises:+ clean/paired caches, working new-password opens, fail-closed+ wrong-password opens, and a close_all + reopen end state that reads+ the canary."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username, old, engine = _make_user(manager, "gap-P3")+ session = manager.get_session(username)+ assert session is not None+ new = "RekeyHeldNewC4!" # noqa: S105++ assert manager.change_password(username, old, new) is True++ # The dead handles exist but the caches are clean and paired.+ with manager._connections_lock:+ assert set(manager.connections) == set(manager._password_verifiers)+ assert username not in manager.connections+ assert username not in manager._password_verifiers++ # New password works (twice: cold open + warm cache hit).+ first = manager.open_user_database(username, new)+ assert first is not None+ assert manager.open_user_database(username, new) is first++ # Wrong password fails closed without disturbing the new engine.+ assert manager.open_user_database(username, "rekey-held-wrong") is None+ assert manager.connections[username] is first+ assert manager._password_matches_cached(username, new) is True++ # End-state health: close_all + reopen still reads the canary, and+ # the dead session stays dead (no accidental healing).+ manager.close_all_databases()+ with pytest.raises(+ Exception, match="file is not a database|decrypt|operational|HMAC"+ ):+ session.execute(text("SELECT 1"))+ session.close()+ reopened = manager.open_user_database(username, new)+ assert reopened is not None+ with reopened.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_p_canary WHERE id = 1")+ ).scalar()+ == "gap-P3"+ )diff --git a/tests/security/test_db_connection_session_lifetime.py b/tests/security/test_db_connection_session_lifetime.pynew file mode 100644index 0000000000..2a517806f0--- /dev/null+++ b/tests/security/test_db_connection_session_lifetime.py@@ -0,0 +1,224 @@+"""Session-vs-engine lifetime after close_user_database.++Incident context (PR #5596): the never-open-on-miss invariant of+``get_session`` protects the CACHE. Separately, an Engine object handed+out by ``open_user_database`` / ``get_session`` may OUTLIVE its cache+entry: ``close_user_database`` calls ``engine.dispose()`` (after a WAL+checkpoint), which closes the pool's connections but leaves the engine+usable -- its creator closure retains the pre-derived hex key, so the+next checkout transparently reconnects without retaining the plaintext+password in that closure.++This file covers both halves of that:++* N1 -- OPEN EXPOSURE, asserted as an ``xfail(strict)`` on the correct+ behavior: a ``Session`` handed out before ``close_user_database`` keeps+ reading plaintext AFTER the close, because ``dispose()`` only drops the+ pooled connections while the creator closure retains the same derived+ hex key. ``close_user_database`` is what a logout runs, so a logout does+ not revoke sessions that are already in flight. The test asserts what+ MUST happen -- the held session can no longer read the user's data --+ so it flips to passing when revocation lands.+* N3 the credential plane around that close holds and is asserted+ normally: a later ``open_user_database(correct)`` cold-opens and+ republishes a NEW engine object (the cache was emptied by the close),+ and a later ``open_user_database(wrong)`` fails CLOSED through the+ verifier.+* N4 a resurrected session is NOT a cross-user credential bypass: it is+ bound to ITS user's engine forever and can never reach another user's+ tables.+"""++import uuid++import pytest+from sqlalchemy import text++from local_deep_research.database.encrypted_db import DatabaseManager++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager writing to an isolated data directory.++ Same self-contained pattern as the round-1/2 files, with the sanctioned+ test-mode KDF knob.+ """+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ mgr = DatabaseManager()+ mgr.data_dir = tmp_path+ yield mgr+ mgr.close_all_databases()+++ strict=True,+ reason=(+ "close_user_database is what a logout runs, so it must revoke "+ "sessions already handed out; today engine.dispose() only drops "+ "the pooled connections and the engine's creator closure "+ "retains the same derived key and reconnects, so a held "+ "Session keeps reading plaintext after logout. Fix: invalidate "+ "the creator (or the engine's key material) in "+ "encrypted_db.py::close_user_database."+ ),+)+def test_close_user_database_revokes_a_held_session(manager):+ """N1 (CORRECT behavior, currently unimplemented): a Session obtained+ before ``close_user_database`` must not be able to read the user's+ data afterwards.++ ``close_user_database`` is the manager-level logout. If a Session+ that predates it keeps serving decrypted rows, then "log out" does+ not mean "stop decrypting" for any request already holding one."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"lifetime_{uuid.uuid4().hex[:8]}"+ password = "LifetimePassword1!" # noqa: S105+ engine = manager.create_user_database(username, password)+ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE gap_n_canary (id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO gap_n_canary (id, note) VALUES (1, :note)"),+ {"note": "gap-N"},+ )++ session = manager.get_session(username)+ assert session is not None+ assert session.bind is engine++ manager.close_user_database(username)+ assert username not in manager.connections+ assert username not in manager._password_verifiers++ try:+ with pytest.raises(Exception): # noqa: B017,PT011 - shape not pinned+ session.execute(+ text("SELECT note FROM gap_n_canary WHERE id = 1")+ ).scalar()+ finally:+ session.close()+++def test_cold_reopen_after_close_republishes_and_fails_closed(manager):+ """N3: after ``close_user_database`` the cache is empty, so the next+ ``open_user_database(correct)`` is a COLD open that publishes a NEW+ engine object reading the canary, and ``open_user_database(wrong)``+ fails closed through the verifier without disturbing it."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"lifetime_{uuid.uuid4().hex[:8]}"+ password = "LifetimePassword1!" # noqa: S105+ engine = manager.create_user_database(username, password)+ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE gap_n_canary (id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO gap_n_canary (id, note) VALUES (1, :note)"),+ {"note": "gap-N"},+ )+ manager.close_user_database(username)++ republished = manager.open_user_database(username, password)+ assert republished is not None+ assert republished is not engine, (+ "open_user_database must republish a fresh engine after the cache "+ "entry was closed (cold open), not resurrect the cache identity"+ )+ assert manager.connections[username] is republished+ with republished.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_n_canary WHERE id = 1")+ ).scalar()+ == "gap-N"+ )++ # A wrong password on the next credential-taking open fails CLOSED.+ assert manager.open_user_database(username, "lifetime-wrong") is None+ assert manager.connections[username] is republished, (+ "a rejected wrong-password open disturbed the republished engine"+ )+ assert manager._password_matches_cached(username, password) is True+ assert manager._password_matches_cached(username, "lifetime-wrong") is False+++def test_session_cannot_reach_another_users_database(manager):+ """N4: a Session (live or resurrected) is bound to its own user's+ engine and can never read another user's tables -- get_session is not+ a cross-user credential bypass."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ alice = f"life_alice_{uuid.uuid4().hex[:8]}"+ bob = f"life_bob_{uuid.uuid4().hex[:8]}"+ alice_password = "AliceLifetimePw1!" # noqa: S105+ bob_password = "BobLifetimePw2!" # noqa: S105++ alice_engine = manager.create_user_database(alice, alice_password)+ bob_engine = manager.create_user_database(bob, bob_password)+ with bob_engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE gap_n_b_private "+ "(id INTEGER PRIMARY KEY, secret TEXT)"+ )+ )+ conn.execute(+ text(+ "INSERT INTO gap_n_b_private (id, secret) "+ "VALUES (1, 'bobs-secret')"+ )+ )++ alice_session = manager.get_session(alice)+ assert alice_session is not None+ assert alice_session.bind is alice_engine+ assert alice_session.bind is not bob_engine++ # Alice cannot see Bob's table -- distinct engine, distinct file.+ with pytest.raises(Exception, match="no such table"):+ alice_session.execute(text("SELECT * FROM gap_n_b_private")).fetchall()++ # ... and closing Alice's connection does not change that. Whether the+ # close revokes the session (see the N1 xfail) or the engine+ # resurrects, the one thing that must never happen is Alice reaching+ # Bob's tables -- so the failure shape is deliberately not pinned.+ manager.close_user_database(alice)+ with pytest.raises(Exception): # noqa: B017,PT011 - shape not pinned+ alice_session.execute(text("SELECT * FROM gap_n_b_private")).fetchall()+ # close_user_database's dispose() can leave the session's underlying+ # DBAPI connection already closed, in which case Session.close()'s own+ # internal rollback raises the same error instead of no-op'ing --+ # cleanup of a session already known to be broken has to tolerate+ # that, the same "shape not pinned" way the read above does.+ try:+ alice_session.close()+ except Exception: # noqa: BLE001 - cleanup of an already-dead session+ pass++ # Bob's own accessor still reads his private data.+ bob_session = manager.get_session(bob)+ assert bob_session is not None+ rows = bob_session.execute(+ text("SELECT secret FROM gap_n_b_private WHERE id = 1")+ ).fetchall()+ bob_session.close()+ assert rows and rows[0][0] == "bobs-secret"diff --git a/tests/security/test_db_connection_symlink_toctou.py b/tests/security/test_db_connection_symlink_toctou.pynew file mode 100644index 0000000000..ed7fac5860--- /dev/null+++ b/tests/security/test_db_connection_symlink_toctou.py@@ -0,0 +1,234 @@+"""Symlink TOCTOU on the .db and .salt paths.++Research context (CAPEC-27 "HTTP Response Splitting"-family redirected-+file attacks; the 2025-26 symlink-race CVE class, e.g. CVE-2026-54370+and the filelock CVE-2025-68146): a local attacker who can plant a+symlink where the application will create or open a file can redirect+the write to a victim path. Planting requires data-dir write access,+which the 0700 owner-only directory already denies to other users --+these tests pin the residual posture for the same-user/compromised-+account case.++Probed and pinned against the real manager:++* AJ1 dangling .db symlink at create -- OPEN EXPOSURE, asserted as an+ ``xfail(strict)`` on the correct behavior. ``Path.exists()`` follows+ symlinks and returns False for a dangling one, so the+ ``db_path.exists()`` guard passes, and ``sqlcipher3.connect`` (via+ ``create_sqlcipher_connection`` with creation_mode=True) follows the+ symlink: the whole database is written AT THE ATTACKER-CHOSEN VICTIM+ PATH outside the data dir, while the salt lands inside and the account+ looks perfectly normal. The test asserts what MUST happen -- an+ ``lstat``/``O_NOFOLLOW`` guard refuses the create and nothing is+ written outside the data dir -- so it flips to passing when the guard+ lands.+* AJ2 .db symlink to an EXISTING victim -- HOLD: the exists() guard+ sees the victim through the link and refuses with "Database already+ exists"; the victim's bytes are untouched.+* AJ3 .salt symlink -- HOLD via O_EXCL no-follow: ``create_database_+ salt`` opens with O_CREAT|O_EXCL, which never follows a symlink (the+ canonical mitigation); the FileExistsError flows into create_user_+ database's orphaned-salt recovery branch, whose unlink removes the+ LINK, and a real salt is created at the expected path. The victim is+ never written.+* AJ4 a symlinked data dir (deployer choice, e.g. /srv symlink) works+ transparently for the full create/open cycle.+"""++import shutil+import uuid++import pytest+from sqlalchemy import text++from local_deep_research.config.paths import get_user_database_filename+from local_deep_research.database.encrypted_db import DatabaseManager++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager writing to an isolated data directory.++ Same self-contained pattern as the round-1..6 files, with the+ sanctioned test-mode KDF knob.+ """+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ mgr = DatabaseManager()+ mgr.data_dir = tmp_path+ yield mgr+ mgr.close_all_databases()+++ strict=True,+ reason=(+ "create_user_database must refuse a symlink at the .db path; "+ "today Path.exists() returns False for a DANGLING symlink so the "+ "existence guard passes and sqlcipher3.connect follows the link, "+ "writing the entire database outside the data dir. Fix: lstat / "+ "O_NOFOLLOW check on db_path before create "+ "(encrypted_db.py::create_user_database)."+ ),+)+def test_dangling_db_symlink_is_refused_at_create(manager):+ """AJ1 (CORRECT behavior, currently unimplemented): a planted+ dangling symlink at the .db path must not redirect the create. The+ database bytes must never land at an attacker-chosen path outside the+ data dir -- an existence guard that follows symlinks (``exists()``)+ is exactly the guard a dangling link defeats.++ Precondition is same-user / compromised-account (the data dir is+ 0700), which is why this is a hardening gap rather than a+ cross-account break -- but the redirected write is unbounded: it goes+ wherever the link points, with the process's own privileges."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"aj1_{uuid.uuid4().hex[:8]}"+ password = "DanglingSymlinkPw1!" # noqa: S105+ filename = get_user_database_filename(username)+ victim = manager.data_dir.parent / f"aj1_victim_{uuid.uuid4().hex[:8]}.db"+ link = manager.data_dir / filename+ link.symlink_to(victim) # dangling: victim does not exist yet++ try:+ # The refusal shape is deliberately not pinned (a guard may raise+ # or may unlink the planted link and create normally inside the+ # data dir); what MUST hold is that nothing is written outside.+ try:+ manager.create_user_database(username, password)+ except (ValueError, OSError):+ pass+ assert not victim.exists(), (+ "the create followed the planted symlink -- the database "+ "landed at the attacker-chosen path outside the data dir"+ )+ # Refusal may leave the planted link untouched. The security+ # boundary is that the create never writes through it; deleting+ # an untrusted pre-existing path is not required for refusal.+ finally:+ manager.close_user_database(username)+ victim.unlink(missing_ok=True)+++def test_db_symlink_to_existing_victim_is_refused(manager):+ """AJ2 (HOLD): a .db symlink pointing at an EXISTING victim file+ trips the db_path.exists() guard (follows the link) -- ValueError+ "Database already exists" -- and the victim's bytes are untouched."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"aj2_{uuid.uuid4().hex[:8]}"+ filename = get_user_database_filename(username)+ victim = manager.data_dir.parent / f"aj2_victim_{uuid.uuid4().hex[:8]}.db"+ victim.write_bytes(b"existing-precious")+ (manager.data_dir / filename).symlink_to(victim)++ # `victim` lives in the per-worker basetemp (tmp_path.parent), which+ # pytest only reclaims on its 3-run rotation -- so the unlink has to be+ # on the failure path too, not just the happy one.+ try:+ with pytest.raises(ValueError, match="already exists"):+ manager.create_user_database(username, "ExistingVictimPw1!") # noqa: S105++ assert victim.read_bytes() == b"existing-precious", (+ "the refused create modified the victim file"+ )+ assert username not in manager.connections+ finally:+ victim.unlink(missing_ok=True)+++def test_salt_symlink_is_never_followed_oexcl_wins(manager):+ """AJ3 (HOLD): a symlink at the .salt path cannot redirect the salt+ write -- create_database_salt's O_CREAT|O_EXCL open refuses to+ follow symlinks; the FileExistsError flows into the orphaned-salt+ recovery branch, which unlinks the LINK and creates a real salt at+ the expected path. The victim is never written; the create succeeds."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"aj3_{uuid.uuid4().hex[:8]}"+ password = "SaltSymlinkPw1!" # noqa: S105+ filename = get_user_database_filename(username)+ victim = manager.data_dir.parent / f"aj3_victim_{uuid.uuid4().hex[:8]}.bin"+ salt_link = manager.data_dir / filename.replace(".db", ".db.salt")+ salt_link.symlink_to(victim)++ # `victim` is outside tmp_path; if the no-follow guard ever regresses it+ # gets CREATED there, so the cleanup belongs on the failure path.+ try:+ engine = manager.create_user_database(username, password)+ assert engine is not None, (+ "create failed entirely in the face of a planted salt symlink"+ )++ assert not victim.exists(), (+ "the salt write FOLLOWED the symlink to the victim -- O_EXCL "+ "no-follow was bypassed"+ )+ assert salt_link.exists() and not salt_link.is_symlink(), (+ "a real salt (not the symlink) must exist at the expected path"+ )+ with engine.connect() as conn:+ assert conn.execute(text("SELECT 1")).scalar() == 1+ manager.close_user_database(username)++ # And the account reopens normally with the recovered salt.+ reopened = manager.open_user_database(username, password)+ assert reopened is not None+ finally:+ victim.unlink(missing_ok=True)+++def test_symlinked_data_dir_works_transparently(manager):+ """AJ4 (positive): a deployer-chosen symlinked data directory+ supports the full create/open cycle, with the artifacts landing in+ the real target directory."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ real_dir = manager.data_dir.parent / f"aj4_real_{uuid.uuid4().hex[:8]}"+ real_dir.mkdir()+ link_dir = manager.data_dir.parent / f"aj4_link_{uuid.uuid4().hex[:8]}"+ link_dir.symlink_to(real_dir, target_is_directory=True)++ manager.data_dir = link_dir # the setter's mkdir tolerates a symlink-to-dir++ # Both live in the per-worker basetemp (tmp_path.parent), which pytest+ # only reclaims on its 3-run rotation -- and this one holds a whole+ # database tree, so remove it however the test ends.+ try:+ username = f"aj4_{uuid.uuid4().hex[:8]}"+ password = "SymlinkDirPw1!" # noqa: S105+ engine = manager.create_user_database(username, password)+ assert engine is not None+ with engine.begin() as conn:+ conn.execute(+ text("CREATE TABLE gap_aj4 (id INTEGER PRIMARY KEY, v TEXT)")+ )+ conn.execute(text("INSERT INTO gap_aj4 VALUES (1, 'gap-AJ4')"))+ manager.close_user_database(username)++ assert (real_dir / get_user_database_filename(username)).exists(), (+ "artifacts did not land in the real directory behind the symlink"+ )+ reopened = manager.open_user_database(username, password)+ assert reopened is not None+ with reopened.connect() as conn:+ assert (+ conn.execute(text("SELECT v FROM gap_aj4")).scalar()+ == "gap-AJ4"+ )+ finally:+ manager.close_all_databases()+ link_dir.unlink(missing_ok=True)+ shutil.rmtree(real_dir, ignore_errors=True)diff --git a/tests/security/test_db_connection_tamper_resilience.py b/tests/security/test_db_connection_tamper_resilience.pynew file mode 100644index 0000000000..606423096f--- /dev/null+++ b/tests/security/test_db_connection_tamper_resilience.py@@ -0,0 +1,296 @@+"""Ciphertext & salt tampering resilience at the DatabaseManager level.++Incident context (PR #5596): the fix's fail-closed cache means a tampered+database must never yield an engine through ANY path -- the cold open is+the last line of defense, and nothing it does on failure may leave+publishable state behind (an engine or verifier cached from a failed open+would re-arm the original bypass shape).++``tests/database/test_sqlcipher_integration.py`` covers tampering only+shallowly: ``test_corrupted_database_returns_none`` overwrites the whole+file with garbage and asserts None (no cache assertions, no wrong-password+variant, no recovery, no salt tampering), and+``test_cipher_integrity_check_detects_tampering`` accepts "may or may not+be detected". ``tests/database/test_encryption_constants.py`` pins the+wrong-size salt ValueError at the UTIL level only. This file pins the+MANAGER-level properties, deterministically:++* K1 in-place ciphertext tamper (bytes flipped inside page 1, so the+ sqlite_master read on the cold path must HMAC-fail): open(correct) and+ open(wrong) both refuse, cache NOTHING, and a restore from a pre-tamper+ backup reopens cleanly with the canary intact;+* K2 salt tampering at the manager level: deleted salt (falls back to the+ legacy salt -> different key -> clean None; and NO auto-recreation of+ the salt -- silent regeneration would destroy the data), swapped salt+ (another user's 32 bytes -> different key -> None), truncated salt+ (ValueError propagates from the derivation chokepoint; nothing cached);+ restore always reopens;+* K3 tamper racing concurrent opens: every post-tamper open refuses, the+ engine/verifier pairing invariant holds under the connections lock, and+ the stabilized cache is empty for the user.+"""++import shutil+import threading+import uuid+from pathlib import Path++import pytest+from sqlalchemy import text++from local_deep_research.database.encrypted_db import DatabaseManager+from local_deep_research.database.sqlcipher_utils import get_salt_file_path++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")++JOIN_TIMEOUT_S = 60+BARRIER_TIMEOUT_S = 30+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager writing to an isolated data directory.++ Same self-contained pattern as the round-1/2 files, with the sanctioned+ test-mode KDF knob.+ """+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ mgr = DatabaseManager()+ mgr.data_dir = tmp_path+ yield mgr+ mgr.close_all_databases()+++def _tamper_bytes(path: Path, offsets) -> None:+ """XOR-flip one byte at each offset, in place."""+ size = path.stat().st_size+ usable = [off for off in offsets if 0 < off < size]+ assert usable, f"setup: no tamper offset fits file of {size} bytes"+ with open(path, "r+b") as handle:+ for off in usable:+ handle.seek(off)+ byte = handle.read(1)+ handle.seek(off)+ handle.write(bytes([byte[0] ^ 0xFF]))+++def _write_canary(engine, note: str) -> None:+ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE gap_k_canary (id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO gap_k_canary (id, note) VALUES (1, :note)"),+ {"note": note},+ )+++def _assert_nothing_cached(manager, username):+ assert username not in manager.connections, (+ "a refused open cached an engine"+ )+ assert username not in manager._password_verifiers, (+ "a refused open cached a verifier"+ )+ # NOTE: ``_init_locks`` gaining an entry on any open attempt is+ # by-design (created before the cold open, retained on close -- see+ # tests/database/test_concurrent_user_db_open.py), so emptiness of+ # that dict is deliberately NOT asserted.+++def _setup_user(manager, note):+ username = f"tamper_{uuid.uuid4().hex[:8]}"+ password = "TamperProofPassword1!" # noqa: S105+ engine = manager.create_user_database(username, password)+ _write_canary(engine, note)+ manager.close_user_database(username)+ db_path = manager._get_user_db_path(username)+ salt_path = get_salt_file_path(db_path)+ return username, password, db_path, salt_path+++def test_ciphertext_tamper_refuses_open_and_restore_reopens(manager):+ """K1: flipping bytes inside page 1 makes the sqlite_master read+ HMAC-fail, so the cold open must refuse for the CORRECT password as+ well as a wrong one, cache nothing, and a restored file must reopen+ with its data intact."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username, password, db_path, salt_path = _setup_user(manager, "gap-K1")+ backup_db = db_path.with_name(db_path.name + ".backup")+ backup_salt = salt_path.with_name(salt_path.name + ".backup")+ shutil.copy2(db_path, backup_db)+ shutil.copy2(salt_path, backup_salt)++ # Tamper page 1 (page size is 16KB; sqlite_master lives on page 1) and+ # the start of page 2. The connection was checkpointed on close, so+ # the .db holds everything.+ _tamper_bytes(db_path, [100, 5000, 10000, 15000, 17000])++ assert manager.open_user_database(username, password) is None, (+ "the CORRECT password opened a tampered database -- HMAC failure "+ "was not enforced on the cold path"+ )+ assert manager.open_user_database(username, "tamper-wrong") is None+ _assert_nothing_cached(manager, username)++ # Restore the pristine artifacts -> the same password reopens and the+ # pre-tamper data is intact.+ shutil.copy2(backup_db, db_path)+ shutil.copy2(backup_salt, salt_path)+ reopened = manager.open_user_database(username, password)+ assert reopened is not None, "restore-from-backup failed to reopen"+ with reopened.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_k_canary WHERE id = 1")+ ).scalar()+ == "gap-K1"+ )+ assert manager._password_matches_cached(username, password) is True+++def test_salt_tamper_refuses_open_without_side_effects(manager):+ """K2: deleting the salt (legacy-salt fallback -> different key ->+ clean None, and the salt is NOT auto-recreated), swapping in another+ user's salt (valid 32 bytes, wrong key material -> None), and+ truncating the salt (ValueError from the derivation chokepoint)+ all refuse without publishing state; restoring always reopens."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username, password, db_path, salt_path = _setup_user(manager, "gap-K2")+ other, other_password, other_db, other_salt = _setup_user(+ manager, "gap-K2-other"+ )+ backup_salt = salt_path.with_name(salt_path.name + ".backup")+ shutil.copy2(salt_path, backup_salt)++ # --- Deleted salt: get_salt_for_database falls back to the LEGACY salt+ # (read-only, sqlcipher_utils.py:60-66), the derived key changes, the+ # HMAC check fails, open returns None. No writer may recreate it.+ salt_path.unlink()+ assert manager.open_user_database(username, password) is None, (+ "open succeeded with a deleted salt (wrong key material accepted)"+ )+ _assert_nothing_cached(manager, username)+ assert not salt_path.exists(), (+ "the manager auto-recreated a deleted salt for an EXISTING "+ "database -- silent salt regeneration would permanently destroy "+ "the data (the original key could never be derived again)"+ )++ # --- Swapped salt: another user's valid 32-byte salt is the right+ # size but the wrong key material.+ shutil.copy2(other_salt, salt_path)+ assert manager.open_user_database(username, password) is None, (+ "open succeeded with another user's salt (cross-user key "+ "material accepted)"+ )+ assert manager.open_user_database(username, other_password) is None, (+ "open succeeded with the other user's PASSWORD on this user's DB"+ )+ _assert_nothing_cached(manager, username)++ # --- Truncated salt: wrong size -> ValueError from the salt reader+ # (manager-level behavior; the util-level raise is pinned in+ # test_encryption_constants.py). It propagates out of open_user_database+ # BEFORE any engine is built or cached.+ salt_path.write_bytes(salt_path.read_bytes()[:10])+ with pytest.raises(ValueError):+ manager.open_user_database(username, password)+ _assert_nothing_cached(manager, username)++ # --- Restore: the original salt reopens the original data.+ shutil.copy2(backup_salt, salt_path)+ reopened = manager.open_user_database(username, password)+ assert reopened is not None+ with reopened.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_k_canary WHERE id = 1")+ ).scalar()+ == "gap-K2"+ )+++def test_tamper_racing_concurrent_opens_never_publishes(manager):+ """K3: with the file tampered, two threads hammering open(correct) (one+ also closing between attempts) must never obtain or publish anything;+ the pairing invariant holds at every sampled instant; the stabilized+ cache is empty for the user; restore reopens."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username, password, db_path, salt_path = _setup_user(manager, "gap-K3")+ backup_db = db_path.with_name(db_path.name + ".backup")+ backup_salt = salt_path.with_name(salt_path.name + ".backup")+ shutil.copy2(db_path, backup_db)+ shutil.copy2(salt_path, backup_salt)+ _tamper_bytes(db_path, [100, 5000, 10000, 15000])++ barrier = threading.Barrier(2)+ errors = {}+ violations = []+ pairing_violations = []++ def opener(label, do_close):+ try:+ barrier.wait(timeout=BARRIER_TIMEOUT_S)+ for i in range(4):+ engine = manager.open_user_database(username, password)+ if engine is not None:+ violations.append(f"{label} #{i}: got {engine!r}")+ if do_close:+ manager.close_user_database(username)+ with manager._connections_lock:+ engines = set(manager.connections)+ verifiers = set(manager._password_verifiers)+ if engines != verifiers:+ pairing_violations.append(+ f"{label} #{i}: {engines} vs {verifiers}"+ )+ except Exception as exc: # noqa: BLE001 - surfaced via `errors` below+ errors[label] = exc++ threads = [+ threading.Thread(target=opener, args=("open-close", True)),+ threading.Thread(target=opener, args=("open-only", False)),+ ]+ for t in threads:+ t.start()+ for t in threads:+ t.join(timeout=JOIN_TIMEOUT_S)+ assert not any(t.is_alive() for t in threads), "tamper race deadlocked"+ assert not errors, f"a racing opener raised: {errors}"+ assert not violations, f"a tampered DB handed out engines: {violations}"+ assert not pairing_violations, (+ f"engine/verifier pairing broke: {pairing_violations}"+ )++ # Stabilized: nothing reachable for this user from cached state.+ with manager._connections_lock:+ assert username not in manager.connections+ assert username not in manager._password_verifiers++ # Restore and recover.+ shutil.copy2(backup_db, db_path)+ shutil.copy2(backup_salt, salt_path)+ reopened = manager.open_user_database(username, password)+ assert reopened is not None+ with reopened.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_k_canary WHERE id = 1")+ ).scalar()+ == "gap-K3"+ )diff --git a/tests/security/test_db_connection_temp_store_posture.py b/tests/security/test_db_connection_temp_store_posture.pynew file mode 100644index 0000000000..43ce6aee8e--- /dev/null+++ b/tests/security/test_db_connection_temp_store_posture.py@@ -0,0 +1,80 @@+"""Temp-store posture: plaintext spill files vs. memory.++Research context (SQLCipher design docs, "Temp Files": temporary files+used by ORDER BY / GROUP BY / large sorts are NOT encrypted by+SQLCipher -- they contain plaintext result data -- unless the engine+keeps them in memory; sqlite.org/pragma.html#pragma_temp_store: 0/1+allow file-backed temp storage, 2 forces MEMORY). An app doing large+sorts with temp_store < 2 writes plaintext table content into the+system temp directory.++Probed and pinned against the real manager (HOLD):++* AL1 every connection this manager builds sets+ ``PRAGMA temp_store = MEMORY`` -- ``apply_performance_pragmas``+ (sqlcipher_utils.py) issues it on every cold connect, so query+ spill stays in process memory and no plaintext temp files reach+ disk. Pinned by reading the pragma back through a live session.++AL2 (forcing a real large sort to observe spill) is deliberately not+shipped: the pragma pin is the deliverable and a spill-sized query+would blow the run-time budget for no extra signal.+"""++import uuid++import pytest+from sqlalchemy import text++from local_deep_research.database.encrypted_db import DatabaseManager++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager writing to an isolated data directory.++ Same self-contained pattern as the round-1..6 files, with the+ sanctioned test-mode KDF knob.+ """+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ mgr = DatabaseManager()+ mgr.data_dir = tmp_path+ yield mgr+ mgr.close_all_databases()+++def test_temp_store_is_memory_on_manager_connections(manager):+ """AL1: temp_store == 2 (MEMORY) on a live manager connection --+ sort spill never becomes a plaintext temp file on disk."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"al1_{uuid.uuid4().hex[:8]}"+ password = "TempStorePw1!" # noqa: S105+ engine = manager.create_user_database(username, password)+ with engine.begin() as conn:+ conn.execute(+ text("CREATE TABLE gap_al (id INTEGER PRIMARY KEY, v TEXT)")+ )+ conn.execute(text("INSERT INTO gap_al VALUES (1, 'gap-AL')"))++ with engine.connect() as conn:+ value = conn.execute(text("PRAGMA temp_store")).scalar()+ assert value == 2, (+ f"temp_store posture changed: observed {value!r} (was 2/MEMORY). "+ "0 or 1 would let large sorts spill plaintext result data into "+ "file-backed temp storage that SQLCipher does not encrypt -- "+ "treat as a posture regression (SQLCipher 'Temp Files' note)."+ )++ # The connection is otherwise healthy (not a stale pragma read).+ with engine.connect() as conn:+ assert conn.execute(text("SELECT v FROM gap_al")).scalar() == "gap-AL"diff --git a/tests/security/test_db_connection_umask_perms.py b/tests/security/test_db_connection_umask_perms.pynew file mode 100644index 0000000000..61c38d5e0b--- /dev/null+++ b/tests/security/test_db_connection_umask_perms.py@@ -0,0 +1,216 @@+"""Artifact permissions under hostile umasks.++Incident context (PR #5596): these files hold the user's entire encrypted+data life -- the .db (ciphertext), the .salt (key material), the WAL+sidecars (plaintext-ordering writes). The connection layer enforces+permissions through TWO different mechanisms with DIFFERENT umask+sensitivity:++* explicit ``chmod`` after the fact (``_ensure_data_dir`` -> 0o700 for+ the directory; ``_best_effort_chmod(db_path, 0o600)`` after structure+ creation) -- chmod is NOT umask-masked, so these hold under any umask;+* explicit modes at creation (``create_database_salt``'s+ ``os.open(..., 0o600)``) -- open(2) modes ARE masked by the process+ umask, so a hostile umask can degrade the salt below 0o600.++This file pins what actually happens at each umask:++* Z1 realistic umasks (0o022 / 0o077 / 0o002): directory 0o700, .db and+ .salt exactly 0o600, WAL/SHM sidecars owner-only, create/open/close all+ clean;+* Z2 extreme umask 0o777 (probed): the salt lands at 0o000, the+ subsequent salt READ inside creation raises PermissionError, and the+ failure-cleanup path removes every artifact -- a clean, loud failure+ with ZERO orphans (see FINDING in the round-6 summary);+* Z3 under the runner's own (fixture-default) umask: every artifact is+ at least owner-only.++The whole module is marked ``serial``: ``os.umask`` is process-global, so+these tests must not share a worker process with anything else.++The whole module is ALSO marked ``nonroot``: every test below starts with+``if os.geteuid() == 0: pytest.skip(...)`` because permission bits are not+enforced for root, so under root every one of them silently no-ops. This+must be carried on the test itself -- it is not safe to rely on a CI step+happening to invoke pytest with ``--user`` or an equivalent unprivileged+runner; that coupling is invisible here and silently regresses to a no-op+the moment a lane runs ``-m serial`` (or this file directly) as root. See+the ``serial`` and ``nonroot`` marker docstrings in pyproject.toml -- a+module carrying both only needs to run once: docker-tests.yml's merged+``serial``/``nonroot`` step selects ``-m 'serial or nonroot'`` under+``--user ldruser``, so this file runs exactly once there regardless of+which marker matched it.++Round-1's cold-open file fingerprinted FAILED opens; round-5 W covered+lifecycle -- neither pinned creation-time permissions vs umask.+"""++import os+import stat+import uuid++import pytest+from sqlalchemy import text++from local_deep_research.database.encrypted_db import DatabaseManager++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")++REALISTIC_UMASKS = [0o022, 0o077, 0o002]++# ``os.umask`` is PROCESS-global, not thread- or test-local: while the+# 0o777 window below is open, ANY file created anywhere in this process+# lands at mode 0o000. That is fine in a dedicated serial run and a+# landmine under '-n auto', so the whole module opts out of the parallel+# lane (see the ``serial`` marker in pyproject.toml and the dedicated+# step in .github/workflows/docker-tests.yml).+#+# Also marked ``nonroot``: every test below self-skips under root (see+# the module docstring above). Declaring it explicitly here -- rather+# than leaning on the fact that CI's 'serial' step happens to invoke+# pytest as an unprivileged user -- makes the non-root requirement a+# property of the test, not an accident of CI wiring that a new lane+# running '-m serial' as root would silently violate.+pytestmark = [pytest.mark.serial, pytest.mark.nonroot]+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager writing to an isolated data directory.++ Same self-contained pattern as the round-1..5 files, with the+ sanctioned test-mode KDF knob.+ """+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ mgr = DatabaseManager()+ mgr.data_dir = tmp_path+ yield mgr+ mgr.close_all_databases()+++def _write_canary(engine, note: str) -> None:+ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE gap_z_canary (id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO gap_z_canary (id, note) VALUES (1, :note)"),+ {"note": note},+ )++[email protected]("umask", REALISTIC_UMASKS)+def test_realistic_umasks_keep_artifacts_owner_only(manager, umask):+ """Z1: under 0o022 / 0o077 / 0o002 the data dir is 0o700 (explicit+ chmod), .db and .salt are exactly 0o600, WAL/SHM sidecars are+ owner-only while open, and the full create/write/open/close cycle+ works."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")+ if os.geteuid() == 0:+ pytest.skip("permission bits are not enforced for root")++ original = os.umask(umask)+ try:+ username = f"umask_{umask:o}_{uuid.uuid4().hex[:8]}"+ password = "UmaskProbePw1!" # noqa: S105+ engine = manager.create_user_database(username, password)+ _write_canary(engine, f"gap-Z-{umask:o}")++ db_path = manager._get_user_db_path(username)+ salt_path = db_path.with_name(db_path.name.replace(".db", ".db.salt"))+ assert stat.S_IMODE(os.stat(manager.data_dir).st_mode) == 0o700+ assert stat.S_IMODE(os.stat(db_path).st_mode) == 0o600, (+ f"db mode under umask {umask:o}"+ )+ assert stat.S_IMODE(os.stat(salt_path).st_mode) == 0o600, (+ f"salt mode under umask {umask:o}"+ )+ for suffix in ("-wal", "-shm"):+ sidecar = db_path.with_name(db_path.name + suffix)+ if sidecar.exists():+ mode = stat.S_IMODE(os.stat(sidecar).st_mode)+ assert mode & 0o077 == 0, (+ f"{suffix} is group/world accessible ({oct(mode)}) "+ f"under umask {umask:o}"+ )++ # Open/close cycle clean under this umask too.+ manager.close_user_database(username)+ reopened = manager.open_user_database(username, password)+ assert reopened is not None+ with reopened.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_z_canary WHERE id = 1")+ ).scalar()+ == f"gap-Z-{umask:o}"+ )+ finally:+ os.umask(original)+++def test_extreme_umask_0777_fails_loudly_with_zero_orphans(manager):+ """Z2 (ACTUAL, probed): umask 0o777 masks the salt's os.open 0o600+ down to 0o000; the salt READ inside creation then raises+ PermissionError, and the create-failure cleanup removes EVERY+ artifact (the unusable salt included) -- a clean failure, no partial+ state, and the username stays reusable once a sane umask is back.+ FINDING: deployers must enforce umask <= 0o077-ish; the app fails+ closed (correctly) rather than silently degrading."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")+ if os.geteuid() == 0:+ pytest.skip("permission bits are not enforced for root")++ username = f"umask777_{uuid.uuid4().hex[:8]}"+ original = os.umask(0o777)+ try:+ with pytest.raises(PermissionError):+ manager.create_user_database(username, "Umask777Pw1!") # noqa: S105+ finally:+ os.umask(original)++ # Zero orphans: no .db, no .salt, no sidecars, nothing.+ artifacts = sorted(p.name for p in manager.data_dir.iterdir())+ assert artifacts == [], (+ f"the umask-0o777 failure left partial artifacts: {artifacts}"+ )+ assert username not in manager.connections+ assert username not in manager._password_verifiers++ # The username is reusable under the restored umask.+ engine = manager.create_user_database(username, "Umask777Pw1!") # noqa: S105+ assert engine is not None+ with engine.connect() as conn:+ assert conn.execute(text("SELECT 1")).scalar() == 1+++def test_fixture_default_umask_artifacts_owner_only(manager):+ """Z3: under whatever umask the runner itself has, every artifact is+ at least owner-only (no group/world bits) and the directory is 0o700."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")+ if os.geteuid() == 0:+ pytest.skip("permission bits are not enforced for root")++ username = f"defumask_{uuid.uuid4().hex[:8]}"+ engine = manager.create_user_database(username, "DefaultUmaskPw1!") # noqa: S105+ _write_canary(engine, "gap-Z3")+ manager.close_user_database(username)++ assert stat.S_IMODE(os.stat(manager.data_dir).st_mode) == 0o700+ for path in manager.data_dir.iterdir():+ mode = stat.S_IMODE(os.stat(path).st_mode)+ assert mode & 0o077 == 0, (+ f"{path.name} is group/world accessible ({oct(mode)}) under "+ "the runner's default umask"+ )diff --git a/tests/security/test_db_connection_unencrypted_mode.py b/tests/security/test_db_connection_unencrypted_mode.pynew file mode 100644index 0000000000..0e473ebd52--- /dev/null+++ b/tests/security/test_db_connection_unencrypted_mode.py@@ -0,0 +1,171 @@+"""Unencrypted fallback mode: the documented plaintext risk surface.++Incident context (PR #5596): the verifier machinery only means something+when there IS a credential to verify. In unencrypted mode+(``has_encryption == False``) the code DOCUMENTS that the cold path opens+the plain-SQLite database with any password and that the cache hit trusts+directly (``_cached_engine_trusted`` short-circuits; see its docstring+and ``test_password_verifier_primitive.py``). This file pins that whole+surface as ACTUAL, DOCUMENTED behavior -- not as a bypass -- by forcing+``has_encryption = False`` in a process that has sqlcipher3 installed+(monkeypatching ``DatabaseManager._check_encryption_available`` before+construction, per the round-5 instructions):++* U1 the full plaintext flow: create -> engine; the .db file is readable+ with VANILLA sqlite3 (no key) -- the at-rest risk, pinned; any password+ opens; change_password returns False with its "Cannot change password"+ warning (encrypted_db.py::change_password); and get_session works;+* U2 ``check_database_integrity`` on a HEALTHY unencrypted database+ must report True. It reported False until #6376: ``PRAGMA+ cipher_integrity_check`` on a plain-SQLite connection returned a closed+ result whose iteration raised ResourceClosedError, which the method's+ bare ``except`` swallowed into False. The method now skips the+ SQLCipher-only pragma when ``has_encryption`` is False, so this is a+ plain regression test.++A U3 "wrong password against a warm cache succeeds" test was dropped: it+duplicated ``test_login_cached_connection_password_extra.py``'s+``test_unencrypted_mode_reuses_cached_engine``.++``tests/database/test_sqlcipher_missing.py`` covers the import-level+RuntimeError / env-var gating of entering this mode; this file covers the+manager-level behavior once inside it. Each test builds its own manager+with the patch in effect (U3) and closes it in teardown.+"""++import sqlite3+import uuid++import pytest+from sqlalchemy import text++from local_deep_research.database.encrypted_db import DatabaseManager+++def unenc_manager(tmp_path, monkeypatch):+ """An UNENCRYPTED-mode DatabaseManager in a process that has+ sqlcipher3: the availability probe is patched to return False before+ ``__init__`` runs, so the constructor takes the documented fallback+ branch without needing the env-var workaround."""+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ monkeypatch.setattr(+ DatabaseManager,+ "_check_encryption_available",+ lambda self: False,+ )+ mgr = DatabaseManager()+ assert mgr.has_encryption is False, (+ "setup: the probe patch did not force unencrypted mode"+ )+ mgr.data_dir = tmp_path+ yield mgr+ mgr.close_all_databases()+++def test_unencrypted_mode_full_flow_is_plaintext_and_passwordless(+ unenc_manager, loguru_caplog_full+):+ """U1: end-to-end documented behavior of the fallback mode."""+ username = f"unenc_{uuid.uuid4().hex[:8]}"+ password = "UnencryptedModePw1!" # noqa: S105+ engine = unenc_manager.create_user_database(username, password)+ assert engine is not None+ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE gap_u_canary (id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO gap_u_canary (id, note) VALUES (1, :note)"),+ {"note": "gap-U"},+ )++ # THE at-rest risk, pinned: the file is readable with vanilla sqlite3,+ # no key, no pragmas.+ db_path = unenc_manager._get_user_db_path(username)+ plain = sqlite3.connect(str(db_path))+ try:+ rows = plain.execute(+ "SELECT note FROM gap_u_canary WHERE id = 1"+ ).fetchall()+ finally:+ plain.close()+ assert rows == [("gap-U",)], (+ "the unencrypted-mode database was not plaintext-readable with a "+ "vanilla sqlite3 connection"+ )++ # close disposes the engine; the file remains plaintext-readable.+ unenc_manager.close_user_database(username)+ plain = sqlite3.connect(str(db_path))+ try:+ assert plain.execute(+ "SELECT note FROM gap_u_canary WHERE id = 1"+ ).fetchall() == [("gap-U",)]+ finally:+ plain.close()++ # ANY password opens (documented: no credential exists to check).+ reopened = unenc_manager.open_user_database(username, password)+ assert reopened is not None+ assert (+ unenc_manager.open_user_database(username, "totally-different")+ is reopened+ )++ # The cache trusts directly in this mode (documented short-circuit).+ with unenc_manager._connections_lock:+ assert (+ unenc_manager._cached_engine_trusted(username, "any-string") is True+ )++ # get_session works and reads data.+ session = unenc_manager.get_session(username)+ assert session is not None+ with session:+ assert (+ session.execute(+ text("SELECT note FROM gap_u_canary WHERE id = 1")+ ).scalar()+ == "gap-U"+ )++ # change_password: documented False + warning+ # (encrypted_db.py::change_password).+ with loguru_caplog_full.at_level("DEBUG"):+ changed = unenc_manager.change_password(+ username,+ password,+ "AnotherPassword2!", # noqa: S105+ )+ assert changed is False, (+ "change_password must refuse to run without SQLCipher"+ )+ assert "Cannot change password" in loguru_caplog_full.text+++def test_check_database_integrity_reports_healthy_unencrypted_database(+ unenc_manager,+):+ """U2: a healthy database must pass its integrity check in EVERY mode.++ Unencrypted mode has no HMACs to verify, so the correct answer for a+ freshly created, readable, uncorrupted database is True -- otherwise+ every caller that gates on this method treats a perfectly healthy+ deployment as corrupt.+ """+ username = f"unencint_{uuid.uuid4().hex[:8]}"+ engine = unenc_manager.create_user_database(username, "UnencIntegrityPw1!") # noqa: S105+ with engine.begin() as conn:+ conn.execute(+ text("CREATE TABLE gap_u_int (id INTEGER PRIMARY KEY, note TEXT)")+ )+ conn.execute(text("INSERT INTO gap_u_int VALUES (1, 'gap-U2')"))+ assert unenc_manager.is_user_connected(username), (+ "setup: the engine must be warm for the accessor to inspect it"+ )++ assert unenc_manager.check_database_integrity(username) is Truediff --git a/tests/security/test_db_connection_username_trust.py b/tests/security/test_db_connection_username_trust.pynew file mode 100644index 0000000000..074e2cf434--- /dev/null+++ b/tests/security/test_db_connection_username_trust.py@@ -0,0 +1,305 @@+"""Username trust boundary at the DatabaseManager connection layer.++Incident context (PR #5596, cached-connection login auth bypass): the+connection cache (``connections`` / ``_password_verifiers``) is keyed by the+EXACT username string, and every credential decision funnels through+``_get_user_db_path`` -> ``get_user_database_filename``+(config/paths.py:135), which sha256-hashes the username into+``ldr_user_{hash16}.db`` and raises ValueError for empty/None usernames+(the #5481 defense-in-depth chokepoint).++That makes the username an attacker-controlled input that reaches THREE+security-relevant surfaces this file pins at the real-SQLCipher level:++* F1 traversal containment: even usernames containing path separators,+ absolute paths, "..", NUL bytes, glob/metacharacters or extreme lengths+ must resolve to a file INSIDE the data directory (the hash destroys all+ structure), and neither open nor create may touch anything outside it;+* F2 the empty/None chokepoint: ValueError BEFORE any filesystem effect;+* F3 confusable-username cache-key exactness: byte-distinct usernames are+ distinct cache keys AND distinct files -- "Alice"/"alice "/"ALICE"/NFD+ lookalikes get nothing from alice's warm engine and disturb nothing of+ hers (the cache is keyed by exact string, the filename by exact hash;+ any normalization regression on either surface would let a lookalike+ share alice's engine or file).++Complements round 1's test_db_connection_cold_open_artifacts.py (which+fingerprinted failed opens for an EXISTING user) and+test_login_cached_connection_password_lifecycle.py::test_multi_user_+isolation (which used ordinary distinct usernames, not adversarial ones).+"""++import hashlib+import re+import unicodedata+import uuid++import pytest+from sqlalchemy import text++from local_deep_research.database.encrypted_db import DatabaseManager++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")++# Every username here must be unusable as a path by the time it reaches the+# filesystem: the sha256[:16] hash keeps only [0-9a-f].+ADVERSARIAL_USERNAMES = [+ "../../etc/pwned",+ "/abs/path",+ "..",+ "a/../../b",+ "x\x00y",+ "Cafe\u0301-*?<>|",+ "u" * 1000,+]++HASHED_FILENAME_RE = re.compile(+ r"^(ldr_user_[0-9a-f]{16}\.db)(\.salt|-wal|-shm|-journal)?$"+)+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager whose data dir is a SUBDIRECTORY of tmp_path.++ Same self-contained pattern as the round-1 files (KDF knob included);+ putting data_dir inside tmp_path makes "outside the data dir" an+ observable, fingerprintable region for the containment assertions.+ """+ data_dir = tmp_path / "encrypted_databases"+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ mgr = DatabaseManager()+ mgr.data_dir = data_dir+ yield mgr+ mgr.close_all_databases()+++def _tree_fingerprint(root) -> dict:+ """relative-posix-path -> (size, sha256, mode) for every file under root."""+ fingerprint = {}+ for path in sorted(root.rglob("*")):+ if path.is_file():+ rel = path.relative_to(root).as_posix()+ fingerprint[rel] = (+ path.stat().st_size,+ hashlib.sha256(path.read_bytes()).hexdigest(),+ path.stat().st_mode,+ )+ return fingerprint+++def _outside(fingerprint: dict, data_rel: str) -> dict:+ """The subset of a tree fingerprint that lives outside the data dir."""+ prefix = data_rel + "/"+ return {k: v for k, v in fingerprint.items() if not k.startswith(prefix)}+++def test_traversal_usernames_resolve_inside_data_dir_and_stay_there(+ manager, tmp_path+):+ """F1: for each adversarial username, the resolved DB path sits DIRECTLY+ inside data_dir; an open (no such file) writes nothing anywhere; a+ create materializes only hashed, owner-only files inside data_dir and+ never touches the sentinel region outside it."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ outside_dir = tmp_path / "outside"+ outside_dir.mkdir()+ (outside_dir / "keep.txt").write_text("sentinel-outside")+ (tmp_path / "sentinel-root.txt").write_text("sentinel-root")+ data_rel = "encrypted_databases"++ outside_before = _outside(_tree_fingerprint(tmp_path), data_rel)+ data_before = {+ k: v+ for k, v in _tree_fingerprint(tmp_path).items()+ if k.startswith(data_rel + "/")+ }++ seen_filenames = set()+ for username in ADVERSARIAL_USERNAMES:+ # --- OPEN: no file exists for this hashed name; the attempt must+ # return None and write NOTHING (the salt lookup only reads).+ whole_before = _tree_fingerprint(tmp_path)+ assert manager.open_user_database(username, "SomePassword1!") is None, (+ f"open() unexpectedly succeeded for adversarial username "+ f"{username[:24]!r}"+ )+ assert _tree_fingerprint(tmp_path) == whole_before, (+ f"open() for {username[:24]!r} wrote to the filesystem"+ )++ # --- Path resolution: contained, directly inside data_dir.+ db_path = manager._get_user_db_path(username)+ assert db_path.resolve().parent == manager.data_dir.resolve(), (+ f"resolved path for {username[:24]!r} escaped the data dir: "+ f"{db_path}"+ )+ assert HASHED_FILENAME_RE.match(db_path.name), (+ f"filename for {username[:24]!r} is not a plain hashed name: "+ f"{db_path.name}"+ )+ seen_filenames.add(db_path.name)++ # --- CREATE: succeeds (containment, not rejection, is the design);+ # the engine is usable; new files are hashed names inside data_dir.+ engine = manager.create_user_database(username, "SomePassword1!")+ assert engine is not None+ with engine.connect() as conn:+ assert conn.execute(text("SELECT 1")).scalar() == 1+ assert db_path.exists()+ assert manager.data_dir.resolve() in db_path.resolve().parents++ manager.close_user_database(username)++ after = _tree_fingerprint(tmp_path)+ assert _outside(after, data_rel) == outside_before, (+ f"create() for {username[:24]!r} touched files outside the "+ "data directory"+ )+ new_inside = {+ k: v+ for k, v in after.items()+ if k.startswith(data_rel + "/") and k not in data_before+ }+ assert new_inside, (+ f"create() for {username[:24]!r} left no artifacts (test bug)"+ )+ for rel in new_inside:+ assert HASHED_FILENAME_RE.match(rel.split("/", 1)[1]), (+ f"artifact for {username[:24]!r} is not a hashed-user "+ f"filename: {rel}"+ )+ # owner-only, exactly like every legitimate user artifact+ assert (+ manager.data_dir / rel.split("/", 1)[1]+ ).stat().st_mode & 0o777 == 0o600+ data_before = {+ k: v for k, v in after.items() if k.startswith(data_rel + "/")+ }++ # Distinct usernames must not have collided onto one shared file.+ assert len(seen_filenames) == len(ADVERSARIAL_USERNAMES), (+ "two adversarial usernames hashed to the same DB filename"+ )+++def test_empty_and_none_usernames_fail_closed_before_filesystem(+ manager, tmp_path+):+ """F2: the sha256 chokepoint raises ValueError for empty/None usernames+ on both entry points, BEFORE any filesystem effect; and ``get_session``+ (a pure cache lookup) just returns None for such keys without raising+ and without side effects."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ (tmp_path / "sentinel-root.txt").write_text("sentinel-root")+ before = _tree_fingerprint(tmp_path)++ # The password is deliberately VALID, and the match= is pinned to the+ # username guard's own wording: both config/paths.py's+ # get_user_database_filename and _is_valid_encryption_key raise plain+ # ValueError, so a bare pytest.raises could not tell which guard+ # fired -- and a regression that started rejecting the password+ # instead would look identical.+ for bad in ("", None):+ with pytest.raises(ValueError, match="empty username"):+ manager.open_user_database(bad, "SomePassword1!")+ with pytest.raises(ValueError, match="empty username"):+ manager.create_user_database(bad, "SomePassword1!")++ assert _tree_fingerprint(tmp_path) == before, (+ "an empty/None username attempt touched the filesystem"+ )+ assert "" not in manager.connections+ assert "" not in manager._password_verifiers++ # get_session's actual contract (read from the code): a dict lookup+ # under _connections_lock -- no path resolution, no open, no raise.+ before_maps = (+ dict(manager.connections),+ dict(manager._password_verifiers),+ dict(manager._init_locks),+ )+ assert manager.get_session("") is None+ assert manager.get_session(None) is None+ assert _tree_fingerprint(tmp_path) == before+ assert (+ dict(manager.connections),+ dict(manager._password_verifiers),+ dict(manager._init_locks),+ ) == before_maps+++def test_confusable_usernames_get_nothing_and_disturb_nothing(manager):+ """F3: alice is warm; byte-distinct lookalikes of her name each fail,+ cache nothing, and leave her engine, verifier, files and readability+ untouched. Two genuinely distinct users coexist with distinct files and+ engines as the positive control."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ alice_password = "AliceExactPassword1!" # noqa: S105+ alice = "alice"+ alice_engine = manager.create_user_database(alice, alice_password)+ with alice_engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE gap_f_canary (id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO gap_f_canary (id, note) VALUES (1, :note)"),+ {"note": "gap-F"},+ )+ files_before = {p.name for p in manager.data_dir.iterdir()}++ nfd_lookalike = unicodedata.normalize("NFD", "a\u0301lice")+ assert nfd_lookalike != alice+ attempts = [+ ("Alice", alice_password),+ ("alice ", alice_password),+ ("ALICE", "attacker-plain-guess"),+ (nfd_lookalike, alice_password),+ ]+ for name, pw in attempts:+ assert manager.open_user_database(name, pw) is None, (+ f"confusable username {name!r} opened a database"+ )+ assert name not in manager.connections, (+ f"confusable username {name!r} got a cache entry"+ )+ assert name not in manager._password_verifiers, (+ f"confusable username {name!r} got a verifier entry"+ )++ # alice's world is exactly as it was.+ assert manager.connections[alice] is alice_engine+ assert manager._password_matches_cached(alice, alice_password) is True+ with alice_engine.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_f_canary WHERE id = 1")+ ).scalar()+ == "gap-F"+ )+ assert {p.name for p in manager.data_dir.iterdir()} == files_before, (+ "a confusable-username attempt created or removed files"+ )++ # Positive control: two distinct real users, distinct files + engines.+ bob = f"bob_{uuid.uuid4().hex[:8]}"+ carol = f"carol_{uuid.uuid4().hex[:8]}"+ engine_bob = manager.create_user_database(bob, "BobPassword2!")+ engine_carol = manager.create_user_database(carol, "CarolPassword3!")+ assert engine_bob is not engine_carol+ assert manager._get_user_db_path(bob) != manager._get_user_db_path(carol)+ assert manager.get_connected_usernames() >= {alice, bob, carol}diff --git a/tests/security/test_db_connection_verifier_memory.py b/tests/security/test_db_connection_verifier_memory.pynew file mode 100644index 0000000000..f6dd0ca71e--- /dev/null+++ b/tests/security/test_db_connection_verifier_memory.py@@ -0,0 +1,138 @@+"""Verifier memory hygiene: what the cache actually stores.++The password-verifier cache stores keyed HMAC digests instead of plaintext+passwords. These tests inspect that cache's tuple shape, absence of a known+password's byte fragments, and matching behavior at the real manager level.+They do not establish secrecy of a whole-process memory snapshot: usable+SQLAlchemy engine creators retain derived database keys. Nor does checking+for byte substrings prove that arbitrary reversible encodings are absent.++* AD1 ``_verifier_key`` is exactly 32 bytes; the stored ``(salt, digest)``+ entry has the expected lengths, contains no tested password fragment,+ and accepts the correct password while rejecting a wrong one.+* AD2 two live managers have different keys, and manager A's verifier+ tuple does not validate under manager B (one short manager-level+ companion to round-1 E's real-DB isolation and the primitive test's+ cross-key check).+"""++import uuid++import pytest+from sqlalchemy import text++from local_deep_research.database.encrypted_db import DatabaseManager++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager writing to an isolated data directory.++ Same self-contained pattern as the round-1..5 files, with the+ sanctioned test-mode KDF knob.+ """+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ mgr = DatabaseManager()+ mgr.data_dir = tmp_path+ yield mgr+ mgr.close_all_databases()+++def test_verifier_stores_no_password_material(manager):+ """AD1: check verifier lengths, known plaintext fragments and matching.++ The substring checks detect direct copies of the fixture password's+ bytes; they make no claim about whole-process memory or encodings.+ """+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ password = "XyZ__5000_End-of-Password" # noqa: S105+ username = f"vmem_{uuid.uuid4().hex[:8]}"+ engine = manager.create_user_database(username, password)+ with engine.begin() as conn:+ conn.execute(text("SELECT 1"))+ manager.close_user_database(username)+ manager.open_user_database(username, password)++ assert isinstance(manager._verifier_key, bytes)+ assert len(manager._verifier_key) == 32, (+ "the verifier key must be the full 32 random bytes generated in "+ "__init__"+ )++ entry = manager._password_verifiers[username]+ assert isinstance(entry, tuple) and len(entry) == 2+ salt, digest = entry+ assert isinstance(salt, bytes) and len(salt) == 16+ assert isinstance(digest, bytes) and len(digest) == 32++ # The password's bytes (whole and every substring window >= 4 bytes)+ # must appear in NEITHER half.+ pw_bytes = password.encode("utf-8")+ windows = {+ pw_bytes[i:j]+ for i in range(len(pw_bytes))+ for j in range(i + 4, len(pw_bytes) + 1)+ }+ for window in windows:+ assert window not in salt, (+ f"password fragment {window!r} found in the verifier salt"+ )+ assert window not in digest, (+ f"password fragment {window!r} found in the verifier digest"+ )+ # Whole-password absence (the headline property, also explicit):+ assert pw_bytes not in salt and pw_bytes not in digest++ # And the verifier still does its job for the real password.+ assert manager._password_matches_cached(username, password) is True+ assert (+ manager._password_matches_cached(username, "not-the-password") is False+ )+++def test_verifier_tuples_do_not_cross_validate_between_managers(+ tmp_path, monkeypatch+):+ """AD2: two live managers derive different keys; A's stored tuple,+ transplanted into B's map, does not validate under B (the digest is+ keyed by A's per-process random key)."""+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")++ manager_a = DatabaseManager()+ manager_b = DatabaseManager()+ if not manager_a.has_encryption:+ manager_a.close_all_databases()+ manager_b.close_all_databases()+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")+ try:+ manager_a.data_dir = tmp_path+ manager_b.data_dir = tmp_path+ assert manager_a._verifier_key != manager_b._verifier_key++ password = "CrossKeyCheckPw1!" # noqa: S105+ username = f"xkey_{uuid.uuid4().hex[:8]}"+ manager_a.create_user_database(username, password)+ a_entry = manager_a._password_verifiers[username]++ # Transplant A's tuple into B's map: it must NOT validate there.+ manager_b._password_verifiers[username] = a_entry+ with manager_b._connections_lock:+ matches = manager_b._verifier_matches(username, password)+ assert matches is False, (+ "a verifier recorded under manager A's key validated under "+ "manager B -- the digest is not actually keyed per process"+ )+ finally:+ manager_a.close_all_databases()+ manager_b.close_all_databases()diff --git a/tests/security/test_db_connection_wal_hygiene.py b/tests/security/test_db_connection_wal_hygiene.pynew file mode 100644index 0000000000..4ad51f43dd--- /dev/null+++ b/tests/security/test_db_connection_wal_hygiene.py@@ -0,0 +1,178 @@+"""WAL hygiene at close_user_database.++Incident context (PR #5596): at-rest security of these databases depends+on what sits next to them on disk. ``close_user_database`` runs+``_checkpoint_wal`` (``PRAGMA wal_checkpoint(TRUNCATE)``,+encrypted_db.py::_checkpoint_wal) before ``engine.dispose()``, so pending+writes are flushed into the main .db and the WAL sidecars can be cleaned+up rather than left holding data indefinitely. This file pins the+observable file-level contract:++* S1 while the engine is open and has written, WAL mode is actually on+ (``PRAGMA journal_mode`` == "wal") and the -wal/-shm sidecars EXIST;+ after ``close_user_database`` the sidecars are GONE (SQLite removes+ them on the final connection close once the WAL is checkpointed and+ empty -- pinned empirically); a reopen with the correct password reads+ the canary, proving the checkpoint lost nothing;+* S2 failed wrong-password opens never grow or create WAL sidecars:+ with the user WARM (sidecars present mid-open) and with the user+ CLOSED (sidecars absent), repeated wrong-password attempts leave the+ sidecar set and byte sizes exactly as they were.++Round 1's test_db_connection_cold_open_artifacts.py fingerprinted failed+opens against a CLOSED user for the whole file set; S2 differs by+targeting sidecar bytes in both the warm (sidecars-present) and closed+states, and S1 is a new property entirely.+"""++import uuid+from pathlib import Path++import pytest+from sqlalchemy import text++from local_deep_research.database.encrypted_db import DatabaseManager++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")++WRONG_ATTEMPTS = 3+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager writing to an isolated data directory.++ Same self-contained pattern as the round-1/2/3 files, with the+ sanctioned test-mode KDF knob.+ """+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ mgr = DatabaseManager()+ mgr.data_dir = tmp_path+ yield mgr+ mgr.close_all_databases()+++def _sidecar_fingerprint(db_path: Path) -> dict:+ """name -> size for the -wal/-shm sidecars of this database."""+ fingerprint = {}+ for suffix in ("-wal", "-shm"):+ sidecar = db_path.with_name(db_path.name + suffix)+ if sidecar.exists():+ fingerprint[sidecar.name] = sidecar.stat().st_size+ return fingerprint+++def _write_canary(engine, note: str) -> None:+ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE gap_s_canary (id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO gap_s_canary (id, note) VALUES (1, :note)"),+ {"note": note},+ )+++def test_close_checkpoints_wal_and_removes_sidecars(manager):+ """S1: WAL is genuinely on while open (journal_mode pragma + present+ sidecars); close removes the sidecars; reopen reads the canary."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"walhygiene_{uuid.uuid4().hex[:8]}"+ password = "WalHygienePassword1!" # noqa: S105+ engine = manager.create_user_database(username, password)+ _write_canary(engine, "gap-S1")++ # WAL mode is actually on for this connection.+ with engine.connect() as conn:+ mode = conn.execute(text("PRAGMA journal_mode")).scalar()+ assert str(mode).lower() == "wal", (+ f"expected WAL journal mode, got {mode!r} -- the rest of this "+ "test's assumptions about sidecars would not hold"+ )++ db_path = manager._get_user_db_path(username)+ mid_open = _sidecar_fingerprint(db_path)+ assert set(mid_open) == {"-wal", "-shm"} or set(mid_open), (+ "expected WAL sidecars to exist while the engine is open and has "+ f"written; found {mid_open}"+ )++ manager.close_user_database(username)++ after_close = _sidecar_fingerprint(db_path)+ assert after_close == {}, (+ "close_user_database left WAL sidecars behind "+ f"({after_close}) -- the TRUNCATE checkpoint + final-connection "+ "close should remove them"+ )++ # The checkpoint lost nothing: reopen reads the canary.+ reopened = manager.open_user_database(username, password)+ assert reopened is not None+ with reopened.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_s_canary WHERE id = 1")+ ).scalar()+ == "gap-S1"+ )+++def test_wrong_password_attempts_never_grow_sidecars(manager):+ """S2: wrong-password attempts (warm user with sidecars present, and+ closed user with sidecars absent) never create or enlarge -wal/-shm."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"walgrow_{uuid.uuid4().hex[:8]}"+ password = "WalGrowPassword1!" # noqa: S105+ engine = manager.create_user_database(username, password)+ _write_canary(engine, "gap-S2")+ db_path = manager._get_user_db_path(username)++ # Warm phase: sidecars are present mid-open; the wrong attempts must+ # not change their sizes (or the file set).+ warm_before = _sidecar_fingerprint(db_path)+ assert warm_before, "setup: sidecars expected while warm"+ for i in range(WRONG_ATTEMPTS):+ assert (+ manager.open_user_database(username, f"wal-grow-wrong-{i}") is None+ )+ assert _sidecar_fingerprint(db_path) == warm_before, (+ "a wrong-password attempt against a WARM user changed WAL "+ "sidecars (sizes or presence)"+ )++ # Closed phase: sidecars absent; the wrong attempts must not create any.+ manager.close_user_database(username)+ closed_before = _sidecar_fingerprint(db_path)+ assert closed_before == {}, "setup: sidecars expected gone after close"+ for i in range(WRONG_ATTEMPTS):+ assert (+ manager.open_user_database(username, f"wal-cold-wrong-{i}") is None+ )+ assert _sidecar_fingerprint(db_path) == closed_before, (+ "a wrong-password attempt against a CLOSED user created or "+ "changed WAL sidecars"+ )++ # And the legit user is unaffected afterwards.+ reopened = manager.open_user_database(username, password)+ assert reopened is not None+ with reopened.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_s_canary WHERE id = 1")+ ).scalar()+ == "gap-S2"+ )diff --git a/tests/security/test_db_connection_wal_rollback_attack.py b/tests/security/test_db_connection_wal_rollback_attack.pynew file mode 100644index 0000000000..366c64b466--- /dev/null+++ b/tests/security/test_db_connection_wal_rollback_attack.py@@ -0,0 +1,275 @@+"""WAL-deletion rollback attack against a warm per-user database.++Research context (sqlite.org/howtocorrupt.html, §"Things that can go+wrong": deleting the -wal file silently rolls the database back to the+state at the last checkpoint -- transactions committed after the+checkpoint are simply lost. For an app whose database rows carry+security state, rollback = silent revivification of revoked state.++Probed and pinned here against the real manager (HOLD on all three+fronts):++* AH1 mid-open WAL deletion SURVIVES: POSIX unlink semantics mean the+ engine's still-open fd keeps the WAL inode alive; the close-time+ ``PRAGMA wal_checkpoint(TRUNCATE)`` (encrypted_db.py::_checkpoint_wal)+ flushes those frames into the main .db through that fd BEFORE+ the final connection close deletes the (name-less) WAL. The post-+ checkpoint canary written into the deleted WAL is readable after+ reopen -- no rollback, no corruption.+* AH2 post-close there IS no rollback window: ``close_user_database``+ checkpoints and SQLite removes the -wal on the last close (round-4 S1+ property), so deleting "the -wal" after close is a no-op against a+ nonexistent file and the canary is durable.+* AH3 a FOREIGN -wal (captured live from a different user's database+ and planted before open) is refused at the credential plane -- the+ open returns None, nothing is cached, and none of the other user's+ data is ever served. That half is asserted normally.+* AH4 the availability half is an OPEN EXPOSURE, asserted as an+ ``xfail(strict)`` on the correct behavior: SQLite's WAL recovery+ WRITES into the target's main .db during that failed open, so removing+ the planted artifacts is not enough -- the account stays permanently+ unopenable and only a restore of the main .db recovers it. A planted+ sidecar must be a recoverable nuisance, not account destruction.+"""++import hashlib+import shutil+import tempfile+import uuid+from pathlib import Path++import pytest+from sqlalchemy import text++from local_deep_research.database.encrypted_db import DatabaseManager++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager writing to an isolated data directory.++ Same self-contained pattern as the round-1..6 files, with the+ sanctioned test-mode KDF knob.+ """+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ mgr = DatabaseManager()+ mgr.data_dir = tmp_path+ yield mgr+ mgr.close_all_databases()+++def _write_row(engine, table: str, value: str) -> None:+ with engine.begin() as conn:+ conn.execute(+ text(+ f"CREATE TABLE IF NOT EXISTS {table} " # noqa: S608+ "(id INTEGER PRIMARY KEY, v TEXT)"+ )+ )+ conn.execute(+ text(f"INSERT INTO {table} (v) VALUES (:v)"), # noqa: S608+ {"v": value},+ )+++def test_midopen_wal_deletion_does_not_lose_committed_rows(manager):+ """AH1 (HOLD): unlinking the -wal while the engine is open does NOT+ roll back the post-checkpoint transaction -- the close-time+ checkpoint runs through the still-open fd and flushes it first."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"ah1_{uuid.uuid4().hex[:8]}"+ password = "WalRollbackPw1!" # noqa: S105+ engine = manager.create_user_database(username, password)+ _write_row(engine, "gap_ah", "pre-checkpoint")+ manager.close_user_database(username) # checkpoint #1++ engine = manager.open_user_database(username, password)+ _write_row(engine, "gap_ah", "AH1-CANARY") # lives in the WAL only+ db_path = manager._get_user_db_path(username)+ wal = db_path.with_name(db_path.name + "-wal")+ assert wal.exists(), "setup: WAL expected while warm with fresh writes"++ wal.unlink() # THE ATTACK (sqlite.org/howtocorrupt rollback vector)++ # Close-time checkpoint through the still-open fd, then reopen.+ manager.close_user_database(username)+ reopened = manager.open_user_database(username, password)+ assert reopened is not None, "reopen failed after mid-open WAL deletion"+ with reopened.connect() as conn:+ rows = [+ row[0]+ for row in conn.execute(text("SELECT v FROM gap_ah")).fetchall()+ ]+ assert "pre-checkpoint" in rows+ assert "AH1-CANARY" in rows, (+ "the post-checkpoint transaction was lost to a WAL-deletion "+ "rollback -- the close-time checkpoint did not flush the "+ "still-open WAL inode"+ )+++def test_postclose_wal_deletion_window_is_empty(manager):+ """AH2 (HOLD): after a clean close there is no -wal to delete; the+ deletion is a no-op and the canary is durable across reopen."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"ah2_{uuid.uuid4().hex[:8]}"+ password = "PostClosePw1!" # noqa: S105+ engine = manager.create_user_database(username, password)+ _write_row(engine, "gap_ah", "AH2-CANARY")+ manager.close_user_database(username)++ db_path = manager._get_user_db_path(username)+ wal = db_path.with_name(db_path.name + "-wal")+ assert not wal.exists(), (+ "setup: close_user_database must have checkpointed and removed "+ "the WAL (round-4 S1 property)"+ )++ wal.unlink(missing_ok=True) # the "attack" hits nothing++ reopened = manager.open_user_database(username, password)+ assert reopened is not None+ with reopened.connect() as conn:+ rows = [+ row[0]+ for row in conn.execute(text("SELECT v FROM gap_ah")).fetchall()+ ]+ assert rows == ["AH2-CANARY"], "canary not durable across close/reopen"+++def _stage_foreign_wal_attack(manager, stash: Path):+ """Create a target user and a second user, capture the second user's+ LIVE -wal, close everything cleanly, back the target's main .db up,+ and plant the foreign -wal at the target's path.++ Returns ``(target, password, target_db, backup, fingerprint_before)``.+ """+ target = f"ah3t_{uuid.uuid4().hex[:8]}"+ other = f"ah3o_{uuid.uuid4().hex[:8]}"+ password = "ForeignWalPw1!" # noqa: S105+ engine_t = manager.create_user_database(target, password)+ _write_row(engine_t, "gap_ah", "target-secret")+ engine_o = manager.create_user_database(other, password)+ _write_row(engine_o, "gap_ah", "OTHER-USER-SECRET")++ other_db = manager._get_user_db_path(other)+ other_wal = other_db.with_name(other_db.name + "-wal")+ assert other_wal.exists(), "setup: other user's WAL expected mid-open"+ stolen = stash / "stolen.wal"+ shutil.copy2(other_wal, stolen)+ manager.close_all_databases()++ target_db = manager._get_user_db_path(target)+ backup = stash / "target.db.bak"+ shutil.copy2(target_db, backup)+ fingerprint_before = hashlib.sha256(target_db.read_bytes()).hexdigest()++ # THE ATTACK: plant the foreign WAL before the target's cold open.+ shutil.copy2(stolen, target_db.with_name(target_db.name + "-wal"))+ return target, password, target_db, backup, fingerprint_before+++def _clear_sidecars(target_db: Path) -> None:+ for suffix in ("-wal", "-shm"):+ target_db.with_name(target_db.name + suffix).unlink(missing_ok=True)+++def _read_rows(engine) -> list:+ with engine.connect() as conn:+ return [+ row[0]+ for row in conn.execute(text("SELECT v FROM gap_ah")).fetchall()+ ]+++def test_foreign_wal_planted_before_open_is_refused(manager):+ """AH3 (credential plane, holds today): a live -wal captured from+ ANOTHER user's database and planted at this user's path before a cold+ open is REFUSED -- the open returns None, nothing is cached, and none+ of the other user's data is ever served. Restoring the main .db from+ a backup brings the account back serving its OWN data."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ with tempfile.TemporaryDirectory() as stash:+ target, password, target_db, backup, _ = _stage_foreign_wal_attack(+ manager, Path(stash)+ )++ assert manager.open_user_database(target, password) is None, (+ "the target opened with a FOREIGN WAL planted -- frames keyed "+ "with another database's key were accepted"+ )+ assert target not in manager.connections+ assert target not in manager._password_verifiers++ # Restore the main .db from the pre-attack backup: full recovery,+ # and the target reads its OWN row, never the other user's.+ shutil.copy2(backup, target_db)+ _clear_sidecars(target_db)+ recovered = manager.open_user_database(target, password)+ assert recovered is not None, "restore-from-backup failed to reopen"+ rows = _read_rows(recovered)+ assert rows == ["target-secret"], f"cross-user data served: {rows}"+++ strict=True,+ reason=(+ "a refused open must not destroy the account: today SQLite's WAL "+ "recovery WRITES the foreign -wal's frames into the target's main "+ ".db during the failed open, so deleting the planted sidecars is "+ "not enough and only a restore of the main .db recovers the user. "+ "Fix: validate/quarantine unexpected -wal/-shm sidecars before "+ "handing the path to sqlcipher3, or open the target read-only for "+ "the credential probe (encrypted_db.py::open_user_database)."+ ),+)+def test_foreign_wal_planted_before_open_leaves_the_target_recoverable(+ manager,+):+ """AH4 (CORRECT behavior, currently unimplemented): after the planted+ foreign -wal is refused, the target's main .db must be untouched and+ removing the planted artifacts must be enough to restore service.++ Anyone able to drop a file next to the database can otherwise destroy+ an account outright -- the credential plane holds, but the data plane+ is gone without an out-of-band backup."""+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ with tempfile.TemporaryDirectory() as stash:+ target, password, target_db, _, fingerprint_before = (+ _stage_foreign_wal_attack(manager, Path(stash))+ )++ assert manager.open_user_database(target, password) is None, (+ "setup: the planted-WAL open must still be refused"+ )++ assert (+ hashlib.sha256(target_db.read_bytes()).hexdigest()+ == fingerprint_before+ ), "the refused open WROTE into the target's main .db"++ _clear_sidecars(target_db)+ recovered = manager.open_user_database(target, password)+ assert recovered is not None, (+ "removing the planted artifacts did not restore service -- the "+ "account is destroyed by a file an attacker merely dropped "+ "next to the database"+ )+ rows = _read_rows(recovered)+ assert rows == ["target-secret"], f"cross-user data served: {rows}"diff --git a/tests/security/test_db_connection_wrong_password_storm.py b/tests/security/test_db_connection_wrong_password_storm.pynew file mode 100644index 0000000000..b641dcd769--- /dev/null+++ b/tests/security/test_db_connection_wrong_password_storm.py@@ -0,0 +1,247 @@+"""Warm-cache wrong-password storm racing close_user_database + reopen.++Incident context (PR #5596): the cached-connection bypass existed because a+cache hit returned the engine with no credential check. The fix's moving+parts that THIS file stresses together, at real-SQLCipher level:++* the verifier's fail-closed liveness under a wrong-password storm (every+ attempt must fall through to a key-validating cold open and fail);+* the atomicity of engine+verifier publication (``_cache_connection``) and+ eviction (``close_user_database``) while another thread continuously+ closes and reopens with the CORRECT password;+* that a close storm never turns into an availability hole or a trust hole+ for the legitimate credential.++``test_login_cached_connection_password_extra.py`` pins the single-threaded+shapes (wrong password leaves the legit cache intact; concurrent FIRST open+with wrong/right). ``test_login_cached_connection_password.py`` pins the+warm-cache rejection itself. Neither drives the interleaving where the+cache is being torn down and rebuilt WHILE the attacker hammers it -- the+state in which a non-atomic publication or a verifier/engine mismatch+would be observable.++The invariant sampled throughout (under ``_connections_lock``, so each+snapshot is atomic): the set of usernames in ``connections`` always equals+the set in ``_password_verifiers``. A cached engine must never exist+without its verifier (fail-closed would save it, but it is still a broken+invariant) and a verifier must never outlive its engine (a stale verifier+is exactly what the change_password fix's eviction closes).+"""++import threading+import time+import uuid+import warnings++import pytest+from sqlalchemy import text++from local_deep_research.database.encrypted_db import DatabaseManager++# Module-level gate. Without a working SQLCipher build every test below+# is a no-op, and the dozens of in-body ``pytest.skip`` calls let a CI+# lane report this whole battery green having executed nothing. Skipping+# at import time makes the missing dependency one visible, uniform signal+# per module instead.+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")++# Bounded concurrency: 2 explicit threads, explicit iteration caps, one+# barrier, wall-clock budget comfortably under 30s.+HAMMER_ITERATIONS = 12+JOIN_TIMEOUT_S = 60+BARRIER_TIMEOUT_S = 30+# Backoff before the single retry of a LEGITIMATE operation. A transient+# SQLITE_BUSY under storm contention is not the property under test, and+# reddening on it turns a loaded runner into a security-gate failure. A+# repeatable refusal still fails on the retry. Never applied to the+# attacker's wrong-password opens -- those must fail first time, every time.+RETRY_BACKOFF_S = 0.1+++def _read_canary(engine):+ """Read the canary through ``engine``; return ``(note, error)``."""+ try:+ with engine.connect() as conn:+ return (+ conn.execute(+ text("SELECT note FROM gap_c_canary WHERE id = 1")+ ).scalar(),+ None,+ )+ except Exception as exc: # noqa: BLE001 - retried once, then reported+ return None, exc+++def manager(tmp_path, monkeypatch):+ """A DatabaseManager writing to an isolated data directory.++ Same self-contained pattern as the incident tests; KDF iterations are+ lowered via the sanctioned test-mode knob (see tests/conftest.py's+ ``app`` fixture) because each wrong-password attempt performs a full+ key-derivation + verify cycle.+ """+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ mgr = DatabaseManager()+ mgr.data_dir = tmp_path+ yield mgr+ mgr.close_all_databases()+++def test_wrong_password_storm_racing_close_and_reopen(manager):+ """T1 (attacker) hammers open(wrong) against whatever cache state exists;+ T2 (owner) hammers close_user_database + open(correct) + SELECT.++ Invariants:+ * T1 NEVER receives an engine -- not on the warm cache, not mid-close,+ not mid-reopen, not on the cold path.+ * T2's retry-once availability policy holds: a working engine whose+ SELECT reads the canary row is available within one retry (verifier+ liveness + atomic publication); a repeatable refusal still fails.+ * Every lock-consistent snapshot during the storm shows engines and+ verifiers exactly paired for this user.+ * Quiesced: closing leaves NEITHER an engine NOR a verifier; the next+ wrong open still fails and the next correct open still works.+ """+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")++ username = f"storm_{uuid.uuid4().hex[:8]}"+ password = "StormCorrectHorse1!" # noqa: S105+ engine = manager.create_user_database(username, password)+ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE gap_c_canary (id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO gap_c_canary (id, note) VALUES (1, :note)"),+ {"note": "gap-C"},+ )++ barrier = threading.Barrier(2)+ errors = {}+ attacker_violations = [] # every case where open(wrong) returned something+ owner_failures = [] # every case where open(correct) failed or mis-read+ pairing_violations = [] # engine/verifier snapshots that disagree+ owner_retries = [] # every iteration where the retry-once path fired++ def attacker():+ try:+ barrier.wait(timeout=BARRIER_TIMEOUT_S)+ for i in range(HAMMER_ITERATIONS):+ engine = manager.open_user_database(+ username, f"attacker-guess-{i}-wrong"+ )+ if engine is not None:+ attacker_violations.append(+ f"iteration {i}: open(wrong) returned {engine!r}"+ )+ except Exception as exc: # noqa: BLE001 - surfaced via `errors` below+ errors["attacker"] = exc++ def owner():+ try:+ barrier.wait(timeout=BARRIER_TIMEOUT_S)+ for i in range(HAMMER_ITERATIONS):+ engine = manager.open_user_database(username, password)+ if engine is None:+ # Retry once (see RETRY_BACKOFF_S).+ owner_retries.append(f"iteration {i}: open(correct) retry")+ time.sleep(RETRY_BACKOFF_S)+ engine = manager.open_user_database(username, password)+ if engine is None:+ owner_failures.append(+ f"iteration {i}: open(correct) returned None twice"+ )+ continue+ note, read_error = _read_canary(engine)+ if read_error is not None:+ # Retry once (see RETRY_BACKOFF_S).+ owner_retries.append(f"iteration {i}: canary read retry")+ time.sleep(RETRY_BACKOFF_S)+ note, read_error = _read_canary(engine)+ if read_error is not None:+ owner_failures.append(+ f"iteration {i}: SELECT on returned engine failed "+ f"twice: {read_error!r}"+ )+ elif note != "gap-C":+ owner_failures.append(+ f"iteration {i}: canary read {note!r}"+ )+ manager.close_user_database(username)+ # Lock-consistent snapshot: engines and verifiers must be+ # exactly paired at every observable instant.+ with manager._connections_lock:+ engines = set(manager.connections)+ verifiers = set(manager._password_verifiers)+ if engines != verifiers:+ pairing_violations.append(+ f"iteration {i}: engines={engines} "+ f"verifiers={verifiers}"+ )+ except Exception as exc: # noqa: BLE001 - surfaced via `errors` below+ errors["owner"] = exc++ threads = [+ threading.Thread(target=attacker, name="gap-c-attacker"),+ threading.Thread(target=owner, name="gap-c-owner"),+ ]+ for t in threads:+ t.start()+ for t in threads:+ t.join(timeout=JOIN_TIMEOUT_S)+ assert not any(t.is_alive() for t in threads), "storm deadlocked"+ assert not errors, f"a storm thread raised: {errors}"++ assert not attacker_violations, (+ "wrong-password opens succeeded during the close/reopen storm: "+ f"{attacker_violations}"+ )+ assert not owner_failures, (+ f"legitimate opens failed during the storm: {owner_failures}"+ )+ assert not pairing_violations, (+ f"engine/verifier pairing broke during the storm: {pairing_violations}"+ )++ # Attempt witness: a run where the owner never needed its retry proves+ # the retry-once policy was present but never exercised under this+ # storm -- not that it works. Record it as a warning that survives+ # into the run report rather than passing silently.+ if not owner_retries:+ warnings.warn(+ "wrong-password storm retry-once policy not witnessed: the "+ "owner thread never needed its single retry against the "+ f"attacker's {HAMMER_ITERATIONS} concurrent wrong-password "+ "attempts, so this run exercised no availability contention.",+ stacklevel=2,+ )++ # Quiesced state: the owner's last action was a close, so neither an+ # engine nor a verifier may remain (no verifier without an engine, no+ # engine without a verifier).+ with manager._connections_lock:+ assert username not in manager.connections, (+ "engine survived the final close"+ )+ assert username not in manager._password_verifiers, (+ "verifier survived the final close -- a stale verifier must "+ "never outlive the engine it described"+ )++ # Recovery canary: the storm left the manager healthy.+ assert manager.open_user_database(username, "still-wrong") is None+ recovered = manager.open_user_database(username, password)+ assert recovered is not None+ with recovered.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM gap_c_canary WHERE id = 1")+ ).scalar()+ == "gap-C"+ )+ assert manager._password_matches_cached(username, password) is Truediff --git a/tests/security/test_sqlcipher_rekey_key_not_leaked.py b/tests/security/test_sqlcipher_rekey_key_not_leaked.pynew file mode 100644index 0000000000..4c82af3531--- /dev/null+++ b/tests/security/test_sqlcipher_rekey_key_not_leaked.py@@ -0,0 +1,222 @@+"""A failed ``PRAGMA rekey`` must not carry the derived master key outwards.++``set_sqlcipher_rekey`` builds ``PRAGMA rekey = "x'<derived key hex>'"`` and+runs it through SQLAlchemy. SQLAlchemy wraps any DBAPI failure in a+``StatementError``, whose ``_sql_message`` appends ``"[SQL: %s]" %+self.statement`` -- so the raw error's ``str()``, its ``.statement`` attribute+and its rendered traceback each contain the derived SQLCipher master key in+hex. The only caller, ``DatabaseManager.change_password``, logs+``redact_secrets(str(e), old_password, new_password)``, and ``redact_secrets``+is a literal replace over just those two plaintext passwords -- it does not+know the key. Without scrubbing at the raise site, a failing rekey puts the+key that decrypts the user's whole database into the application log.++Subject under test is the real ``set_sqlcipher_rekey`` with a real derived key+and (in AA1) real SQLAlchemy error wrapping over real sqlite3; only the+connection's failure is arranged.++Revert that must turn these red: in+``src/local_deep_research/database/sqlcipher_utils.py::set_sqlcipher_rekey``,+drop the ``failure`` capture and the ``raise SQLCipherRekeyError(...) from+None`` and restore the bare++ try:+ cursor_or_conn.execute(text(safe_sql))+ except TypeError:+ cursor_or_conn.execute(safe_sql)++AA1 and AA2 then fail on ``str(exc)`` (and AA1 also on ``.statement``).+AA0 is the positive control: it asserts the arranged collaborator error+really does carry the key, so AA1/AA2 cannot pass by testing nothing.+"""++import sqlite3+import traceback++import pytest+from sqlalchemy import create_engine, event, exc as sa_exc, text+from sqlalchemy.sql.elements import TextClause++from local_deep_research.database.sqlcipher_utils import (+ SQLCipherRekeyError,+ get_key_from_password,+ set_sqlcipher_rekey,+)++NEW_PASSWORD = "rekey-target-password" # noqa: S105 — test fixture value++[email protected](autouse=True)+def fast_kdf(monkeypatch):+ """Sanctioned test-mode KDF knob, as in the rest of this battery.++ Key derivation must still be the real one (the hex we assert on is the+ real derived key), just cheap.+ """+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+++def key_hex(fast_kdf):+ """The hex the production code will embed in the rekey statement.++ Depends on ``fast_kdf`` explicitly rather than relying on autouse+ ordering: derived at a different iteration count this would not be the+ hex the subject embeds, and every assertion would pass vacuously.++ ``db_path=None`` selects the legacy salt, so this is reproducible without+ a database file -- and it is derived by the same function the subject+ calls, not hard-coded.+ """+ return get_key_from_password(+ NEW_PASSWORD, db_path=None+ ).hex() # gitleaks:allow+++def _leak_surfaces(exception):+ """Every surface of the propagated exception itself: its string forms,+ ``.statement``, rendered traceback and chained-exception attributes.++ Scoped to the exception object -- it does NOT cover frame locals (e.g.+ ``safe_sql``, ``failure``) reachable from ``exception.__traceback__``,+ which a loguru sink with ``diagnose=True`` would render. That surface+ is outside this test; the sole caller logs an f-string with no+ traceback, so it is unreachable today, but a future+ ``logger.exception()`` on this path would need its own check.+ """+ return {+ "str(exc)": str(exception),+ "repr(exc)": repr(exception),+ "statement": str(getattr(exception, "statement", "")),+ "traceback": "".join(+ traceback.format_exception(+ type(exception), exception, exception.__traceback__+ )+ ),+ "__cause__": ""+ if exception.__cause__ is None+ else str(exception.__cause__),+ "__context__": (+ "" if exception.__context__ is None else str(exception.__context__)+ ),+ }+++def _assert_no_key(exception, key_hex):+ leaked = {+ name: value+ for name, value in _leak_surfaces(exception).items()+ if key_hex in value+ }+ assert not leaked, (+ f"derived SQLCipher key reachable from the propagated exception via "+ f"{sorted(leaked)}"+ )+++def _failing_sqlalchemy_connection():+ """A real SQLAlchemy connection whose statement execution fails.++ The ``do_execute`` hook raises a real ``sqlite3.OperationalError``, so+ SQLAlchemy performs its own real wrapping into a ``StatementError``+ subclass with ``.statement`` populated -- the exact shape a live+ SQLCipher rekey failure produces.+ """+ engine = create_engine("sqlite://")++ @event.listens_for(engine, "do_execute")+ def _raise(cursor, statement, parameters, context): # noqa: ARG001+ raise sqlite3.OperationalError("file is not a database")++ return engine+++def test_aa0_control_sqlalchemy_wrapping_does_embed_the_key(key_hex):+ """AA0 (positive control): the collaborator error really carries the key.++ Executes the same statement shape directly, without the subject, and+ asserts SQLAlchemy's wrapped error exposes the hex on both ``str()`` and+ ``.statement``. If this ever stops holding, AA1/AA2 have become vacuous+ and must be re-derived rather than trusted.+ """+ engine = _failing_sqlalchemy_connection()+ statement = f"PRAGMA rekey = \"x'{key_hex}'\"" # gitleaks:allow++ with engine.connect() as conn:+ with pytest.raises(sa_exc.StatementError) as caught:+ conn.execute(text(statement))++ raw = caught.value+ assert key_hex in str(raw), (+ "control: SQLAlchemy no longer inlines [SQL: ...]"+ )+ assert key_hex in str(raw.statement), "control: .statement no longer set"+++def test_aa1_failed_rekey_via_sqlalchemy_does_not_expose_key(key_hex):+ """AA1: real SQLAlchemy wrapping -- no surface of the raised error+ references the derived key, and the chain is cut."""+ engine = _failing_sqlalchemy_connection()++ with engine.connect() as conn:+ with pytest.raises(SQLCipherRekeyError) as caught:+ set_sqlcipher_rekey(conn, NEW_PASSWORD, db_path=None)++ raised = caught.value+ _assert_no_key(raised, key_hex)+ assert raised.__cause__ is None+ assert raised.__context__ is None, (+ "implicit context still references the StatementError carrying the key"+ )+ assert "OperationalError" in str(raised), (+ "the failing error's type is the one diagnostic worth keeping"+ )+++def test_aa2_failed_rekey_on_raw_connection_does_not_expose_key(key_hex):+ """AA2: the raw-SQLCipher-connection branch (the ``except TypeError``+ fallback) is scrubbed too.++ The stub rejects a ``TextClause`` the way a raw sqlcipher3 connection+ does, then fails on the plain string -- and the failure it raises is a+ ``StatementError`` carrying the statement, so the key is genuinely+ present in the collaborator error this branch sees.+ """+ statements = []++ class RawConnection:+ def execute(self, statement):+ if isinstance(statement, TextClause):+ raise TypeError("raw connection expects str, not TextClause")+ statements.append(statement)+ raise sa_exc.StatementError(+ message="unable to open database file",+ statement=statement,+ params=None,+ orig=sqlite3.OperationalError("unable to open database file"),+ )++ with pytest.raises(SQLCipherRekeyError) as caught:+ set_sqlcipher_rekey(RawConnection(), NEW_PASSWORD, db_path=None)++ assert statements, "the raw branch was never reached"+ assert key_hex in statements[0], (+ "control: the statement handed to the raw connection must contain the key"+ )+ _assert_no_key(caught.value, key_hex)+ assert caught.value.__context__ is None+++def test_aa3_successful_rekey_still_executes_the_pragma(key_hex):+ """AA3: the scrubbing wrapper did not change the success path -- the+ statement still reaches the connection, unchanged, and nothing raises."""+ executed = []++ class RecordingConnection:+ def execute(self, statement):+ executed.append(str(statement))++ set_sqlcipher_rekey(RecordingConnection(), NEW_PASSWORD, db_path=None)++ assert len(executed) == 1+ assert executed[0] == f"PRAGMA rekey = \"x'{key_hex}'\"" # gitleaks:allow