diff --git a/publisher/db/__init__.py b/publisher/db/__init__.py index 6b968ce..75a0cc0 100644 --- a/publisher/db/__init__.py +++ b/publisher/db/__init__.py @@ -21,6 +21,14 @@ _session_factory: sessionmaker | None = None +class DatabaseConnectionError(Exception): + """Establishing a database connection failed. + + Not a ValueError, so handlers that catch ValueError around key lookups + don't report connection problems to clients. + """ + + def _make_sqlcipher3_creator(db_path: str, key: bytes): """Return a function that opens the encrypted SQLCipher database.""" # sqlcipher3 re-exports its C extension with import *, which pyright can't follow. @@ -37,7 +45,9 @@ def connect(): conn.execute("SELECT count(*) FROM sqlite_master;") except sqlcipher3.DatabaseError: # pyright: ignore[reportAttributeAccessIssue] conn.close() - raise ValueError("Wrong key, or the database file is corrupted.") from None + raise DatabaseConnectionError( + "Wrong key, or the database file is corrupted." + ) from None return conn diff --git a/tests/db/test_engine.py b/tests/db/test_engine.py index 1fc171a..e2dac04 100644 --- a/tests/db/test_engine.py +++ b/tests/db/test_engine.py @@ -1,6 +1,8 @@ # SPDX-License-Identifier: GPL-3.0-only import dataclasses +import sys +import types import pytest from sqlalchemy import Column, Integer, MetaData, Table @@ -32,3 +34,33 @@ def test_sqlcipher_errors_are_wrapped(encrypted_engine): conn.execute(table.insert().values(id=1)) with pytest.raises(IntegrityError), encrypted_engine.begin() as conn: conn.execute(table.insert().values(id=1)) + + +def test_failing_sqlcipher_integrity_check_is_not_a_value_error(monkeypatch, tmp_path): + """A failed integrity check raises DatabaseConnectionError, not ValueError. + + Callers catch ValueError around key lookups; a plain ValueError would send + the connection failure message to clients. + """ + + class FakeDatabaseError(Exception): + pass + + class FakeConnection: + def execute(self, statement): + if "sqlite_master" in statement: + raise FakeDatabaseError("file is not a database") + + def close(self): + pass + + fake = types.ModuleType("sqlcipher3") + fake.connect = lambda *args, **kwargs: FakeConnection() + fake.DatabaseError = FakeDatabaseError + monkeypatch.setitem(sys.modules, "sqlcipher3", fake) + + connect = db._make_sqlcipher3_creator(str(tmp_path / "encrypted.db"), b"\x01" * 32) + with pytest.raises(db.DatabaseConnectionError) as excinfo: + connect() + assert not isinstance(excinfo.value, ValueError) + assert "Wrong key" in str(excinfo.value)