~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
fix(db): keep the rekey key out of the raising frame and keep the DBAPI message (#6449)
Lukas Buck8b177f967187
diff --git a/changelog.d/6444.security.md b/changelog.d/6444.security.mdnew file mode 100644index 0000000000..c7d39f8554--- /dev/null+++ b/changelog.d/6444.security.md@@ -0,0 +1,22 @@+A failed password change can no longer put the derived SQLCipher master key+into the application log, on any of its surfaces. `set_sqlcipher_rekey` builds+`PRAGMA rekey = "x'<key hex>'"`, and SQLAlchemy embeds the statement it failed+on in the error it raises, so the key reached the change-password log through+the exception's own message. That was fixed in #5654 by raising a key-free+error instead — a scrub the fragment for that change did not record, and the+more security-relevant of the two fixes it carried. Two residuals in the same+few lines are closed now: the derived key and the rekey statement stayed bound+in the raising frame, which sits in the propagated exception's traceback and+would be printed by a log sink rendering frame locals (loguru `diagnose=True`,+debug-only since #4185); and the failing exception itself was held there,+pinning its own traceback through the SQLAlchemy frames that carry the+statement. The key material is dropped before the new error is raised, and+only the failure's type name and its scrubbed message are kept.++The same change gives the change-password log back a diagnostic it had lost.+Every rekey failure was reduced to `PRAGMA rekey failed (<ExceptionType>)`,+which is right where the message embeds the statement — but on a raw+`sqlcipher3` connection it never did, so `database is locked`, `file is not a+database` and a disk error became one indistinguishable line. The message now+comes through scrubbed of the key, and is dropped entirely if any fragment of+the key survives scrubbing, so a truncated rendering cannot leak part of it.diff --git a/src/local_deep_research/database/sqlcipher_utils.py b/src/local_deep_research/database/sqlcipher_utils.pyindex b237461661..93015aa6eb 100644--- a/src/local_deep_research/database/sqlcipher_utils.py+++ b/src/local_deep_research/database/sqlcipher_utils.py@@ -15,6 +15,7 @@ from typing import Any, Dict, Optional, Unionfrom loguru import logger+from ..security.log_sanitizer import redact_secretsfrom ..settings.env_registry import get_env_settingfrom ..utilities.type_utils import to_bool@@ -239,6 +240,45 @@ class SQLCipherRekeyError(RuntimeError):"""+# Shortest run of key hex treated as a leak by :func:`_rekey_failure_detail`.+# 16 hex characters is 8 bytes of the 32-byte master key -- far too little to+# be useful to an attacker, and far more than any coincidental hex run in a+# SQLite error message ("database disk image is malformed", a page number, a+# file path). Well under the length at which a renderer would ellipsise.+_KEY_FRAGMENT_LENGTH = 16+++def _contains_key_fragment(message: str, key_hex: str) -> bool:+ """Whether *message* still shows any run of the key, not just the whole."""+ return any(+ key_hex[start : start + _KEY_FRAGMENT_LENGTH] in message+ for start in range(len(key_hex) - _KEY_FRAGMENT_LENGTH + 1)+ )+++def _rekey_failure_detail(+ exc: BaseException, key_hex: str, statement: str+) -> str:+ """The failure's own message with the derived key scrubbed out of it.++ The type name alone cannot tell ``database is locked`` from ``file is not+ a database`` or a disk-full error, and on the raw ``sqlcipher3``+ connection path the DBAPI message never contained the statement in the+ first place -- so there is a real diagnostic here worth keeping, once the+ key is gone.++ ``redact_secrets`` replaces literal substrings, which covers the+ SQLAlchemy path (``_sql_message`` appends the statement verbatim). It+ cannot cover a renderer that truncated the hex mid-run, so this fails+ closed: if any fragment of the key survives, the whole detail is dropped+ and the caller is left with the type name.+ """+ detail = redact_secrets(str(exc), statement, key_hex)+ if _contains_key_fragment(detail, key_hex):+ return ""+ return detail++def set_sqlcipher_rekey(cursor_or_conn: Any,new_password: str,@@ -258,9 +298,11 @@ def set_sqlcipher_rekey("""# Use the same key derivation as set_sqlcipher_key for consistencykey = get_key_from_password(new_password, db_path=db_path) # gitleaks:allow+ key_hex = key.hex()+ del key# The hex encoding already prevents injection since it only contains [0-9a-f]- safe_sql = f"PRAGMA rekey = \"x'{key.hex()}'\""+ 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@@ -270,9 +312,16 @@ def set_sqlcipher_rekey(# 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] = None+ # the handler has exited leaves ``__context__`` unset, so no attribute of+ # the propagated exception references the key. The raising frame's own+ # locals are a separate surface, and are dropped further down.+ #+ # Keep the failure's *name* and its scrubbed message rather than the+ # exception object: holding ``exc`` past the ``except`` block would pin+ # its own traceback -- through SQLAlchemy frames that carry the statement+ # -- to this frame for as long as the new error propagates.+ failure_type: Optional[str] = None+ failure_detail = ""try:try:# Try SQLAlchemy connection (needs text() wrapper)@@ -283,12 +332,22 @@ def set_sqlcipher_rekey(# Raw SQLCipher connection - use string directlycursor_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+ failure_type = type(exc).__name__+ failure_detail = _rekey_failure_detail(exc, key_hex, safe_sql)++ # This frame stays in the propagated exception's traceback, so a sink that+ # renders frame locals (loguru ``diagnose=True``) would print whatever is+ # still bound here. ``exc`` is already gone -- Python unbinds it at the end+ # of the ``except`` block -- so the key and the statement are what is left.+ # ``new_password`` stays: the caller's own frame holds it either way, so+ # dropping it here would suggest a protection that is not there.+ del key_hex, safe_sql++ if failure_type is not None:+ message = f"PRAGMA rekey failed ({failure_type})"+ if failure_detail:+ message = f"{message}: {failure_detail}"+ raise SQLCipherRekeyError(message) from None# Default SQLCipher configuration (can be overridden by settings)diff --git a/tests/security/test_sqlcipher_rekey_key_not_leaked.py b/tests/security/test_sqlcipher_rekey_key_not_leaked.pyindex 4c82af3531..9a5201c6e7 100644--- a/tests/security/test_sqlcipher_rekey_key_not_leaked.py+++ b/tests/security/test_sqlcipher_rekey_key_not_leaked.py@@ -77,12 +77,9 @@ 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.+ Scoped to the exception object. The frame locals reachable from+ ``exception.__traceback__``, which a loguru sink with ``diagnose=True``+ would render, are the separate surface AA4 covers (#6444)."""return {"str(exc)": str(exception),@@ -220,3 +217,123 @@ def test_aa3_successful_rekey_still_executes_the_pragma(key_hex):assert len(executed) == 1assert executed[0] == f"PRAGMA rekey = \"x'{key_hex}'\"" # gitleaks:allow+++def _subject_frame_locals(exception):+ """Locals still bound in ``set_sqlcipher_rekey``'s own frame.++ That frame sits in the propagated exception's traceback, and a loguru+ sink with ``diagnose=True`` (``LDR_LOGURU_DIAGNOSE``) renders frame+ locals — so anything left bound here is as reachable as the exception's+ own attributes. Scoped to the subject's frame: a caller's frame is the+ caller's business, and this test's own frame holds ``key_hex`` by+ construction.+ """+ values = {}+ traceback_ = exception.__traceback__+ while traceback_ is not None:+ frame = traceback_.tb_frame+ if frame.f_code.co_name == "set_sqlcipher_rekey":+ values = {+ name: repr(value) for name, value in frame.f_locals.items()+ }+ traceback_ = traceback_.tb_next+ return values+++def test_aa4_raising_frame_keeps_neither_the_key_nor_the_statement(key_hex):+ """AA4: the derived key is gone from the raising frame's locals (#6444).++ ``key``/``safe_sql`` used to stay bound, and the captured exception stayed+ with them — pinning its own traceback, through SQLAlchemy frames carrying+ the statement, for as long as the new error propagated.+ """+ engine = _failing_sqlalchemy_connection()++ with engine.connect() as conn:+ with pytest.raises(SQLCipherRekeyError) as caught:+ set_sqlcipher_rekey(conn, NEW_PASSWORD, db_path=None)++ frame_locals = _subject_frame_locals(caught.value)+ assert frame_locals, "the subject's frame is no longer in the traceback"+ still_bound = {"key", "key_hex", "safe_sql"} & set(frame_locals)+ assert not still_bound, (+ f"key material still bound in the raising frame: {sorted(still_bound)}"+ )+ leaked = {+ name: value for name, value in frame_locals.items() if key_hex in value+ }+ assert not leaked, (+ f"derived key still bound in the raising frame: {sorted(leaked)}"+ )+++def test_aa5_raw_connection_failures_stay_distinguishable(key_hex):+ """AA5: the DBAPI message survives on the raw path, scrubbed (#6444).++ On the raw ``sqlcipher3`` connection the message never contained the+ statement, so reducing every failure to its type name turned ``database+ is locked``, ``file is not a database`` and a disk-full error into the+ same line in the change-password log.+ """+ messages = {}+ for dbapi_message in (+ "database is locked",+ "file is not a database",+ "disk I/O error",+ ):++ class RawConnection:+ def __init__(self, message):+ self.message = message++ def execute(self, statement):+ if isinstance(statement, TextClause):+ raise TypeError(+ "raw connection expects str, not TextClause"+ )+ raise sqlite3.OperationalError(self.message)++ with pytest.raises(SQLCipherRekeyError) as caught:+ set_sqlcipher_rekey(+ RawConnection(dbapi_message), NEW_PASSWORD, db_path=None+ )++ messages[dbapi_message] = str(caught.value)+ _assert_no_key(caught.value, key_hex)++ for dbapi_message, raised in messages.items():+ assert dbapi_message in raised, (+ f"{dbapi_message!r} no longer reaches the caller"+ )+ assert "OperationalError" in raised+ assert len(set(messages.values())) == len(messages), (+ "the three failures are still indistinguishable"+ )+++def test_aa6_a_truncated_key_in_the_message_drops_the_detail(key_hex):+ """AA6: scrubbing fails closed on a fragment it cannot replace (#6444).++ ``redact_secrets`` replaces literal substrings. A renderer that ellipsised+ the hex mid-run would leave a fragment no literal replace can catch, so+ the detail is dropped wholesale rather than emitted in part.+ """+ fragment = key_hex[:24]++ class RawConnection:+ def execute(self, statement):+ if isinstance(statement, TextClause):+ raise TypeError("raw connection expects str, not TextClause")+ raise sqlite3.OperationalError(+ f'near "x\'{fragment}...": syntax error'+ )++ with pytest.raises(SQLCipherRekeyError) as caught:+ set_sqlcipher_rekey(RawConnection(), NEW_PASSWORD, db_path=None)++ raised = str(caught.value)+ assert fragment not in raised+ assert raised == "PRAGMA rekey failed (OperationalError)", (+ "a message carrying a key fragment must be dropped, not partially kept"+ )