Loheide-eu-mitarbeiterplatt.../tests/Feature/Update/UpdaterTest.php
Friederich Loheide 43244d751a Self-Updater und Lizenzprüfung
Umsetzung von docs/specs/self-updater.md für Laravel:
- Installierter Stand als SHA in storage/.version, Fortschritt in storage/.update-progress,
  selbstheilender Wartungsmodus in storage/.maintenance
- Update-Client je Kanal (stable/development), nur HTTPS, begrenzte Redirects,
  ZIP-Download per Stream mit PK- und SHA-256-Prüfung
- Entpacken mit zweistufigem ZIP-Slip-Schutz, Übernahme mit geschützten Pfaden
  (atomar je Datei, nie löschen), Migrationen, Cache- und OPcache-Reset
- Lizenzspeicher außerhalb der DB, Geräte-ID als Zufallszahl, rotierendes Gerätetoken
  wird bei jeder Antwort (auch Fehler und Downloads) sofort gespeichert
- Lizenzfehler mit verständlichen Meldungen – sie sperren nie das Portal
- Seite „Aktualisierung“ mit Kanal, Suche, Changelog-Vorschau, Fortschritt,
  Migrationen, Änderungsprotokoll, Lizenz und Datenschutzhinweis
- Wartungs-Middleware (503 + Retry-After) und Auto-Migration per Fingerabdruck
- Audit-Log für Updates, Kanalwechsel und Lizenzänderungen
- Version 0.2.0

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-26 06:02:19 +00:00

