diff --git a/.gitignore b/.gitignore index 2dbf64e..962e14e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,7 @@ .aider* .DS_Store tools/export_kontodaten_*.csv +tools/.env +live_credentials.txt +tools/dumps/ +__pycache__/ diff --git a/LIVE_MIGRATION_NOTES.md b/LIVE_MIGRATION_NOTES.md new file mode 100644 index 0000000..2288940 --- /dev/null +++ b/LIVE_MIGRATION_NOTES.md @@ -0,0 +1,294 @@ +# Live-Migration – Findings & Runbook + +Stand: 2026-10-29 +Ziel: Go-Live der neuen App auf `hoschis-tippspiel.de`. + +> Die Daten stammen **ausschließlich aus der Legacy-Live-DB** (altes Projekt), +> nicht aus dem Testsystem. Das Testsystem `tippspiel.programmschmiede.de` ist +> nur ein Referenz-Deployment der neuen App und nicht Teil der Datenkette. + +> Alle Zugangsdaten stehen ausschließlich in `docs/live_credentials.txt` +> (gitignored). In diesem Dokument werden bewusst **keine Passwörter, Keys oder +> Tokens** wiederholt. + +--- + +## 0. Datenfluss + +``` +Legacy-Live-DB (altes Projekt) + d0274241@hoschis-tippspiel.de / d0274241 + │ + │ mysqldump (entspricht tools/dump_pfosten.py im alten Repo) + ▼ +/home/torsten/repos/tippspiel/tools/pfosten_.sql + │ + │ tools/import_from_dump.sh + ▼ +Lokale Docker-DB "tippspiel_legacy" + │ + │ tools/import.php (Migration + IBAN-Verschlüsselung) + ▼ +Lokale Docker-DB "tippspiel2027" + │ + │ mysqldump + FTP + ▼ +Live: DB d048c52f@hoschis-tippspiel.de + Dateien in /tippspiel (FTP) +``` + +Das Testsystem wird weder gelesen noch beschrieben. Es wurde nur genutzt, um +die neue App vorab zu testen. + +--- + +## 1. Zugangs-Checks (nur lesend durchgeführt) + +### FTP live ✅ + +| Punkt | Ergebnis | +|---|---| +| Host | `hoschis-tippspiel.de` → `dd28338.kasserver.com` (`85.13.130.205`) | +| Login | `ftp_user` aus `docs/live_credentials.txt` erfolgreich | +| Rechte | Lesezugriff auf Root, Listing funktioniert | +| Alias | `w0172dd3.kasserver.com` funktioniert ebenfalls | +| Root-Inhalt | `logs`, `cgi-bin`, `pfosten` (Legacy-App) | +| Zielordner | `/tippspiel` existiert noch nicht und wird beim Deploy angelegt | + +### DB live ✅ (nach Korrektur des Passworts) + +| Punkt | Ergebnis | +|---|---| +| Host | `hoschis-tippspiel.de:3306` (`dd28338`) | +| Server | MariaDB `10.11.14-MariaDB-0ubuntu0.24.04.1-log` | +| Login | `mysql_db`-User aus `docs/live_credentials.txt` erfolgreich | +| Rechte | `GRANT ALL PRIVILEGES ON .*` (nur diese DB) | +| Tabellen | **0 – die Live-DB ist noch leer** | +| `max_allowed_packet` | 64 MB | +| `sql_mode` | `NO_ENGINE_SUBSTITUTION` | +| `character_set_server` | `latin1` (Schema/Tabellen nutzen utf8mb4) | +| `default_storage_engine` | InnoDB | + +### Verlauf der DB-Fehlerdiagnose + +1. Erster Versuch mit dem alten Passwort: `ERROR 1045 Access denied`. +2. Kontrollen: Legacy-Live-DB (`d0274241`) und Testsystem-DB (`d0489c69`) + funktionierten von derselben Maschine aus → Client/Firewall/externer + DB-Zugriff grundsätzlich in Ordnung, Problem lag an der Kombination für + `d048c52f`. +3. Nach Korrektur im KAS, aber ohne Aktualisierung der Datei: weiterhin `1045`. +4. Nach Aktualisierung von `mysql_pw` in `docs/live_credentials.txt`: Login + erfolgreich. + +### Server-/Umgebungsunterschiede + +| | Testsystem | Livesystem | +|---|---|---| +| FTP-Host | `programmschmiede.de` | `hoschis-tippspiel.de` | +| DB-Host (extern) | `programmschmiede.de` | `hoschis-tippspiel.de` | +| DB-Server | `dd42734` | `dd28338` | +| FTP-Zielordner | `tippspiel.programmschmiede.de` | `tippspiel` | +| App-URL | `https://tippspiel.programmschmiede.de` | `https://hoschis-tippspiel.de` | + +--- + +## 2. Go-Live-Script + +Neu: **`tools/live_migration.py`** (Python 3, nutzt `mysqldump`/`mysql` und +`ftplib`). Es bildet den bisherigen Ablauf aus `tools/import_from_dump.sh` plus +`tools/deploy_test.py` ab, nur mit Live-Zielen. + +### Schritte + +1. **Dump der Legacy-Live-DB** per `mysqldump` → + `/home/torsten/repos/tippspiel/tools/pfosten_.sql` + (entspricht dem Dump-Ziel des alten Repos; Quelle: + `d0274241@hoschis-tippspiel.de`, per Env + `LEGACY_HOST` / `LEGACY_USER` / `LEGACY_PASS` / `LEGACY_DB` überschreibbar). +2. **Lokaler Import + Migration** über `tools/import_from_dump.sh`: + Dump → Docker-DB `tippspiel_legacy`, danach `import.php` → `tippspiel2027`. + (Alternative: mit `--skip-dump`/`--source-dump` einen bereits vorhandenen + Dump aus dem alten Repo verwenden.) +3. **Live-DB aktualisieren**: + - vorhandene Live-Tabellen werden vorher nach `~/backups/tippspiel-live` + gesichert, + - dann gedroppt und die lokale `tippspiel2027` eingespielt, + - anschließend Prüfung auf fehlende Tabellen und exakte Zeilenzahlen + (lokal vs. live). +4. **FTP-Upload**: `tippspiel/public` und `tippspiel/src` nach `/tippspiel`, + danach `.htaccess` in `/tippspiel/public` schreiben. + +### Aufruf + +```bash +# Nur prüfen, nichts schreiben (Zugänge, Dumps, Ziele) +./tools/live_migration.py --dry-run + +# Kompletter Go-Live (fragt vor dem Leeren der Live-DB nach "JA") +./tools/live_migration.py + +# Varianten +./tools/live_migration.py --db-only # nur DB, keine Dateien +./tools/live_migration.py --skip-db-import # nur Dateien aktualisieren +./tools/live_migration.py --skip-dump # neuesten vorhandenen Dump nutzen +./tools/live_migration.py --source-dump PFAD # bestimmten Dump verwenden +``` + +Weitere Optionen: `--app-url`, `--apifootball-key`, `--dump-dir`, +`--backup-dir`, `--skip-img-upload`, `--yes`, `--check-url`, `--check-only`. + +### Sicherheitsnetze im Script + +- Abbruch, wenn `iban_key` in `docs/live_credentials.txt` fehlt oder nicht zum + `IBAN_KEY` in `tools/docker-compose.yml` passt (sonst wären live + verschlüsselte IBANs nicht lesbar). +- Backup der vorhandenen Live-Tabellen vor dem Drop; Backup-Verzeichnis `0700`, + Dump-Dateien `0600` (enthalten E-Mails, PayPal-Daten, IBAN-Ciphertexte). +- Explizite Bestätigung (`JA`) vor dem Leeren der Live-DB. +- Verifikation nach dem Import: fehlende Tabellen oder abweichende + Zeilenzahlen führen zu einem Fehler. +- `--dry-run` führt keinerlei Schreiboperationen aus. +- `--check-url` prüft nach dem Deploy Login-Seite, `css/style.css` und + `manifest.json` und erkennt, ob noch die Legacy-App antwortet. + +### `.htaccess` (wird beim Deploy erzeugt) + +Enthält `DB_HOST localhost`, `DB_USER`, `DB_PASS`, `DB_NEW_NAME`, `APP_URL`, +`IBAN_KEY` sowie optional alle Credentials-Keys mit den +Präfixen `APIFOOTBALL_`, `SMTP_`, `MAIL_`. + +> Die Zugangsdaten liegen damit als `SetEnv` im Klartext auf dem Webspace. +> Das ist beim Testsystem bewusst so und aktuell die einzige Env-Konfiguration, +> die der Webspace bietet. Die Datei darf nicht in Backups/Repositories landen. + +> **Wichtig (Go-Live 29.10.2026):** `SetEnv`-Werte müssen in Anführungszeichen +> stehen. `SetEnv MAIL_FROM_NAME Hoschis Tippspiel` (Leerzeichen im Wert) lässt +> Apache die `.htaccess` nicht parsen und beantwortet **jede** Anfrage mit +> HTTP 500 – auch statische Dateien. `build_htaccess()` quotet die Werte +> deshalb seit dem Fix; Rewrite-Regeln sind zusätzlich in +> `` gekapselt. + +### Weitere Änderung + +- `tools/import_from_dump.sh` akzeptiert jetzt optional `DUMP=/pfad/zum.sql` + (Default unverändert: neuester `pfosten*.sql` im `DUMP_DIR`). + +--- + +## 3. Durchgeführte Tests + +| Test | Ergebnis | +|---|---| +| `--dry-run` gegen Live | FTP-Login ok, `/tippspiel` wird neu angelegt, Live-DB-Login ok (0 Tabellen), lokale Docker-DB ok | +| Legacy-Dump nach `/tmp` | 16,2 MB, gültiger Dump | +| SMTP-Login (STARTTLS, 587) | erfolgreich, ohne Mailversand | +| Smoke-Test Testsystem | Login, CSS, Manifest ok | +| Smoke-Test Livesystem | erkennt korrekt noch die Legacy-App | +| Zeitzone nach Bootstrap | `Europe/Berlin` (im Container geprüft) | +| Lokaler Komplettlauf mit Dump vom 29.10.2026 06:20 | erfolgreich | +| Lokaler Rehearsal-Lauf 29.10.2026 21:14 (Dump → Docker → Dump → Wegwerf-DB) | alle Tabellen zeilengleich | +| **Go-Live 29.10.2026 21:16** | DB 15 Tabellen / 211.787 Tipps live, 261 Dateien hochgeladen | +| Erster Smoke-Test nach Go-Live | HTTP 500 (unquoted `SetEnv MAIL_FROM_NAME`) | +| Smoke-Test nach `.htaccess`-Fix | Login, CSS, Manifest ok | + +Ergebnis des lokalen Migrationslaufs (Referenz für die Verifikation heute Abend): + +``` +users 180 +settings 1 +seasons 14 +rounds 671 +games 3,072 +tipps 211,787 +payments 2,277 +quotas 388 +roundmails 614 +manual_payouts 54 +teams 207 +team_aliases 446 +``` + +Nicht zugeordnete Team-Spalten der Saison „Hinrunde 26/27“: +`Mannschaft 1` … `Mannschaft 8` (Platzhalter, kein Fehler). + +--- + +## 4. Offene Punkte für den Go-Live + +1. **PHP-Version in KAS prüfen** ✅ erledigt (29.10.2026): Die Live-App + liefert Login-Seite, CSS und Manifest korrekt aus, d. h. es läuft eine + kompatible PHP-Version (≥ 8.1) mit `pdo_mysql`. +2. **Docroot** ✅ erledigt (29.10.2026): Die Domain zeigt auf + `/tippspiel/public` (verifiziert über `/manifest.json` = 200 und + `/robots.txt` = 404 sowie den Login-Redirect von `/`). +3. **Schreibfenster der Legacy-App**: Zwischen Dump und Docroot-Umschaltung + nimmt die alte App weiter Tipps an – diese gehen verloren. Legacy vorher in + Wartung/Schreibschutz nehmen oder das Fenster bewusst klein halten. +4. **Cron-Jobs**: Reminder-Cron auf + `https://hoschis-tippspiel.de/index.php?page=reminder` umstellen (seit + 29.10.2026 ohne Token); einen evtl. noch laufenden Legacy-Scheduler unter + `/pfosten` deaktivieren (sonst doppelte Mails). Die alte Legacy-URL + `/roundmails/checkReminder` läuft ins Leere (404). Auch + `tools/sync_live_to_test.sh` prüfen/stoppen, da die Legacy-DB nach dem + Switch einfriert. +5. **Live-DB ist leer** – Schema und Daten stammen aus dem Legacy-Dump und + werden über die lokale Migration eingespielt. Der erste echte Import ist + also gleichzeitig der Schema-Import. +6. **`APIFOOTBALL_KEY`** ✅ erledigt: `apifootball_key` steht jetzt in + `docs/live_credentials.txt` (übernommen aus `tools/docker-compose.yml`, + Wert unverändert) und wird beim Deploy als `SetEnv APIFOOTBALL_KEY` + geschrieben. +7. **SMTP** ✅ erledigt: Werte aus `/pfosten/.env` (Legacy-Live) übernommen + (`MAIL_*` → `smtp_*`/`mail_*`) und in `docs/live_credentials.txt` + eingetragen. SMTP-Login gegen `w0172dd3.kasserver.com:587` (STARTTLS) + erfolgreich getestet, ohne eine Mail zu senden. Hinweis: + `MAIL_FROM_NAME` enthielt in der Legacy-`.env` dieselbe Adresse wie + `MAIL_FROM` (also keinen Anzeigenamen); deshalb steht dort jetzt + `Hoschis Tippspiel` (wie in `tools/docker-compose.yml`). +8. **Zeitzone** ✅ erledigt: `public/index.php` setzt zentral + `date_default_timezone_set('Europe/Berlin')`. Damit hängt die Tipp-Sperre + nicht mehr von der PHP-Zeitzone des Servers ab. +9. **Dateirechte** ✅ erledigt: `docs/live_credentials.txt` ist `0600`, + Live-Backups werden mit Verzeichnis `0700` / Datei `0600` angelegt. +10. **Smoke-Test** ✅ erledigt: `--check-url` prüft nach dem Deploy Login-Seite, + CSS und Manifest und erkennt die noch aktive Legacy-App. +11. **Legacy-Rollback**: Die alte App bleibt unter `/pfosten` unangetastet; ein + Rollback ist durch Zurücksetzen des Docroots auf `/pfosten/public` möglich. + Zusätzlich liegt das DB-Backup in `~/backups/tippspiel-live`. +12. **IBAN-Key-Rotation** ✅ erledigt (29.10.2026): `tools/docker-compose.yml` + enthält keinen Schlüssel mehr; der lokale Schlüssel liegt in `tools/.env` + (gitignored, 0600), der Live-Schlüssel in `docs/live_credentials.txt` + (gitignored, 0600) und wird als `SetEnv IBAN_KEY` ausgerollt. Der vorher + verschlüsselte Bestand (1 IBAN) wurde mit `tools/import_accounts.php` + umgeschlüsselt. Die Live-Zugänge in + `docs/legacy/tippspiel/pfosten/.env_production` (getrackt) sind weiterhin + offen. Ebenfalls offen: CSRF-Tokens und `session_regenerate_id()` nach Login. + +--- + +## 5. Runbook für heute Abend + +```bash +# 1. Credentials final prüfen (Passwort, iban_key, APIFOOTBALL_KEY, SMTP) +$EDITOR docs/live_credentials.txt + +# 2. Dry-Run +./tools/live_migration.py --dry-run + +# 3. Go-Live (DB + Dateien) +./tools/live_migration.py + +# 4. Docroot in KAS auf /tippspiel/public umstellen + +# 5. Smoke-Test +./tools/live_migration.py --check-only + +# 6. Danach prüfen +# - https://hoschis-tippspiel.de (Login, Tipps, Rangliste) +# - Admin: Kontoliste (IBAN-Anzeige), Zahlungen +# - Logs unter /logs auf dem FTP +``` + + +Backups: `~/backups/tippspiel-live` +Dumps: `/home/torsten/repos/tippspiel/tools/pfosten_*.sql` diff --git a/README.md b/README.md index f4dfc9b..11970bc 100644 --- a/README.md +++ b/README.md @@ -114,6 +114,50 @@ Das Skript `deploy_test.py` lädt das Projekt per FTP nach `tippspiel.programmsc > Achtung: Zugangsdaten landen als `SetEnv` in der `.htaccess` auf dem Server. Das ist für ein direkt bespielbares Testsystem bewusst so gewollt, sollte aber nicht für ein Produktivsystem übernommen werden. +## Deployment auf das Livesystem + +`live_migration.py` ist der Go-Live-Lauf und kombiniert `import_from_dump.sh` mit einem Live-Deploy nach dem Vorbild von `deploy_test.py`. Datenquelle ist ausschließlich die Legacy-Live-DB (altes Projekt); das Testsystem ist nur Referenz und wird weder gelesen noch beschrieben: + +1. aktuellen Dump der Legacy-Live-DB ziehen (`/home/torsten/repos/tippspiel/tools/pfosten_.sql`), +2. lokal nach `tippspiel_legacy` einspielen und mit `import.php` nach `tippspiel2027` migrieren, +3. die migrierte DB in die Live-DB aus `docs/live_credentials.txt` einspielen + (vorher wird ein Backup der vorhandenen Live-Tabellen abgelegt), +4. `public/` und `src/` per FTP nach `/tippspiel` hochladen und dort die `.htaccess` schreiben. + +```bash +# Nur prüfen (Zugänge, Dumps, Ziele) - schreibt nichts +./live_migration.py --dry-run + +# Kompletter Go-Live (fragt vor dem Leeren der Live-DB nach) +./live_migration.py + +# Varianten +./live_migration.py --db-only # nur DB, keine Dateien +./live_migration.py --skip-db-import # nur Dateien aktualisieren +./live_migration.py --source-dump /pfad/pfosten_....sql +./live_migration.py --check-url # danach HTTP-Smoke-Test (APP_URL) +./live_migration.py --check-only # nur HTTP-Smoke-Test +``` + +Der Smoke-Test prüft nach dem Upload Login-Seite, `css/style.css` und +`manifest.json`. Er erkennt auch, ob noch die Legacy-App (Laravel) unter der +Domain antwortet – dann ist der Docroot in KAS noch nicht auf +`/tippspiel/public` umgestellt. + +Backups der Live-DB landen standardmäßig unter `~/backups/tippspiel-live` +(überschreibbar via `--backup-dir`) mit Verzeichnis-Rechten `0700` und +Datei-Rechten `0600`. Die Dumps enthalten E-Mail-Adressen, PayPal-Daten und +verschlüsselte IBANs und sollten entsprechend behandelt werden. + +Der FTP-Zielordner ist fest `tippspiel`, die Domain muss also auf +`/tippspiel/public` zeigen. `APP_URL` lässt sich über `--app-url` setzen +(Default `https://hoschis-tippspiel.de`). + +> Hinweis: Wie beim Testsystem landen die Zugangsdaten als `SetEnv` in der +> `.htaccess`. Für ein Produktivsystem ist das nur akzeptabel, weil der +> Webspace keine andere Env-Konfiguration bereitstellt - die Datei darf nicht +> in Backups oder Repositories landen. + ## IBAN-Verschlüsselung (Datenschutz) Die IBAN der Spieler wird nicht mehr im Klartext, sondern verschlüsselt in der @@ -125,6 +169,11 @@ Lesezugriff auf die Datenbank keine IBAN im Klartext. - `App\Core\Crypto` verschlüsselt mit libsodium (`sodium_crypto_secretbox`, authentifizierte Verschlüsselung). Der Ciphertext wird mit dem Präfix `enc:v1:` markiert und base64-codiert gespeichert. +- `App\Core\Iban` normalisiert Eingaben (Leerzeichen, Bindestriche und ein + vorangestelltes „IBAN" werden entfernt) und prüft Format und + Mod-97-Prüfziffer. Die Validierung greift bei Registrierung, in den + Einstellungen und bei der Admin-Bearbeitung; ungültige IBANs werden mit + einer Fehlermeldung abgelehnt. - Der Schlüssel liegt ausschließlich in der Umgebungsvariable `IBAN_KEY` (base64, 32 Byte) — nie in der Datenbank und nie im Git. - Entschlüsselt wird nur dort, wo die IBAN wirklich gebraucht wird: in der @@ -141,9 +190,13 @@ openssl rand -base64 32 **Einrichtung** 1. `IBAN_KEY` als Umgebungsvariable setzen: - - lokal: in `docker-compose.yml` (dort ist ein reiner Dev-Schlüssel hinterlegt), - - Testsystem: `iban_key=` in `docs/testsystem_credentials.txt` ergänzen — - `deploy_test.py` schreibt den Wert als `SetEnv IBAN_KEY` in die `.htaccess`. + - lokal: in `tools/.env` (gitignored) als `IBAN_KEY=…`; `docker-compose.yml` + reicht den Wert nur noch durch (`IBAN_KEY=${IBAN_KEY:-}`), + - Live: `iban_key=` in `docs/live_credentials.txt` — `live_migration.py` + schreibt den Wert als `SetEnv IBAN_KEY` in die `.htaccess`, + - Testsystem: `iban_key=` in `docs/testsystem_credentials.txt` — + `deploy_test.py` schreibt den Wert ebenfalls in die `.htaccess`. + Alle drei Stellen müssen denselben Schlüssel enthalten. 2. **Neue Importe verschlüsseln automatisch:** `import.php` verschlüsselt IBANs beim Migrieren aus dem Legacy-Dump direkt mit — Klartext-IBANs landen damit gar nicht erst in der neuen DB. Dafür läuft der Import im App-Container @@ -154,6 +207,13 @@ openssl rand -base64 32 ```bash docker compose exec app php encrypt_ibans.php ``` + **IBAN und Mobilnummern aus einem Kontodaten-CSV nachträglich einspielen** + (Vorschau ohne `--apply`, überschreibt keine vorhandenen Werte): + ```bash + docker compose exec app php import_accounts.php export_kontodaten_20261023_130939.csv + ``` + Mit gesetztem `IBAN_KEY_OLD` werden dabei vorhandene, noch mit dem alten + Schlüssel verschlüsselte IBANs auf den neuen Schlüssel umgeschlüsselt. 4. Danach erzeugte DB-Dumps enthalten nur noch verschlüsselte IBANs. **Hinweise** @@ -161,10 +221,11 @@ openssl rand -base64 32 - Ohne gesetzten `IBAN_KEY` wird die IBAN unverschlüsselt gespeichert (Abwärtskompatibilität) — dafür erscheint eine Warnung im Log. Für den Schutz ist der Schlüssel also zwingend zu setzen. -- **Der Schlüssel in `docker-compose.yml` und `iban_key` in - `docs/testsystem_credentials.txt` müssen identisch sein**, sonst kann die - Remote die lokal verschlüsselten IBANs nicht entschlüsseln (sie werden dann - als „fehlt“/leer angezeigt). +- **`IBAN_KEY` in `tools/.env` und `iban_key` in `docs/live_credentials.txt` + bzw. `docs/testsystem_credentials.txt` müssen identisch sein**, sonst kann die + jeweilige Umgebung die lokal verschlüsselten IBANs nicht entschlüsseln (sie + werden dann als „fehlt“/leer angezeigt). `live_migration.py --dry-run` prüft + die Übereinstimmung zwischen `tools/.env` und `docs/live_credentials.txt`. - Altbestand im Klartext bleibt lesbar (Werte ohne `enc:v1:`-Präfix), bis `encrypt_ibans.php` gelaufen ist. - Ein Verlust des Schlüssels macht die IBANs unlesbar — den Schlüssel sicher und @@ -184,7 +245,6 @@ Rundmails und Erinnerungen werden per SMTP verschickt. Konfiguriert wird das üb | `SMTP_USER`, `SMTP_PASS` | Zugangsdaten (leer lassen, wenn der Server keine Anmeldung verlangt) | | `MAIL_FROM`, `MAIL_FROM_NAME` | Absender der Mails | | `APP_URL` | Öffentliche Adresse des Tippspiels, wird für Links in Mails verwendet | -| `REMINDER_TOKEN` | Geheimes Token für die Erinnerungs-Route (siehe unten) | Lokal fängt [Mailpit](http://localhost:8025) alle Mails ab, es wird nichts an echte Adressen verschickt. @@ -193,21 +253,20 @@ Lokal fängt [Mailpit](http://localhost:8025) alle Mails ab, es wird nichts an e Spieler mit fehlenden Tipps oder fehlendem Joker bekommen automatisch eine Erinnerung. Ausgelöst wird das über eine von außen erreichbare Web-Route, die ein Cron-Job auf einem beliebigen Rechner aufruft: ```bash -curl -fsS -H "X-Reminder-Token: " "https:///index.php?page=reminder" -``` - -Alternativ kann das Token als Parameter übergeben werden, falls der aufrufende Dienst keine Header setzen kann (das Token landet dann allerdings in Server-Logs): - -```bash -curl -fsS "https:///index.php?page=reminder&token=" +curl -fsS "https:///index.php?page=reminder" ``` Beispiel für die crontab, täglich um 18:00 Uhr: ``` -0 18 * * * curl -fsS -H "X-Reminder-Token: geheim" "https://tippspiel.example.de/index.php?page=reminder" >> /var/log/tippspiel-reminder.log 2>&1 +0 18 * * * curl -fsS "https://tippspiel.example.de/index.php?page=reminder" >> /var/log/tippspiel-reminder.log 2>&1 ``` +> Die Route ist **nicht** durch ein Token geschützt: Wer die URL kennt, kann den +> Lauf auslösen. Das führt im 48-Stunden-Fenster höchstens zu zusätzlichen +> Erinnerungsmails und zum Aufräumen alter Einträge; Daten lassen sich darüber +> nicht ändern. Wenn das stört, die URL nicht öffentlich teilen. + **Was bei jedem Aufruf passiert:** - Es wird die erste tippbare Runde der aktiven Saison ermittelt, also die erste Runde ohne gesperrtes Spiel. @@ -223,29 +282,43 @@ Jeder Aufruf innerhalb des 48-Stunden-Fensters verschickt erneut eine Erinnerung | HTTP-Status | Bedeutung | |---|---| | `200` | Erfolgreich. Erste Zeile: Anzahl gelöschter alter Erinnerungen, zweite Zeile: Ergebnis des Versands, z.B. `Runde 17: Erinnerung an 3 Empfänger versendet.` oder `... - nichts zu tun.` | -| `403` | Token fehlt oder ist falsch | -| `503` | `REMINDER_TOKEN` ist auf dem Server nicht gesetzt, Erinnerungen sind deaktiviert | | `500` | Fehler, z.B. Mailserver nicht erreichbar (Meldung steht im Antworttext) | Mit `curl -f` beendet sich curl bei 4xx/5xx mit einem Fehlercode, sodass Cron-Überwachung Fehlschläge bemerkt. -Ein sicheres Token lässt sich z.B. so erzeugen: `openssl rand -hex 32` +## Datenbank-Dumps (Backups) -**Woher bekommt das externe System das Token?** +Für den Regelbetrieb gibt es ein eigenständiges Dump-Script (unabhängig von +`live_migration.py`): -Das Token ist ein gemeinsam genutztes Geheimnis („shared secret"), das du selbst -erzeugst und an zwei Stellen hinterlegst: +```bash +./tools/dump_tippspiel.py # Dump nach tools/dumps, 14 Stück behalten +./tools/dump_tippspiel.py --keep 30 # mehr Historie +./tools/dump_tippspiel.py --keep 0 # nichts aufräumen +./tools/dump_tippspiel.py --check # nur Verbindung prüfen +./tools/dump_tippspiel.py --dir /pfad # anderes Zielverzeichnis +``` -1. **Server-Seite** — damit die Route den Wert akzeptiert, muss `REMINDER_TOKEN` - als Umgebungsvariable gesetzt sein: - - lokal: `docker-compose.yml` (dort ist `REMINDER_TOKEN=lokal-geheim` hinterlegt), - - Testsystem: `reminder_token=` in `docs/testsystem_credentials.txt` ergänzen — - `deploy_test.py` schreibt den Wert als `SetEnv REMINDER_TOKEN` in die `.htaccess`. -2. **Externes System** — derselbe Wert muss im Cron-Job stehen, der die Route - aufruft (siehe curl-Beispiele oben). +- Zugangsdaten: `docs/live_credentials.txt`; überschreibbar per `DB_HOST`, + `DB_PORT`, `DB_USER`, `DB_PASS`, `DB_NAME`. +- Dateiname: `tools/dumps/tippspiel_live_.sql` +- Rechte: Verzeichnis `0700`, Datei `0600` (Dumps enthalten E-Mails, + PayPal-Adressen und IBAN-Ciphertexte). +- Aufräumen: standardmäßig bleiben die letzten 14 Dumps; gelöscht werden nur + Dateien nach dem Muster `tippspiel_live_*.sql`. +- `tools/dumps/` ist gitignored. -Ohne gesetzten `REMINDER_TOKEN` antwortet die Route mit `503` und der Cron löst -keine Erinnerungen aus. +Cron-Beispiel (täglich 03:30): + +``` +30 3 * * * /home/torsten/repos/tippspiel2027/tools/dump_tippspiel.py >> /var/log/tippspiel-dump.log 2>&1 +``` + +Zurückspielen (Vorsicht: der Dump enthält `DROP TABLE`/`CREATE TABLE`): + +```bash +mysql -h -u -p < tools/dumps/tippspiel_live_<...>.sql +``` ## Nützliche Befehle diff --git a/tippspiel/public/css/style.css b/tippspiel/public/css/style.css index 8fd5d40..c9e8a88 100644 --- a/tippspiel/public/css/style.css +++ b/tippspiel/public/css/style.css @@ -136,6 +136,12 @@ body.home-page .page { margin: 0.25em 0; text-align: center; } +/* Dauerhafte Profil-Warnungen (fehlende Zahlungsmöglichkeit/Handynummer): + gleiche Optik wie der Lock-Hinweis, aber ohne Pulsieren und etwas kleiner. */ +.lock-warning.profile-warning { + animation: none; + font-size: clamp(1.1rem, 2.6vw, 1.4rem); +} /* Direkter Weg zur Tippabgabe der gefährdeten Runde */ .lock-warning .lock-warning-link { display: inline-block; diff --git a/tippspiel/public/index.php b/tippspiel/public/index.php index 84cacf6..779eb27 100644 --- a/tippspiel/public/index.php +++ b/tippspiel/public/index.php @@ -1,5 +1,10 @@ trim($_POST['paypal'] ?? ''), 'mobile' => trim($_POST['mobile'] ?? ''), ]; - $data['iban'] = strtoupper(str_replace(' ', '', $data['iban'])); + $data['iban'] = Iban::normalize($data['iban']); $password_confirm = $_POST['password_confirm'] ?? ''; $error = null; @@ -137,6 +131,8 @@ if ($page === 'reminder') { $error = 'Bitte fülle alle Pflichtfelder aus.'; } elseif ($data['iban'] === '' && $data['paypal'] === '') { $error = 'Bitte gib eine Zahlungsmöglichkeit an (IBAN oder PayPal).'; + } elseif ($data['iban'] !== '' && !Iban::isValid($data['iban'])) { + $error = 'Bitte eine gültige IBAN angeben.'; } elseif ($data['password'] !== $password_confirm) { $error = 'Die Passwörter stimmen nicht überein.'; } elseif (User::findByEmail($data['email'])) { @@ -416,12 +412,14 @@ if ($page === 'reminder') { foreach (User::BANK_FIELDS as $field) { $data[$field] = $_POST[$field] ?? ''; } - $data['iban'] = strtoupper(str_replace(' ', '', $data['iban'])); + $data['iban'] = Iban::normalize($data['iban']); if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) { $error = 'Bitte eine gültige E-Mail-Adresse eintragen.'; } elseif (User::emailExists($data['email'], $user['id'])) { $error = 'Diese E-Mail-Adresse wird bereits von einem anderen Spieler verwendet.'; + } elseif ($data['iban'] !== '' && !Iban::isValid($data['iban'])) { + $error = 'Bitte eine gültige IBAN angeben.'; } else { User::updateProfile($user['id'], $data); $_SESSION['settings_message'] = 'Deine Daten wurden gespeichert.'; @@ -761,12 +759,16 @@ if ($page === 'reminder') { 'lastname' => $_POST['lastname'], 'email' => $_POST['email'], 'password' => $_POST['password'], - 'iban' => strtoupper(str_replace(' ', '', trim($_POST['iban'] ?? ''))), + 'iban' => Iban::normalize(trim($_POST['iban'] ?? '')), 'paypal' => trim($_POST['paypal'] ?? ''), 'mobile' => trim($_POST['mobile'] ?? ''), 'admin' => isset($_POST['admin']) ? 1 : 0, ]; + if ($data['iban'] !== '' && !Iban::isValid($data['iban'])) { + throw new \Exception('Bitte eine gültige IBAN angeben.'); + } + User::update($userId, $data); if ($currentSeason) { Payment::setPaidStatus($userId, $currentSeason['id'], isset($_POST['has_paid'])); @@ -1015,6 +1017,8 @@ if ($page === 'reminder') { try { $currentSeason = Season::getViewSeason(); $message = Setting::getMessage(); + // Profil-Warnungen gelten immer, nicht nur im Zeitfenster vor dem Lock. + $profileWarnings = User::getProfileWarnings((int)Auth::id()); $lockWarning = $currentSeason ? Round::getLockWarning((int)$currentSeason['id'], (int)Auth::id()) : null; diff --git a/tippspiel/src/Core/Iban.php b/tippspiel/src/Core/Iban.php new file mode 100644 index 0000000..73ee085 --- /dev/null +++ b/tippspiel/src/Core/Iban.php @@ -0,0 +1,51 @@ +command('RCPT TO:<' . $to . '>', [250, 251]); $this->command('DATA', [354]); + $at = strrpos($from, '@'); + $domain = $at === false ? 'localhost' : substr($from, $at + 1); + $messageId = '<' . bin2hex(random_bytes(16)) . '@' . $domain . '>'; + $boundary = '=_tippspiel_' . bin2hex(random_bytes(12)); + $headers = [ 'Date: ' . date('r'), 'From: ' . self::encodeHeader($fromName) . ' <' . $from . '>', 'To: <' . $to . '>', 'Subject: ' . self::encodeHeader($subject), + 'Message-ID: ' . $messageId, + 'X-Mailer: Tippspiel', 'MIME-Version: 1.0', - 'Content-Type: text/html; charset=UTF-8', - 'Content-Transfer-Encoding: base64', + 'Content-Type: multipart/alternative; boundary="' . $boundary . '"', ]; if ($replyTo) { $headers[] = 'Reply-To: <' . $replyTo . '>'; } - $body = chunk_split(base64_encode($html), 76, "\r\n"); + // Text- und HTML-Teil: reine HTML-Mails werden von vielen Filtern + // schlechter bewertet als multipart/alternative. + $body = + '--' . $boundary . "\r\n" + . "Content-Type: text/plain; charset=UTF-8\r\n" + . "Content-Transfer-Encoding: base64\r\n\r\n" + . chunk_split(base64_encode(self::toPlainText($html)), 76, "\r\n") + . '--' . $boundary . "\r\n" + . "Content-Type: text/html; charset=UTF-8\r\n" + . "Content-Transfer-Encoding: base64\r\n\r\n" + . chunk_split(base64_encode($html), 76, "\r\n") + . '--' . $boundary . "--\r\n"; + // base64 enthält keine Zeilen, die mit "." beginnen – kein Dot-Stuffing nötig fwrite($this->socket, implode("\r\n", $headers) . "\r\n\r\n" . $body . ".\r\n"); $this->expect([250]); } + private static function toPlainText($html) { + $text = preg_replace('//i', "\n", $html); + $text = preg_replace('/<\/p>/i', "\n\n", $text); + $text = html_entity_decode(strip_tags($text), ENT_QUOTES | ENT_HTML5, 'UTF-8'); + $text = preg_replace("/\n{3,}/", "\n\n", $text); + return trim($text); + } + private function command($line, array $expectedCodes) { fwrite($this->socket, $line . "\r\n"); return $this->expect($expectedCodes); diff --git a/tippspiel/src/Models/Round.php b/tippspiel/src/Models/Round.php index a7107e8..72237c9 100644 --- a/tippspiel/src/Models/Round.php +++ b/tippspiel/src/Models/Round.php @@ -161,11 +161,7 @@ class Round { 'remaining' => self::formatRemainingTime($secondsLeft), 'missing_tipps' => in_array((int)$userId, $missing['tipps'], true), 'missing_joker' => in_array((int)$userId, $missing['joker'], true), - 'missing_payment' => $user - ? trim((string)$user['iban']) === '' && trim((string)$user['paypal']) === '' - : false, 'missing_email' => $user ? trim((string)$user['email']) === '' : false, - 'missing_mobile' => $user ? trim((string)$user['mobile']) === '' : false, ]; } diff --git a/tippspiel/src/Models/User.php b/tippspiel/src/Models/User.php index ce75dae..7f0df0a 100644 --- a/tippspiel/src/Models/User.php +++ b/tippspiel/src/Models/User.php @@ -57,6 +57,29 @@ class User { return $stmt->fetch(\PDO::FETCH_ASSOC); } + /** + * Liefert unabhängig vom Runden-Lock fehlende Profildaten, die für die + * Teilnahme bzw. eine spätere Auszahlung gebraucht werden. + * + * @param int $userId + * @return array z.B. ['missing_payment' => true, 'missing_mobile' => true] + */ + public static function getProfileWarnings($userId) { + $user = self::findById($userId); + if (!$user) { + return []; + } + + $warnings = []; + if (trim((string)$user['iban']) === '' && trim((string)$user['paypal']) === '') { + $warnings['missing_payment'] = true; + } + if (trim((string)$user['mobile']) === '') { + $warnings['missing_mobile'] = true; + } + return $warnings; + } + /** * Prüft, ob der Name "Vorname Nachname" bereits vergeben ist (inkl. gelöschter Benutzer, * wie im Legacy RegistrationController). diff --git a/tippspiel/src/Views/admin/roundmails.php b/tippspiel/src/Views/admin/roundmails.php index 157330a..57e5d79 100644 --- a/tippspiel/src/Views/admin/roundmails.php +++ b/tippspiel/src/Views/admin/roundmails.php @@ -1,13 +1,13 @@ -

