Make background tasks idempotent - prevent duplicate bans on retry

CRITICAL FIX: Background tasks (especially blocklist_import) crashed mid-execution,
leaving partial state. On retry, the same bans were applied again, causing duplicates.

Solution: Content-hash based operation tracking for blocklist imports:
- Added import_runs table (migration 6) to track operations by source + content hash
- Before banning, check if this exact content has already been imported
- If completed: skip banning (already done), optionally re-warm cache
- If new or failed: proceed with ban and mark as completed or failed

Changes:
- Database: Migration 6 adds import_runs table with operation state tracking
- Model: Added ImportRunEntry for import run records
- Repository: New import_run_repo module with CRUD operations
- Workflow: Updated blocklist_import_workflow to check operation history before banning
- Dependencies: Registered import_run_repo for dependency injection
- Tests: Added test_import_source_idempotent_on_retry and test_import_source_different_content_not_reused
- Documentation: Added Task Idempotency section to Backend-Development.md

Verification:
- All 7 import tests pass (5 existing + 2 new idempotency tests)
- Type checking: mypy --strict 
- Linting: ruff 
- No API changes, backwards compatible via automatic migration

Fixes: Background tasks not idempotent #CRITICAL

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
2026-04-30 21:54:14 +02:00
parent 400ab1a3f1
commit 52f237d5d4
20 changed files with 1029 additions and 226 deletions

View File

@@ -1,97 +1,3 @@
## [CRITICAL] Missing security headers (CSP, X-Frame-Options, etc.)
**Where found**
- Backend does not set `Content-Security-Policy`, `X-Frame-Options`, `X-Content-Type-Options` headers
- Frontend HTML served without CSP meta tags
**Why this is needed**
Without security headers, browsers won't protect against XSS, clickjacking, MIME-sniffing, referrer leakage attacks.
**Goal**
Add security headers to all HTTP responses.
**What to do**
1. Add security headers middleware to `backend/app/main.py`:
```python
@app.middleware("http")
async def add_security_headers(request, call_next):
response = await call_next(request)
response.headers["Content-Security-Policy"] = "default-src 'self'"
response.headers["X-Frame-Options"] = "DENY"
response.headers["X-Content-Type-Options"] = "nosniff"
return response
```
2. In frontend `index.html`, add CSP meta tag
3. Test with browser DevTools Security tab
**Possible traps and issues**
- CSP `'unsafe-inline'` defeats security — avoid if possible
- CDN resources may need explicit allowlist
- Too restrictive CSP breaks functionality; too loose defeats security
**Docs changes needed**
- Add section in `Docs/Security.md` § HTTP Security Headers
**Doc references**
- `Docs/Security.md` (security headers)
---
## [CRITICAL] Background tasks lack timeout protection
**Where found**
- `backend/app/tasks/blocklist_import.py` — no timeout
- `backend/app/tasks/health_check.py` — no timeout
- All task functions lack timeout wrapper
**Why this is needed**
If task hangs (API unreachable, network partition), task runs forever. Never completes → lock never released → duplicate work, resource exhaustion.
**Goal**
Ensure all background tasks complete within bounded time or fail gracefully.
**What to do**
1. Wrap all task functions with `asyncio.wait_for(task, timeout)`:
```python
await asyncio.wait_for(blocklist_service.import_all(...), timeout=300)
```
2. Set appropriate timeouts per task:
- Blocklist import: 300s (5 min)
- Health probe: 10s
- Geo cache flush: 60s
3. Log timeout events and trigger alerts
**Possible traps and issues**
- Timeout too short → legitimate tasks killed prematurely
- Timeout too long → resource leak if many tasks hang
- Killing task mid-operation may leave inconsistent state
**Docs changes needed**
- Add section in `Docs/Backend-Development.md` § Background Tasks
**Doc references**
- `Docs/Backend-Development.md` (background tasks)
- `backend/app/tasks/` (task modules)
---
## [CRITICAL] Background tasks not idempotent
**Where found**