Author SHA1 Message Date
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
Xika e1ddd2a293 fix(webdav): fall back to Depth:1 recursion when PROPFIND infinity returns HTTP 500
ci / verify (pull_request) Successful in 30s
Some WebDAV servers (Nextcloud, ownCloud, Apache mod_dav with infinite
depth disabled) reject Depth:infinity PROPFIND with HTTP 500/403/501.
list_files now retries with a recursive Depth:1 traversal of child
collections, preserving full relative paths for year-folder filtering
and dedup keys.

BIT-33518
Paperclip-Ref: BIT-33518
2026-11-29 01:17:52 +00:00
spark f55629212c Merge pull request 'chore(runtime): PHP 8.5 + Node.js 24.22.1 baseline (BIT-31720)' (#6) from task/BIT-31720-runtime-baseline into main
ci / verify (push) Successful in 51s
Merge PR #6 (BIT-31720)
2026-10-23 18:43:33 +01:00
4 changed files with 271 additions and 4 deletions

No files matched your search

+1 -1
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
+79 -3
View File
@@ -16,6 +16,7 @@ logger = logging.getLogger(__name__)
# Reject HTML stubs / placeholders before download when PROPFIND reports size.
MIN_WEBDAV_FILE_BYTES = 4 * 1024
WEBDAV_LIST_TIMEOUT_SECONDS = 180.0
OC_NS = "{http://owncloud.org/ns}"
NC_NS = "{http://nextcloud.org/ns}"
@@ -325,12 +326,87 @@ def _parse_propfind_response(root_url: str, content: bytes) -> list[WebdavFile]:
return files
def _propfind(
client: httpx.Client,
url: str,
depth: str,
) -> httpx.Response:
headers = {"Depth": depth, "Content-Type": "application/xml; charset=utf-8"}
return client.request("PROPFIND", url, content=PROPFIND_BODY, headers=headers)
def _parse_propfind_collections(root_url: str, content: bytes) -> list[str]:
"""Return absolute URLs of child collections (excluding root) in a PROPFIND body."""
try:
root = element_tree.fromstring(content)
except element_tree.ParseError as exc:
raise WebdavError("Invalid PROPFIND XML response") from exc
base = root_url.rstrip("/") + "/"
children: list[str] = []
for response_elem in root.findall(f"{DAV_NS}response"):
if not _is_collection(response_elem):
continue
href = _element_text(response_elem, "href")
if not href:
continue
absolute = href if href.startswith("http") else urljoin(base, href)
if absolute.rstrip("/") == root_url.rstrip("/"):
continue
if absolute.startswith(base):
children.append(absolute)
return children
def _list_files_depth_one_recursive(config: WebdavConfig) -> list[WebdavFile]:
"""Recursive Depth:1 traversal for servers that reject Depth: infinity."""
root_url = build_webdav_root(config)
files: list[WebdavFile] = []
seen_collections: set[str] = set()
with _client(config, timeout=WEBDAV_LIST_TIMEOUT_SECONDS) as client:
queue: list[str] = [root_url]
while queue:
url = queue.pop(0)
response = _propfind(client, url, "1")
if response.status_code == 404:
raise WebdavNotFoundError(f"WebDAV folder not found: {url}")
if response.status_code == 401:
raise WebdavError("WebDAV authentication failed (401)")
if response.status_code >= 400:
raise WebdavError(
f"PROPFIND failed: HTTP {response.status_code} {response.text[:200]}"
)
files.extend(_parse_propfind_response(root_url, response.content))
for child in _parse_propfind_collections(url, response.content):
if child not in seen_collections:
seen_collections.add(child)
queue.append(child)
return files
# Status codes that typically indicate "Depth: infinity not supported".
_DEPTH_INFINITY_UNSUPPORTED = {403, 500, 501}
def list_files(config: WebdavConfig) -> list[WebdavFile]:
root_url = build_webdav_root(config)
headers = {"Depth": "infinity", "Content-Type": "application/xml; charset=utf-8"}
with _client(config) as client:
response = client.request("PROPFIND", root_url, content=PROPFIND_BODY, headers=headers)
try:
with _client(config, timeout=WEBDAV_LIST_TIMEOUT_SECONDS) as client:
response = _propfind(client, root_url, "infinity")
except httpx.TimeoutException as exc:
raise WebdavError(
f"PROPFIND timed out after {WEBDAV_LIST_TIMEOUT_SECONDS:.0f}s: {root_url}"
) from exc
if response.status_code in _DEPTH_INFINITY_UNSUPPORTED:
logger.warning(
"WebDAV PROPFIND Depth:infinity returned HTTP %s; falling back to Depth:1 recursion",
response.status_code,
)
return _list_files_depth_one_recursive(config)
if response.status_code == 404:
raise WebdavNotFoundError(f"WebDAV folder not found: {root_url}")
+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
+137
View File
@@ -4,9 +4,11 @@ from forwarder.webdav.client import (
MIN_WEBDAV_FILE_BYTES,
WebdavConfig,
WebdavFile,
_parse_propfind_collections,
_parse_propfind_response,
build_webdav_root,
get_webdav_message_key,
list_files,
normalize_webdav_folder_path,
parse_webdav_message_key,
webdav_bytes_below_min_size,
@@ -232,3 +234,138 @@ def test_parse_propfind_response():
assert not webdav_file_matches_min_year(invoice, 2025)
photo = next(item for item in files if item.name == "photo.jpg")
assert webdav_file_matches_min_year(photo, 2025)
def _propfind_response(folder_href: str, entries: list[dict]) -> bytes:
"""Build a minimal DAV multistatus body for tests."""
parts = [
b'<?xml version="1.0" encoding="utf-8"?>',
b'<D:multistatus xmlns:D="DAV:">',
]
for entry in entries:
is_collection = entry.get("collection", False)
href = entry["href"].encode()
parts.append(b" <D:response>")
parts.append(b" <D:href>" + href + b"</D:href>")
parts.append(b" <D:propstat><D:prop>")
if is_collection:
parts.append(b" <D:resourcetype><D:collection/></D:resourcetype>")
else:
parts.append(b" <D:resourcetype/>")
parts.append(b" <D:getetag>" + entry.get("etag", b'"x"') + b"</D:getetag>")
parts.append(
b" <D:getlastmodified>"
+ entry.get("modified", b"Mon, 01 Jan 2024 10:00:00 GMT")
+ b"</D:getlastmodified>"
)
parts.append(
b" <D:getcontentlength>"
+ str(entry.get("size", 5000)).encode()
+ b"</D:getcontentlength>"
)
parts.append(b" </D:prop></D:propstat>")
parts.append(b" </D:response>")
parts.append(b"</D:multistatus>")
return b"\n".join(parts)
ROOT_URL = "https://cloud.example.com/remote.php/dav/files/user/Faturas"
def _make_config() -> WebdavConfig:
return WebdavConfig(
base_url="https://cloud.example.com/remote.php/dav/files/user",
folder_path="/Faturas",
user="user",
password="secret",
verify_ssl=False,
)
def test_parse_propfind_collections_skips_root():
body = _propfind_response(
ROOT_URL + "/",
[
{"href": ROOT_URL + "/", "collection": True},
{"href": ROOT_URL + "/2025/", "collection": True},
{"href": ROOT_URL + "/invoice.pdf"},
],
)
children = _parse_propfind_collections(ROOT_URL, body)
assert children == [ROOT_URL + "/2025/"]
def test_list_files_falls_back_to_depth_one_on_http_500(monkeypatch):
"""Depth:infinity returning HTTP 500 triggers recursive Depth:1 traversal."""
import httpx
import forwarder.webdav.client as webdav_client
root_body = _propfind_response(
ROOT_URL + "/",
[
{"href": ROOT_URL + "/", "collection": True},
{"href": ROOT_URL + "/2025/", "collection": True},
{"href": ROOT_URL + "/invoice.pdf", "etag": b'"abc"'},
],
)
sub_body = _propfind_response(
ROOT_URL + "/2025/",
[
{"href": ROOT_URL + "/2025/", "collection": True},
{"href": ROOT_URL + "/2025/receipt.pdf", "etag": b'"def"', "size": 9000},
],
)
def handler(request: httpx.Request) -> httpx.Response:
depth = request.headers.get("Depth")
url = str(request.url).rstrip("/")
if depth == "infinity":
return httpx.Response(500, text="infinite depth disabled")
if url == ROOT_URL and depth == "1":
return httpx.Response(207, content=root_body)
if url == ROOT_URL + "/2025" and depth == "1":
return httpx.Response(207, content=sub_body)
return httpx.Response(404)
transport = httpx.MockTransport(handler)
def _fake_client(config, *, timeout=60.0):
return httpx.Client(
transport=transport,
auth=(config.user, config.password),
headers={"User-Agent": "Bizdocs-Forwarder/1.0"},
)
monkeypatch.setattr(webdav_client, "_client", _fake_client)
files = list_files(_make_config())
paths = sorted(item.relative_path for item in files)
assert paths == ["2025/receipt.pdf", "invoice.pdf"]
receipt = next(item for item in files if item.name == "receipt.pdf")
assert receipt.size == 9000
assert webdav_file_matches_min_year(receipt, 2025)
def test_list_files_still_raises_on_persistent_500(monkeypatch):
"""A 500 that is not resolved by Depth:1 fallback surfaces as WebdavError."""
import httpx
import forwarder.webdav.client as webdav_client
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(500, text="server error")
transport = httpx.MockTransport(handler)
def _fake_client(config, *, timeout=60.0):
return httpx.Client(
transport=transport,
auth=(config.user, config.password),
headers={"User-Agent": "Bizdocs-Forwarder/1.0"},
)
monkeypatch.setattr(webdav_client, "_client", _fake_client)
import pytest
with pytest.raises(webdav_client.WebdavError):
list_files(_make_config())