From 66d7189aa5dc280805a881e117735c2ed2ec26c5 Mon Sep 17 00:00:00 2001 From: 1sonhador <1sonhador@gmail.com> Date: Wed, 1 Jul 2026 10:09:52 +0100 Subject: [PATCH] feat: cap SMTP forwards at 200 per rolling hour Count successful forward_attempts in the last hour and stop sync/retry when MAX_FORWARDS_PER_HOUR is reached to protect domain sending limits. --- .env.example | 2 ++ admin-ui/src/lib/api.ts | 1 + admin-ui/src/pages/Emails.tsx | 14 +++++--- src/forwarder/api/routes/messages.py | 11 ++++++- src/forwarder/config.py | 1 + src/forwarder/services/rate_limit.py | 44 ++++++++++++++++++++++++++ src/forwarder/services/sync_service.py | 7 ++++ tests/test_rate_limit.py | 36 +++++++++++++++++++++ 8 files changed, 110 insertions(+), 6 deletions(-) create mode 100644 src/forwarder/services/rate_limit.py create mode 100644 tests/test_rate_limit.py diff --git a/.env.example b/.env.example index 9bba11c..cce0102 100644 --- a/.env.example +++ b/.env.example @@ -15,6 +15,8 @@ ADMIN_PASSWORD=change_me # Worker SYNC_INTERVAL_MINUTES=15 +# Max successful SMTP forwards per rolling hour (0 = unlimited) +MAX_FORWARDS_PER_HOUR=200 # Gitea webhook autodeploy (deploy-hook service on :9090) DEPLOY_WEBHOOK_SECRET=change_me_random_64_chars diff --git a/admin-ui/src/lib/api.ts b/admin-ui/src/lib/api.ts index f14d1e1..d3994cc 100644 --- a/admin-ui/src/lib/api.ts +++ b/admin-ui/src/lib/api.ts @@ -62,6 +62,7 @@ export interface RetryBatchResult { attempted: number succeeded: number failed: number + rate_limited: boolean errors: string[] } diff --git a/admin-ui/src/pages/Emails.tsx b/admin-ui/src/pages/Emails.tsx index edc29be..7d50798 100644 --- a/admin-ui/src/pages/Emails.tsx +++ b/admin-ui/src/pages/Emails.tsx @@ -58,10 +58,12 @@ export default function Emails() { setActionMsg(null) try { const r = await api.messages.retryBatch({ limit }) - const ok = r.succeeded > 0 && r.failed === 0 + const ok = r.succeeded > 0 && r.failed === 0 && !r.rate_limited setActionMsg({ ok, - text: `Batch: ${r.succeeded}/${r.attempted} OK${r.errors.length ? ` — ${r.errors[0]}` : ''}`, + text: r.rate_limited + ? `Limite horário (200/h): ${r.succeeded}/${r.attempted} enviados neste lote.` + : `Batch: ${r.succeeded}/${r.attempted} OK${r.errors.length ? ` — ${r.errors[0]}` : ''}`, }) reload() } catch (e) { @@ -89,7 +91,7 @@ export default function Emails() { return } const ok = confirm( - `Repetir todas as ${failedCount} mensagens falhadas?\n\nIsto pode demorar vários minutos. Mantém a conta inactiva durante o processo.`, + `Repetir todas as ${failedCount} mensagens falhadas?\n\nEnvio limitado a 200/hora — continua automaticamente nas horas seguintes. Mantém a conta inactiva durante o processo.`, ) if (!ok) return @@ -108,11 +110,13 @@ export default function Emails() { ok: false, text: `A repetir… ${totalSucceeded} OK, ${totalFailed} falhas (${totalAttempted} processadas)`, }) - if (r.attempted === 0) break + if (r.attempted === 0 || r.rate_limited) break } setActionMsg({ ok: totalFailed === 0, - text: `Concluído: ${totalSucceeded} reencaminhadas, ${totalFailed} falharam (${totalAttempted} processadas).`, + text: `Concluído: ${totalSucceeded} reencaminhadas, ${totalFailed} falharam (${totalAttempted} processadas).${ + totalAttempted < failedCount ? ' Limite horário — continua mais tarde.' : '' + }`, }) reload() } catch (e) { diff --git a/src/forwarder/api/routes/messages.py b/src/forwarder/api/routes/messages.py index f50b642..0322c0b 100644 --- a/src/forwarder/api/routes/messages.py +++ b/src/forwarder/api/routes/messages.py @@ -7,6 +7,7 @@ from forwarder.api.deps import CurrentUser, DbSession from forwarder.api.schemas import MessageListResponse, MessageResponse from forwarder.db.models import Account, Message, MessageStatus from forwarder.services.sync_service import retry_single_message +from forwarder.services.rate_limit import ForwardRateLimitError router = APIRouter(prefix="/messages", tags=["messages"]) @@ -95,6 +96,7 @@ def retry_batch( succeeded = 0 failed = 0 attempted = 0 + rate_limited = False errors: list[str] = [] while True: @@ -115,18 +117,23 @@ def retry_batch( try: retry_single_message(db, message.id) succeeded += 1 + except ForwardRateLimitError as exc: + rate_limited = True + errors.append(str(exc)) + break except Exception as exc: failed += 1 errors.append(f"#{message.id}: {exc}") attempted += 1 - if not all_failed: + if rate_limited or not all_failed: break return { "attempted": attempted, "succeeded": succeeded, "failed": failed, + "rate_limited": rate_limited, "errors": errors[:10], } @@ -149,6 +156,8 @@ def retry_message( try: updated = retry_single_message(db, message_id) + except ForwardRateLimitError as exc: + raise HTTPException(status_code=429, detail=str(exc)) from exc except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc except Exception as exc: diff --git a/src/forwarder/config.py b/src/forwarder/config.py index b28181a..110c143 100644 --- a/src/forwarder/config.py +++ b/src/forwarder/config.py @@ -18,6 +18,7 @@ class Settings(BaseSettings): admin_username: str = "admin" admin_password: str = "change-me" sync_interval_minutes: int = 15 + max_forwards_per_hour: int = 200 api_host: str = "0.0.0.0" api_port: int = 8000 diff --git a/src/forwarder/services/rate_limit.py b/src/forwarder/services/rate_limit.py new file mode 100644 index 0000000..738cd5e --- /dev/null +++ b/src/forwarder/services/rate_limit.py @@ -0,0 +1,44 @@ +"""Outbound SMTP forward rate limiting (protects domain sending reputation).""" + +from __future__ import annotations + +from datetime import datetime, timedelta, timezone + +from sqlalchemy import func +from sqlalchemy.orm import Session + +from forwarder.config import get_settings +from forwarder.db.models import ForwardAttempt + + +class ForwardRateLimitError(Exception): + """Raised when the hourly forward cap is reached.""" + + def __init__(self, *, limit: int, used: int) -> None: + self.limit = limit + self.used = used + super().__init__(f"Forward rate limit reached ({used}/{limit} per hour)") + + +def count_forwards_last_hour(db: Session) -> int: + since = datetime.now(timezone.utc) - timedelta(hours=1) + return ( + db.query(func.count(ForwardAttempt.id)) + .filter( + ForwardAttempt.success.is_(True), + ForwardAttempt.dry_run.is_(False), + ForwardAttempt.created_at >= since, + ) + .scalar() + or 0 + ) + + +def check_forward_allowed(db: Session) -> None: + settings = get_settings() + limit = settings.max_forwards_per_hour + if limit <= 0: + return + used = count_forwards_last_hour(db) + if used >= limit: + raise ForwardRateLimitError(limit=limit, used=used) diff --git a/src/forwarder/services/sync_service.py b/src/forwarder/services/sync_service.py index 134e530..5976454 100644 --- a/src/forwarder/services/sync_service.py +++ b/src/forwarder/services/sync_service.py @@ -32,6 +32,7 @@ from forwarder.email.parsing import ( from forwarder.email.smtp_client import SmtpConfig, create_smtp_client, forward_invoice_attachments from forwarder.error_reporter import report_error, report_error_with_cooldown from forwarder.services.account_service import get_account +from forwarder.services.rate_limit import ForwardRateLimitError, check_forward_allowed logger = logging.getLogger(__name__) @@ -256,6 +257,7 @@ def sync_account( continue try: + check_forward_allowed(db) forward_invoice_attachments( msg, smtp_config=smtp_config, @@ -282,6 +284,10 @@ def sync_account( result.messages_forwarded += 1 handled_count += 1 logger.info("Forwarded: %s", subject) + except ForwardRateLimitError as exc: + logger.warning("Hourly forward limit reached, stopping sync: %s", exc) + stop_all = True + break except Exception as exc: error_text = str(exc) logger.error("Forward failed for %s: %s", subject, error_text) @@ -389,6 +395,7 @@ def retry_single_message(db: Session, message_id: int) -> Message: smtp = create_smtp_client(smtp_config) allowed_extensions = set(account.allowed_extensions or []) + check_forward_allowed(db) forward_invoice_attachments( msg, smtp_config=smtp_config, diff --git a/tests/test_rate_limit.py b/tests/test_rate_limit.py new file mode 100644 index 0000000..596f533 --- /dev/null +++ b/tests/test_rate_limit.py @@ -0,0 +1,36 @@ +"""Rate limit tests.""" + +from __future__ import annotations + +from unittest.mock import MagicMock, patch + +import pytest + +from forwarder.services.rate_limit import ForwardRateLimitError, check_forward_allowed + + +def test_check_forward_allowed_when_under_limit(): + db = MagicMock() + with patch("forwarder.services.rate_limit.get_settings") as settings: + settings.return_value.max_forwards_per_hour = 200 + with patch("forwarder.services.rate_limit.count_forwards_last_hour", return_value=199): + check_forward_allowed(db) + + +def test_check_forward_allowed_raises_at_limit(): + db = MagicMock() + with patch("forwarder.services.rate_limit.get_settings") as settings: + settings.return_value.max_forwards_per_hour = 200 + with patch("forwarder.services.rate_limit.count_forwards_last_hour", return_value=200): + with pytest.raises(ForwardRateLimitError) as exc: + check_forward_allowed(db) + assert exc.value.limit == 200 + assert exc.value.used == 200 + + +def test_unlimited_when_config_zero(): + db = MagicMock() + with patch("forwarder.services.rate_limit.get_settings") as settings: + settings.return_value.max_forwards_per_hour = 0 + with patch("forwarder.services.rate_limit.count_forwards_last_hour", return_value=9999): + check_forward_allowed(db)