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(migrations): chmod migrations dir in Docker + fail loud on migration error (#3635)

LearningCircuitde2184541521
diff --git a/Dockerfile b/Dockerfile
index b1f2a7527c..05d0504437 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -253,6 +253,18 @@ RUN mkdir -p /app/.config/local_deep_research /home/ldruser/.local/share && \
COPY --chown=ldruser:ldruser --from=builder /install/.venv/ /install/.venv
ENV PATH="/install/.venv/bin:$PATH"
+# Strip world-write bit from the migrations subtree. The runtime check in
+# alembic_runner._validate_migrations_permissions refuses to run migrations
+# if anything under migrations/versions/ is world-writable, and pip/pdm can
+# leave permissive modes on the dir entries depending on the build host's
+# umask (see pip#8164, conda#12829). Without this normalisation a per-user
+# DB silently stays at its previous Alembic revision on every login, which
+# manifests downstream as e.g. "no such table: papers" on academic-source
+# saves. Targeted at the migrations subtree only — we deliberately avoid
+# blanket-chmoding the venv.
+RUN find /install/.venv -type d -path '*/local_deep_research/database/migrations' \
+ -exec chmod -R go-w {} +
+
# Verify SQLCipher as ldruser via setpriv.
# Running as ldruser ensures Python __pycache__ files created during import
# are owned by ldruser. Browser binaries are NOT installed in the production
diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.py
index 6e2a165f01..5f14b68ea0 100644
--- a/src/local_deep_research/database/encrypted_db.py
+++ b/src/local_deep_research/database/encrypted_db.py
@@ -610,14 +610,15 @@ class DatabaseManager:
"Pre-migration backup failed — proceeding with migration"
)
- try:
- initialize_database(engine)
- except Exception:
- logger.exception(
- f"Database migration failed for {username} — "
- "database remains at previous working revision (safe). "
- "Migrations will be retried on next process restart."
- )
+ # Let migration failures propagate to the outer except: a half-
+ # initialised DB whose alembic_version disagrees with the schema
+ # is *not* "safe" — every later query that touches a table the
+ # failed migration was supposed to create raises confusing
+ # downstream errors (e.g. "no such table: papers" on academic
+ # source saves). Failing the open here means login fails loudly
+ # and ops sees a clean migration traceback instead of cascading
+ # PendingRollbackErrors hours later.
+ initialize_database(engine)
# Store connection AFTER migrations complete
with self._connections_lock:
diff --git a/tests/database/test_alembic_migrations.py b/tests/database/test_alembic_migrations.py
index 0ac7204fff..e7a3957f40 100644
--- a/tests/database/test_alembic_migrations.py
+++ b/tests/database/test_alembic_migrations.py
@@ -3975,6 +3975,62 @@ class TestMigrationFilePermissions:
# Should not raise even if file would be "insecure" on Unix
_validate_migrations_permissions(mock_migrations)
+ @pytest.mark.skipif(
+ os.name == "nt", reason="File permissions work differently on Windows"
+ )
+ def test_world_writable_versions_dir_rejected(self, tmp_path):
+ """Reject a world-writable versions/ directory even when files inside are secure.
+
+ Regression: a Docker image landed with mode 0o777 on the directory
+ itself (files were 0o644). Every per-user login then tripped this
+ check, swallowed the resulting ValueError, and silently left the DB
+ at its previous Alembic revision — surfacing later as
+ ``no such table: papers`` on academic-source saves.
+ """
+ from local_deep_research.database.alembic_runner import (
+ _validate_migrations_permissions,
+ )
+
+ mock_migrations = tmp_path / "migrations"
+ mock_versions = mock_migrations / "versions"
+ mock_versions.mkdir(parents=True)
+
+ # File itself is fine — the only insecure thing is the directory.
+ secure_migration = mock_versions / "001_migration.py"
+ secure_migration.write_text("# content")
+ os.chmod(secure_migration, 0o644)
+
+ os.chmod(mock_versions, 0o777) # noqa: S103 — intentionally testing rejection
+
+ with pytest.raises(ValueError) as exc_info:
+ _validate_migrations_permissions(mock_migrations)
+
+ msg = str(exc_info.value)
+ assert "world-writable" in msg
+ assert "versions" in msg
+
+ @pytest.mark.skipif(
+ os.name == "nt", reason="File permissions work differently on Windows"
+ )
+ def test_shipped_versions_dir_not_world_writable(self):
+ """The actual shipped versions/ directory must not be world-writable.
+
+ Companion to ``test_migration_files_not_world_writable`` (which only
+ covers the files). The runtime check rejects either; both need to
+ be guarded against packaging regressions.
+ """
+ migrations_dir = get_migrations_dir()
+ versions_dir = migrations_dir / "versions"
+ if not versions_dir.exists():
+ pytest.skip("No versions directory exists yet")
+
+ st = versions_dir.stat()
+ assert not (st.st_mode & 0o002), (
+ f"versions/ directory is world-writable (mode={oct(st.st_mode)}). "
+ "If this fires in CI after a packaging change, normalise the "
+ "perms in Dockerfile/build, not by weakening this test."
+ )
+
# =============================================================================
# Backward Compatibility Tests
diff --git a/tests/database/test_encrypted_db_manager.py b/tests/database/test_encrypted_db_manager.py
index d0e99f548e..b61b0bf24b 100644
--- a/tests/database/test_encrypted_db_manager.py
+++ b/tests/database/test_encrypted_db_manager.py
@@ -281,6 +281,70 @@ class TestDatabaseOpening:
assert result is None
+ @patch("local_deep_research.database.encrypted_db.get_data_directory")
+ def test_open_database_migration_failure_returns_none(
+ self, mock_data_dir, tmp_path
+ ):
+ """A failure inside ``initialize_database`` must surface as None.
+
+ Regression: the open path used to swallow migration exceptions and
+ cache the engine anyway, leaving downstream queries to hit a
+ schema/alembic_version mismatch (e.g. ``no such table: papers``).
+ Now the failure propagates to the outer cleanup path: engine
+ disposed, no entry stored in ``connections``, ``None`` returned —
+ same shape as any other open failure.
+ """
+ from local_deep_research.database.encrypted_db import DatabaseManager
+
+ mock_data_dir.return_value = tmp_path
+
+ db_file = tmp_path / "encrypted_databases" / "test.db"
+ db_file.parent.mkdir(parents=True, exist_ok=True)
+ db_file.touch()
+
+ with patch.object(
+ DatabaseManager, "_check_encryption_available", return_value=False
+ ):
+ with patch.dict("os.environ", {"LDR_ALLOW_UNENCRYPTED": "true"}):
+ manager = DatabaseManager()
+
+ with patch.object(
+ manager, "_get_user_db_path", return_value=db_file
+ ):
+ with patch(
+ "local_deep_research.database.encrypted_db.create_engine"
+ ) as mock_engine_factory:
+ mock_engine = MagicMock()
+ mock_engine_factory.return_value = mock_engine
+ # SELECT 1 connection check passes
+ mock_engine.connect.return_value.__enter__ = MagicMock(
+ return_value=MagicMock()
+ )
+ mock_engine.connect.return_value.__exit__ = MagicMock(
+ return_value=False
+ )
+
+ with patch(
+ "local_deep_research.database.encrypted_db.event"
+ ):
+ with patch(
+ "local_deep_research.database.alembic_runner.needs_migration",
+ return_value=False,
+ ):
+ with patch(
+ "local_deep_research.database.initialize.initialize_database",
+ side_effect=ValueError(
+ "Migrations directory has insecure permissions (world-writable)"
+ ),
+ ):
+ result = manager.open_user_database(
+ "testuser", "password"
+ )
+
+ assert result is None
+ assert "testuser" not in manager.connections
+ mock_engine.dispose.assert_called_once()
+
class TestDatabaseClosure:
"""Tests for close_user_database functionality."""