Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
948b6ba2c6 | ||
|
|
54c317e452 | ||
|
|
969dbe08ce | ||
|
|
77ee80d3f1 | ||
|
|
c389503fb9 | ||
|
|
c9d1ad4b48 | ||
|
|
3ca283aa41 | ||
|
|
66dcd1f78e | ||
|
|
f39338a2a9 | ||
|
|
e1ddd2a293 | ||
|
|
f55629212c | ||
|
|
0998a016fa | ||
|
|
e160520655 | ||
|
|
4998a0f009 | ||
|
|
a782a97a1d | ||
|
|
c0c3109174 | ||
|
|
4fd7e51a7c | ||
|
|
ac932323c8 | ||
|
|
5bc5e0d889 | ||
|
|
bc39e00192 | ||
|
|
91b1a726e8 |
No files matched your search
@@ -0,0 +1,30 @@
|
|||||||
|
name: ci
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
pull_request:
|
||||||
|
branches: [main]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
verify:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: PHP 8.5 syntax check (webhook-receiver.php)
|
||||||
|
run: |
|
||||||
|
php -v
|
||||||
|
php -l deploy/webhook-receiver.php
|
||||||
|
|
||||||
|
- name: Setup Node.js 24.22.1
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: "24.22.1"
|
||||||
|
|
||||||
|
- name: Build admin-ui
|
||||||
|
working-directory: admin-ui
|
||||||
|
run: |
|
||||||
|
npm ci
|
||||||
|
npm run build
|
||||||
@@ -50,6 +50,9 @@ processed_emails.json
|
|||||||
storage/deploy-logs/*
|
storage/deploy-logs/*
|
||||||
!storage/deploy-logs/.gitkeep
|
!storage/deploy-logs/.gitkeep
|
||||||
|
|
||||||
|
# Git credentials (deploy-hook container)
|
||||||
|
.git-credentials
|
||||||
|
|
||||||
# OS
|
# OS
|
||||||
.DS_Store
|
.DS_Store
|
||||||
Thumbs.db
|
Thumbs.db
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
FROM node:20-alpine AS build
|
FROM node:24-alpine AS build
|
||||||
ARG GIT_SHA=unknown
|
ARG GIT_SHA=unknown
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY package.json package-lock.json ./
|
COPY package.json package-lock.json ./
|
||||||
|
|||||||
@@ -23,5 +23,8 @@
|
|||||||
"tailwindcss": "^3.4.14",
|
"tailwindcss": "^3.4.14",
|
||||||
"typescript": "^5.6.3",
|
"typescript": "^5.6.3",
|
||||||
"vite": "^5.4.10"
|
"vite": "^5.4.10"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=24.22.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
FROM php:8.3-cli-alpine
|
FROM php:8.5-cli-alpine
|
||||||
|
|
||||||
RUN apk add --no-cache bash git curl docker-cli docker-cli-compose
|
RUN apk add --no-cache bash git curl docker-cli docker-cli-compose
|
||||||
|
|
||||||
|
|||||||
@@ -66,12 +66,13 @@ log "Building API + worker ($GIT_SHA)"
|
|||||||
$COMPOSE build --build-arg GIT_SHA="$GIT_SHA" web
|
$COMPOSE build --build-arg GIT_SHA="$GIT_SHA" web
|
||||||
remove_stale_service_containers web
|
remove_stale_service_containers web
|
||||||
$COMPOSE up -d --force-recreate 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
|
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..."
|
log "API not ready yet (attempt $i/5), retrying in 5s..."
|
||||||
sleep 5
|
sleep 5
|
||||||
done
|
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)"
|
write_status "ok $GIT_SHA $(date -Iseconds)"
|
||||||
log "Deploy OK ($GIT_SHA)"
|
log "Deploy OK ($GIT_SHA)"
|
||||||
log "Refreshing deploy-hook (self-restart — runs detached)"
|
log "Refreshing deploy-hook (self-restart — runs detached)"
|
||||||
|
|||||||
@@ -13,7 +13,12 @@ def get_fernet() -> Fernet:
|
|||||||
key = get_settings().encryption_key.strip()
|
key = get_settings().encryption_key.strip()
|
||||||
if not key:
|
if not key:
|
||||||
raise EncryptionError("ENCRYPTION_KEY is not configured")
|
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:
|
def encrypt_password(plain: str) -> str:
|
||||||
|
|||||||
@@ -12,6 +12,9 @@ MIN_PDF_BYTES = 1024
|
|||||||
MIN_XML_BYTES = 80
|
MIN_XML_BYTES = 80
|
||||||
MIN_ZIP_BYTES = 22
|
MIN_ZIP_BYTES = 22
|
||||||
|
|
||||||
|
_PDF_MAGIC = b"%PDF-"
|
||||||
|
_PDF_HEADER_SCAN_BYTES = 1024
|
||||||
|
|
||||||
MIN_IMAGE_WIDTH = 200
|
MIN_IMAGE_WIDTH = 200
|
||||||
MIN_IMAGE_HEIGHT = 200
|
MIN_IMAGE_HEIGHT = 200
|
||||||
|
|
||||||
@@ -124,12 +127,18 @@ def _image_meets_min_dimensions(data: bytes, ext: str) -> bool:
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def _find_pdf_magic(data: bytes) -> int | None:
|
||||||
|
"""Return byte offset of %PDF- within the header window, or None."""
|
||||||
|
if not data:
|
||||||
|
return None
|
||||||
|
index = data[:_PDF_HEADER_SCAN_BYTES].find(_PDF_MAGIC)
|
||||||
|
return index if index >= 0 else None
|
||||||
|
|
||||||
|
|
||||||
def _is_valid_pdf(data: bytes) -> bool:
|
def _is_valid_pdf(data: bytes) -> bool:
|
||||||
if len(data) < MIN_PDF_BYTES:
|
if len(data) < MIN_PDF_BYTES:
|
||||||
return False
|
return False
|
||||||
if not data.startswith(b"%PDF-"):
|
return _find_pdf_magic(data) is not None
|
||||||
return False
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
def _is_valid_xml(data: bytes) -> bool:
|
def _is_valid_xml(data: bytes) -> bool:
|
||||||
@@ -199,7 +208,12 @@ def is_plausible_invoice_file(
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
if ext == ".pdf" or content_type == "application/pdf":
|
if ext == ".pdf" or content_type == "application/pdf":
|
||||||
return _is_valid_pdf(data)
|
if _is_valid_pdf(data):
|
||||||
|
return True
|
||||||
|
# Some mobile scanners store JPEG/PNG bytes under a .pdf filename.
|
||||||
|
if _is_valid_image(data, ".jpeg") or _is_valid_image(data, ".png"):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
if ext == ".xml" or content_type in ("application/xml", "text/xml"):
|
if ext == ".xml" or content_type in ("application/xml", "text/xml"):
|
||||||
return _is_valid_xml(data)
|
return _is_valid_xml(data)
|
||||||
@@ -208,3 +222,41 @@ def is_plausible_invoice_file(
|
|||||||
return _is_valid_zip(data)
|
return _is_valid_zip(data)
|
||||||
|
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def invoice_validation_failure_reason(
|
||||||
|
data: bytes,
|
||||||
|
*,
|
||||||
|
filename: str,
|
||||||
|
content_type: str,
|
||||||
|
) -> str | None:
|
||||||
|
"""Human-readable reason when is_plausible_invoice_file would return False."""
|
||||||
|
if is_plausible_invoice_file(data, filename=filename, content_type=content_type):
|
||||||
|
return None
|
||||||
|
|
||||||
|
ext = _extension_from_filename(filename)
|
||||||
|
content_type = (content_type or "").lower()
|
||||||
|
|
||||||
|
if not data:
|
||||||
|
return "empty file"
|
||||||
|
|
||||||
|
if ext == ".pdf" or content_type == "application/pdf":
|
||||||
|
if len(data) < MIN_PDF_BYTES:
|
||||||
|
return f"too small ({len(data)} bytes, min {MIN_PDF_BYTES})"
|
||||||
|
if _find_pdf_magic(data) is None:
|
||||||
|
head = data[:16].hex()
|
||||||
|
return f"PDF header %PDF- not found in first {_PDF_HEADER_SCAN_BYTES} bytes (head={head})"
|
||||||
|
return "not a valid PDF or invoice scan image"
|
||||||
|
|
||||||
|
if ext in (".png", ".jpg", ".jpeg") or content_type.startswith("image/"):
|
||||||
|
if len(data) < MIN_IMAGE_BYTES:
|
||||||
|
return f"image too small ({len(data)} bytes, min {MIN_IMAGE_BYTES})"
|
||||||
|
return "image below minimum dimensions or invalid format"
|
||||||
|
|
||||||
|
if ext == ".xml" or content_type in ("application/xml", "text/xml"):
|
||||||
|
return "invalid or too small XML"
|
||||||
|
|
||||||
|
if ext == ".zip" or content_type in ("application/zip", "application/x-zip-compressed"):
|
||||||
|
return "invalid or too small ZIP"
|
||||||
|
|
||||||
|
return f"unsupported type ({ext or content_type or 'unknown'})"
|
||||||
@@ -12,7 +12,10 @@ import smtplib
|
|||||||
from forwarder.bizdocs.client import BizdocsClient, BizdocsCredentials, BizdocsSession
|
from forwarder.bizdocs.client import BizdocsClient, BizdocsCredentials, BizdocsSession
|
||||||
from forwarder.bizdocs.errors import BizdocsError
|
from forwarder.bizdocs.errors import BizdocsError
|
||||||
from forwarder.db.models import Account, DEFAULT_ALLOWED_EXTENSIONS, DeliveryMode
|
from forwarder.db.models import Account, DEFAULT_ALLOWED_EXTENSIONS, DeliveryMode
|
||||||
from forwarder.email.invoice_validation import is_plausible_invoice_file
|
from forwarder.email.invoice_validation import (
|
||||||
|
invoice_validation_failure_reason,
|
||||||
|
is_plausible_invoice_file,
|
||||||
|
)
|
||||||
from forwarder.email.parsing import InvoiceAttachment, collect_matching_attachments
|
from forwarder.email.parsing import InvoiceAttachment, collect_matching_attachments
|
||||||
from forwarder.email.smtp_client import SmtpConfig, create_smtp_client, forward_invoice_attachments
|
from forwarder.email.smtp_client import SmtpConfig, create_smtp_client, forward_invoice_attachments
|
||||||
|
|
||||||
@@ -104,7 +107,15 @@ def deliver_invoice_file(
|
|||||||
content_type = _content_type_for_filename(filename)
|
content_type = _content_type_for_filename(filename)
|
||||||
|
|
||||||
if not is_plausible_invoice_file(data, filename=filename, content_type=content_type):
|
if not is_plausible_invoice_file(data, filename=filename, content_type=content_type):
|
||||||
raise ValueError(f"File {filename} failed invoice validation")
|
detail = invoice_validation_failure_reason(
|
||||||
|
data,
|
||||||
|
filename=filename,
|
||||||
|
content_type=content_type,
|
||||||
|
)
|
||||||
|
message = f"File {filename} failed invoice validation"
|
||||||
|
if detail:
|
||||||
|
message = f"{message}: {detail}"
|
||||||
|
raise ValueError(message)
|
||||||
|
|
||||||
if account.delivery_mode == DeliveryMode.api:
|
if account.delivery_mode == DeliveryMode.api:
|
||||||
if bizdocs_session is None:
|
if bizdocs_session is None:
|
||||||
|
|||||||
@@ -260,7 +260,7 @@ def sync_account(
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
msg = fetch_message(imap, uid)
|
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)
|
logger.error("Fetch error UID %s in %s: %s", uid_str, folder, exc)
|
||||||
result.messages_failed += 1
|
result.messages_failed += 1
|
||||||
continue
|
continue
|
||||||
@@ -414,7 +414,7 @@ def sync_account(
|
|||||||
if imap is not None:
|
if imap is not None:
|
||||||
try:
|
try:
|
||||||
imap.logout()
|
imap.logout()
|
||||||
except imaplib.IMAP4.error:
|
except (imaplib.IMAP4.error, OSError):
|
||||||
pass
|
pass
|
||||||
if smtp is not None:
|
if smtp is not None:
|
||||||
try:
|
try:
|
||||||
@@ -567,7 +567,7 @@ def retry_single_message(db: Session, message_id: int) -> Message:
|
|||||||
if imap is not None:
|
if imap is not None:
|
||||||
try:
|
try:
|
||||||
imap.logout()
|
imap.logout()
|
||||||
except imaplib.IMAP4.error:
|
except (imaplib.IMAP4.error, OSError):
|
||||||
pass
|
pass
|
||||||
if smtp is not None:
|
if smtp is not None:
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
# Reject HTML stubs / placeholders before download when PROPFIND reports size.
|
# Reject HTML stubs / placeholders before download when PROPFIND reports size.
|
||||||
MIN_WEBDAV_FILE_BYTES = 4 * 1024
|
MIN_WEBDAV_FILE_BYTES = 4 * 1024
|
||||||
|
WEBDAV_LIST_TIMEOUT_SECONDS = 180.0
|
||||||
|
|
||||||
OC_NS = "{http://owncloud.org/ns}"
|
OC_NS = "{http://owncloud.org/ns}"
|
||||||
NC_NS = "{http://nextcloud.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
|
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]:
|
def list_files(config: WebdavConfig) -> list[WebdavFile]:
|
||||||
root_url = build_webdav_root(config)
|
root_url = build_webdav_root(config)
|
||||||
headers = {"Depth": "infinity", "Content-Type": "application/xml; charset=utf-8"}
|
|
||||||
|
|
||||||
with _client(config) as client:
|
try:
|
||||||
response = client.request("PROPFIND", root_url, content=PROPFIND_BODY, headers=headers)
|
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:
|
if response.status_code == 404:
|
||||||
raise WebdavNotFoundError(f"WebDAV folder not found: {root_url}")
|
raise WebdavNotFoundError(f"WebDAV folder not found: {root_url}")
|
||||||
|
|||||||
@@ -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"
|
||||||
@@ -112,6 +112,33 @@ def test_accepts_valid_pdf_attachment():
|
|||||||
assert len(collect_matching_attachments(msg)) == 1
|
assert len(collect_matching_attachments(msg)) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_accepts_pdf_with_leading_whitespace():
|
||||||
|
pdf = b" \n\r\t" + b"%PDF-1.4\n" + (b"% invoice body\n" * 80)
|
||||||
|
assert is_plausible_invoice_file(
|
||||||
|
pdf,
|
||||||
|
filename="1784074260.pdf",
|
||||||
|
content_type="application/pdf",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_accepts_pdf_with_utf8_bom():
|
||||||
|
pdf = b"\xef\xbb\xbf%PDF-1.4\n" + (b"% body\n" * 150)
|
||||||
|
assert is_plausible_invoice_file(
|
||||||
|
pdf,
|
||||||
|
filename="scan.pdf",
|
||||||
|
content_type="application/pdf",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_accepts_jpeg_bytes_with_pdf_extension():
|
||||||
|
data = _fake_jpeg(800, 1200)
|
||||||
|
assert is_plausible_invoice_file(
|
||||||
|
data,
|
||||||
|
filename="1784074260.pdf",
|
||||||
|
content_type="application/pdf",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def test_rejects_truncated_pdf():
|
def test_rejects_truncated_pdf():
|
||||||
msg = _msg_with_part(
|
msg = _msg_with_part(
|
||||||
data=b"%PDF",
|
data=b"%PDF",
|
||||||
|
|||||||
@@ -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"
|
||||||
@@ -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
|
||||||
@@ -4,9 +4,11 @@ from forwarder.webdav.client import (
|
|||||||
MIN_WEBDAV_FILE_BYTES,
|
MIN_WEBDAV_FILE_BYTES,
|
||||||
WebdavConfig,
|
WebdavConfig,
|
||||||
WebdavFile,
|
WebdavFile,
|
||||||
|
_parse_propfind_collections,
|
||||||
_parse_propfind_response,
|
_parse_propfind_response,
|
||||||
build_webdav_root,
|
build_webdav_root,
|
||||||
get_webdav_message_key,
|
get_webdav_message_key,
|
||||||
|
list_files,
|
||||||
normalize_webdav_folder_path,
|
normalize_webdav_folder_path,
|
||||||
parse_webdav_message_key,
|
parse_webdav_message_key,
|
||||||
webdav_bytes_below_min_size,
|
webdav_bytes_below_min_size,
|
||||||
@@ -232,3 +234,138 @@ def test_parse_propfind_response():
|
|||||||
assert not webdav_file_matches_min_year(invoice, 2025)
|
assert not webdav_file_matches_min_year(invoice, 2025)
|
||||||
photo = next(item for item in files if item.name == "photo.jpg")
|
photo = next(item for item in files if item.name == "photo.jpg")
|
||||||
assert webdav_file_matches_min_year(photo, 2025)
|
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())
|
||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
# Build stage — compile the React admin UI
|
# Build stage — compile the React admin UI
|
||||||
FROM node:20-alpine AS builder
|
FROM node:24-alpine AS builder
|
||||||
|
|
||||||
WORKDIR /build
|
WORKDIR /build
|
||||||
COPY admin-ui/package*.json ./
|
COPY admin-ui/package*.json ./
|
||||||
|
|||||||
Reference in new issue
Block a user