193 lines
6.9 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace Tests\Feature\Update;
use App\Models\AuditLog;
use App\Models\User;
use App\Support\License\LicenseStore;
use App\Support\Update\Changelog;
use App\Support\Update\Channels;
use App\Support\Update\Filesystem;
use App\Support\Update\InstalledVersion;
use App\Support\Update\MaintenanceFlag;
use App\Support\Update\Migrations;
use App\Support\Update\UpdateProgress;
use App\Support\Update\Updater;
use App\Support\Update\ZipExtractor;
use App\Version;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use RuntimeException;
use Tests\TestCase;
use ZipArchive;
class UpdaterTest extends TestCase
{
use RefreshDatabase;
private const SHA = '1111111111111111111111111111111111111111';
private string $dir;
protected function setUp(): void
{
parent::setUp();
$this->dir = sys_get_temp_dir().'/inhaus-upd-'.bin2hex(random_bytes(4));
mkdir($this->dir.'/storage', 0777, true);
$this->app->useStoragePath($this->dir.'/storage');
$this->app->instance(LicenseStore::class, new LicenseStore($this->dir.'/license.json'));
$this->app->instance(InstalledVersion::class, new InstalledVersion($this->dir.'/.version'));
$this->app->instance(UpdateProgress::class, new UpdateProgress($this->dir.'/.progress'));
$this->app->instance(MaintenanceFlag::class, new MaintenanceFlag($this->dir.'/.maintenance'));
mkdir($this->dir.'/storage/app', 0777, true);
}
protected function tearDown(): void
{
Filesystem::deleteDirectory($this->dir);
parent::tearDown();
}
private function zipContents(): string
{
$path = $this->dir.'/build.zip';
$zip = new ZipArchive;
$zip->open($path, ZipArchive::CREATE | ZipArchive::OVERWRITE);
$zip->addFromString('repo-1111111/app/Neu.php', '<?php // neu');
$zip->addFromString('repo-1111111/.env', 'APP_KEY=aus-dem-archiv');
$zip->close();
return file_get_contents($path);
}
private function updater(string $target): Updater
{
return new Updater(
app(Channels::class),
app(InstalledVersion::class),
app(UpdateProgress::class),
app(MaintenanceFlag::class),
new ZipExtractor,
app(Migrations::class),
$target,
);
}
public function test_full_update_run(): void
{
$zip = $this->zipContents();
Http::fake([
'update.loheide.cloud/mitarbeiterportal/version*' => Http::response(['sha' => self::SHA, 'version' => '0.3.0']),
'update.loheide.cloud/mitarbeiterportal/zip*' => Http::response($zip, 200, [
'Content-Type' => 'application/zip',
'X-Commit-Sha' => self::SHA,
'X-Content-Sha256' => hash('sha256', $zip),
]),
]);
$target = $this->dir.'/app-root';
mkdir($target);
file_put_contents($target.'/.env', 'APP_KEY=geheim');
$admin = User::factory()->admin()->create();
$result = $this->updater($target)->installUpdate($admin->id);
$this->assertSame(self::SHA, $result['sha']);
$this->assertSame(0, $result['migrations']);
$this->assertFileExists($target.'/app/Neu.php');
$this->assertSame('APP_KEY=geheim', file_get_contents($target.'/.env'));
$this->assertSame(self::SHA, app(InstalledVersion::class)->current());
$this->assertSame('done', app(UpdateProgress::class)->get()['step']);
$this->assertSame(100, app(UpdateProgress::class)->get()['pct']);
$this->assertFalse(app(MaintenanceFlag::class)->isActive());
$this->assertDirectoryDoesNotExist($this->dir.'/storage/.update-staging');
$audit = AuditLog::query()->where('action', 'update.installed')->firstOrFail();
$this->assertSame($admin->id, $audit->user_id);
$this->assertSame(['channel' => 'stable', 'sha' => self::SHA, 'migrations' => 0, 'files' => 1], $audit->data);
}
public function test_error_page_instead_of_zip_is_rejected(): void
{
Http::fake([
'*/version*' => Http::response(['sha' => self::SHA]),
'*/zip*' => Http::response('<html>Proxy-Fehler</html>', 200, ['Content-Type' => 'text/html']),
]);
$target = $this->dir.'/app-root';
mkdir($target);
try {
$this->updater($target)->installUpdate();
$this->fail('Das Update hätte abbrechen müssen.');
} catch (RuntimeException $e) {
$this->assertStringContainsString('kein ZIP-Archiv', $e->getMessage());
}
$progress = app(UpdateProgress::class)->get();
$this->assertSame('error', $progress['step']);
$this->assertSame(-1, $progress['pct']);
$this->assertFalse(app(MaintenanceFlag::class)->isActive(), 'Wartungsmodus muss auch im Fehlerfall enden.');
$this->assertNull(app(InstalledVersion::class)->current());
$this->assertSame(1, AuditLog::query()->where('action', 'update.failed')->count());
}
public function test_checksum_mismatch_is_rejected(): void
{
$zip = $this->zipContents();
Http::fake([
'*/version*' => Http::response(['sha' => self::SHA]),
'*/zip*' => Http::response($zip, 200, ['X-Content-Sha256' => str_repeat('0', 64)]),
]);
$target = $this->dir.'/app-root';
mkdir($target);
$this->expectExceptionMessage('Prüfsumme');
$this->updater($target)->installUpdate();
}
public function test_migration_counter(): void
{
$migrations = app(Migrations::class);
$this->assertSame([], $migrations->pending());
$this->assertSame(0, $migrations->run());
$this->assertNotEmpty($migrations->status());
$this->assertTrue(collect($migrations->status())->every(fn (array $m) => $m['ran']));
$this->assertSame(40, strlen($migrations->fingerprint()));
}
public function test_changelog_is_parsed_and_rendered_safely(): void
{
$sections = app(Changelog::class)->sections(<<<'MD'
# Änderungsprotokoll
Einleitung
## 1.2.0
- Neue **Funktion**
- [Link](javascript:alert(1)) und <script>alert(1)</script>
## 1.1.3 – Fehlerbehebung
- Fix
MD);
$this->assertCount(2, $sections);
$this->assertSame('1.2.0', $sections[0]['version']);
$this->assertSame('1.1.3', $sections[1]['version']);
$this->assertSame('1.1.3 – Fehlerbehebung', $sections[1]['heading']);
$this->assertStringContainsString('<strong>Funktion</strong>', $sections[0]['html']);
$this->assertStringNotContainsString('javascript:', $sections[0]['html']);
$this->assertStringNotContainsString('<script>', $sections[0]['html']);
$this->assertSame(Version::VERSION, app(Changelog::class)->sections()[0]['version']);
}
}