Runden-E-Mails

+

Rundmails

diff --git a/tippspiel/src/Views/home.php b/tippspiel/src/Views/home.php index d45cc1c..9e30fca 100644 --- a/tippspiel/src/Views/home.php +++ b/tippspiel/src/Views/home.php @@ -6,6 +6,20 @@ $bodyClass = 'home-page'; require __DIR__ . '/partials/header.php'; ?> + +
+ +

Fehlende Zahlungsmöglichkeit (IBAN oder PayPal)

+ + +

Fehlende Handynummer

+ +

+ Daten ergänzen +

+
+ +
@@ -14,15 +28,9 @@ require __DIR__ . '/partials/header.php';

Fehlender Joker für

- -

Fehlende Zahlungsmöglichkeit (IBAN oder PayPal)

-

Fehlende E-Mail-Adresse

- -

Fehlende Handynummer

-

sperrt sich: format('Y-m-d H:i:s'); ?> diff --git a/tippspiel/src/Views/info/guide_admin.php b/tippspiel/src/Views/info/guide_admin.php index 84e9fef..194b0c5 100644 --- a/tippspiel/src/Views/info/guide_admin.php +++ b/tippspiel/src/Views/info/guide_admin.php @@ -55,7 +55,7 @@ ohne alle Spieler umzuschalten:

