Some checks failed
CI / PHP Lint-1 (push) Successful in 43s
CI / PHP Lint (push) Successful in 45s
CI / PHP Lint (pull_request) Successful in 38s
CI / Unit Tests & Static Analysis (push) Failing after 43s
CI / PHP Lint-1 (pull_request) Successful in 40s
CI / Unit Tests & Static Analysis (pull_request) Failing after 41s
Aktualisierung per Klick im Administrationsbereich, ohne Zugang zum Server. Der bisherige Updater lud ein ZIP und entpackte es ungeprüft über die Produktion; das ist vollständig ersetzt. Neu in updater/: - Version: Release-Version als Konstante, installierter Commit-SHA in storage/.version (Datei, nicht Datenbank - der Updater muss den Stand auch bei hängender Datenbank lesen können) - Progress: Fortschrittsdatei mit eigenem Fehlerzustand (pct = -1) und Verfallszeit, damit ein abgestürzter Lauf den nächsten nicht blockiert - Maintenance: Wartungsmarkierung mit Ablauf, die sich beim Prüfen selbst aufräumt - ProxyClient: nur HTTPS, Zertifikatsprüfung an, begrenzte Weiterleitungen, 503 mirror_pending/not_released als Bitte um Geduld - Updater: Prüfsumme gegen X-Content-Sha256, zweistufiger ZIP-Slip-Schutz, geschützte Pfade, atomares Schreiben je Datei, nie löschen - AutoMigrate: zieht Migrationen beim ersten Seitenaufruf nach, nur bei geändertem Fingerabdruck und mit Sperre gegen Parallellauf - guard.php: Wartungs-Wächter für die Einstiegsseiten, JSON für die Schnittstellen; ausgenommen bleiben Update-Seite, Anmeldung und Health-Check - Changelog: zerlegt CHANGELOG.md und rendert Markdown ohne unsichere Links Oberfläche: Seite "Aktualisierung" mit Stand, Kanal, Suche, Fortschritt, Migrationsliste und Versionsgeschichte. Der Datenschutzhinweis steht dauerhaft neben der Schaltfläche, nicht in einem Dialog. Fehlt changelog_preview in der Antwort, bleibt es bei "neue Fassung verfügbar" - kein leerer Kasten, kein erfundener Ersatztext. Commit-Texte werden nirgends angezeigt. Außerdem (Punkt 2 der Liste): - cron_test.php entfernt: ohne jede Anmeldung erreichbar, meldete Datenbankfehler samt Meldung und die Spalten der vouchers-Tabelle - test.php verweigert ohne config.php die Auskunft; bisher lief die Diagnose auf einer frisch entpackten Installation ohne Anmeldung PHPStan prüft jetzt den gesamten updater/-Ordner. 18 neue Tests (93 Tests, 243 Assertions), Ablauf gegen den echten Update-Dienst durchgespielt. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
509 lines
18 KiB
PHP
509 lines
18 KiB
PHP
<?php
|
|
namespace Updater;
|
|
|
|
/**
|
|
* Der eigentliche Selbst-Updater.
|
|
*
|
|
* [diese Installation] <-HTTPS-> [Update-Proxy] <-pull- [Git-Repository]
|
|
*
|
|
* Ablauf einer Aktualisierung (installUpdate): Wartungsmodus an, Ziel-Stand
|
|
* ermitteln, ZIP streamen, kontrolliert entpacken, ueber die Produktion legen,
|
|
* Migrationen nachziehen, Caches leeren, neuen Stand speichern.
|
|
*
|
|
* Es gibt keine Tags und keine Releases: gezaehlt wird der Stand des Branches,
|
|
* seine Identitaet ist der Commit-SHA.
|
|
*/
|
|
class Updater
|
|
{
|
|
public const CHANNELS = [
|
|
'stable' => 'https://update.loheide.cloud/unifivouchertool',
|
|
'development' => 'https://update.loheide.cloud/unifivouchertool-development',
|
|
];
|
|
|
|
/**
|
|
* Pfade, die beim Uebernehmen NIE ueberschrieben werden - relativ zum
|
|
* Projektstamm. Ordner enden auf "/", Dateien treffen exakt.
|
|
*/
|
|
public const PROTECTED_PATHS = [
|
|
'config.php', // Zugangsdaten und APP_KEY dieser Installation
|
|
'.env',
|
|
'.env.example',
|
|
'.git/',
|
|
'.gitignore',
|
|
'uploads/', // hochgeladene Logos und Hintergruende
|
|
'vendor/',
|
|
'node_modules/',
|
|
'composer.lock',
|
|
'package-lock.json',
|
|
'updater/storage/', // installierter Stand, Fortschritt, Staging
|
|
'data/', // lokale Datenbankdateien, falls vorhanden
|
|
];
|
|
|
|
/** @var \Database|null */
|
|
private $db;
|
|
/** @var AuditLogger|null */
|
|
private $audit;
|
|
/** @var string */
|
|
private $channel;
|
|
/** @var ProxyClient */
|
|
private $client;
|
|
/** @var string */
|
|
private $rootDir;
|
|
/** @var string */
|
|
private $storageDir;
|
|
|
|
/**
|
|
* $rootDir und $db sind absichtlich ueberschreibbar: die Dateioperationen
|
|
* (Entpacken, Uebernehmen) lassen sich so in einem Testverzeichnis pruefen,
|
|
* ohne Datenbank und ohne die laufende Installation anzufassen.
|
|
*/
|
|
public function __construct(?\Database $db = null, ?AuditLogger $audit = null, string $channel = 'stable', ?ProxyClient $client = null, ?string $rootDir = null)
|
|
{
|
|
$this->db = $db;
|
|
$this->audit = $audit;
|
|
$this->channel = isset(self::CHANNELS[$channel]) ? $channel : 'stable';
|
|
$this->client = $client ?: new ProxyClient(self::CHANNELS[$this->channel]);
|
|
$this->rootDir = $rootDir !== null ? rtrim($rootDir, '/') : dirname(__DIR__);
|
|
$this->storageDir = Version::storageDir();
|
|
if (!is_dir($this->storageDir)) {
|
|
@mkdir($this->storageDir, 0775, true);
|
|
}
|
|
}
|
|
|
|
public function channel(): string
|
|
{
|
|
return $this->channel;
|
|
}
|
|
|
|
public function proxyUrl(): string
|
|
{
|
|
return $this->client->baseUrl();
|
|
}
|
|
|
|
// ---------------------------------------------------------------- Pruefen
|
|
|
|
/**
|
|
* Fragt den Proxy, ob es etwas Neues gibt.
|
|
*
|
|
* Angezeigt werden spaeter genau zwei Dinge: dass eine neue Fassung da ist
|
|
* und was daran neu ist. Commit-Texte gibt es hier bewusst nicht - die sind
|
|
* fuer Entwickler geschrieben.
|
|
*/
|
|
public function check(): array
|
|
{
|
|
$current = Version::current();
|
|
$data = $this->client->check($current);
|
|
|
|
$result = [
|
|
'has_update' => (bool)($data['has_update'] ?? false),
|
|
'current_sha' => $current,
|
|
'latest_sha' => (string)($data['latest_sha'] ?? ''),
|
|
'version' => $data['version'] ?? null,
|
|
'released_at' => $data['released_at'] ?? null,
|
|
'versions_behind' => (int)($data['versions_behind'] ?? 0),
|
|
'channel' => $this->channel,
|
|
'changelog' => null,
|
|
'changelog_complete' => true,
|
|
'channel_switch' => null,
|
|
];
|
|
|
|
// Ein fehlendes changelog_preview bedeutet: es gibt nichts zu berichten.
|
|
// Dann bleibt es bei "neue Fassung verfuegbar" - ohne Ersatztext.
|
|
if (isset($data['changelog_preview']['entries']) && is_array($data['changelog_preview']['entries'])) {
|
|
$entries = [];
|
|
foreach ($data['changelog_preview']['entries'] as $entry) {
|
|
if (!is_array($entry)) {
|
|
continue;
|
|
}
|
|
$entries[] = [
|
|
'version' => (string)($entry['version'] ?? ''),
|
|
'heading' => (string)($entry['heading'] ?? ''),
|
|
'text' => (string)($entry['text'] ?? ''),
|
|
];
|
|
}
|
|
if ($entries !== []) {
|
|
$result['changelog'] = $entries;
|
|
$result['changelog_complete'] = (bool)($data['changelog_preview']['complete'] ?? true);
|
|
}
|
|
}
|
|
|
|
// Kanalwechsel: der gemeldete Stand stammt aus einem anderen Kanal.
|
|
// Bei "back" ist er aelter als der laufende - das ist beim Zurueck-
|
|
// schalten auf den Hauptkanal der Normalfall und kein Grund abzubrechen.
|
|
if (isset($data['channel_switch']) && is_array($data['channel_switch'])) {
|
|
$result['channel_switch'] = [
|
|
'from_channel' => (string)($data['channel_switch']['from_channel'] ?? ''),
|
|
'to_channel' => (string)($data['channel_switch']['to_channel'] ?? ''),
|
|
'direction' => ($data['channel_switch']['direction'] ?? 'forward') === 'back' ? 'back' : 'forward',
|
|
];
|
|
}
|
|
|
|
// Frische Installation: der Proxy antwortet wie "aktuell". Den
|
|
// gemeldeten Stand merken wir uns, damit die naechste Pruefung
|
|
// vergleichen kann.
|
|
if ($current === null && Version::isSha($result['latest_sha'])) {
|
|
Version::save($result['latest_sha']);
|
|
$result['current_sha'] = $result['latest_sha'];
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
// ------------------------------------------------------------ Installation
|
|
|
|
/**
|
|
* Fuehrt die Aktualisierung durch. Der Wartungsmodus wird im finally in
|
|
* jedem Fall wieder abgebaut.
|
|
*
|
|
* @return array{success:bool, sha?:string, migrations?:int, error?:string}
|
|
*/
|
|
public function installUpdate(?int $userId = null): array
|
|
{
|
|
$zipPath = $this->storageDir . '/.update.zip';
|
|
$staging = $this->storageDir . '/.update-staging';
|
|
$targetSha = '';
|
|
$migrations = 0;
|
|
|
|
Progress::set(0, 'maintenance', 'Wartungsmodus wird aktiviert …');
|
|
Maintenance::activate();
|
|
|
|
try {
|
|
Progress::set(5, 'version', 'Neuesten Stand ermitteln …');
|
|
$version = $this->client->version();
|
|
$targetSha = (string)($version['sha'] ?? '');
|
|
if (!Version::isSha($targetSha)) {
|
|
throw new \RuntimeException('Der Update-Dienst hat keinen gueltigen Stand gemeldet.');
|
|
}
|
|
|
|
Progress::set(20, 'download', 'Update wird geladen …');
|
|
$meta = $this->client->downloadZip($targetSha, $zipPath);
|
|
$this->assertIsZip($zipPath);
|
|
$this->assertChecksum($zipPath, $meta['content_sha256']);
|
|
|
|
Progress::set(50, 'extract', 'Update wird entpackt …');
|
|
$this->removeTree($staging);
|
|
@mkdir($staging, 0775, true);
|
|
$this->extractZip($zipPath, $staging);
|
|
$stagingRoot = $this->resolveStagingRoot($staging);
|
|
|
|
Progress::set(65, 'apply', 'Dateien werden uebernommen …');
|
|
$this->applyStaging($stagingRoot);
|
|
|
|
Progress::set(80, 'migrate', 'Datenbank wird nachgezogen …');
|
|
$migrations = count($this->runMigrations());
|
|
|
|
Progress::set(90, 'cache', 'Zwischenspeicher wird geleert …');
|
|
$this->clearCaches();
|
|
|
|
Version::save($targetSha);
|
|
Progress::set(100, 'done', 'Aktualisierung abgeschlossen.');
|
|
|
|
$this->log('update_installed', [
|
|
'channel' => $this->channel,
|
|
'sha' => $targetSha,
|
|
'migrations' => $migrations,
|
|
], $userId);
|
|
|
|
return ['success' => true, 'sha' => $targetSha, 'migrations' => $migrations];
|
|
} catch (\Throwable $e) {
|
|
Progress::error($e->getMessage());
|
|
$this->log('update_failed', [
|
|
'channel' => $this->channel,
|
|
'sha' => $targetSha,
|
|
'error' => $e->getMessage(),
|
|
], $userId);
|
|
|
|
return ['success' => false, 'error' => $e->getMessage()];
|
|
} finally {
|
|
Maintenance::deactivate();
|
|
@unlink($zipPath);
|
|
$this->removeTree($staging);
|
|
}
|
|
}
|
|
|
|
/** Migrationen einzeln ausloesbar (Schaltflaeche in der Oberflaeche). */
|
|
public function runMigrations(): array
|
|
{
|
|
$runner = new MigrationRunner($this->requireDb()->getConnection(), __DIR__ . '/migrations', $this->storageDir);
|
|
|
|
return $runner->runPending(true);
|
|
}
|
|
|
|
public function migrationStatus(): array
|
|
{
|
|
$runner = new MigrationRunner($this->requireDb()->getConnection(), __DIR__ . '/migrations', $this->storageDir);
|
|
|
|
return $runner->status();
|
|
}
|
|
|
|
// ------------------------------------------------------------------ Pruefen
|
|
|
|
/**
|
|
* Beginnt die Datei mit "PK"? Sonst hat in Wahrheit eine Fehlerseite
|
|
* geantwortet, und das Entpacken wuerde mit einer nichtssagenden Meldung
|
|
* scheitern.
|
|
*/
|
|
private function assertIsZip(string $path): void
|
|
{
|
|
$fh = @fopen($path, 'rb');
|
|
$magic = $fh ? (string)fread($fh, 2) : '';
|
|
if ($fh) {
|
|
fclose($fh);
|
|
}
|
|
if ($magic !== 'PK') {
|
|
throw new \RuntimeException(
|
|
'Die Gegenstelle hat kein Update-Paket geliefert (Antwort ist kein ZIP-Archiv).'
|
|
);
|
|
}
|
|
}
|
|
|
|
/** Der Proxy nennt die Pruefsumme des Pakets im Kopf X-Content-Sha256. */
|
|
private function assertChecksum(string $path, string $expected): void
|
|
{
|
|
$expected = strtolower(trim($expected));
|
|
if ($expected === '' || !preg_match('/^[0-9a-f]{64}$/', $expected)) {
|
|
return; // Kopfzeile fehlt: nicht erzwingbar, aber auch kein Fehler
|
|
}
|
|
|
|
$actual = hash_file('sha256', $path);
|
|
if (!is_string($actual) || !hash_equals($expected, $actual)) {
|
|
throw new \RuntimeException('Das geladene Update-Paket ist unvollstaendig oder beschaedigt.');
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------- Entpacken
|
|
|
|
/**
|
|
* Entpackt kontrolliert - Eintrag fuer Eintrag, mit zweistufigem
|
|
* ZIP-Slip-Schutz:
|
|
* a) Namen vorab ablehnen (absolute Pfade, Laufwerksbuchstaben,
|
|
* ".."-Segmente, Null-Bytes)
|
|
* b) nach dem Schreiben den aufgeloesten Pfad pruefen
|
|
* Die zweite Stufe faengt ab, was die erste uebersieht.
|
|
*/
|
|
public function extractZip(string $zipPath, string $destination): int
|
|
{
|
|
if (!class_exists('ZipArchive')) {
|
|
throw new \RuntimeException('Die PHP-Erweiterung "zip" fehlt - das Update kann nicht entpackt werden.');
|
|
}
|
|
|
|
$zip = new \ZipArchive();
|
|
if ($zip->open($zipPath) !== true) {
|
|
throw new \RuntimeException('Das Update-Paket konnte nicht geoeffnet werden.');
|
|
}
|
|
|
|
if (!is_dir($destination) && !@mkdir($destination, 0775, true) && !is_dir($destination)) {
|
|
$zip->close();
|
|
throw new \RuntimeException('Arbeitsverzeichnis konnte nicht angelegt werden: ' . $destination);
|
|
}
|
|
$realDest = realpath($destination);
|
|
if ($realDest === false) {
|
|
$zip->close();
|
|
throw new \RuntimeException('Arbeitsverzeichnis konnte nicht aufgeloest werden: ' . $destination);
|
|
}
|
|
|
|
$written = 0;
|
|
for ($i = 0; $i < $zip->numFiles; $i++) {
|
|
$name = (string)$zip->getNameIndex($i);
|
|
if ($name === '' || !self::isSafeEntryName($name)) {
|
|
continue; // Stufe a
|
|
}
|
|
|
|
$target = $realDest . '/' . $name;
|
|
if (substr($name, -1) === '/') {
|
|
if (!is_dir($target)) {
|
|
@mkdir($target, 0775, true);
|
|
}
|
|
continue;
|
|
}
|
|
|
|
$dir = dirname($target);
|
|
if (!is_dir($dir) && !@mkdir($dir, 0775, true) && !is_dir($dir)) {
|
|
throw new \RuntimeException('Verzeichnis konnte nicht angelegt werden: ' . $dir);
|
|
}
|
|
|
|
$stream = $zip->getStream($name);
|
|
if ($stream === false) {
|
|
continue;
|
|
}
|
|
$out = @fopen($target, 'wb');
|
|
if ($out === false) {
|
|
fclose($stream);
|
|
throw new \RuntimeException('Datei konnte nicht geschrieben werden: ' . $name);
|
|
}
|
|
stream_copy_to_stream($stream, $out);
|
|
fclose($stream);
|
|
fclose($out);
|
|
|
|
// Stufe b: liegt die geschriebene Datei wirklich im Arbeitsverzeichnis?
|
|
$real = realpath($target);
|
|
if ($real === false || strpos($real, $realDest . DIRECTORY_SEPARATOR) !== 0) {
|
|
@unlink($target);
|
|
continue;
|
|
}
|
|
$written++;
|
|
}
|
|
$zip->close();
|
|
|
|
return $written;
|
|
}
|
|
|
|
/** Stufe a des ZIP-Slip-Schutzes, ohne Dateisystem-Zugriff pruefbar. */
|
|
public static function isSafeEntryName(string $name): bool
|
|
{
|
|
if ($name === '' || strpos($name, "\0") !== false) {
|
|
return false;
|
|
}
|
|
$normalised = str_replace('\\', '/', $name);
|
|
if ($normalised[0] === '/' || preg_match('#^[a-zA-Z]:#', $normalised)) {
|
|
return false;
|
|
}
|
|
foreach (explode('/', $normalised) as $segment) {
|
|
if ($segment === '..') {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
/** Das Archiv hat einen gemeinsamen Deckel-Ordner - der faellt weg. */
|
|
private function resolveStagingRoot(string $staging): string
|
|
{
|
|
$entries = array_values(array_diff((array)scandir($staging), ['.', '..']));
|
|
if (count($entries) === 1 && is_dir($staging . '/' . $entries[0])) {
|
|
return $staging . '/' . $entries[0];
|
|
}
|
|
|
|
return $staging;
|
|
}
|
|
|
|
// --------------------------------------------------------------- Uebernehmen
|
|
|
|
/**
|
|
* Legt den neuen Stand ueber die Produktion.
|
|
*
|
|
* Zwei bewusste Entscheidungen:
|
|
* - je Datei erst daneben schreiben, dann umbenennen. Ein Abbruch
|
|
* mittendrin hinterlaesst sonst eine halbe PHP-Datei, die den naechsten
|
|
* Aufruf mit einem Parse-Fehler abwuergt.
|
|
* - nur ueberschreiben und ergaenzen, nie loeschen. Eine im neuen Stand
|
|
* fehlende Datei bleibt liegen: etwas unaufgeraeumter, aber ein Fehler
|
|
* in der Pfadberechnung nimmt so keine Nutzdaten mit.
|
|
*
|
|
* @return int Anzahl uebernommener Dateien
|
|
*/
|
|
public function applyStaging(string $stagingRoot): int
|
|
{
|
|
$stagingRoot = rtrim($stagingRoot, '/');
|
|
$iterator = new \RecursiveIteratorIterator(
|
|
new \RecursiveDirectoryIterator($stagingRoot, \FilesystemIterator::SKIP_DOTS),
|
|
\RecursiveIteratorIterator::SELF_FIRST
|
|
);
|
|
|
|
$count = 0;
|
|
foreach ($iterator as $item) {
|
|
$rel = ltrim(str_replace('\\', '/', substr($item->getPathname(), strlen($stagingRoot))), '/');
|
|
if ($rel === '' || self::isProtected($rel)) {
|
|
continue;
|
|
}
|
|
|
|
$target = $this->rootDir . '/' . $rel;
|
|
if ($item->isDir()) {
|
|
if (!is_dir($target)) {
|
|
@mkdir($target, 0775, true);
|
|
}
|
|
continue;
|
|
}
|
|
|
|
$dir = dirname($target);
|
|
if (!is_dir($dir) && !@mkdir($dir, 0775, true) && !is_dir($dir)) {
|
|
throw new \RuntimeException('Verzeichnis konnte nicht angelegt werden: ' . dirname($rel));
|
|
}
|
|
|
|
$tmp = $target . '.new';
|
|
if (!@copy($item->getPathname(), $tmp)) {
|
|
throw new \RuntimeException(
|
|
'Datei konnte nicht geschrieben werden: ' . $rel . ' (Schreibrechte des Webservers pruefen)'
|
|
);
|
|
}
|
|
if (!@rename($tmp, $target)) {
|
|
@unlink($tmp);
|
|
throw new \RuntimeException('Datei konnte nicht ersetzt werden: ' . $rel);
|
|
}
|
|
$count++;
|
|
}
|
|
|
|
return $count;
|
|
}
|
|
|
|
public static function isProtected(string $rel): bool
|
|
{
|
|
$rel = ltrim(str_replace('\\', '/', $rel), '/');
|
|
foreach (self::PROTECTED_PATHS as $protected) {
|
|
if (substr($protected, -1) === '/') {
|
|
if (strpos($rel . '/', $protected) === 0) {
|
|
return true;
|
|
}
|
|
} elseif ($rel === $protected) {
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
// -------------------------------------------------------------------- Rest
|
|
|
|
/**
|
|
* Zwischenspeicher leeren. Ohne das Verwerfen des Bytecode-Caches laeuft
|
|
* nach dem Update noch eine Weile der alte Code.
|
|
*/
|
|
private function clearCaches(): void
|
|
{
|
|
if (function_exists('opcache_reset')) {
|
|
@opcache_reset();
|
|
}
|
|
if (function_exists('apcu_clear_cache')) {
|
|
@apcu_clear_cache();
|
|
}
|
|
// Dieses Projekt haelt keinen View-, Config- oder Route-Cache vor;
|
|
// der Migrations-Fingerabdruck wird verworfen, damit der naechste
|
|
// Aufruf sauber nachzieht.
|
|
$fingerprint = $this->storageDir . '/.migration-fingerprint';
|
|
if (is_file($fingerprint)) {
|
|
@unlink($fingerprint);
|
|
}
|
|
}
|
|
|
|
private function removeTree(string $dir): void
|
|
{
|
|
if (!is_dir($dir)) {
|
|
return;
|
|
}
|
|
$it = new \RecursiveIteratorIterator(
|
|
new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS),
|
|
\RecursiveIteratorIterator::CHILD_FIRST
|
|
);
|
|
foreach ($it as $item) {
|
|
$item->isDir() ? @rmdir($item->getPathname()) : @unlink($item->getPathname());
|
|
}
|
|
@rmdir($dir);
|
|
}
|
|
|
|
private function requireDb(): \Database
|
|
{
|
|
if ($this->db === null) {
|
|
throw new \RuntimeException('Fuer Migrationen wird eine Datenbankverbindung benoetigt.');
|
|
}
|
|
|
|
return $this->db;
|
|
}
|
|
|
|
private function log(string $action, array $details, ?int $userId): void
|
|
{
|
|
if ($this->audit) {
|
|
$this->audit->log($action, $details, $userId);
|
|
}
|
|
}
|
|
}
|