Skip to content

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

fix(db): detect index corruption in unencrypted integrity checks (#6409)

LearningCircuit0a5cfcd74e32
diff --git a/changelog.d/6409.bugfix.md b/changelog.d/6409.bugfix.md
new file mode 100644
index 0000000000..cf6bab6ee3
--- /dev/null
+++ b/changelog.d/6409.bugfix.md
@@ -0,0 +1 @@
+Unencrypted database integrity checks now detect mismatches between table data and indexes.
diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.py
index 40bcdf3929..27ebab78b7 100644
--- a/src/local_deep_research/database/encrypted_db.py
+++ b/src/local_deep_research/database/encrypted_db.py
@@ -1567,7 +1567,12 @@ class DatabaseManager:
# 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."""
+ """Check database structure and encrypted page authentication.
+
+ Plain SQLite uses the full integrity check to verify that indexes
+ match table contents. SQLCipher retains the quick structural check
+ and its independent page-HMAC verification.
+ """
with self._connections_lock:
if username not in self.connections:
return False
@@ -1575,8 +1580,21 @@ class DatabaseManager:
try:
with engine.connect() as conn:
- # Quick integrity check
- result = conn.execute(text("PRAGMA quick_check"))
+ # quick_check omits index/table consistency and UNIQUE
+ # checks. Check those too for the unencrypted fallback: the
+ # page HMAC that SQLCipher verifies below catches page-level
+ # bit damage, but not a cryptographically valid page whose
+ # index and table contents have become logically
+ # inconsistent with each other — quick_check's cheaper
+ # structural check misses that class regardless of
+ # encryption, so the SQLCipher path deliberately keeps it
+ # rather than paying for the full scan on every check.
+ integrity_pragma = (
+ "PRAGMA quick_check"
+ if self.has_encryption
+ else "PRAGMA integrity_check"
+ )
+ result = conn.execute(text(integrity_pragma))
if result.fetchone()[0] != "ok":
return False
diff --git a/src/local_deep_research/web/dependencies/rate_limit.py b/src/local_deep_research/web/dependencies/rate_limit.py
index 797b4bbe23..1085de151d 100644
--- a/src/local_deep_research/web/dependencies/rate_limit.py
+++ b/src/local_deep_research/web/dependencies/rate_limit.py
@@ -323,6 +323,13 @@ PASSWORD_CHANGE_RATE_LIMIT = _config.get(
VALIDATE_PASSWORD_RATE_LIMIT = _config.get(
"rate_limit_validate_password", "30 per minute"
)
+# /auth/integrity-check runs a full SQLite `integrity_check` scan (not the
+# cheap `quick_check`), so a tight per-route bucket keeps a signed-in user
+# from re-triggering the expensive path back-to-back; it otherwise falls
+# through to the global default (5000/hour).
+INTEGRITY_CHECK_RATE_LIMIT = _config.get(
+ "rate_limit_integrity_check", "10 per minute"
+)
# Settings-mutation endpoints (save/update/delete/import/reset/fix).
SETTINGS_RATE_LIMIT = _config.get("rate_limit_settings", "30 per minute")
diff --git a/src/local_deep_research/web/routers/auth.py b/src/local_deep_research/web/routers/auth.py
index c9416faa8f..54fcf0d316 100644
--- a/src/local_deep_research/web/routers/auth.py
+++ b/src/local_deep_research/web/routers/auth.py
@@ -9,6 +9,7 @@ from fastapi.responses import JSONResponse, RedirectResponse
from ..dependencies.auth import clear_session_if_unrecoverable, require_auth
from ..dependencies.flash import flash
from ..dependencies.rate_limit import (
+ INTEGRITY_CHECK_RATE_LIMIT,
LOGIN_RATE_LIMIT,
PASSWORD_CHANGE_RATE_LIMIT,
REGISTRATION_RATE_LIMIT,
@@ -1252,6 +1253,7 @@ def change_password(
@router.get("/integrity-check")
[email protected](INTEGRITY_CHECK_RATE_LIMIT)
def integrity_check(
request: Request, username: Annotated[str, Depends(require_auth)]
):
@@ -1259,7 +1261,10 @@ def integrity_check(
Check database integrity for current user.
Uses Depends(require_auth) for the auth gate — single source of
- truth, consistent with every other authed endpoint.
+ truth, consistent with every other authed endpoint. Rate-limited
+ (unlike a plain lookup, this runs SQLite's full `integrity_check`
+ scan, not the cheap `quick_check`) so a signed-in user can't
+ re-trigger the expensive path back-to-back.
"""
is_valid = db_manager.check_database_integrity(username)
diff --git a/tests/database/test_integrity_check_corruption.py b/tests/database/test_integrity_check_corruption.py
new file mode 100644
index 0000000000..7cb72084c8
--- /dev/null
+++ b/tests/database/test_integrity_check_corruption.py
@@ -0,0 +1,176 @@
+"""Real damaged databases must not pass the user's integrity check."""
+
+from contextlib import ExitStack
+from unittest.mock import patch
+
+import pytest
+from sqlalchemy import text
+
+from local_deep_research.database import encrypted_db
+
+
+PASSWORD = "IntegrityTestPassword123!"
+USERNAME = "integrity_corruption"
+
+
+def database_manager(request, tmp_path, monkeypatch):
+ """Use real database creation, choosing fallback unless parametrized."""
+ encrypted = getattr(request, "param", "fallback") == "sqlcipher"
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+ monkeypatch.setenv("LDR_BOOTSTRAP_ALLOW_UNENCRYPTED", "true")
+ monkeypatch.setenv("LDR_DB_KDF_ITERATIONS", "1000")
+ if encrypted:
+ try:
+ encrypted_db.get_sqlcipher_module()
+ except ImportError:
+ pytest.skip("SQLCipher is not installed")
+
+ with ExitStack() as stack:
+ stack.enter_context(
+ patch.object(
+ encrypted_db, "get_data_directory", return_value=tmp_path
+ )
+ )
+ if not encrypted:
+ stack.enter_context(
+ patch.object(
+ encrypted_db,
+ "get_sqlcipher_module",
+ side_effect=ImportError("Test the unencrypted fallback"),
+ )
+ )
+ manager = encrypted_db.DatabaseManager()
+ assert manager.has_encryption is encrypted
+ try:
+ yield manager
+ finally:
+ manager.close_all_databases()
+
+
+def _flush_and_dispose(engine):
+ """Put committed pages on disk and discard cached copies before damage."""
+ with engine.connect() as conn:
+ checkpoint = conn.exec_driver_sql(
+ "PRAGMA wal_checkpoint(TRUNCATE)"
+ ).fetchone()
+ assert checkpoint[0] == 0
+ engine.dispose()
+
+
+def test_fallback_rejects_indexed_value_corruption(database_manager):
+ """A valid record with a stale index passes quick_check, but is corrupt."""
+ engine = database_manager.create_user_database(USERNAME, PASSWORD)
+ marker = b"integrity_indexed_payload"
+ with engine.begin() as conn:
+ conn.exec_driver_sql(
+ "CREATE TABLE integrity_payload (id INTEGER PRIMARY KEY, body TEXT)"
+ )
+ conn.exec_driver_sql(
+ "CREATE INDEX integrity_body_idx ON integrity_payload(body)"
+ )
+ conn.execute(
+ text("INSERT INTO integrity_payload(body) VALUES(:body)"),
+ {"body": marker.decode()},
+ )
+ page_size = int(conn.exec_driver_sql("PRAGMA page_size").scalar())
+ root_page = conn.exec_driver_sql(
+ "SELECT rootpage FROM sqlite_master WHERE name='integrity_payload'"
+ ).scalar()
+ _flush_and_dispose(engine)
+
+ path = database_manager._get_user_db_path(USERNAME)
+ damaged = bytearray(path.read_bytes())
+ page_start = (root_page - 1) * page_size
+ offset = damaged.index(marker, page_start, page_start + page_size)
+ # Change only the table's text value; its record size and index stay intact.
+ damaged[offset] = ord("x")
+ path.write_bytes(damaged)
+
+ with engine.connect() as conn:
+ assert conn.exec_driver_sql("PRAGMA quick_check").fetchall() == [
+ ("ok",)
+ ]
+ errors = conn.exec_driver_sql("PRAGMA integrity_check").fetchall()
+ assert any(
+ "missing from index integrity_body_idx" in r[0] for r in errors
+ )
+ assert (
+ conn.exec_driver_sql(
+ "SELECT body FROM integrity_payload NOT INDEXED"
+ ).scalar()
+ == "x" + marker.decode()[1:]
+ )
+
+ engine.dispose()
+ assert database_manager.check_database_integrity(USERNAME) is False
+
+
+# Regression guards, not falsifiers: both pragmas already reject all three
+# cases identically before and after this change; the falsifier is
+# test_fallback_rejects_indexed_value_corruption above.
[email protected]("damage", ["table_page", "file_header", "truncate"])
+def test_fallback_rejects_physical_corruption(database_manager, damage):
+ engine = database_manager.create_user_database(USERNAME, PASSWORD)
+ with engine.begin() as conn:
+ conn.exec_driver_sql("CREATE TABLE integrity_payload (body BLOB)")
+ conn.exec_driver_sql(
+ "INSERT INTO integrity_payload VALUES(zeroblob(16000))"
+ )
+ page_size = int(conn.exec_driver_sql("PRAGMA page_size").scalar())
+ root_page = conn.exec_driver_sql(
+ "SELECT rootpage FROM sqlite_master WHERE name='integrity_payload'"
+ ).scalar()
+ _flush_and_dispose(engine)
+
+ path = database_manager._get_user_db_path(USERNAME)
+ damaged = bytearray(path.read_bytes())
+ if damage == "truncate":
+ damaged = damaged[: page_size + 73]
+ else:
+ # Offset 100 is the first page's b-tree header, after SQLite's header.
+ offset = 100 if damage == "file_header" else (root_page - 1) * page_size
+ damaged[offset] ^= 0xFF
+ path.write_bytes(damaged)
+
+ assert database_manager.check_database_integrity(USERNAME) is False
+
+
[email protected]("database_manager", ["sqlcipher"], indirect=True)
+def test_encrypted_rejects_hmac_failure_on_unused_page(database_manager):
+ """Freelist leaf contents are skipped by quick_check, but HMAC covers them."""
+ engine = database_manager.create_user_database(USERNAME, PASSWORD)
+ with engine.begin() as conn:
+ conn.exec_driver_sql("PRAGMA secure_delete=OFF")
+ conn.exec_driver_sql("CREATE TABLE integrity_free (body BLOB)")
+ page_size = int(conn.exec_driver_sql("PRAGMA page_size").scalar())
+ for _ in range(20):
+ conn.execute(
+ text("INSERT INTO integrity_free VALUES(zeroblob(:size))"),
+ {"size": page_size * 3},
+ )
+ last_page = int(conn.exec_driver_sql("PRAGMA page_count").scalar())
+ conn.exec_driver_sql("DROP TABLE integrity_free")
+ with engine.connect() as conn:
+ assert int(conn.exec_driver_sql("PRAGMA freelist_count").scalar()) > 10
+ assert (
+ conn.exec_driver_sql("PRAGMA cipher_integrity_check").fetchall()
+ == []
+ )
+ _flush_and_dispose(engine)
+
+ # Dropping the large table leaves its final overflow page on the freelist.
+ path = database_manager._get_user_db_path(USERNAME)
+ damaged = bytearray(path.read_bytes())
+ damaged[(last_page - 1) * page_size + 100] ^= 0xFF
+ path.write_bytes(damaged)
+
+ with engine.connect() as conn:
+ assert conn.exec_driver_sql("PRAGMA quick_check").fetchall() == [
+ ("ok",)
+ ]
+ assert conn.exec_driver_sql("PRAGMA cipher_integrity_check").fetchall()
+
+ # The production check must detect damage on its own fresh connection.
+ engine.dispose()
+ assert database_manager.check_database_integrity(USERNAME) is False
diff --git a/tests/security/test_injection_and_template_safety.py b/tests/security/test_injection_and_template_safety.py
index 5c5b88eecd..21cc6359d0 100644
--- a/tests/security/test_injection_and_template_safety.py
+++ b/tests/security/test_injection_and_template_safety.py
@@ -166,6 +166,10 @@ REVIEWED_RAW_SQL_MODULES = {
# PRAGMA key/rekey from a hex digest; PRAGMAs from allow-listed
# settings. PRAGMA takes no bind parameters.
"database/sqlcipher_utils.py",
+ # check_database_integrity picks one of two literal PRAGMAs
+ # (quick_check / integrity_check) on has_encryption; no request value
+ # reaches the string. PRAGMA takes no bind parameters.
+ "database/encrypted_db.py",
# PRAGMA user_version from a module-level int constant
"journal_quality/db.py",
# Migrations: table names are literals inside the migration itself.
diff --git a/tests/web/routers/test_auth_rate_limits.py b/tests/web/routers/test_auth_rate_limits.py
index e6686a874a..37aebce82e 100644
--- a/tests/web/routers/test_auth_rate_limits.py
+++ b/tests/web/routers/test_auth_rate_limits.py
@@ -13,7 +13,13 @@ branch's setup (``web/dependencies/rate_limit.py`` + ``routers/auth.py``):
- ``/auth/change-password`` has its own bucket, independent of login in
both directions, and 429s after its threshold;
- buckets are keyed per client IP: exhausting IP A leaves IP B usable
- and IP A stays blocked.
+ and IP A stays blocked;
+- ``/auth/integrity-check`` carries its own registered limit (introspected
+ from ``limiter._route_limits``, mirroring
+ ``tests/web/routers/test_notes_rate_limit_keys.py``, rather than driven
+ behaviorally like the buckets above — it needs real SQLCipher/fallback
+ setup to hit 200, which the plain 400-validation trick the other buckets
+ use doesn't have an equivalent for).
Enforcement notes:
- ``limiter.enabled`` is resolved from env at import time (CI disables
@@ -30,12 +36,14 @@ Enforcement notes:
tests, which use the ``authenticated_client`` fixture.
"""
+import importlib
import uuid
import pytest
from fastapi.testclient import TestClient
from local_deep_research.web.dependencies.rate_limit import (
+ INTEGRITY_CHECK_RATE_LIMIT,
LOGIN_RATE_LIMIT,
PASSWORD_CHANGE_RATE_LIMIT,
REGISTRATION_RATE_LIMIT,
@@ -404,3 +412,45 @@ class TestWrongCredentialsUnderALiveLimiter:
f"attempt {LOGIN_ATTEMPTS + 1} must be rate-limited, got "
f"{resp.status_code}"
)
+
+
+AUTH_MODULE = "local_deep_research.web.routers.auth"
+
+
+class TestIntegrityCheckRateLimit:
+ """``/auth/integrity-check`` must carry its own registered limit.
+
+ Unlike login/register/change-password/validate-password, this route
+ previously had no ``@limiter.limit`` decorator at all and fell through
+ to the global default (``DEFAULT_RATE_LIMIT``, 5000 per hour / 50000
+ per day) — no threshold small enough to drive behaviorally in a test.
+ So, like ``tests/web/routers/test_notes_rate_limit_keys.py``, this
+ introspects the real registered ``slowapi.wrappers.Limit`` off the
+ live ``limiter`` object instead of sending requests.
+
+ Revert this test catches: remove
+ ``@limiter.limit(INTEGRITY_CHECK_RATE_LIMIT)`` from
+ ``integrity_check`` in ``web/routers/auth.py`` — the qualified name
+ then has no entry in ``limiter._route_limits`` and the first
+ assertion below fails.
+ """
+
+ def test_integrity_check_has_a_registered_limit(self):
+ auth_mod = importlib.import_module(AUTH_MODULE)
+ qualified = f"{AUTH_MODULE}.integrity_check"
+ limits = auth_mod.limiter._route_limits.get(qualified, [])
+ assert limits, (
+ f"{qualified} has no registered rate limit — "
+ "/auth/integrity-check must not fall through to the global "
+ "default"
+ )
+
+ expected_amount = _first_amount(INTEGRITY_CHECK_RATE_LIMIT)
+ seen = {
+ (lim.limit.amount, lim.limit.GRANULARITY.name) for lim in limits
+ }
+ assert all(amount == expected_amount for amount, _ in seen), (
+ f"expected {expected_amount} per window from "
+ f"INTEGRITY_CHECK_RATE_LIMIT={INTEGRITY_CHECK_RATE_LIMIT!r}, "
+ f"got {seen}"
+ )
diff --git a/tests/web/test_rate_limit_census.py b/tests/web/test_rate_limit_census.py
index 64def76dcc..e5038082be 100644
--- a/tests/web/test_rate_limit_census.py
+++ b/tests/web/test_rate_limit_census.py
@@ -143,6 +143,9 @@ UNIFIED = Bucket("unified_search", "_user_key", None, ("60 per 1 minute",))
AUTH_LOGIN = Bucket(PER_URL, "_get_client_ip", None, ("5 per 15 minute",))
AUTH_REGISTER = Bucket(PER_URL, "_get_client_ip", None, ("3 per 1 hour",))
AUTH_VALIDATE = Bucket(PER_URL, "_get_client_ip", None, ("30 per 1 minute",))
+# /auth/integrity-check runs SQLite's full integrity_check scan, so it gets
+# its own tight per-IP budget rather than sharing a brute-force bucket.
+AUTH_INTEGRITY = Bucket(PER_URL, "_get_client_ip", None, ("10 per 1 minute",))
CHAT_10 = Bucket(PER_URL, "_chat_user_key", None, ("10 per 1 minute",))
CHAT_20 = Bucket(PER_URL, "_chat_user_key", None, ("20 per 1 minute",))
CHAT_30 = Bucket(PER_URL, "_chat_user_key", None, ("30 per 1 minute",))
@@ -164,6 +167,7 @@ CENSUS = {
"auth.change_password": (AUTH_LOGIN,),
"auth.register": (AUTH_REGISTER,),
"auth.validate_password": (AUTH_VALIDATE,),
+ "auth.integrity_check": (AUTH_INTEGRITY,),
# --- benchmark: both start endpoints in ONE bucket -------------------
"benchmark.start_benchmark": (BENCH_START,),
"benchmark.start_benchmark_simple": (BENCH_START,),
@@ -907,6 +911,7 @@ class TestAuthBucketsHaveASingleOccupant:
("auth.register", "/auth/register"),
("auth.change_password", "/auth/change-password"),
("auth.validate_password", "/auth/validate-password"),
+ ("auth.integrity_check", "/auth/integrity-check"),
],
)
def test_auth_limit_sits_alone_on_one_static_path(self, endpoint, path):