auf andere Spieler aus.
  • Die persönliche Ansicht wirkt auf die Verwaltungsseiten (Spiele & Ergebnisse eintragen, Benutzer verwalten, Kontoliste, - Runden-E-Mails versenden) sowie auf die reinen Ansichtsseiten + Rundmails) sowie auf die reinen Ansichtsseiten (Startseite, Rangliste, Geldrangliste, Quoten, Anleitung). Nur die Tippabgabe bleibt immer bei der für alle aktiven Saison – getippt wird nur in der laufenden Saison.
  • diff --git a/tippspiel/src/Views/partials/header.php b/tippspiel/src/Views/partials/header.php index 8fbbd58..237a724 100644 --- a/tippspiel/src/Views/partials/header.php +++ b/tippspiel/src/Views/partials/header.php @@ -55,7 +55,7 @@ if (App\Core\Auth::check()) { Benutzer verwalten Saisons verwalten Spiele & Ergebnisse eintragen - Runden-E-Mails versenden + Rundmails Kontoliste Aktuelle Mitteilung Robo-Admin Aktivität diff --git a/tools/deploy_test.py b/tools/deploy_test.py index eb32546..b7c8129 100755 --- a/tools/deploy_test.py +++ b/tools/deploy_test.py @@ -71,7 +71,6 @@ def build_htaccess(creds): "SetEnv DB_NEW_NAME " + creds["mysql_db"], "SetEnv APP_URL " + APP_URL, "SetEnv IBAN_KEY " + creds.get("iban_key", ""), - "SetEnv REMINDER_TOKEN " + creds.get("reminder_token", ""), "SetEnv APIFOOTBALL_KEY " + creds.get("apifootball_key", ""), "", ] diff --git a/tools/docker-compose.yml b/tools/docker-compose.yml index c16af1f..4275a62 100644 --- a/tools/docker-compose.yml +++ b/tools/docker-compose.yml @@ -20,11 +20,10 @@ services: - MAIL_FROM=hoschis.tippspiel.info@gmail.com - MAIL_FROM_NAME=Hoschis Tippspiel - APP_URL=http://localhost:8080 - - REMINDER_TOKEN=lokal-geheim # Schlüssel für die IBAN-Verschlüsselung (base64, 32 Byte). - # MUSS mit "iban_key" in docs/testsystem_credentials.txt übereinstimmen: - # die lokale DB wird verschlüsselt und per deploy_test.py zur Remote synct. - - IBAN_KEY=/eG0tnvUGe02AR3ABgIJyMQdujnilxK7NkXhQubd3Rw= + # Wird aus tools/.env gelesen (gitignored). MUSS zum "iban_key" in + # docs/live_credentials.txt passen. + - IBAN_KEY=${IBAN_KEY:-} # API Key für api-sports.io - APIFOOTBALL_KEY=269586edd11d7fde903f692810326004 depends_on: diff --git a/tools/dump_tippspiel.py b/tools/dump_tippspiel.py new file mode 100755 index 0000000..422eb8b --- /dev/null +++ b/tools/dump_tippspiel.py @@ -0,0 +1,220 @@ +#!/usr/bin/env python3 +""" +Dumpt die Live-DB des Tippspiels nach tools/dumps. + +Aufruf: + ./dump_tippspiel.py # Dump nach tools/dumps, 14 Dumps behalten + ./dump_tippspiel.py --keep 30 # 30 Dumps behalten + ./dump_tippspiel.py --keep 0 # nichts aufräumen + ./dump_tippspiel.py --dir /pfad # anderes Zielverzeichnis + ./dump_tippspiel.py --check # nur Verbindung/Parameter prüfen + +Zugangsdaten kommen aus docs/live_credentials.txt (gitignored), überschreibbar +per Umgebungsvariablen DB_HOST / DB_PORT / DB_USER / DB_PASS / DB_NAME. + +Die Dumps enthalten personenbezogene Daten (E-Mails, PayPal-Adressen, +IBAN-Ciphertexte) und werden deshalb mit 0600 in einem 0700-Verzeichnis +abgelegt. Alte Dumps werden nur nach dem Muster tippspiel_live_*.sql gelöscht. +""" + +import argparse +import glob +import os +import subprocess +import sys +import tempfile +from datetime import datetime + +REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +CRED_FILE = os.path.join(REPO_ROOT, "docs", "live_credentials.txt") +DEFAULT_DUMP_DIR = os.path.join(REPO_ROOT, "tools", "dumps") +DUMP_PATTERN = "tippspiel_live_*.sql" +DEFAULT_KEEP = 14 + + +def log(message=""): + print(message, flush=True) + + +def read_credentials(path): + creds = {} + with open(path, "r", encoding="utf-8") as handle: + for line in handle: + line = line.strip() + if not line or line.startswith("#") or "=" not in line: + continue + key, _, value = line.partition("=") + creds[key.strip()] = value.strip() + return creds + + +def connection(): + if not os.path.isfile(CRED_FILE): + raise SystemExit("Fehler: Credentials nicht gefunden: %s" % CRED_FILE) + + creds = read_credentials(CRED_FILE) + missing = [key for key in ("ftp_url", "mysql_db", "mysql_pw") if not creds.get(key)] + if missing: + raise SystemExit( + "Fehler: Fehlende Einträge in %s: %s" % (CRED_FILE, ", ".join(missing)) + ) + + return { + "host": os.environ.get("DB_HOST") or creds.get("db_host") or creds["ftp_url"], + "port": os.environ.get("DB_PORT") or creds.get("db_port") or "3306", + "user": os.environ.get("DB_USER") or creds.get("mysql_user") or creds["mysql_db"], + "password": os.environ.get("DB_PASS") or creds["mysql_pw"], + "name": os.environ.get("DB_NAME") or creds["mysql_db"], + } + + +def dump_command(conn): + return [ + "mysqldump", + "--no-tablespaces", + "--column-statistics=0", + "--single-transaction", + "--quick", + "--default-character-set=utf8mb4", + "-h", str(conn["host"]), + "-P", str(conn["port"]), + "-u", str(conn["user"]), + str(conn["name"]), + ] + + +def ensure_private_dir(path): + os.makedirs(path, mode=0o700, exist_ok=True) + try: + os.chmod(path, 0o700) + except OSError: + pass + + +def check_connection(conn): + env = dict(os.environ, MYSQL_PWD=str(conn["password"])) + proc = subprocess.run( + [ + "mysql", + "--connect-timeout=15", + "--default-character-set=utf8mb4", + "-h", str(conn["host"]), + "-P", str(conn["port"]), + "-u", str(conn["user"]), + "-N", "-B", "-e", "SELECT 1;", + str(conn["name"]), + ], + env=env, + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + if proc.returncode != 0: + raise SystemExit( + "Fehler: Datenbank nicht erreichbar:\n%s" + % proc.stderr.decode("utf-8", "replace").strip() + ) + + +def dump_database(conn, path): + env = dict(os.environ, MYSQL_PWD=str(conn["password"])) + with open(path, "wb") as out: + proc = subprocess.run( + dump_command(conn), + env=env, + stdin=subprocess.DEVNULL, + stdout=out, + stderr=subprocess.PIPE, + ) + if proc.returncode != 0: + raise SystemExit( + "Fehler: mysqldump fehlgeschlagen:\n%s" + % proc.stderr.decode("utf-8", "replace").strip() + ) + if os.path.getsize(path) == 0: + raise SystemExit("Fehler: Dump ist leer: %s" % path) + os.chmod(path, 0o600) + return path + + +def prune(dump_dir, keep): + if keep <= 0: + return [] + dumps = sorted(glob.glob(os.path.join(dump_dir, DUMP_PATTERN))) + removed = [] + for path in dumps[:-keep]: + try: + os.unlink(path) + removed.append(path) + except OSError as exc: + log(" Warnung: konnte %s nicht löschen: %s" % (path, exc)) + return removed + + +def main(): + parser = argparse.ArgumentParser( + description="Dumpt die Live-DB nach tools/dumps und räumt alte Dumps auf.", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog="Beispiele:\n" + " %(prog)s\n" + " %(prog)s --keep 30\n" + " %(prog)s --keep 0\n" + " %(prog)s --check\n", + ) + parser.add_argument("--dir", default=os.environ.get("DUMP_DIR", DEFAULT_DUMP_DIR), + help="Zielverzeichnis (Default: %(default)s)") + parser.add_argument("--keep", type=int, default=DEFAULT_KEEP, + help="Anzahl aufzubewahrender Dumps, 0 = nichts löschen " + "(Default: %(default)s)") + parser.add_argument("--check", action="store_true", + help="nur Verbindung und Parameter prüfen, keinen Dump schreiben") + args = parser.parse_args() + + if args.keep < 0: + parser.error("--keep darf nicht negativ sein") + + conn = connection() + log("Ziel: %s@%s:%s/%s" % (conn["user"], conn["host"], conn["port"], conn["name"])) + + try: + check_connection(conn) + except SystemExit: + raise + log("Login: OK") + + if args.check: + log("Check beendet, kein Dump geschrieben.") + return 0 + + ensure_private_dir(args.dir) + stamp = datetime.now().strftime("%Y-%m-%d_%H%M%S") + final_path = os.path.join(args.dir, "tippspiel_live_%s.sql" % stamp) + + fd, tmp_path = tempfile.mkstemp(prefix=".tippspiel_dump_", suffix=".tmp", dir=args.dir) + os.close(fd) + try: + dump_database(conn, tmp_path) + os.replace(tmp_path, final_path) + finally: + if os.path.exists(tmp_path): + os.unlink(tmp_path) + + size_mb = os.path.getsize(final_path) / 1024 / 1024 + log("Dump: %s (%.1f MB, 0600)" % (final_path, size_mb)) + + removed = prune(args.dir, args.keep) + for path in removed: + log("Alte Datei gelöscht: %s" % path) + remaining = sorted(glob.glob(os.path.join(args.dir, DUMP_PATTERN))) + log("Vorhanden: %d Dump(s)%s" % ( + len(remaining), + "" if args.keep <= 0 else " (keep=%d)" % args.keep, + )) + return 0 + + +if __name__ == "__main__": + try: + sys.exit(main()) + except KeyboardInterrupt: + sys.exit(130) diff --git a/tools/import_accounts.php b/tools/import_accounts.php new file mode 100644 index 0000000..9a70368 --- /dev/null +++ b/tools/import_accounts.php @@ -0,0 +1,291 @@ + [--apply] +// +// Ohne --apply wird nur geprüft und berichtet, es wird nichts geschrieben. +// +// Verhalten: +// - Zuordnung über user_id, zusätzlich wird die E-Mail-Adresse verglichen. +// - Leere Felder werden gefüllt; bereits gesetzte Werte werden nicht +// überschrieben (der neuere Stand in der App gewinnt). +// - IBANs werden mit dem Schlüssel aus IBAN_KEY verschlüsselt (App\Core\Crypto). +// - Ist IBAN_KEY_OLD gesetzt, werden vorhandene, noch mit dem alten Schlüssel +// verschlüsselte IBANs auf den neuen Schlüssel umgeschlüsselt. +// +// Beispiel (Live, Schlüsselwechsel + Import): +// docker compose exec -T \ +// -e DB_HOST=... -e DB_USER=... -e DB_PASS=... -e DB_NEW_NAME=... \ +// -e IBAN_KEY="" -e IBAN_KEY_OLD="" \ +// app php import_accounts.php export_kontodaten_20261023_130939.csv --apply + +$apply = false; +$csvPath = null; +foreach (array_slice($argv, 1) as $arg) { + if ($arg === '--apply') { + $apply = true; + } elseif ($arg === '--help' || $arg === '-h') { + echo "Aufruf: php import_accounts.php [--apply]\n"; + exit(0); + } elseif ($csvPath === null) { + $csvPath = $arg; + } else { + fwrite(STDERR, "Unbekanntes Argument: $arg\n"); + exit(1); + } +} + +if ($csvPath === null) { + $candidates = glob(__DIR__ . '/export_kontodaten_*.csv') ?: []; + sort($candidates); + $csvPath = end($candidates) ?: null; +} +if ($csvPath === null || !is_file($csvPath)) { + fwrite(STDERR, "Fehler: CSV-Datei nicht gefunden.\n"); + exit(1); +} + +$host = getenv('DB_HOST') ?: '127.0.0.1'; +$port = (int)(getenv('DB_PORT') ?: 3306); +$user = getenv('DB_USER') ?: 'root'; +$pass = getenv('DB_PASS') ?: ''; +$dbName = getenv('DB_NEW_NAME') ?: 'tippspiel2027'; + +// Crypto-Klasse laden (funktioniert im Container und direkt auf dem Host). +$cryptoCandidates = [ + __DIR__ . '/../tippspiel/src/Core/Crypto.php', + __DIR__ . '/src/Core/Crypto.php', +]; +$cryptoFile = null; +foreach ($cryptoCandidates as $candidate) { + if (file_exists($candidate)) { + $cryptoFile = $candidate; + break; + } +} +if ($cryptoFile === null) { + die("Fehler: Crypto.php nicht gefunden.\n"); +} +require_once $cryptoFile; + +$ibanCandidates = [ + __DIR__ . '/../tippspiel/src/Core/Iban.php', + __DIR__ . '/src/Core/Iban.php', +]; +$ibanFile = null; +foreach ($ibanCandidates as $candidate) { + if (file_exists($candidate)) { + $ibanFile = $candidate; + break; + } +} +if ($ibanFile === null) { + die("Fehler: Iban.php nicht gefunden.\n"); +} +require_once $ibanFile; + +use App\Core\Crypto; +use App\Core\Iban; + +function maskedIban($iban) { + $iban = (string)$iban; + return strlen($iban) <= 6 ? '…' : substr($iban, 0, 4) . '…' . substr($iban, -4); +} + +try { + $newKey = (string)getenv('IBAN_KEY'); + if (Crypto::key() === null) { + die("Fehler: IBAN_KEY ist nicht gesetzt. Schlüssel erzeugen mit: openssl rand -base64 32\n"); + } + $oldKey = (string)getenv('IBAN_KEY_OLD'); + + $pdo = new PDO("mysql:host=$host;port=$port;dbname=$dbName;charset=utf8mb4", $user, $pass); + $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + + echo ($apply ? "MODUS: schreiben" : "MODUS: Vorschau (nichts wird geschrieben)") + . "\nZiel: {$user}@{$host}:{$port}/{$dbName}\n\n"; + + // Bestand laden + $users = []; + foreach ($pdo->query("SELECT id, email, iban, mobile FROM users") as $row) { + $users[(int)$row['id']] = $row; + } + + $updateIban = $pdo->prepare( + "UPDATE users SET iban = ?, updated_at = NOW() WHERE id = ? AND (iban IS NULL OR iban = '')" + ); + $updateMobile = $pdo->prepare( + "UPDATE users SET mobile = ?, updated_at = NOW() WHERE id = ? AND (mobile IS NULL OR mobile = '')" + ); + $updateExistingIban = $pdo->prepare("UPDATE users SET iban = ?, updated_at = NOW() WHERE id = ?"); + + // 1) Vorhandene IBANs auf den neuen Schlüssel umschlüsseln + $rekeyed = 0; + $rekeyFailed = []; + foreach ($users as $id => $row) { + $iban = trim((string)$row['iban']); + if ($iban === '') { + continue; + } + if (Crypto::isEncrypted($iban)) { + try { + Crypto::decrypt($iban); + continue; // bereits mit dem neuen Schlüssel lesbar + } catch (\Throwable $e) { + // mit altem Schlüssel versuchen + } + if ($oldKey === '') { + $rekeyFailed[] = $id; + continue; + } + putenv('IBAN_KEY=' . $oldKey); + try { + $plain = Crypto::decrypt($iban); + } catch (\Throwable $e) { + putenv('IBAN_KEY=' . $newKey); + $rekeyFailed[] = $id; + continue; + } + putenv('IBAN_KEY=' . $newKey); + $cipher = Crypto::encrypt($plain); + if ($apply) { + $updateExistingIban->execute([$cipher, $id]); + } + $users[$id]['iban'] = $cipher; + $rekeyed++; + } else { + // Klartext aus Altbestand + $cipher = Crypto::encrypt($iban); + if ($apply) { + $updateExistingIban->execute([$cipher, $id]); + } + $users[$id]['iban'] = $cipher; + $rekeyed++; + } + } + + // 2) CSV einlesen + $fh = fopen($csvPath, 'r'); + if ($fh === false) { + die("Fehler: CSV kann nicht geöffnet werden: $csvPath\n"); + } + $header = fgetcsv($fh, 0, ';'); + if ($header === false) { + die("Fehler: CSV ist leer.\n"); + } + $header[0] = preg_replace('/^\xEF\xBB\xBF/', '', $header[0]); + $columns = array_flip($header); + foreach (['user_id', 'email', 'iban', 'mobile'] as $required) { + if (!isset($columns[$required])) { + die("Fehler: Spalte '$required' fehlt im CSV.\n"); + } + } + + $rows = 0; + $missing = []; + $mismatch = []; + $invalid = []; + $ibanSet = 0; + $ibanExists = 0; + $ibanDiffers = []; + $mobileSet = 0; + $mobileExists = 0; + + while (($line = fgetcsv($fh, 0, ';')) !== false) { + if ($line === [null] || count($line) < count($header)) { + continue; + } + $rows++; + $id = (int)$line[$columns['user_id']]; + $email = trim((string)$line[$columns['email']]); + + if (!isset($users[$id])) { + $missing[] = $id; + continue; + } + if (strcasecmp(trim((string)$users[$id]['email']), $email) !== 0) { + $mismatch[] = $id; + continue; + } + + $rawIban = trim((string)$line[$columns['iban']]); + if ($rawIban !== '') { + $iban = Iban::normalize($rawIban); + if (!Iban::isValid($iban)) { + $invalid[] = $id . ' (' . maskedIban($iban) . ')'; + } elseif (trim((string)$users[$id]['iban']) === '') { + $cipher = Crypto::encrypt($iban); + if ($apply) { + $updateIban->execute([$cipher, $id]); + } + $users[$id]['iban'] = $cipher; + $ibanSet++; + } else { + $ibanExists++; + $existing = ''; + try { + $existing = Iban::normalize(Crypto::decrypt($users[$id]['iban'])); + } catch (\Throwable $e) { + $existing = null; + } + if ($existing !== $iban) { + $ibanDiffers[] = $id; + } + } + } + + $mobile = trim((string)$line[$columns['mobile']]); + if ($mobile !== '') { + if (trim((string)$users[$id]['mobile']) === '') { + if ($apply) { + $updateMobile->execute([$mobile, $id]); + } + $users[$id]['mobile'] = $mobile; + $mobileSet++; + } else { + $mobileExists++; + } + } + } + fclose($fh); + + echo "CSV: {$rows} Zeilen aus " . basename($csvPath) . "\n"; + echo "IBANs umgeschlüsselt/verschlüsselt: {$rekeyed}\n"; + echo "IBANs neu gesetzt: {$ibanSet}\n"; + echo "IBANs bereits vorhanden (behalten): {$ibanExists}\n"; + echo "Mobilnummern neu gesetzt: {$mobileSet}\n"; + echo "Mobilnummern bereits vorhanden: {$mobileExists}\n"; + + if ($ibanDiffers) { + echo "Hinweis: abweichende vorhandene IBAN (App-Stand gewinnt), User-IDs: " + . implode(', ', $ibanDiffers) . "\n"; + } + if ($invalid) { + echo "Ungültige IBAN im CSV (übersprungen): " . implode(', ', $invalid) . "\n"; + } + if ($missing) { + echo "Unbekannte User-IDs: " . implode(', ', $missing) . "\n"; + } + if ($mismatch) { + echo "E-Mail passt nicht zur User-ID: " . implode(', ', $mismatch) . "\n"; + } + if ($rekeyFailed) { + echo "WARNUNG: IBAN nicht entschlüsselbar (weder neuer noch alter Schlüssel), User-IDs: " + . implode(', ', $rekeyFailed) . "\n"; + } + + if (!$apply) { + echo "\nVorschau beendet. Zum Schreiben --apply ergänzen.\n"; + } else { + echo "\nImport abgeschlossen.\n"; + } +} catch (PDOException $e) { + fwrite(STDERR, "Datenbankfehler: " . $e->getMessage() . "\n"); + exit(1); +} catch (\Throwable $e) { + fwrite(STDERR, "Fehler: " . $e->getMessage() . "\n"); + exit(1); +} diff --git a/tools/import_from_dump.sh b/tools/import_from_dump.sh index 8e96c30..92b0fe9 100755 --- a/tools/import_from_dump.sh +++ b/tools/import_from_dump.sh @@ -16,7 +16,7 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" DUMP_DIR="${DUMP_DIR:-/home/torsten/repos/tippspiel/tools}" LEGACY_DB="${DB_OLD_NAME:-tippspiel_legacy}" -DUMP="$(ls -1 "$DUMP_DIR"/pfosten*.sql | tail -1)" +DUMP="${DUMP:-$(ls -1 "$DUMP_DIR"/pfosten*.sql | tail -1)}" if [[ -z "$DUMP" ]]; then echo "Fehler: Kein Dump (pfosten*.sql) in $DUMP_DIR gefunden." >&2 exit 1 diff --git a/tools/live_migration.py b/tools/live_migration.py new file mode 100755 index 0000000..4e333d1 --- /dev/null +++ b/tools/live_migration.py @@ -0,0 +1,790 @@ +#!/usr/bin/env python3 +""" +Go-Live: aktuellen Legacy-Live-Dump laden, lokal migrieren und ins Livesystem +(FTP-Ordner "tippspiel") ausrollen. + +Ablauf (wie import_from_dump.sh + deploy_test.py, nur mit Live-Zielen): + + 1. Dump der Legacy-Live-DB per mysqldump nach /pfosten_.sql + 2. import_from_dump.sh: Dump in die lokale Docker-DB "tippspiel_legacy" + einspielen und mit import.php nach "tippspiel2027" migrieren + 3. Lokale "tippspiel2027" dumpen und in die Live-DB aus + docs/live_credentials.txt einspielen (vorher Backup der Zieltabelle, + danach werden die vorhandenen Tabellen gedroppt) + 4. tippspiel/public und tippspiel/src per FTP nach /tippspiel hochladen + und dort die .htaccess mit den Live-Env-Variablen schreiben + +Zugangsdaten: + - Live-FTP + Live-DB: docs/live_credentials.txt + - Legacy-Live-DB (Quelle): wie tools/sync_live_to_test.sh, per Env + LEGACY_HOST / LEGACY_USER / LEGACY_PASS / LEGACY_DB überschreibbar + +Beispiele: + ./live_migration.py --dry-run # nur prüfen, nichts schreiben + ./live_migration.py # kompletter Go-Live + ./live_migration.py --db-only # nur DB, keine Dateien + ./live_migration.py --skip-db-import # nur Dateien neu hochladen + ./live_migration.py --source-dump /pfad/pfosten_2026-10-29_180000.sql + +Achtung: Schritt 3 leert die Live-DB. Das Script fragt vorher explizit nach +und legt vorher ein Backup der vorhandenen Live-Tabellen an. +""" + +import argparse +import io +import os +import re +import subprocess +import sys +import tempfile +import urllib.error +import urllib.request +from datetime import datetime +from ftplib import FTP, error_perm + +REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TOOLS_DIR = os.path.join(REPO_ROOT, "tools") +APP_DIR = os.path.join(REPO_ROOT, "tippspiel") +CRED_FILE = os.path.join(REPO_ROOT, "docs", "live_credentials.txt") +COMPOSE_FILE = os.path.join(TOOLS_DIR, "docker-compose.yml") +IMPORT_SCRIPT = os.path.join(TOOLS_DIR, "import_from_dump.sh") + +DEFAULT_DUMP_DIR = "/home/torsten/repos/tippspiel/tools" +DEFAULT_BACKUP_DIR = os.path.expanduser("~/backups/tippspiel-live") +REMOTE_ROOT = "tippspiel" +FTP_PORT = 21 +DEFAULT_APP_URL = "https://hoschis-tippspiel.de" + +# Lokale, migrierte DB (siehe tools/docker-compose.yml) +LOCAL_DB = { + "host": "127.0.0.1", + "port": "3306", + "user": "root", + "password": "root", + "name": "tippspiel2027", +} + +# Legacy-Live-DB als Quelle (siehe tools/sync_live_to_test.sh) +LEGACY_DB = { + "host": os.environ.get("LEGACY_HOST", "hoschis-tippspiel.de"), + "port": os.environ.get("LEGACY_PORT", "3306"), + "user": os.environ.get("LEGACY_USER", "d0274241"), + "password": os.environ.get("LEGACY_PASS", "superpfosten!"), + "name": os.environ.get("LEGACY_DB", "d0274241"), +} + +# Env-Variablen, die bei Bedarf aus den Credentials in die .htaccess wandern +OPTIONAL_ENV_PREFIXES = ("APIFOOTBALL_", "SMTP_", "MAIL_") + +# Reihenfolge der Env-Variablen in der .htaccess +HTACCESS_ORDER = ( + "DB_HOST", + "DB_USER", + "DB_PASS", + "DB_NEW_NAME", + "APP_URL", + "IBAN_KEY", + "APIFOOTBALL_KEY", + "SMTP_HOST", + "SMTP_PORT", + "SMTP_ENCRYPTION", + "SMTP_USER", + "SMTP_PASS", + "MAIL_FROM", + "MAIL_FROM_NAME", +) + +FTP_SKIP = {".DS_Store", "Thumbs.db"} + + +class MigrationError(RuntimeError): + pass + + +def log(message=""): + print(message, flush=True) + + +def timestamp(): + return datetime.now().strftime("%Y-%m-%d_%H%M%S") + + +def restrict_permissions(path): + """Setzt restriktive Rechte (0600) auf Dateien mit personenbezogenen Daten.""" + try: + os.chmod(path, 0o600) + except OSError: + pass + + +def ensure_private_dir(path): + """Legt ein Verzeichnis an und beschränkt es auf den eigenen User (0700).""" + os.makedirs(path, mode=0o700, exist_ok=True) + try: + os.chmod(path, 0o700) + except OSError: + pass + + +# -------------------------------------------------------------------------- +# Prozess-Helfer +# -------------------------------------------------------------------------- + +def run(cmd, env=None, stdin_path=None, capture=True, check=True): + """Führt einen Befehl aus und liefert stdout (bytes) bzw. None.""" + stdin = open(stdin_path, "rb") if stdin_path else subprocess.DEVNULL + try: + proc = subprocess.run( + cmd, + env=env, + stdin=stdin, + stdout=subprocess.PIPE if capture else None, + stderr=subprocess.PIPE if capture else None, + ) + finally: + if stdin_path: + stdin.close() + + if check and proc.returncode != 0: + stderr = "" + if capture and proc.stderr: + stderr = proc.stderr.decode("utf-8", "replace").strip() + raise MigrationError( + "Befehl fehlgeschlagen (Exit %d): %s\n%s" + % (proc.returncode, " ".join(cmd), stderr) + ) + return proc.stdout if capture else None + + +def mysql_env(conn): + return dict(os.environ, MYSQL_PWD=str(conn["password"])) + + +def mysql_cmd(conn, db=True): + cmd = [ + "mysql", + "--connect-timeout=15", + "--default-character-set=utf8mb4", + "-h", str(conn["host"]), + "-P", str(conn["port"]), + "-u", str(conn["user"]), + ] + if db: + cmd.append(str(conn["name"])) + return cmd + + +def mysql_query(conn, sql, db=True): + return run( + mysql_cmd(conn, db=db) + ["-N", "-B", "-e", sql], + env=mysql_env(conn), + ).decode("utf-8", "replace") + + +def mysqldump_cmd(conn): + return [ + "mysqldump", + "--no-tablespaces", + "--column-statistics=0", + "--single-transaction", + "--quick", + "--default-character-set=utf8mb4", + "-h", str(conn["host"]), + "-P", str(conn["port"]), + "-u", str(conn["user"]), + str(conn["name"]), + ] + + +def dump_database(conn, path): + """Schreibt einen konsistenten SQL-Dump nach path.""" + with open(path, "wb") as out: + proc = subprocess.run( + mysqldump_cmd(conn), + env=mysql_env(conn), + stdin=subprocess.DEVNULL, + stdout=out, + stderr=subprocess.PIPE, + ) + if proc.returncode != 0: + raise MigrationError( + "mysqldump für '%s' fehlgeschlagen:\n%s" + % (conn["name"], proc.stderr.decode("utf-8", "replace").strip()) + ) + if os.path.getsize(path) == 0: + raise MigrationError("Dump von '%s' ist leer: %s" % (conn["name"], path)) + # Dumps enthalten E-Mails, PayPal-Adressen und IBAN-Ciphertexte + restrict_permissions(path) + return path + + +def list_tables(conn): + out = mysql_query(conn, "SHOW TABLES;") + return sorted(line.strip() for line in out.splitlines() if line.strip()) + + +def table_counts(conn, tables): + if not tables: + return {} + sql = " UNION ALL ".join( + "SELECT '%s', COUNT(*) FROM `%s`" % (t, t) for t in tables + ) + out = mysql_query(conn, sql + ";") + counts = {} + for line in out.splitlines(): + if not line.strip(): + continue + name, _, value = line.partition("\t") + counts[name.strip()] = int(value.strip() or 0) + return counts + + +# -------------------------------------------------------------------------- +# Credentials / Konfiguration +# -------------------------------------------------------------------------- + +def read_credentials(path): + creds = {} + with open(path, "r", encoding="utf-8") as handle: + for line in handle: + line = line.strip() + if not line or line.startswith("#") or "=" not in line: + continue + key, _, value = line.partition("=") + creds[key.strip()] = value.strip() + return creds + + +def live_connection(creds): + return { + "host": creds.get("db_host") or creds["ftp_url"], + "port": creds.get("db_port") or "3306", + "user": creds.get("mysql_user") or creds["mysql_db"], + "password": creds["mysql_pw"], + "name": creds["mysql_db"], + } + + +def compose_iban_key(): + """Liest den lokalen IBAN_KEY (muss zum Live-Key passen). + + Reihenfolge: Umgebungsvariable IBAN_KEY, tools/.env (gitignored), + tools/docker-compose.yml (Altbestand). + """ + env_key = os.environ.get("IBAN_KEY") + if env_key: + return env_key + + env_file = os.path.join(TOOLS_DIR, ".env") + try: + with open(env_file, "r", encoding="utf-8") as handle: + for line in handle: + line = line.strip() + if line.startswith("IBAN_KEY="): + return line.split("=", 1)[1].strip().strip('"').strip("'") + except OSError: + pass + + try: + with open(COMPOSE_FILE, "r", encoding="utf-8") as handle: + text = handle.read() + except OSError: + return None + match = re.search(r"^\s*-\s*IBAN_KEY=(.*)$", text, re.MULTILINE) + return match.group(1).strip() if match else None + + +def optional_env(creds, args): + values = {} + for key, value in creds.items(): + upper = key.upper() + if upper.startswith(OPTIONAL_ENV_PREFIXES) and value: + values[upper] = value + if args.apifootball_key: + values["APIFOOTBALL_KEY"] = args.apifootball_key + return {k: v for k, v in values.items() if v} + + +def htaccess_value(value): + """SetEnv-Werte müssen gequotet werden: Werte mit Leerzeichen (z. B. + MAIL_FROM_NAME) führen sonst zu einem 500 auf jede Anfrage, weil Apache + die Zeile nicht parsen kann.""" + escaped = str(value).replace("\\", "\\\\").replace('"', '\\"') + return '"%s"' % escaped + + +def build_htaccess(creds, args, db_host): + values = { + "DB_HOST": db_host, + "DB_USER": creds.get("mysql_user") or creds["mysql_db"], + "DB_PASS": creds["mysql_pw"], + "DB_NEW_NAME": creds["mysql_db"], + "APP_URL": args.app_url, + "IBAN_KEY": creds.get("iban_key", ""), + } + values.update(optional_env(creds, args)) + + lines = [ + "# Auto-generiert von live_migration.py - NICHT manuell editieren", + "Options -Indexes", + "", + "", + "RewriteEngine On", + "RewriteCond %{HTTPS} off", + "RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]", + "", + "", + ] + for name in HTACCESS_ORDER: + if values.get(name): + lines.append("SetEnv %s %s" % (name, htaccess_value(values[name]))) + lines.append("") + return "\n".join(lines), values + + +def newest_dump(dump_dir): + candidates = sorted( + os.path.join(dump_dir, name) + for name in os.listdir(dump_dir) + if name.startswith("pfosten") and name.endswith(".sql") + ) if os.path.isdir(dump_dir) else [] + candidates = [path for path in candidates if os.path.getsize(path) > 0] + return candidates[-1] if candidates else None + + +# -------------------------------------------------------------------------- +# Schritte +# -------------------------------------------------------------------------- + +def step_dump_legacy(args): + dump_path = os.path.join(args.dump_dir, "pfosten_%s.sql" % timestamp()) + os.makedirs(args.dump_dir, exist_ok=True) + log("== Schritt 1/4: Dump der Legacy-Live-DB ==") + log(" Quelle: %s@%s/%s" % (LEGACY_DB["user"], LEGACY_DB["host"], LEGACY_DB["name"])) + log(" Ziel: %s" % dump_path) + dump_database(LEGACY_DB, dump_path) + log(" OK, %.1f MB" % (os.path.getsize(dump_path) / 1024 / 1024)) + return dump_path + + +def step_local_import(dump_path): + log("") + log("== Schritt 2/4: Lokaler Import + Migration ==") + log(" Dump: %s" % dump_path) + log(" Legacy-DB (Docker): %s" % "tippspiel_legacy") + log(" Ziel-DB (Docker): %s" % LOCAL_DB["name"]) + env = dict(os.environ, DUMP=dump_path, DUMP_DIR=os.path.dirname(dump_path)) + run(["bash", IMPORT_SCRIPT], env=env, capture=False) + + tables = list_tables(LOCAL_DB) + if not tables: + raise MigrationError("Lokale DB '%s' hat nach dem Import keine Tabellen." % LOCAL_DB["name"]) + counts = table_counts(LOCAL_DB, tables) + if not counts.get("users"): + raise MigrationError("Lokale DB '%s' enthält keine Users - Import fehlgeschlagen?" % LOCAL_DB["name"]) + log(" OK, %d Tabellen, %d Users, %d Tipps" + % (len(tables), counts.get("users", 0), counts.get("tipps", 0))) + + +def step_sync_live_db(args, live): + log("") + log("== Schritt 3/4: Live-DB '%s' auf %s aktualisieren ==" % (live["name"], live["host"])) + + existing = list_tables(live) + log(" Vorhandene Tabellen live: %d" % len(existing)) + + if existing: + ensure_private_dir(args.backup_dir) + backup_path = os.path.join( + args.backup_dir, "live_%s_%s.sql" % (live["name"], timestamp()) + ) + log(" Sichere vorhandene Live-DB nach %s ..." % backup_path) + dump_database(live, backup_path) + log(" Backup OK, %.1f MB" % (os.path.getsize(backup_path) / 1024 / 1024)) + + local_tables = list_tables(LOCAL_DB) + local_counts = table_counts(LOCAL_DB, local_tables) + fd, dump_path = tempfile.mkstemp(prefix="tippspiel2027_", suffix=".sql") + os.close(fd) + try: + log(" Dumpe lokale '%s' ..." % LOCAL_DB["name"]) + dump_database(LOCAL_DB, dump_path) + + if existing: + log(" Lösche %d vorhandene Tabellen live ..." % len(existing)) + drop_sql = ( + "SET FOREIGN_KEY_CHECKS=0; " + + " ".join("DROP TABLE IF EXISTS `%s`;" % t for t in existing) + + " SET FOREIGN_KEY_CHECKS=1;" + ) + mysql_query(live, drop_sql) + + log(" Spiele %.1f MB in '%s' ein ..." + % (os.path.getsize(dump_path) / 1024 / 1024, live["name"])) + run(mysql_cmd(live), env=mysql_env(live), stdin_path=dump_path) + finally: + if os.path.exists(dump_path): + os.unlink(dump_path) + + remote_tables = list_tables(live) + missing = sorted(set(local_tables) - set(remote_tables)) + if missing: + raise MigrationError("Nach dem Import fehlen live Tabellen: %s" % ", ".join(missing)) + + remote_counts = table_counts(live, remote_tables) + mismatches = [ + "%s (lokal %d, live %d)" % (t, local_counts.get(t, 0), remote_counts.get(t, 0)) + for t in local_tables + if local_counts.get(t, 0) != remote_counts.get(t, 0) + ] + if mismatches: + raise MigrationError("Zeilenanzahl weicht ab: %s" % ", ".join(mismatches)) + + log(" OK, %d Tabellen übernommen und verifiziert:" % len(remote_tables)) + for table in local_tables: + if remote_counts.get(table): + log(" %-16s %6d Zeilen" % (table, remote_counts[table])) + + +def smoke_test(base_url): + """Prüft nach dem Deploy, ob die neue App wirklich ausgeliefert wird.""" + base = base_url.rstrip("/") + log("") + log("== Smoke-Test gegen %s ==" % base) + failures = [] + + def fetch(path): + request = urllib.request.Request( + base + path, headers={"User-Agent": "live_migration/1.0"} + ) + with urllib.request.urlopen(request, timeout=20) as response: + return ( + response.status, + response.geturl(), + response.headers.get_all("Set-Cookie") or [], + response.read(300000), + ) + + try: + status, final_url, cookies, body = fetch("/") + text = body.decode("utf-8", "replace") + legacy = any("laravel_session" in cookie for cookie in cookies) + if status != 200: + failures.append("App: HTTP %d" % status) + elif legacy: + failures.append( + "App: noch die Legacy-App erreichbar (laravel_session) - " + "ist der Docroot schon auf /%s/public umgestellt?" % REMOTE_ROOT + ) + elif "Datenbankverbindung fehlgeschlagen" in text: + failures.append("App: DB-Verbindung fehlgeschlagen") + elif "page=login" not in text: + failures.append("App: Login-Seite der neuen App nicht erkannt") + else: + log(" [ok] App/Login erreichbar (%s)" % final_url) + except urllib.error.HTTPError as exc: + failures.append("App: HTTP %s" % exc.code) + except Exception as exc: + failures.append("App: %s: %s" % (type(exc).__name__, exc)) + + for path, label in (("/css/style.css", "CSS"), ("/manifest.json", "Manifest")): + try: + status, _, _, body = fetch(path) + if status == 200 and body: + log(" [ok] %s erreichbar (%d Bytes)" % (label, len(body))) + else: + failures.append("%s: HTTP %d oder leer" % (label, status)) + except Exception as exc: + failures.append("%s: %s" % (label, exc)) + + for message in failures: + log(" [FEHLER] %s" % message) + return not failures + + +def mkd_ignore_exists(ftp, name): + try: + ftp.mkd(name) + except error_perm as exc: + if not str(exc.args[0]).startswith("550"): + raise + + +def upload_dir(ftp, local_dir, remote_dir, skip=None): + mkd_ignore_exists(ftp, remote_dir) + skip = skip or set() + count = 0 + for name in sorted(os.listdir(local_dir)): + if name in skip or name in FTP_SKIP: + continue + local_path = os.path.join(local_dir, name) + if os.path.isfile(local_path): + with open(local_path, "rb") as handle: + ftp.storbinary("STOR " + name, handle) + count += 1 + elif os.path.isdir(local_path): + mkd_ignore_exists(ftp, name) + ftp.cwd(name) + count += upload_dir(ftp, local_path, remote_dir + "/" + name) + ftp.cwd("..") + return count + + +def step_upload(args, creds, htaccess): + log("") + log("== Schritt 4/4: FTP-Upload nach /%s ==" % REMOTE_ROOT) + ftp = FTP() + ftp.connect(creds["ftp_url"], FTP_PORT, timeout=60) + try: + ftp.login(creds["ftp_user"], creds["ftp_pw"]) + mkd_ignore_exists(ftp, REMOTE_ROOT) + ftp.cwd(REMOTE_ROOT) + for sub in ("public", "src"): + local_sub = os.path.join(APP_DIR, sub) + if not os.path.isdir(local_sub): + raise MigrationError("Lokales Verzeichnis fehlt: %s" % local_sub) + log(" Lade %s/ hoch ..." % sub) + mkd_ignore_exists(ftp, sub) + ftp.cwd(sub) + skip = {"img"} if (sub == "public" and args.skip_img_upload) else None + uploaded = upload_dir(ftp, local_sub, "%s/%s" % (REMOTE_ROOT, sub), skip=skip) + log(" %d Dateien hochgeladen." % uploaded) + ftp.cwd("..") + + log(" Schreibe public/.htaccess ...") + ftp.cwd("public") + ftp.storbinary("STOR .htaccess", io.BytesIO(htaccess.encode("utf-8"))) + ftp.cwd("..") + ftp.quit() + except Exception: + try: + ftp.close() + except Exception: + pass + raise + + +# -------------------------------------------------------------------------- +# Dry-Run +# -------------------------------------------------------------------------- + +def dry_run(args, creds, live): + log("== Dry-Run: es wird nichts geschrieben ==") + log("") + log("Live-FTP: %s@%s, Zielordner /%s" % (creds["ftp_user"], creds["ftp_url"], REMOTE_ROOT)) + log("Live-DB: %s@%s/%s" % (live["user"], live["host"], live["name"])) + log("App-URL: %s" % args.app_url) + log("Dump-Dir: %s" % args.dump_dir) + log("Backup-Dir:%s" % args.backup_dir) + log("") + + if args.source_dump: + if os.path.isfile(args.source_dump): + log("[ok] Source-Dump vorhanden: %s (%.1f MB)" + % (args.source_dump, os.path.getsize(args.source_dump) / 1024 / 1024)) + else: + log("[FEHLT] Source-Dump nicht gefunden: %s" % args.source_dump) + elif args.skip_dump: + found = newest_dump(args.dump_dir) + if found: + log("[ok] Neuester vorhandener Dump: %s" % found) + else: + log("[FEHLT] Kein pfosten*.sql in %s" % args.dump_dir) + else: + log("[plan] Würde Legacy-DB %s@%s/%s nach %s dumpen" + % (LEGACY_DB["user"], LEGACY_DB["host"], LEGACY_DB["name"], args.dump_dir)) + + try: + mysql_query(LOCAL_DB, "SELECT 1;") + log("[ok] Lokale Docker-DB erreichbar (%s@%s:%s)" + % (LOCAL_DB["user"], LOCAL_DB["host"], LOCAL_DB["port"])) + except Exception as exc: + log("[warn] Lokale Docker-DB nicht erreichbar: %s" % exc) + + try: + tables = list_tables(live) + log("[ok] Live-DB-Login erfolgreich, %d vorhandene Tabellen%s" + % (len(tables), " (werden gedroppt)" if tables else " (leer)")) + except Exception as exc: + log("[FEHLER] Live-DB-Login fehlgeschlagen: %s" % exc) + + try: + ftp = FTP() + ftp.connect(creds["ftp_url"], FTP_PORT, timeout=30) + ftp.login(creds["ftp_user"], creds["ftp_pw"]) + entries = [e for e in ftp.nlst() if e not in (".", "..")] + has_root = REMOTE_ROOT in entries + log("[ok] FTP-Login erfolgreich, Root: %s" % ", ".join(sorted(entries))) + log(" Zielordner /%s %s" % (REMOTE_ROOT, "existiert bereits" if has_root else "wird neu angelegt")) + ftp.quit() + except Exception as exc: + log("[FEHLER] FTP-Login fehlgeschlagen: %s" % exc) + + log("") + log("Geplante Schritte:") + if args.skip_db_import: + log(" - DB: übersprungen (--skip-db-import)") + else: + log(" - Legacy-Dump ziehen, lokal migrieren, Live-DB neu befüllen") + if args.db_only: + log(" - FTP: übersprungen (--db-only)") + else: + log(" - FTP: public/ + src/ nach /%s, .htaccess schreiben" % REMOTE_ROOT) + + +# -------------------------------------------------------------------------- +# Main +# -------------------------------------------------------------------------- + +def parse_args(): + parser = argparse.ArgumentParser( + description="Go-Live: Legacy-Dump laden, lokal migrieren und ins " + "Livesystem ausrollen (Live-DB + FTP-Ordner '%s')." % REMOTE_ROOT, + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog="Beispiele:\n" + " %(prog)s --dry-run\n" + " %(prog)s\n" + " %(prog)s --db-only\n" + " %(prog)s --skip-db-import\n", + ) + parser.add_argument("--dry-run", action="store_true", + help="nur prüfen (Zugänge, Dumps, Ziele), nichts ändern") + parser.add_argument("--yes", action="store_true", + help="ohne interaktive Rückfrage ausführen") + parser.add_argument("--db-only", action="store_true", + help="nur DB synchronisieren, keine Dateien hochladen") + parser.add_argument("--skip-db-import", action="store_true", + help="DB-Schritte überspringen (nur Dateien hochladen)") + parser.add_argument("--skip-dump", action="store_true", + help="keinen neuen Dump ziehen, neuesten vorhandenen nutzen") + parser.add_argument("--source-dump", metavar="PFAD", + help="vorhandenen Dump verwenden statt neu zu dumpen") + parser.add_argument("--dump-dir", default=os.environ.get("DUMP_DIR", DEFAULT_DUMP_DIR), + help="Verzeichnis für pfosten*.sql (Default: %(default)s)") + parser.add_argument("--backup-dir", default=os.environ.get("BACKUP_DIR", DEFAULT_BACKUP_DIR), + help="Verzeichnis für Live-DB-Backups (Default: %(default)s)") + parser.add_argument("--app-url", default=os.environ.get("APP_URL", DEFAULT_APP_URL), + help="APP_URL für die .htaccess (Default: %(default)s)") + parser.add_argument("--apifootball-key", default=os.environ.get("APIFOOTBALL_KEY"), + help="optionaler APIFOOTBALL_KEY für die .htaccess") + parser.add_argument("--skip-img-upload", action="store_true", + help="public/img/ nicht hochladen") + parser.add_argument("--check-url", nargs="?", const="", metavar="URL", + help="nach dem Deploy einen HTTP-Smoke-Test ausführen " + "(ohne Wert: APP_URL)") + parser.add_argument("--check-only", action="store_true", + help="nur den HTTP-Smoke-Test ausführen, nichts deployen") + return parser.parse_args() + + +def main(): + args = parse_args() + + if args.check_only: + return 0 if smoke_test(args.check_url or args.app_url) else 1 + + if not os.path.isfile(CRED_FILE): + log("Fehler: Credentials nicht gefunden: %s" % CRED_FILE) + return 1 + creds = read_credentials(CRED_FILE) + missing = [key for key in ("ftp_url", "ftp_user", "ftp_pw", "mysql_db", "mysql_pw") + if not creds.get(key)] + if missing: + log("Fehler: Fehlende Einträge in %s: %s" % (CRED_FILE, ", ".join(missing))) + return 1 + + if not creds.get("iban_key"): + log("Fehler: 'iban_key' fehlt in %s. Ohne Schlüssel würden IBANs im " + "Klartext in die Live-DB geschrieben." % CRED_FILE) + return 1 + local_key = compose_iban_key() + if local_key and local_key != creds["iban_key"]: + log("Fehler: lokaler IBAN_KEY (tools/.env bzw. tools/docker-compose.yml) weicht " + "von 'iban_key' in %s ab." % CRED_FILE) + log(" Lokal verschlüsselte IBANs wären live nicht lesbar.") + return 1 + + live = live_connection(creds) + app_db_host = creds.get("db_host") or "localhost" + htaccess, written_env = build_htaccess(creds, args, app_db_host) + + if args.dry_run: + dry_run(args, creds, live) + return 0 + + if args.skip_db_import and args.db_only: + log("Fehler: --skip-db-import und --db-only zusammen ergeben nichts zu tun.") + return 1 + + log("Ziel:") + log(" FTP: %s@%s -> /%s" % (creds["ftp_user"], creds["ftp_url"], REMOTE_ROOT)) + log(" DB: %s@%s/%s" % (live["user"], live["host"], live["name"])) + log(" App: %s" % args.app_url) + log(" Modus: %s" % ( + "nur DB" if args.db_only else + "nur Dateien" if args.skip_db_import else + "DB + Dateien" + )) + log("") + if "APIFOOTBALL_KEY" not in written_env: + log("Hinweis: Kein APIFOOTBALL_KEY gesetzt - automatischer Ergebnisabruf " + "bleibt live deaktiviert.") + if "SMTP_HOST" not in written_env: + log("Hinweis: Kein SMTP_HOST gesetzt - Mailversand (Rundmails/Erinnerungen) " + "bleibt live deaktiviert.") + log("") + log("ACHTUNG: Die Live-DB wird geleert und neu befüllt.") + if not args.yes: + answer = input("Zum Fortfahren 'JA' eingeben: ").strip() + if answer != "JA": + log("Abgebrochen.") + return 1 + + try: + if not args.skip_db_import: + if args.source_dump: + dump_path = args.source_dump + if not os.path.isfile(dump_path): + raise MigrationError("Source-Dump nicht gefunden: %s" % dump_path) + log("== Schritt 1/4: Dump der Legacy-Live-DB ==") + log(" Verwende vorhandenen Dump: %s" % dump_path) + elif args.skip_dump: + dump_path = newest_dump(args.dump_dir) + if not dump_path: + raise MigrationError("Kein pfosten*.sql in %s gefunden." % args.dump_dir) + log("== Schritt 1/4: Dump der Legacy-Live-DB ==") + log(" Verwende neuesten vorhandenen Dump: %s" % dump_path) + else: + dump_path = step_dump_legacy(args) + + step_local_import(dump_path) + step_sync_live_db(args, live) + + if not args.db_only: + step_upload(args, creds, htaccess) + + if args.check_url is not None: + if args.db_only: + log("Hinweis: --check-url wird bei --db-only übersprungen.") + elif not smoke_test(args.check_url or args.app_url): + log("") + log("WARNUNG: Smoke-Test fehlgeschlagen. Die Dateien sind " + "hochgeladen, die App liefert aber (noch) nicht wie erwartet " + "aus - z. B. weil der Docroot noch auf die Legacy-App zeigt.") + return 1 + + except MigrationError as exc: + log("") + log("FEHLER: %s" % exc) + return 1 + + log("") + log("Fertig.") + log(" App: https://%s (FTP-Ordner /%s)" % (creds["ftp_url"], REMOTE_ROOT)) + if not args.db_only: + log(" .htaccess liegt in /%s/public/.htaccess" % REMOTE_ROOT) + return 0 + + +if __name__ == "__main__": + sys.exit(main())