Files
certain/backend/app/routers/backup.py
T
ScarriffleandClaude Opus 5 7fc8763d57 feat: 2FA, Passwortrichtlinie und wiederherstellbares JSON-Backup
Zwei-Faktor per TOTP mit zehn Einmal-Wiederherstellungscodes. Der
Zwischenzustand "Passwort stimmt, Code fehlt" haengt an der vorhandenen
Sitzungstabelle (pending_2fa, zehn Minuten Laufzeit) und gilt nirgends als
angemeldet; nach dem Code wird das Cookie getauscht statt weiterverwendet.
Der Wiederverwendungsschutz merkt sich das tatsaechlich getroffene
Zeitfenster, nicht die aktuelle Uhrzeit - sonst liesse sich ein Code aus dem
naechsten Fenster gleich darauf nochmal einloesen.

Passwortrichtlinie (Laenge, Zeichenklassen, MFA-Pflicht) in der neuen
globalen Tabelle app_settings, durchgesetzt beim Anlegen, Zuruecksetzen und
Aendern von Passwoertern. Bestehende Passwoerter lassen sich nicht gegen eine
neue Richtlinie pruefen - der Hash gibt nichts her. Beim Anmelden liegt das
Passwort aber kurz im Klartext vor: dort wird geprueft und bei Verstoss ein
Wechsel verlangt, mit passendem Grund fuer den Hinweistext.

Nebenbei geschlossen: must_change_password war bisher nur im Frontend
erzwungen, wer die API direkt ansprach kam vorbei. enforce_account_state
haengt jetzt am /api-Sammelrouter und laesst nur noch durch, was man zum
Erfuellen der Pflicht braucht.

Das JSON-Backup liess sich bisher grundsaetzlich nicht zurueckladen: keine
Version, Kategorien nur ueber mehrdeutige Namen, sieben Tabellen fehlten.
Daneben steht nun ein Format v2, das Beziehungen ueber lokale IDs abbildet,
je Benutzer oder systemweit. Zurueckgeladen wird nach einer Pruefansicht,
wahlweise ersetzend oder ergaenzend; vor dem Ersetzen legt der Server einen
Schnappschuss der Datenbank an. Der alte Ansichts-Export bleibt fuer
Tabellenkalkulationen bestehen und wird beim Hochladen ausdruecklich
abgewiesen, statt halb zu raten.

Frontend: wiederverwendbares Passwortfeld mit Augensymbol, animierte
Anforderungsliste, 2FA-Seite, Admin-Karte fuer die Richtlinie und Karte zum
Zurueckladen. Neue Bewegung ist in prefers-reduced-motion hinterlegt; Secret
und Codes sind markierbar, sonst verhinderte das globale user-select das
Kopieren.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-20 10:11:22 +02:00

