Author SHA1 Message Date
spark 948b6ba2c6 Merge pull request 'fix(crypto): catch ValueError on malformed Fernet key, raise EncryptionError (BIT-33940)' (#12) from fix/BIT-33940-fernet-key-validation into main
ci / verify (push) Successful in 32s
2026-12-04 10:32:08 +00:00
spark 54c317e452 fix(deploy): configurable health check URL for deploy-hook container (BIT-33898) (#10)
ci / verify (push) Successful in 53s
2026-12-04 10:19:41 +00:00
Xika 969dbe08ce fix(crypto): catch ValueError on malformed Fernet key, raise EncryptionError (BIT-33940)
ci / verify (pull_request) Successful in 49s
get_fernet() only checked for an empty ENCRYPTION_KEY. A non-empty but
malformed key (not 32 url-safe base64 bytes) let Fernet() raise a raw
ValueError that crashed sync_account. Wrap the constructor and re-raise
as EncryptionError with a clear message.

Paperclip-BIT-33940
2026-12-04 10:18:29 +00:00
Xika 77ee80d3f1 fix(deploy): configurable health check URL for deploy-hook container (BIT-33898)
ci / verify (pull_request) Successful in 35s
The deploy-pull.sh health check used 127.0.0.1:8000 which doesn't
reach the API from inside the deploy-hook container (separate network
namespace). Add HEALTH_CHECK_URL env var so the container can use
http://api:8000 via Docker DNS. Also add .git-credentials to .gitignore
for the credential file mounted into the deploy-hook container.

Paperclip-Issue: BIT-33898
Paperclip-Agent: nelson-baptista
2026-12-04 10:16:28 +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
Xika 66dcd1f78e fix(imap): catch TimeoutError on per-message fetch so sync continues (BIT-33891)
ci / verify (pull_request) Successful in 26s
TimeoutError (OSError subclass) escaped the imaplib.IMAP4.error handler
in sync_account, killing the entire sync run on a single slow fetch.
Catch OSError alongside IMAP4.error to skip the timed-out message and
continue scanning.

Paperclip-BIT-33891
2026-12-03 23:17:08 +00:00
bug-squasher f39338a2a9 fix(webdav): fall back to Depth:1 recursion when PROPFIND infinity returns HTTP 500 (BIT-33518) (#7)
ci / verify (push) Successful in 28s
Depth:infinity PROPFIND returns HTTP 500 on servers that disable it (Nextcloud/ownCloud/mod_dav). list_files now falls back to recursive Depth:1 traversal, preserving full relative paths for year-folder filtering and dedup.

BIT-33518
Paperclip-Ref: BIT-33518
2026-11-29 01:18:42 +00:00
7 changed files with 173 additions and 6 deletions

No files matched your search

+3
View File
@@ -50,6 +50,9 @@ processed_emails.json
storage/deploy-logs/*
!storage/deploy-logs/.gitkeep
# Git credentials (deploy-hook container)
.git-credentials
# OS
.DS_Store
Thumbs.db
+3 -2
View File
@@ -66,12 +66,13 @@ log "Building API + worker ($GIT_SHA)"
$COMPOSE build --build-arg GIT_SHA="$GIT_SHA" web
remove_stale_service_containers web
$COMPOSE up -d --force-recreate web
HEALTH_URL="${HEALTH_CHECK_URL:-http://127.0.0.1:8000/api/health}"
for i in 1 2 3 4 5; do
curl -sf --max-time 8 http://127.0.0.1:8000/api/health >/dev/null && break
curl -sf --max-time 8 "$HEALTH_URL" >/dev/null && break
log "API not ready yet (attempt $i/5), retrying in 5s..."
sleep 5
done
curl -sf --max-time 8 http://127.0.0.1:8000/api/health >/dev/null
curl -sf --max-time 8 "$HEALTH_URL" >/dev/null
write_status "ok $GIT_SHA $(date -Iseconds)"
log "Deploy OK ($GIT_SHA)"
log "Refreshing deploy-hook (self-restart — runs detached)"
+6 -1
View File
@@ -13,7 +13,12 @@ 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)
try:
return Fernet(key.encode() if isinstance(key, str) else key)
except ValueError as exc:
raise EncryptionError(
"ENCRYPTION_KEY must be 32 url-safe base64-encoded bytes"
) from exc
def encrypt_password(plain: str) -> str:
+3 -3
View File
@@ -260,7 +260,7 @@ def sync_account(
try:
msg = fetch_message(imap, uid)
except imaplib.IMAP4.error as exc:
except (imaplib.IMAP4.error, OSError) as exc:
logger.error("Fetch error UID %s in %s: %s", uid_str, folder, exc)
result.messages_failed += 1
continue
@@ -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:
+47
View File
@@ -0,0 +1,47 @@
"""Crypto / Fernet key tests."""
from __future__ import annotations
from unittest.mock import patch
import pytest
from cryptography.fernet import Fernet
from forwarder.crypto import EncryptionError, decrypt_password, encrypt_password, get_fernet
def _make_settings(key: str):
fake = type("FakeSettings", (), {"encryption_key": key})()
return fake
def test_get_fernet_with_valid_key():
key = Fernet.generate_key().decode()
with patch("forwarder.crypto.get_settings", return_value=_make_settings(key)):
f = get_fernet()
assert isinstance(f, Fernet)
def test_get_fernet_empty_key_raises_encryption_error():
with patch("forwarder.crypto.get_settings", return_value=_make_settings("")):
with pytest.raises(EncryptionError, match="not configured"):
get_fernet()
def test_get_fernet_invalid_key_raises_encryption_error():
with patch("forwarder.crypto.get_settings", return_value=_make_settings("not-a-valid-fernet-key")):
with pytest.raises(EncryptionError, match="32 url-safe base64"):
get_fernet()
def test_decrypt_password_with_invalid_key_raises_encryption_error():
with patch("forwarder.crypto.get_settings", return_value=_make_settings("bad-key")):
with pytest.raises(EncryptionError, match="32 url-safe base64"):
decrypt_password("some-token")
def test_encrypt_then_decrypt_roundtrip():
key = Fernet.generate_key().decode()
with patch("forwarder.crypto.get_settings", return_value=_make_settings(key)):
token = encrypt_password("secret123")
assert decrypt_password(token) == "secret123"
+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"
+54
View File
@@ -0,0 +1,54 @@
"""Tests for IMAP timeout handling in sync_account."""
from __future__ import annotations
from unittest.mock import MagicMock, patch
from forwarder.db.models import DeliveryMode, SourceType, SyncRunStatus
from forwarder.services.sync_service import sync_account
def _make_account() -> MagicMock:
account = MagicMock()
account.source_type = SourceType.imap
account.imap_host = "imap.example.com"
account.imap_port = 993
account.imap_user = "[email protected]"
account.imap_password_encrypted = b"encrypted"
account.delivery_mode = DeliveryMode.api
account.bizdocs_password_encrypted = b"encrypted"
account.allowed_extensions = None
account.imap_folder_selection_mode = "default"
account.imap_selected_folders = None
account.include_all_attachments = False
return account
def test_sync_continues_after_fetch_timeout():
"""A TimeoutError on fetch_message must not kill the entire sync run."""
db = MagicMock()
db.query.return_value.filter.return_value.all.return_value = []
imap = MagicMock()
imap.uid.side_effect = lambda *args: ("OK", [b"1 2"]) if args[0] == "search" else ("OK", [None])
account = _make_account()
fetch_calls: list = []
def _fetch_side_effect(_imap, uid):
fetch_calls.append(uid)
raise TimeoutError("The read operation timed out")
with patch("forwarder.services.sync_service.get_account", return_value=account):
with patch("forwarder.services.sync_service.decrypt_password", return_value="secret"):
with patch("forwarder.services.sync_service.connect_imap", return_value=imap):
with patch("forwarder.services.sync_service.list_mailboxes", return_value=["INBOX"]):
with patch("forwarder.services.sync_service.select_folder_readonly", return_value=True):
with patch("forwarder.services.sync_service.fetch_message", side_effect=_fetch_side_effect):
with patch("forwarder.services.sync_service.report_error_with_cooldown"):
sync_run = sync_account(db, 1, dry_run=True)
assert sync_run.status == SyncRunStatus.completed
assert sync_run.messages_failed == 2
assert len(fetch_calls) == 2