fix(connection): fail-fast IMAP/SMTP tests; add Gitea webhook autodeploy

Connection tests use 5s timeouts and run IMAP/SMTP in parallel so the UI
gets a clear error instead of nginx 504. Add deploy-hook service (:9090) and
deploy-pull.sh for push-to-main deploys on CT 243.
This commit is contained in:
1sonhador committed 2026-07-01 01:09:53 +01:00
1 parent d476cb0204
commit f6b276511a
12 files changed
+270 -31

No files matched your search

+5
View File
@@ -15,3 +15,8 @@ ADMIN_PASSWORD=change_me
# Worker # Worker
SYNC_INTERVAL_MINUTES=15 SYNC_INTERVAL_MINUTES=15
# Gitea webhook autodeploy (deploy-hook service on :9090)
DEPLOY_WEBHOOK_SECRET=change_me_random_64_chars
# On CT 243 production, set absolute path to clone:
# FORWARDER_REPO_DIR=/opt/forwarder
+2
View File
@@ -47,6 +47,8 @@ processed_emails.json
# Docker # Docker
*.log *.log
storage/deploy-logs/*
!storage/deploy-logs/.gitkeep
# OS # OS
.DS_Store .DS_Store
+30 -4
View File
@@ -40,11 +40,37 @@ forwarder worker # second terminal
cd admin-ui && npm install && npm run dev # third terminal cd admin-ui && npm install && npm run dev # third terminal
``` ```
## Deploy (Proxmox CT) ## Deploy (Proxmox CT 243)
**Autodeploy:** push to `main` on Gitea → webhook → `deploy-hook` (:9090) → `deploy/deploy-pull.sh` → `docker compose build && up`.
### One-time setup (CT)
```bash ```bash
git clone https://git.bitreport.pt/BitReport.pt/forwarder.git git clone https://git.bitreport.pt/BitReport.pt/forwarder.git /opt/forwarder
cd forwarder && cp .env.example .env cd /opt/forwarder
cp .env.example .env # or ln -s /etc/forwarder/forwarder.env .env
# Set DEPLOY_WEBHOOK_SECRET in .env (same value as Gitea webhook secret)
export FORWARDER_REPO_DIR=/opt/forwarder
docker compose up -d --build docker compose up -d --build
docker compose exec api alembic upgrade head ```
### Gitea webhook
Repo → Settings → Webhooks → Add:
| Field | Value |
|-------|-------|
| URL | `http://10.10.50.43:9090/` |
| Secret | same as `DEPLOY_WEBHOOK_SECRET` in `.env` |
| Events | Push |
Test: `curl -s http://10.10.50.43:9090/` → `{"status":"ok",...}`
Deploy logs: `/opt/forwarder/storage/deploy-logs/`
### Manual deploy (emergency only)
```bash
cd /opt/forwarder && bash deploy/deploy-pull.sh
``` ```
+2 -1
View File
@@ -13,8 +13,9 @@ server {
proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 30s; proxy_read_timeout 15s;
proxy_connect_timeout 5s; proxy_connect_timeout 5s;
proxy_send_timeout 15s;
} }
location / { location / {
+10
View File
@@ -0,0 +1,10 @@
FROM php:8.3-cli-alpine
RUN apk add --no-cache bash git curl docker-cli docker-cli-compose
WORKDIR /opt/deploy
COPY deploy-pull.sh webhook-receiver.php ./
RUN chmod +x deploy-pull.sh
EXPOSE 8080
CMD ["php", "-S", "0.0.0.0:8080", "webhook-receiver.php"]
+45
View File
@@ -0,0 +1,45 @@
#!/usr/bin/env bash
# BizDocs Forwarder — pull from Gitea + docker compose rebuild (CT 243 / /opt/forwarder).
# Invoked by deploy-hook webhook or manually after SSH setup.
set -euo pipefail
REPO_DIR="${FORWARDER_REPO_DIR:-/opt/forwarder}"
DEPLOY_BRANCH="${DEPLOY_BRANCH:-main}"
COMPOSE="docker compose"
log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] [forwarder-deploy] $*"; }
if [ ! -d "$REPO_DIR/.git" ]; then
log "FATAL: git repo missing at $REPO_DIR"
exit 1
fi
cd "$REPO_DIR"
log "Fetching origin/$DEPLOY_BRANCH"
git fetch origin "$DEPLOY_BRANCH"
git reset --hard "origin/$DEPLOY_BRANCH"
log "HEAD $(git rev-parse --short HEAD) — $(git log -1 --format=%s)"
if [ ! -f .env ] && [ -f /etc/forwarder/forwarder.env ]; then
log "Linking .env from /etc/forwarder/forwarder.env"
ln -sf /etc/forwarder/forwarder.env .env
fi
if [ ! -f .env ]; then
log "FATAL: .env missing (copy .env.example or /etc/forwarder/forwarder.env)"
exit 1
fi
log "Building containers"
$COMPOSE build
log "Running migrations"
$COMPOSE run --rm migrate
log "Starting stack"
$COMPOSE up -d
log "Health check"
curl -sf --max-time 10 http://127.0.0.1:8000/api/health >/dev/null
log "Deploy OK"
+109
View File
@@ -0,0 +1,109 @@
<?php
declare(strict_types=1);
/**
* Gitea push webhook → deploy-pull.sh (BizDocs Forwarder standalone repo).
* Env: DEPLOY_WEBHOOK_SECRET, FORWARDER_REPO_DIR, DEPLOY_BRANCH
*/
header('Content-Type: application/json');
$secret = getenv('DEPLOY_WEBHOOK_SECRET') ?: '';
$repoDir = getenv('FORWARDER_REPO_DIR') ?: '/opt/forwarder';
$deployBranch = getenv('DEPLOY_BRANCH') ?: 'main';
$allowedRepo = 'bitreport.pt/forwarder';
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
http_response_code(200);
echo json_encode([
'status' => 'ok',
'message' => 'Forwarder deploy webhook. POST Gitea push events.',
'repo_dir' => $repoDir,
], JSON_UNESCAPED_SLASHES);
exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
exit;
}
if ($secret === '') {
http_response_code(500);
echo json_encode(['error' => 'DEPLOY_WEBHOOK_SECRET not configured']);
exit;
}
$rawBody = file_get_contents('php://input');
if ($rawBody === false || $rawBody === '') {
http_response_code(400);
echo json_encode(['error' => 'Empty body']);
exit;
}
$signatureHeader = $_SERVER['HTTP_X_GITEA_SIGNATURE'] ?? '';
if ($signatureHeader === '' && !empty($_SERVER['HTTP_X_HUB_SIGNATURE_256'])) {
$raw = trim((string) $_SERVER['HTTP_X_HUB_SIGNATURE_256']);
$signatureHeader = str_starts_with($raw, 'sha256=') ? substr($raw, 7) : $raw;
}
if ($signatureHeader === '' || !hash_equals(hash_hmac('sha256', $rawBody, $secret), $signatureHeader)) {
http_response_code(403);
echo json_encode(['error' => 'Invalid signature']);
exit;
}
$event = $_SERVER['HTTP_X_GITEA_EVENT'] ?? '';
if ($event !== 'push') {
http_response_code(200);
echo json_encode(['status' => 'ignored', 'reason' => 'Not a push event']);
exit;
}
$payload = json_decode($rawBody, true);
if (!is_array($payload)) {
http_response_code(400);
echo json_encode(['error' => 'Invalid JSON']);
exit;
}
$repoFullName = strtolower((string) ($payload['repository']['full_name'] ?? ''));
if ($repoFullName !== $allowedRepo) {
http_response_code(403);
echo json_encode(['error' => 'Repository not allowed', 'repo' => $repoFullName]);
exit;
}
$ref = (string) ($payload['ref'] ?? '');
if ($ref !== 'refs/heads/' . $deployBranch) {
http_response_code(200);
echo json_encode(['status' => 'ignored', 'reason' => 'Branch mismatch', 'ref' => $ref]);
exit;
}
$deployScript = __DIR__ . '/deploy-pull.sh';
if (!is_file($deployScript)) {
http_response_code(500);
echo json_encode(['error' => 'deploy-pull.sh missing']);
exit;
}
$logFile = $repoDir . '/storage/deploy-logs/deploy-' . date('Ymd-His') . '.log';
@mkdir(dirname($logFile), 0750, true);
$cmd = sprintf(
'nohup env FORWARDER_REPO_DIR=%s DEPLOY_BRANCH=%s bash %s >> %s 2>&1 &',
escapeshellarg($repoDir),
escapeshellarg($deployBranch),
escapeshellarg($deployScript),
escapeshellarg($logFile)
);
exec($cmd);
http_response_code(202);
echo json_encode([
'status' => 'queued',
'log' => $logFile,
'head' => $payload['after'] ?? null,
]);
+17
View File
@@ -60,5 +60,22 @@ services:
depends_on: depends_on:
- api - api
deploy-hook:
build:
context: ./deploy
dockerfile: Dockerfile
restart: unless-stopped
ports:
- "9090:8080"
environment:
FORWARDER_REPO_DIR: /opt/forwarder
DEPLOY_BRANCH: main
DEPLOY_WEBHOOK_SECRET: ${DEPLOY_WEBHOOK_SECRET:-}
volumes:
- ${FORWARDER_REPO_DIR:-.}:/opt/forwarder
- /var/run/docker.sock:/var/run/docker.sock
env_file:
- .env
volumes: volumes:
mysql_data: mysql_data:
+22 -17
View File
@@ -1,10 +1,13 @@
from __future__ import annotations from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor
from fastapi import APIRouter from fastapi import APIRouter
from pydantic import BaseModel from pydantic import BaseModel
from forwarder.api.deps import CurrentUser, DbSession from forwarder.api.deps import CurrentUser
from forwarder.services import account_service from forwarder.email.imap_client import ImapConfig, test_imap_connection
from forwarder.email.smtp_client import SmtpConfig, test_smtp_connection
router = APIRouter(prefix="/connection", tags=["connection"]) router = APIRouter(prefix="/connection", tags=["connection"])
@@ -34,24 +37,26 @@ class ConnectionTestResult(BaseModel):
@router.post("/test", response_model=ConnectionTestResult) @router.post("/test", response_model=ConnectionTestResult)
def test_connection( def test_connection(
payload: ConnectionTestPayload, payload: ConnectionTestPayload,
db: DbSession,
_user: CurrentUser, _user: CurrentUser,
) -> ConnectionTestResult: ) -> ConnectionTestResult:
imap_cfg = { imap_cfg = ImapConfig(
"imap_host": payload.imap_host, host=payload.imap_host,
"imap_port": payload.imap_port, port=payload.imap_port,
"imap_user": payload.imap_user, user=payload.imap_user,
"imap_password": payload.imap_password, password=payload.imap_password,
} )
imap_ok, imap_msg = account_service.run_imap_test(db, None, imap_cfg) smtp_cfg = SmtpConfig(
host=payload.smtp_host,
port=payload.smtp_port,
user=payload.smtp_user,
password=payload.smtp_password,
)
smtp_cfg = { with ThreadPoolExecutor(max_workers=2) as executor:
"smtp_host": payload.smtp_host, imap_future = executor.submit(test_imap_connection, imap_cfg)
"smtp_port": payload.smtp_port, smtp_future = executor.submit(test_smtp_connection, smtp_cfg)
"smtp_user": payload.smtp_user, imap_ok, imap_msg = imap_future.result()
"smtp_password": payload.smtp_password, smtp_ok, smtp_msg = smtp_future.result()
}
smtp_ok, smtp_msg = account_service.run_smtp_test(db, None, smtp_cfg)
return ConnectionTestResult( return ConnectionTestResult(
imap_ok=imap_ok, imap_ok=imap_ok,
+13 -4
View File
@@ -8,6 +8,9 @@ import re
from dataclasses import dataclass from dataclasses import dataclass
from email import policy from email import policy
DEFAULT_IMAP_TIMEOUT = 30
CONNECTION_TEST_IMAP_TIMEOUT = 5
SKIP_FOLDERS = [ SKIP_FOLDERS = [
"trash", "trash",
"junk", "junk",
@@ -78,16 +81,22 @@ def fetch_message(
return email.message_from_bytes(raw_email, policy=policy.default) return email.message_from_bytes(raw_email, policy=policy.default)
def connect_imap(config: ImapConfig) -> imaplib.IMAP4_SSL: def connect_imap(
imap = imaplib.IMAP4_SSL(config.host, config.port) config: ImapConfig,
timeout: float = DEFAULT_IMAP_TIMEOUT,
) -> imaplib.IMAP4_SSL:
imap = imaplib.IMAP4_SSL(config.host, config.port, timeout=timeout)
imap.login(config.user, config.password) imap.login(config.user, config.password)
return imap return imap
def test_imap_connection(config: ImapConfig) -> tuple[bool, str]: def test_imap_connection(
config: ImapConfig,
timeout: float = CONNECTION_TEST_IMAP_TIMEOUT,
) -> tuple[bool, str]:
imap = None imap = None
try: try:
imap = connect_imap(config) imap = connect_imap(config, timeout=timeout)
folders = list_mailboxes(imap) folders = list_mailboxes(imap)
return True, f"IMAP OK — {len(folders)} mailbox(es) found" return True, f"IMAP OK — {len(folders)} mailbox(es) found"
except Exception as exc: except Exception as exc:
+15 -5
View File
@@ -8,6 +8,10 @@ from email import policy
from email.message import EmailMessage from email.message import EmailMessage
DEFAULT_SMTP_TIMEOUT = 30
CONNECTION_TEST_SMTP_TIMEOUT = 5
@dataclass @dataclass
class SmtpConfig: class SmtpConfig:
host: str host: str
@@ -17,11 +21,14 @@ class SmtpConfig:
use_tls: bool = True use_tls: bool = True
def create_smtp_client(config: SmtpConfig) -> smtplib.SMTP: def create_smtp_client(
config: SmtpConfig,
timeout: float = DEFAULT_SMTP_TIMEOUT,
) -> smtplib.SMTP:
if config.port == 465 and not config.use_tls: if config.port == 465 and not config.use_tls:
client = smtplib.SMTP_SSL(config.host, config.port, timeout=60) client = smtplib.SMTP_SSL(config.host, config.port, timeout=timeout)
else: else:
client = smtplib.SMTP(config.host, config.port, timeout=60) client = smtplib.SMTP(config.host, config.port, timeout=timeout)
if config.use_tls: if config.use_tls:
client.starttls() client.starttls()
client.login(config.user, config.password) client.login(config.user, config.password)
@@ -77,10 +84,13 @@ def forward_email_as_eml(
pass pass
def test_smtp_connection(config: SmtpConfig) -> tuple[bool, str]: def test_smtp_connection(
config: SmtpConfig,
timeout: float = CONNECTION_TEST_SMTP_TIMEOUT,
) -> tuple[bool, str]:
client = None client = None
try: try:
client = create_smtp_client(config) client = create_smtp_client(config, timeout=timeout)
return True, "SMTP login OK" return True, "SMTP login OK"
except Exception as exc: except Exception as exc:
return False, str(exc) return False, str(exc)
View File
Whitespace-only changes.