362 lines
13 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Backup & Export: kompletter DB-Download (Admin), Datenexport je Nutzer und
das wiederherstellbare Voll-Backup als JSON (siehe ``services/backup_data``)."""
import csv
import io
import os
import sqlite3
import tempfile
from datetime import datetime, timezone
from pathlib import Path
from fastapi import APIRouter, Depends, File, Form, HTTPException, Response, UploadFile
from fastapi.responses import FileResponse
from sqlalchemy.orm import Session
from starlette.background import BackgroundTask
from ..config import get_settings
from ..database import get_db
from ..deps import get_current_user, require_admin
from ..models import (
Account,
AccountIdentifier,
BudgetTemplateLine,
Category,
CategoryGroup,
DashboardLayout,
PlannedIncomeLine,
Role,
Transaction,
User,
)
from ..services import backup_data, sessions
router = APIRouter(tags=["backup"])
# Ein Backup ist reiner Text; alles darüber ist mit Sicherheit keins mehr.
MAX_BACKUP_BYTES = 64 * 1024 * 1024
def _ts() -> str:
return datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
def _sqlite_path() -> str | None:
url = get_settings().effective_database_url
return url.replace("sqlite:///", "", 1) if url.startswith("sqlite:///") else None
def _snapshot_before_restore() -> str | None:
"""Legt vor einem ersetzenden Restore eine Kopie der Datenbank ab.
Dieselbe Absicherung, die ``deploy/update.sh`` vor einem Update macht: wer
versehentlich das falsche Backup einspielt, hat noch einen Weg zurück."""
db_path = _sqlite_path()
if db_path is None or not os.path.exists(db_path):
return None
ziel_ordner = Path(get_settings().data_dir) / "backups"
ziel_ordner.mkdir(parents=True, exist_ok=True)
ziel = ziel_ordner / f"pre-restore-{_ts()}.db"
src = sqlite3.connect(db_path)
dst = sqlite3.connect(str(ziel))
try:
with dst:
src.backup(dst)
finally:
dst.close()
src.close()
return str(ziel)
def _money(cents: int | None) -> str:
return f"{(cents or 0) / 100:.2f}"
# --- Komplettes DB-Backup (nur Admin) --------------------------------------
@router.get("/backup/db")
def backup_db(_: User = Depends(require_admin)):
db_path = _sqlite_path()
if db_path is None:
raise HTTPException(status_code=400, detail="DB-Backup ist nur für SQLite verfügbar.")
tmp = tempfile.NamedTemporaryFile(prefix="cf-backup-", suffix=".db", delete=False)
tmp.close()
# Online-Backup-API: konsistente Kopie auch bei laufendem Betrieb.
src = sqlite3.connect(db_path)
dst = sqlite3.connect(tmp.name)
try:
with dst:
src.backup(dst)
finally:
dst.close()
src.close()
return FileResponse(
tmp.name,
media_type="application/octet-stream",
filename=f"certain-finance-{_ts()}.db",
background=BackgroundTask(os.remove, tmp.name),
)
# --- Transaktionsexport ----------------------------------------------------
def _maps(db: Session, user: User) -> tuple[dict[int, Account], dict[int, Category]]:
accs = {a.id: a for a in db.query(Account).filter(Account.owner_id == user.id)}
cats = {c.id: c for c in db.query(Category).filter(Category.owner_id == user.id)}
return accs, cats
def _txns(db: Session, user: User) -> list[Transaction]:
return (
db.query(Transaction)
.filter(Transaction.owner_id == user.id)
.order_by(Transaction.date, Transaction.id)
.all()
)
@router.get("/export/transactions.csv")
def export_transactions_csv(db: Session = Depends(get_db), user: User = Depends(get_current_user)):
accs, cats = _maps(db, user)
buf = io.StringIO()
w = csv.writer(buf, delimiter=";")
w.writerow(["Datum", "Typ", "Konto", "Betrag", "Waehrung", "EUR-Wert",
"Zielkonto", "Kategorie", "Empfaenger", "Verwendungszweck", "Notiz"])
for t in _txns(db, user):
acc = accs.get(t.account_id)
w.writerow([
t.date.isoformat(), t.type.value, acc.name if acc else "",
_money(t.amount_cents), acc.currency if acc else "", _money(t.amount_eur_cents),
accs[t.to_account_id].name if t.to_account_id and t.to_account_id in accs else "",
cats[t.category_id].name if t.category_id and t.category_id in cats else "",
t.payee or "", t.description or "", t.notes or "",
])
return Response(
content=buf.getvalue().encode("utf-8-sig"),
media_type="text/csv",
headers={"Content-Disposition": f'attachment; filename="transaktionen-{_ts()}.csv"'},
)
def _txn_dict(t: Transaction, accs: dict[int, Account], cats: dict[int, Category]) -> dict:
acc = accs.get(t.account_id)
return {
"date": t.date.isoformat(),
"type": t.type.value,
"account": acc.name if acc else None,
"currency": acc.currency if acc else None,
"amount_cents": t.amount_cents,
"amount_eur_cents": t.amount_eur_cents,
"to_account": accs[t.to_account_id].name if t.to_account_id in accs else None,
"to_amount_cents": t.to_amount_cents,
"category": cats[t.category_id].name if t.category_id in cats else None,
"payee": t.payee,
"description": t.description,
"notes": t.notes,
}
@router.get("/export/transactions.json")
def export_transactions_json(db: Session = Depends(get_db), user: User = Depends(get_current_user)):
accs, cats = _maps(db, user)
data = [_txn_dict(t, accs, cats) for t in _txns(db, user)]
return Response(
content=_json_bytes(data),
media_type="application/json",
headers={"Content-Disposition": f'attachment; filename="transaktionen-{_ts()}.json"'},
)
# --- Gesamt-Export (alle eigenen Daten als JSON) ---------------------------
def _json_bytes(obj) -> bytes:
import json
return json.dumps(obj, ensure_ascii=False, indent=2).encode("utf-8")
@router.get("/export/all.json")
def export_all_json(db: Session = Depends(get_db), user: User = Depends(get_current_user)):
accs, cats = _maps(db, user)
idents: dict[int, list] = {}
for i in db.query(AccountIdentifier).join(Account).filter(Account.owner_id == user.id):
idents.setdefault(i.account_id, []).append({"kind": i.kind.value, "value": i.value})
accounts = [{
"name": a.name, "type": a.type.value, "currency": a.currency,
"opening_balance_cents": a.opening_balance_cents,
"opening_date": a.opening_date.isoformat() if a.opening_date else None,
"icon": a.icon, "color": a.color, "archived": a.is_archived,
"identifiers": idents.get(a.id, []),
} for a in accs.values()]
groups = []
for g in db.query(CategoryGroup).filter(CategoryGroup.owner_id == user.id).order_by(CategoryGroup.position):
groups.append({
"name": g.name, "kind": g.kind.value, "icon": g.icon, "color": g.color,
"categories": [
{"name": c.name, "icon": c.icon, "color": c.color}
for c in sorted(g.categories, key=lambda x: x.position)
],
})
budget_template = [
{"category": cats[l.category_id].name if l.category_id in cats else None, "planned_cents": l.planned_cents}
for l in db.query(BudgetTemplateLine).filter(BudgetTemplateLine.owner_id == user.id)
]
planned_income = [
{"label": l.label, "planned_cents": l.planned_cents,
"category": cats[l.category_id].name if l.category_id in cats else None,
"target_account": accs[l.target_account_id].name if l.target_account_id in accs else None}
for l in db.query(PlannedIncomeLine).filter(PlannedIncomeLine.owner_id == user.id)
]
dash = db.query(DashboardLayout).filter(DashboardLayout.owner_id == user.id).first()
data = {
"exported_at": datetime.now(timezone.utc).isoformat(),
"app": "Certain Finance",
"user": user.username,
"accounts": accounts,
"category_groups": groups,
"transactions": [_txn_dict(t, accs, cats) for t in _txns(db, user)],
"budget_template": budget_template,
"planned_income": planned_income,
"dashboard_layout": dash.layout if dash else None,
}
return Response(
content=_json_bytes(data),
media_type="application/json",
headers={"Content-Disposition": f'attachment; filename="certain-finance-export-{_ts()}.json"'},
)
# --- Voll-Backup (wiederherstellbar) ---------------------------------------
def _download(obj: dict, name: str) -> Response:
return Response(
content=backup_data.to_bytes(obj),
media_type="application/json",
headers={"Content-Disposition": f'attachment; filename="{name}-{_ts()}.json"'},
)
@router.get("/export/backup.json")
def export_backup(db: Session = Depends(get_db), user: User = Depends(get_current_user)):
"""Alle eigenen Daten – vollständig und wieder einspielbar."""
return _download(backup_data.export_user(db, user), "certain-finance-backup")
@router.get("/export/system-backup.json")
def export_system_backup(db: Session = Depends(get_db), _: User = Depends(require_admin)):
"""Die ganze Instanz inklusive Benutzerkonten. Enthält Passwort-Hashes und
TOTP-Secrets – die Datei ist wie ein Passwort zu behandeln."""
return _download(backup_data.export_system(db), "certain-finance-system-backup")
async def _read_upload(file: UploadFile) -> bytes:
roh = await file.read()
if len(roh) > MAX_BACKUP_BYTES:
raise HTTPException(status_code=400, detail="Die Datei ist zu gross für ein Backup.")
return roh
@router.post("/backup/restore/preview")
async def restore_preview(
file: UploadFile = File(...),
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
"""Prüft die Datei und meldet, was darin steckt. Schreibt nichts."""
try:
data = backup_data.parse(await _read_upload(file))
except backup_data.BackupError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
scope = data["scope"]
if scope == "system" and user.role != Role.admin:
raise HTTPException(
status_code=403,
detail="Ein systemweites Backup darf nur ein Administrator einspielen.",
)
hinweise: list[str] = []
if scope == "system":
hinweise.append(
"Systemweite Wiederherstellung: alle Benutzer und deren Daten werden "
"ersetzt. Danach sind alle Sitzungen beendet und du musst dich neu anmelden."
)
if not any(u.get("role") == "admin" for u in data.get("users") or []):
hinweise.append("Achtung: im Backup ist kein Administrator enthalten.")
return {
"scope": scope,
"exported_at": data.get("exported_at"),
"app_version": data.get("app_version"),
"username": data.get("username"),
"user_count": len(data.get("users") or []) if scope == "system" else 1,
"tables": backup_data.summarize(data),
"notes": hinweise,
}
@router.post("/backup/restore")
async def restore(
file: UploadFile = File(...),
mode: str = Form("replace"),
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
"""Spielt ein Backup ein – ``replace`` (ersetzen) oder ``merge`` (ergänzen).
Alles läuft in einer Transaktion: entweder es geht komplett durch oder es
wird gar nichts geschrieben."""
if mode not in ("replace", "merge"):
raise HTTPException(status_code=400, detail="Unbekannter Modus.")
try:
data = backup_data.parse(await _read_upload(file))
except backup_data.BackupError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
scope = data["scope"]
if scope == "system" and user.role != Role.admin:
raise HTTPException(
status_code=403,
detail="Ein systemweites Backup darf nur ein Administrator einspielen.",
)
if scope == "system" and mode != "replace":
raise HTTPException(
status_code=400,
detail="Ein systemweites Backup kann nur ersetzend eingespielt werden.",
)
schnappschuss = _snapshot_before_restore() if mode == "replace" else None
try:
if scope == "system":
bilanz = backup_data.restore_system(db, data)
else:
bilanz = backup_data.restore_user_data(
db, user, data.get("data") or {}, merge=(mode == "merge")
)
db.commit()
except backup_data.BackupError as exc:
db.rollback()
raise HTTPException(status_code=400, detail=str(exc)) from exc
except Exception as exc: # pragma: no cover - Schutznetz gegen halbe Zustände
db.rollback()
raise HTTPException(
status_code=400, detail=f"Wiederherstellung fehlgeschlagen: {exc}"
) from exc
if scope == "system":
# Die eigene Sitzung wurde mitgelöscht; alle übrigen ebenfalls beenden.
sessions.revoke_all_everywhere(db)
return {
"scope": scope,
"mode": mode,
"restored": bilanz,
"snapshot": os.path.basename(schnappschuss) if schnappschuss else None,
"logout_required": scope == "system",
}