Loheide-eu-mitarbeiterplatt.../tests/Feature/Update/UpdaterTest.php
Friederich Loheide e211db9f30
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Has been skipped
CI / PHP 8.4 / mariadb:10.6 (pull_request) Has been skipped
CI / PHP 8.3 / mariadb:11.4 (pull_request) Has been skipped
CI / PHP 8.4 / mariadb:11.4 (pull_request) Has been skipped
CI / PHP 8.3 / mysql:8.0 (pull_request) Has been skipped
CI / PHP 8.4 / mysql:8.0 (pull_request) Has been skipped
CI / PHP 8.3 / mysql:8.4 (pull_request) Has been skipped
CI / PHP 8.4 / mysql:8.4 (pull_request) Has been skipped
CI / Browser-Tests (pull_request) Failing after 7m34s
CI / PHP 8.3 / mysql:8.4-1 (pull_request) Successful in 11m55s
CI / Bekannte Sicherheitslücken in Paketen (pull_request) Successful in 16m43s
CI / Build-Artefakte aktuell (pull_request) Successful in 13m17s
Automatische Updates, Browser-Tests, CI grün (0.63.0)
- Opt-in „Updates automatisch installieren“ (AutoUpdate, alle 10 Minuten)
- Playwright-Tests in tests/Browser, CI-Job „Browser-Tests“
- CI: volle Matrix nur auf main, PRs mit einem MySQL-Job
- MySQL-JSON-Reihenfolge in zwei Tests, QM-Suchausschnitt ohne <mark>, h1 auf Startseite/Editor

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 17:29:20 +00:00

252 lines
9.9 KiB
PHP
Raw Permalink 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\AutoUpdate;
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);
// Schritt 1: Dateien getauscht, Datenbank folgt in der nächsten Anfrage (mit dem neuen Code)
$this->assertSame(self::SHA, $result['sha']);
$this->assertTrue($result['pending']);
$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('finalize', app(UpdateProgress::class)->get()['step']);
$this->assertTrue(app(MaintenanceFlag::class)->isActive());
$this->assertTrue(app(UpdateProgress::class)->isRunning());
$this->assertSame(0, AuditLog::query()->where('action', 'update.installed')->count());
// Eine Anfrage, die schon vor dem Austausch lief, darf Schritt 2 nicht ausführen
$this->assertNull($this->updater($target)->finishPending(microtime(true) - 60));
$this->assertFileExists(Updater::pendingPath());
// Schritt 2
$finished = $this->updater($target)->finishPending(microtime(true) + 1);
$this->assertSame(0, $finished['migrations']);
$this->assertSame(1, $finished['files']);
$this->assertFileDoesNotExist(Updater::pendingPath());
$this->assertNull($this->updater($target)->finishPending(microtime(true) + 1));
$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->assertEquals(['channel' => 'stable', 'sha' => self::SHA, 'migrations' => 0, 'files' => 1], $audit->data);
}
public function test_auto_update_installs_only_when_enabled(): void
{
$zip = $this->zipContents();
Http::fake([
'*/check*' => Http::response(['has_update' => true, 'latest_sha' => self::SHA, 'version' => '9.9.0']),
'*/version*' => Http::response(['sha' => self::SHA]),
'*/zip*' => Http::response($zip, 200, ['X-Commit-Sha' => self::SHA, 'X-Content-Sha256' => hash('sha256', $zip)]),
]);
$target = $this->dir.'/app-root';
mkdir($target);
$this->app->instance(Updater::class, $this->updater($target)); // nie über das echte Projekt
$auto = app(AutoUpdate::class);
$this->assertNull($auto->run());
$this->assertFileDoesNotExist($target.'/app/Neu.php');
$this->actingAs(User::factory()->admin()->create())
->postJson('/admin/update/auto', ['enabled' => true])->assertOk();
$this->assertTrue($auto->enabled());
$this->assertTrue($auto->run()['pending']);
$this->assertFileExists($target.'/app/Neu.php');
$this->assertSame('finalize', app(UpdateProgress::class)->get()['step']);
// Während der zweite Schritt aussteht, startet kein weiteres Update
$this->assertNull($auto->run());
}
public function test_next_request_finishes_a_pending_update(): void
{
app(MaintenanceFlag::class)->activate(300);
app(UpdateProgress::class)->set(75, 'finalize', 'Datenbank folgt …');
file_put_contents(Updater::pendingPath(), json_encode(['channel' => 'stable', 'sha' => self::SHA, 'files' => 3, 'user_id' => null, 'ready_at' => $_SERVER['REQUEST_TIME_FLOAT'] - 1]));
$this->get('/login')->assertOk();
$this->assertFileDoesNotExist(Updater::pendingPath());
$this->assertFalse(app(MaintenanceFlag::class)->isActive());
$this->assertSame('done', app(UpdateProgress::class)->get()['step']);
$this->assertSame(1, AuditLog::query()->where('action', 'update.installed')->count());
}
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']);
}
}