~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(database): write salt files in binary mode on Windows (#7257)
LearningCircuita81b76c1e305
diff --git a/.github/scripts/check_native_database.py b/.github/scripts/check_native_database.pynew file mode 100644index 0000000000..6e248c6dc6--- /dev/null+++ b/.github/scripts/check_native_database.py@@ -0,0 +1,32 @@+"""Run the native database regressions; empty or skipped runs do not qualify."""++import argparse+import platform+from pathlib import Path+import sys+import unittest+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--require-windows", action="store_true")+ args = parser.parse_args()+ if args.require_windows and sys.platform != "win32":+ parser.error("native Windows qualification requires a Windows process")++ root = Path(__file__).resolve().parents[2]+ suite = unittest.defaultTestLoader.discover(+ str(root / "tests" / "ci" / "standalone"),+ pattern="test_native_database_*.py",+ )+ if not suite.countTestCases():+ parser.error("no native database tests were discovered")+ print(+ f"Platform: {platform.platform()}; Python: {platform.python_version()}"+ )+ result = unittest.TextTestRunner(verbosity=2).run(suite)+ return int(not result.wasSuccessful() or bool(result.skipped))+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/.github/workflows/windows-database-tests.yml b/.github/workflows/windows-database-tests.ymlnew file mode 100644index 0000000000..e3d9b62d17--- /dev/null+++ b/.github/workflows/windows-database-tests.yml@@ -0,0 +1,68 @@+name: Native Windows Database Tests++on:+ pull_request:+ branches: [main]+ paths:+ - '.github/workflows/windows-database-tests.yml'+ - '.github/scripts/check_native_database.py'+ - 'tests/ci/standalone/test_native_database_*.py'+ - 'src/local_deep_research/database/**'+ - 'src/local_deep_research/config/paths.py'+ - 'src/local_deep_research/settings/**'+ - 'pyproject.toml'+ - 'pdm.lock'+ push:+ branches: [main]+ paths:+ - '.github/workflows/windows-database-tests.yml'+ - '.github/scripts/check_native_database.py'+ - 'tests/ci/standalone/test_native_database_*.py'+ - 'src/local_deep_research/database/**'+ - 'src/local_deep_research/config/paths.py'+ - 'src/local_deep_research/settings/**'+ - 'pyproject.toml'+ - 'pdm.lock'+ workflow_dispatch:++permissions:+ contents: read++concurrency:+ group: native-windows-database-${{ github.event.pull_request.number || github.ref }}+ cancel-in-progress: true++jobs:+ database:+ name: Native Windows SQLCipher (Python ${{ matrix.python-version }})+ runs-on: windows-2025+ timeout-minutes: 45+ strategy:+ fail-fast: false+ matrix:+ python-version: ['3.12', '3.14']+ env:+ PYTHONPATH: src+ steps:+ - name: Harden runner+ uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1+ with:+ egress-policy: audit+ - name: Checkout+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ - name: Set up PDM and Python+ uses: pdm-project/setup-pdm@544d7237314ee09c256785bd360f6b30add38b37 # v4.6+ with:+ python-version: ${{ matrix.python-version }}+ architecture: x64+ version: '2.28.0'+ - name: Verify dependency lock+ run: pdm lock --check+ - name: Install locked production dependencies+ # These qualify the database source with real native dependencies;+ # the independent package/UI jobs qualify the built application.+ run: pdm sync --prod --no-self --fail-fast+ - name: Test native file I/O and encrypted recovery+ run: pdm run python .github/scripts/check_native_database.py --require-windowsdiff --git a/changelog.d/+salt-file-binary-mode.bugfix.md b/changelog.d/+salt-file-binary-mode.bugfix.mdnew file mode 100644index 0000000000..529a03ac63--- /dev/null+++ b/changelog.d/+salt-file-binary-mode.bugfix.md@@ -0,0 +1 @@+On native Windows (pip installs), about 12% of attempts to register a new account failed with "Registration failed. Please try again.": the per-database `.salt` file was written in text mode, so every newline byte in the random salt gained a carriage return and the file was then rejected as corrupted. Salt files are now written in binary mode. A salt file that already has a carriage return inserted before each newline byte, for example after copying a data directory with a tool that converts line endings, is now read back as the original salt with a warning; the file itself is not rewritten.diff --git a/docs/ci/workflow-status.md b/docs/ci/workflow-status.mdindex 3e06d9389e..5ca4ba325b 100644--- a/docs/ci/workflow-status.md+++ b/docs/ci/workflow-status.md@@ -179,3 +179,8 @@ the table above.itself. Needs no application server, no auth and no secrets: the specloads the production sanitizer modules and its fixture page from diskvia `setContent()`, so it is safe to run on fork PRs.++- `windows-database-tests.yml` — native Windows SQLCipher and file-I/O+ tests on Python 3.12 and 3.14; PR to main, push:main, manual.+ Path-filtered to database/settings sources, config paths, locked+ dependencies, the native test modules, runner, and workflow.diff --git a/src/local_deep_research/database/sqlcipher_utils.py b/src/local_deep_research/database/sqlcipher_utils.pyindex 1658360507..eb9dce2a68 100644--- a/src/local_deep_research/database/sqlcipher_utils.py+++ b/src/local_deep_research/database/sqlcipher_utils.py@@ -49,11 +49,19 @@ def get_salt_for_database(db_path: Union[str, Path]) -> bytes:For new databases (v2+): reads from the .salt file alongside the database.For legacy databases (v1): returns LEGACY_PBKDF2_SALT for backwards compatibility.+ A salt file with a CR byte inserted before every LF byte, as a Windows+ text-mode write produces (see ``create_database_salt``), is read back+ as the original salt, and a warning names the file. The file is not+ rewritten: this function never writes to disk.+Args:db_path: Path to the database fileReturns:The salt bytes to use for key derivation++ Raises:+ ValueError: If the salt file has any other unexpected size."""salt_file = get_salt_file_path(db_path)@@ -70,10 +78,32 @@ def get_salt_for_database(db_path: Union[str, Path]) -> bytes:# v2: Per-database random saltif len(salt) != SALT_SIZE:- raise ValueError(- f"Salt file {salt_file} has unexpected size ({len(salt)} bytes), "- f"expected {SALT_SIZE}. The salt file may be corrupted."+ # Undo Windows text-mode newline translation. A text-mode write+ # stores a CR (0x0D) before every LF (0x0A) and changes no other+ # byte. So every LF in a damaged file is an original salt byte, and+ # the byte just before it is the CR that the write inserted.+ # Replacing each CR LF pair with LF removes exactly those CRs: two+ # pairs never share a byte, since no byte is both CR and LF, and an+ # original CR stays, even one just before an original LF (stored as+ # CR CR LF). The round-trip check accepts the file only if it is+ # exactly what a text-mode write of the recovered salt produces.+ # This runs on every platform, since a data directory can be+ # copied from one system to another.+ recovered = salt.replace(b"\r\n", b"\n")+ if (+ len(recovered) != SALT_SIZE+ or recovered.replace(b"\n", b"\r\n") != salt+ ):+ raise ValueError(+ f"Salt file {salt_file} has unexpected size ({len(salt)} bytes), "+ f"expected {SALT_SIZE}. The salt file may be corrupted."+ )+ logger.warning(+ f"Salt file {salt_file} has a CR byte inserted before each LF "+ f"byte (Windows text-mode newline translation). Using the "+ f"recovered {SALT_SIZE}-byte salt; the file is left unchanged.")+ return recoveredreturn salt@@ -113,8 +143,12 @@ def create_database_salt(db_path: Union[str, Path]) -> bytes:create_directory(salt_file.parent, context="database salt file directory")- # Write salt file with owner-only permissions (0o600)- fd = os.open(str(salt_file), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)+ # Write salt file with owner-only permissions (0o600). O_BINARY exists+ # only on Windows, where os.open() otherwise gives a text-mode+ # descriptor and os.write() stores a CR before every LF byte, so about+ # 12% of salts would be saved with extra bytes.+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0)+ fd = os.open(str(salt_file), flags, 0o600)try:os.write(fd, salt)finally:diff --git a/tests/ci/standalone/test_native_database_salts.py b/tests/ci/standalone/test_native_database_salts.pynew file mode 100644index 0000000000..3839a2dbb2--- /dev/null+++ b/tests/ci/standalone/test_native_database_salts.py@@ -0,0 +1,125 @@+"""Real salt-file I/O, also run on native Windows without pytest fixtures.++Only the random salt source is controlled. File descriptors, binary/text+translation and SQLCipher are real; a missing encryption driver fails the run.+"""++from contextlib import closing+import os+from pathlib import Path+import tempfile+from types import SimpleNamespace+import unittest+from unittest.mock import Mock, patch++from local_deep_research.database import sqlcipher_utils+from local_deep_research.database.sqlcipher_compat import get_sqlcipher_module+++SALTS = (+ b"\x00\x1a\xff\r\n\r\r\n" + bytes(range(24)),+ b"\n" * 32,+ b"\r\n" * 16,+)+++class NativeSaltTests(unittest.TestCase):+ def setUp(self):+ temporary = tempfile.TemporaryDirectory(prefix="ldr-native-salt-")+ self.addCleanup(temporary.cleanup)+ self.root = Path(temporary.name) / "original's café data"+ self.root.mkdir()+ environment = patch.dict(+ os.environ,+ {+ "LDR_DATA_DIR": str(self.root),+ "LDR_TEST_MODE": "false",+ "LDR_DB_CONFIG_KDF_ITERATIONS": "256000",+ },+ )+ environment.start()+ self.addCleanup(environment.stop)+ self.assertEqual(+ sqlcipher_utils.get_sqlcipher_settings()["kdf_iterations"], 256000+ )+ self.sqlcipher = get_sqlcipher_module()++ def create_salt(self, path, salt):+ random_bytes = Mock(return_value=salt)+ with patch.object(+ sqlcipher_utils,+ "secrets",+ SimpleNamespace(token_bytes=random_bytes),+ ):+ self.assertEqual(sqlcipher_utils.create_database_salt(path), salt)+ random_bytes.assert_called_once_with(sqlcipher_utils.SALT_SIZE)++ def test_writer_preserves_all_bytes_with_real_file_descriptors(self):+ for index, salt in enumerate(SALTS):+ with self.subTest(salt=index):+ path = self.root / f"writer-{index}.db"+ self.create_salt(path, salt)+ stored = sqlcipher_utils.get_salt_file_path(path).read_bytes()+ self.assertEqual(stored, salt)+ self.assertEqual(len(stored), 32)++ def test_existing_salt_is_never_overwritten(self):+ path = self.root / "existing.db"+ self.create_salt(path, SALTS[0])+ with self.assertRaises(FileExistsError):+ sqlcipher_utils.create_database_salt(path)+ self.assertEqual(+ sqlcipher_utils.get_salt_file_path(path).read_bytes(), SALTS[0]+ )++ def test_encrypted_database_reopens_with_a_translated_salt(self):+ password = "native-salt-test-password" # noqa: S105+ for index, salt in enumerate(SALTS):+ with self.subTest(salt=index):+ path = self.root / f"encrypted-{index}.db"+ self.create_salt(path, salt)+ with closing(+ sqlcipher_utils.create_sqlcipher_connection(+ path, password, creation_mode=True+ )+ ) as connection:+ self.assertTrue(+ connection.execute("PRAGMA cipher_version").fetchone()[+ 0+ ]+ )+ connection.execute("CREATE TABLE canary (value TEXT)")+ connection.execute(+ "INSERT INTO canary VALUES (?)", ("preserved",)+ )+ connection.commit()++ self.assertNotEqual(+ path.read_bytes()[:16], b"SQLite format 3\0"+ )+ salt_file = sqlcipher_utils.get_salt_file_path(path)+ translated = salt.replace(b"\n", b"\r\n")+ salt_file.write_bytes(translated)+ with closing(+ sqlcipher_utils.create_sqlcipher_connection(path, password)+ ) as connection:+ self.assertEqual(+ connection.execute(+ "SELECT value FROM canary"+ ).fetchall(),+ [("preserved",)],+ )+ with self.assertRaises(+ (ValueError, self.sqlcipher.DatabaseError)+ ):+ with closing(+ sqlcipher_utils.create_sqlcipher_connection(+ path, "wrong-password"+ )+ ):+ pass+ self.assertEqual(salt_file.read_bytes(), translated)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/database/test_salt_file_binary_mode.py b/tests/database/test_salt_file_binary_mode.pynew file mode 100644index 0000000000..575ba5e87d--- /dev/null+++ b/tests/database/test_salt_file_binary_mode.py@@ -0,0 +1,263 @@+"""Per-database salt files and Windows text-mode newline translation.++On Windows, ``os.open`` without ``O_BINARY`` returns a text-mode+descriptor, and ``os.write`` then stores a CR (0x0D) before every LF+(0x0A). A random 32-byte salt contains an LF with probability+1 - (255/256)**32, about 12%, so such a salt file was stored with 33 or+more bytes and ``get_salt_for_database`` refused it as corrupted.++These tests pin both halves of the fix:++* ``create_database_salt`` passes ``O_BINARY`` wherever the platform+ defines it;+* ``get_salt_for_database`` reads a file damaged this way back as the+ original salt, never rewrites it, and still refuses every other size.+"""++import os+import random+from types import SimpleNamespace++import pytest+from sqlalchemy import text++from local_deep_research.database import sqlcipher_utils+from local_deep_research.database.sqlcipher_utils import (+ SALT_SIZE,+ create_database_salt,+ get_salt_file_path,+ get_salt_for_database,+)+++def _text_mode_write(salt: bytes) -> bytes:+ """The bytes a Windows text-mode write stores for *salt*."""+ return salt.replace(b"\n", b"\r\n")+++def _warnings(caplog):+ return [+ r+ for r in caplog.records+ if r.levelname in ("WARNING", "ERROR", "CRITICAL")+ ]+++# 32-byte salts containing LF, including CR LF and CR CR LF runs whose CR+# bytes belong to the salt rather than being inserted by the write.+SALTS_WITH_LF = [+ pytest.param(b"\n" + b"\x01" * 31, id="leading-lf"),+ pytest.param(b"\x02" * 31 + b"\n", id="trailing-lf"),+ pytest.param(b"\x03" * 10 + b"\r\n" + b"\x04" * 20, id="crlf-run"),+ pytest.param(b"\x05" * 9 + b"\r\r\n" + b"\x06" * 20, id="crcrlf-run"),+ pytest.param(b"\r\n\n\r\r\n\r" + b"\x07" * 25, id="mixed-runs"),+ pytest.param(b"\n" * SALT_SIZE, id="all-lf"),+]+++def test_create_database_salt_opens_the_salt_file_with_o_binary(+ tmp_path, monkeypatch+):+ """The writer must request binary mode wherever the platform has it.++ ``os.O_BINARY`` does not exist on POSIX, so a sentinel bit stands in+ for it. The wrapper records the flags and swaps the sentinel back for+ the real flag (0 here) before the real call.+ """+ real_open = os.open+ real_binary = getattr(os, "O_BINARY", 0)+ sentinel = 1 << 30+ assert not sentinel & (os.O_WRONLY | os.O_CREAT | os.O_EXCL | real_binary)+ monkeypatch.setattr(os, "O_BINARY", sentinel, raising=False)++ calls = []++ def recording_open(path, flags, *args, **kwargs):+ calls.append((os.fspath(path), flags))+ if flags & sentinel:+ flags = (flags & ~sentinel) | real_binary+ return real_open(path, flags, *args, **kwargs)++ monkeypatch.setattr(os, "open", recording_open)++ db_path = tmp_path / "user.db"+ salt = create_database_salt(db_path)++ salt_file = get_salt_file_path(db_path)+ salt_opens = [flags for path, flags in calls if path == str(salt_file)]+ assert len(salt_opens) == 1+ assert salt_opens[0] & sentinel, "the salt file was opened without O_BINARY"+ assert salt_file.read_bytes() == salt++[email protected]("salt", SALTS_WITH_LF)+def test_a_text_mode_damaged_salt_reads_back_as_the_original(tmp_path, salt):+ assert len(salt) == SALT_SIZE+ db_path = tmp_path / "user.db"+ salt_file = get_salt_file_path(db_path)+ damaged = _text_mode_write(salt)+ salt_file.write_bytes(damaged)++ assert get_salt_for_database(db_path) == salt+ # No healing write: the damaged file stays exactly as it was.+ assert salt_file.read_bytes() == damaged+++def test_recovery_is_exact_for_salts_made_of_cr_and_lf_runs(tmp_path):+ """Class check over salts drawn mostly from CR and LF bytes, so that+ every run shape (LF LF, CR LF, CR CR LF, a trailing CR, ...) occurs."""+ rng = random.Random(1439)+ alphabet = b"\r\n\r\n\x00\xff"+ db_path = tmp_path / "user.db"+ salt_file = get_salt_file_path(db_path)+ for _ in range(500):+ salt = bytes(rng.choice(alphabet) for _ in range(SALT_SIZE))+ salt_file.write_bytes(_text_mode_write(salt))+ assert get_salt_for_database(db_path) == salt+++def test_recovery_warns_once_naming_the_file_but_not_the_bytes(+ tmp_path, loguru_caplog+):+ salt = b"\x08" * 15 + b"\n" + b"\x09" * 15 + b"\r"+ damaged = _text_mode_write(salt)+ db_path = tmp_path / "user.db"+ salt_file = get_salt_file_path(db_path)+ salt_file.write_bytes(damaged)++ with loguru_caplog.at_level("WARNING"):+ assert get_salt_for_database(db_path) == salt++ warnings = _warnings(loguru_caplog)+ assert len(warnings) == 1+ assert str(salt_file) in warnings[0].getMessage()+ logged = loguru_caplog.text+ for form in (salt, damaged):+ assert form.hex() not in logged+ assert form.hex().upper() not in logged+ assert repr(form) not in logged+++ "salt",+ [+ pytest.param(b"\r\n" * 16, id="all-crlf"),+ pytest.param(b"A" * 15 + b"\r\n" + b"B" * 15, id="one-crlf"),+ pytest.param(b"\r\r\n" + b"C" * 29, id="crcrlf"),+ ],+)+def test_an_intact_salt_containing_crlf_is_returned_unchanged(+ tmp_path, salt, loguru_caplog+):+ """A file of exactly SALT_SIZE bytes is never translated: CR LF in a+ 32-byte salt is salt data, not damage."""+ assert len(salt) == SALT_SIZE+ db_path = tmp_path / "user.db"+ get_salt_file_path(db_path).write_bytes(salt)++ with loguru_caplog.at_level("WARNING"):+ assert get_salt_for_database(db_path) == salt+ assert not _warnings(loguru_caplog)+++ "content",+ [+ pytest.param(b"A" * 33, id="33-bytes-no-crlf"),+ # Collapsing CR LF gives 32 bytes, but the bare LF shows that this+ # is not what a text-mode write produces.+ pytest.param(+ b"B" * 30 + b"\r\n" + b"\n", id="33-bytes-crlf-and-bare-lf"+ ),+ pytest.param(b"C" * 31, id="31-bytes"),+ pytest.param(b"D" * 29 + b"\r\n", id="31-bytes-with-crlf"),+ # Only a single translation is undone.+ pytest.param(+ _text_mode_write(_text_mode_write(b"\n" + b"E" * 31)),+ id="translated-twice",+ ),+ pytest.param(b"", id="empty"),+ ],+)+def test_any_other_wrong_size_still_raises(tmp_path, content):+ db_path = tmp_path / "user.db"+ get_salt_file_path(db_path).write_bytes(content)++ with pytest.raises(+ ValueError, match=rf"unexpected size \({len(content)} bytes\)"+ ) as exc_info:+ get_salt_for_database(db_path)+ assert "may be corrupted" in str(exc_info.value)+++def test_a_damaged_salt_file_still_opens_its_database(tmp_path, monkeypatch):+ """End to end: a real SQLCipher database whose salt contains LF bytes,+ with its salt file rewritten the way a Windows text-mode write stores+ it, opens with the right password through the normal open path."""+ pytest.importorskip(+ "sqlcipher3", reason="requires SQLCipher (encrypted mode)"+ )+ from local_deep_research.database.encrypted_db import DatabaseManager++ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ manager = DatabaseManager()+ manager.data_dir = tmp_path+ try:+ if not manager.has_encryption:+ pytest.skip("requires SQLCipher (encrypted mode)")++ salt = (+ b"\n"+ + b"\x20" * 9+ + b"\r\n"+ + b"\x21" * 9+ + b"\r\r\n"+ + b"\x22" * 8+ )+ assert len(salt) == SALT_SIZE++ def fixed_token_bytes(nbytes):+ assert nbytes == SALT_SIZE+ return salt++ username = "salt_text_mode_user"+ password = "SaltTextModePassword1!" # noqa: S105+ with monkeypatch.context() as patch:+ patch.setattr(+ sqlcipher_utils,+ "secrets",+ SimpleNamespace(token_bytes=fixed_token_bytes),+ )+ engine = manager.create_user_database(username, password)+ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE salt_canary (id INTEGER PRIMARY KEY, note TEXT)"+ )+ )+ conn.execute(+ text("INSERT INTO salt_canary (id, note) VALUES (1, 'intact')")+ )+ manager.close_user_database(username)++ salt_file = get_salt_file_path(manager._get_user_db_path(username))+ assert salt_file.read_bytes() == salt+ damaged = _text_mode_write(salt)+ salt_file.write_bytes(damaged)++ reopened = manager.open_user_database(username, password)+ assert reopened is not None, "the damaged salt file locked the user out"+ with reopened.connect() as conn:+ assert (+ conn.execute(+ text("SELECT note FROM salt_canary WHERE id = 1")+ ).scalar()+ == "intact"+ )+ manager.close_user_database(username)++ assert manager.open_user_database(username, "Wrong-Password-1!") is None+ assert salt_file.read_bytes() == damaged+ finally:+ manager.close_all_databases()