Author SHA1 Message Date
Xika 1243c7db57 fix(crypto): raise clear EncryptionError for invalid Fernet key (BIT-33939)
ci / verify (pull_request) Successful in 50s
get_fernet() let Fernet() raise a raw ValueError when ENCRYPTION_KEY was
malformed (e.g. the 'change_me_fernet_key' placeholder shipped in
.env.example), crashing the WebDAV sync loop with a cryptic
'Fernet key must be 32 url-safe base64-encoded bytes.' message.

Guard the Fernet() construction so an invalid key raises EncryptionError
with actionable guidance pointing at Fernet.generate_key(). Also blank
the invalid placeholder in .env.example so it cannot be copied verbatim
into production.

Paperclip-Issue: BIT-33939
2026-12-04 10:16:50 +00:00
spark c389503fb9 Merge pull request 'fix(imap): catch TimeoutError on per-message fetch so sync continues (BIT-33891)' (#8) from fix/BIT-33891-imap-timeout into main
ci / verify (push) Successful in 32s
2026-12-03 23:31:18 +00:00
spark c9d1ad4b48 Merge pull request 'fix(imap): catch OSError on logout of timed-out socket (BIT-33892)' (#9) from fix/BIT-33892-imap-logout-oserror into main
ci / verify (push) Successful in 35s
2026-12-03 23:31:13 +00:00
Xika 3ca283aa41 fix(imap): catch OSError on logout of timed-out socket (BIT-33892)
ci / verify (pull_request) Successful in 27s
The finally block in sync_account and retry_single_message only caught
imaplib.IMAP4.error from imap.logout(). When the underlying socket had
already timed out, logout() raises OSError('cannot read from timed out
object') which escaped the handler and crashed the sync run.

Add OSError to the except tuple so cleanup completes cleanly.

Paperclip-BIT-33892
2026-12-03 23:22:43 +00:00
5 changed files with 122 additions and 4 deletions

No files matched your search

+2 -1
View File
@@ -8,7 +8,8 @@ MYSQL_PASSWORD=change_me_db
# App
DATABASE_URL=mysql+pymysql://forwarder:change_me_db@mysql:3306/forwarder?charset=utf8mb4
ENCRYPTION_KEY=change_me_fernet_key
# Generate with: python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
ENCRYPTION_KEY=
APP_SECRET=change_me_jwt_secret
ADMIN_USERNAME=admin
ADMIN_PASSWORD=change_me
+10 -1
View File
@@ -13,7 +13,16 @@ def get_fernet() -> Fernet:
key = get_settings().encryption_key.strip()
if not key:
raise EncryptionError("ENCRYPTION_KEY is not configured")
return Fernet(key.encode() if isinstance(key, str) else key)
raw = key.encode() if isinstance(key, str) else key
try:
return Fernet(raw)
except (ValueError, TypeError) as exc:
raise EncryptionError(
"ENCRYPTION_KEY is not a valid Fernet key: it must be 32 url-safe "
"base64-encoded bytes (44 chars). Generate one with: "
"python -c \"from cryptography.fernet import Fernet; "
"print(Fernet.generate_key().decode())\""
) from exc
def encrypt_password(plain: str) -> str:
+2 -2
View File
@@ -414,7 +414,7 @@ def sync_account(
if imap is not None:
try:
imap.logout()
except imaplib.IMAP4.error:
except (imaplib.IMAP4.error, OSError):
pass
if smtp is not None:
try:
@@ -567,7 +567,7 @@ def retry_single_message(db: Session, message_id: int) -> Message:
if imap is not None:
try:
imap.logout()
except imaplib.IMAP4.error:
except (imaplib.IMAP4.error, OSError):
pass
if smtp is not None:
try:
+51
View File
@@ -0,0 +1,51 @@
"""Fernet key validation tests."""
from __future__ import annotations
from unittest.mock import MagicMock, patch
import pytest
from cryptography.fernet import Fernet
from forwarder.crypto import EncryptionError, decrypt_password, get_fernet
def _settings_with_key(key: str):
settings = MagicMock()
settings.encryption_key = key
return settings
def test_get_fernet_raises_encryption_error_when_missing():
with patch("forwarder.crypto.get_settings", return_value=_settings_with_key(" ")):
with pytest.raises(EncryptionError, match="not configured"):
get_fernet()
def test_get_fernet_raises_encryption_error_for_invalid_key():
with patch("forwarder.crypto.get_settings", return_value=_settings_with_key("change_me_fernet_key")):
with pytest.raises(EncryptionError, match="valid Fernet key"):
get_fernet()
def test_get_fernet_does_not_leak_value_error_for_invalid_key():
with patch("forwarder.crypto.get_settings", return_value=_settings_with_key("change_me_fernet_key")):
try:
get_fernet()
except ValueError as exc:
pytest.fail(f"raw ValueError leaked instead of EncryptionError: {exc}")
except EncryptionError:
pass
def test_get_fernet_accepts_generated_key():
valid = Fernet.generate_key().decode()
with patch("forwarder.crypto.get_settings", return_value=_settings_with_key(valid)):
f = get_fernet()
assert isinstance(f, Fernet)
def test_decrypt_password_raises_encryption_error_for_invalid_key():
with patch("forwarder.crypto.get_settings", return_value=_settings_with_key("not-a-fernet-key")):
with pytest.raises(EncryptionError, match="valid Fernet key"):
decrypt_password("some-token")
+57
View File
@@ -0,0 +1,57 @@
"""Tests for IMAP logout handling on a timed-out socket.
Regression test for BIT-33892: ``OSError: cannot read from timed out object``
raised by ``imap.logout()`` when the underlying socket has already timed out.
The ``finally`` block must swallow ``OSError`` alongside ``imaplib.IMAP4.error``
so the sync run can finish cleanly instead of crashing.
"""
from __future__ import annotations
from unittest.mock import MagicMock, patch
import pytest
from forwarder.services.sync_service import sync_account
def test_sync_account_swallows_logout_oserror(monkeypatch):
"""logout() raising OSError (timed-out socket) must not crash sync_account."""
db = MagicMock()
account = MagicMock()
account.id = 1
account.source_type = "imap"
account.delivery_mode = "smtp"
account.imap_host = "imap.example.com"
account.imap_port = 993
account.imap_user = "[email protected]"
account.imap_password_encrypted = b"enc"
account.smtp_host = "smtp.example.com"
account.smtp_port = 587
account.smtp_user = "[email protected]"
account.smtp_password_encrypted = b"enc"
account.smtp_use_tls = True
account.allowed_extensions = None
imap = MagicMock()
imap.logout.side_effect = OSError("cannot read from timed out object")
smtp = MagicMock()
smtp.quit = MagicMock()
def fake_list_mailboxes(_imap):
return []
with (
patch("forwarder.services.sync_service.get_account", return_value=account),
patch("forwarder.services.sync_service.decrypt_password", return_value="secret"),
patch("forwarder.services.sync_service.connect_imap", return_value=imap),
patch("forwarder.services.sync_service.create_smtp_client", return_value=smtp),
patch("forwarder.services.sync_service.list_mailboxes", side_effect=fake_list_mailboxes),
patch("forwarder.services.sync_service._get_known_message_keys", return_value=set()),
):
sync_run = sync_account(db, 1, dry_run=False)
imap.logout.assert_called_once()
smtp.quit.assert_called_once()
assert sync_run.status.value == "completed"