Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion publisher/db/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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

Expand Down
32 changes: 32 additions & 0 deletions tests/db/test_engine.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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)