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>
This commit is contained in:
Friederich Loheide 2026-09-26 06:02:19 +00:00
parent a36752e09a
commit 43244d751a
41 changed files with 3184 additions and 3 deletions

View file

@ -0,0 +1,148 @@
<?php
namespace Tests\Feature\Update;
use App\Support\Update\Filesystem;
use App\Support\Update\ProtectedPaths;
use App\Support\Update\StagingApplier;
use App\Support\Update\ZipExtractor;
use RuntimeException;
use Tests\TestCase;
use ZipArchive;
class ArchiveTest extends TestCase
{
private string $dir;
protected function setUp(): void
{
parent::setUp();
$this->dir = sys_get_temp_dir().'/inhaus-zip-'.bin2hex(random_bytes(4));
mkdir($this->dir);
}
protected function tearDown(): void
{
Filesystem::deleteDirectory($this->dir);
parent::tearDown();
}
/**
* @param array<string, string> $files
*/
private function zip(array $files): string
{
$path = $this->dir.'/archiv.zip';
$zip = new ZipArchive;
$zip->open($path, ZipArchive::CREATE | ZipArchive::OVERWRITE);
foreach ($files as $name => $contents) {
$zip->addFromString($name, $contents);
}
$zip->close();
return $path;
}
public function test_common_top_level_folder_is_stripped(): void
{
$zip = $this->zip([
'repo-abc/app/Version.php' => '<?php // neu',
'repo-abc/README.md' => 'Hallo',
]);
$count = (new ZipExtractor)->extract($zip, $this->dir.'/staging');
$this->assertSame(2, $count);
$this->assertFileExists($this->dir.'/staging/app/Version.php');
$this->assertFileExists($this->dir.'/staging/README.md');
}
public function test_zip_slip_creates_nothing_outside_staging(): void
{
$zip = $this->zip([
'repo-abc/ok.txt' => 'ok',
'repo-abc/../../evil.php' => '<?php echo "böse";',
]);
try {
(new ZipExtractor)->extract($zip, $this->dir.'/staging');
$this->fail('Das Archiv hätte abgelehnt werden müssen.');
} catch (RuntimeException $e) {
$this->assertStringContainsString('Unsicherer Pfad', $e->getMessage());
}
$this->assertFileDoesNotExist($this->dir.'/evil.php');
$this->assertFileDoesNotExist(dirname($this->dir).'/evil.php');
$this->assertFileDoesNotExist($this->dir.'/staging/../evil.php');
}
public function test_dangerous_entry_names_are_rejected(): void
{
foreach (['../evil', 'a/../../evil', '/etc/passwd', 'C:\\Windows\\evil.dll', "a\0b", '..\\evil'] as $name) {
$this->assertFalse(ZipExtractor::isSafeEntryName($name), $name);
}
foreach (['app/Version.php', 'repo-abc/public/.htaccess', 'a/..b/c'] as $name) {
$this->assertTrue(ZipExtractor::isSafeEntryName($name), $name);
}
}
public function test_protected_paths_are_skipped_and_nothing_is_deleted(): void
{
$staging = $this->dir.'/staging';
$target = $this->dir.'/target';
foreach ([
'app/Neu.php' => 'neu',
'app/Version.php' => 'neue Version',
'.env' => 'APP_KEY=aus-dem-archiv',
'storage/app/license.json' => '{}',
'public/uploads/bild.jpg' => 'fremd',
'plugins/kunde/plugin.json' => '{}',
'vendor/autoload.php' => 'neu',
] as $file => $contents) {
@mkdir(dirname("{$staging}/{$file}"), 0777, true);
file_put_contents("{$staging}/{$file}", $contents);
}
foreach ([
'app/Version.php' => 'alte Version',
'app/Alt.php' => 'bleibt',
'.env' => 'APP_KEY=geheim',
'storage/app/license.json' => '{"email":"lizenz@example.com"}',
] as $file => $contents) {
@mkdir(dirname("{$target}/{$file}"), 0777, true);
file_put_contents("{$target}/{$file}", $contents);
}
$result = (new StagingApplier(new ProtectedPaths(config('updater.protected_paths'))))->apply($staging, $target);
$this->assertSame(['copied' => 3, 'skipped' => 4], $result);
$this->assertSame('neue Version', file_get_contents("{$target}/app/Version.php"));
$this->assertSame('neu', file_get_contents("{$target}/app/Neu.php"));
$this->assertSame('neu', file_get_contents("{$target}/vendor/autoload.php"));
$this->assertSame('bleibt', file_get_contents("{$target}/app/Alt.php"));
$this->assertSame('APP_KEY=geheim', file_get_contents("{$target}/.env"));
$this->assertSame('{"email":"lizenz@example.com"}', file_get_contents("{$target}/storage/app/license.json"));
$this->assertFileDoesNotExist("{$target}/public/uploads/bild.jpg");
$this->assertFileDoesNotExist("{$target}/plugins/kunde/plugin.json");
$this->assertEmpty(glob("{$target}/app/*.update-*"));
}
public function test_protected_path_matching(): void
{
$paths = new ProtectedPaths(['.env', 'storage/', 'config/local.php']);
$this->assertTrue($paths->isProtected('.env'));
$this->assertTrue($paths->isProtected('storage'));
$this->assertTrue($paths->isProtected('storage/logs/x.log'));
$this->assertTrue($paths->isProtected('config/local.php'));
$this->assertFalse($paths->isProtected('.env.example'));
$this->assertFalse($paths->isProtected('storagebox/a'));
$this->assertFalse($paths->isProtected('config/app.php'));
}
}

View file

@ -0,0 +1,193 @@
<?php
namespace Tests\Feature\Update;
use App\Models\User;
use App\Support\License\LicenseService;
use App\Support\License\LicenseStore;
use App\Support\License\ServerError;
use App\Support\Update\Channels;
use App\Support\Update\Filesystem;
use App\Support\Update\InstalledVersion;
use App\Version;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;
class LicenseTest extends TestCase
{
use RefreshDatabase;
private string $dir;
protected function setUp(): void
{
parent::setUp();
$this->dir = sys_get_temp_dir().'/inhaus-lic-'.bin2hex(random_bytes(4));
mkdir($this->dir);
$this->app->instance(LicenseStore::class, new LicenseStore($this->dir.'/license.json'));
$this->app->instance(InstalledVersion::class, new InstalledVersion($this->dir.'/.version'));
}
protected function tearDown(): void
{
Filesystem::deleteDirectory($this->dir);
parent::tearDown();
}
private function store(): LicenseStore
{
return app(LicenseStore::class);
}
public function test_device_id_is_created_once_and_kept(): void
{
$id = $this->store()->deviceId();
$this->assertMatchesRegularExpression('/^[0-9a-f]{32}$/', $id);
$this->assertSame($id, (new LicenseStore($this->dir.'/license.json'))->deviceId());
}
public function test_license_headers_are_sent_with_device_data(): void
{
$this->store()->setLicense('lizenz@firma.de', 'SCHLUESSEL-123');
$this->store()->saveDeviceToken('token-1');
Http::fake(['*' => Http::response(['has_update' => false, 'latest_sha' => str_repeat('a', 40)])]);
app(Channels::class)->client()->check(null);
Http::assertSent(function (Request $request) {
parse_str((string) parse_url($request->url(), PHP_URL_QUERY), $query);
return $request->hasHeader('X-License-Email', 'lizenz@firma.de')
&& $request->hasHeader('Authorization', 'Bearer SCHLUESSEL-123')
&& $request->hasHeader('X-Device-Id', $this->store()->deviceId())
&& $request->hasHeader('X-Device-Token', 'token-1')
&& ($query['hostname'] ?? null) === gethostname()
&& str_contains($query['device_label'] ?? '', base_path())
&& ($query['app_version'] ?? null) === Version::VERSION
&& str_starts_with($request->url(), 'https://update.loheide.cloud/mitarbeiterportal/check');
});
}
public function test_no_license_headers_without_license(): void
{
Http::fake(['*' => Http::response(['code' => 'license_required', 'error' => 'x'], 401)]);
try {
app(Channels::class)->client()->version();
} catch (ServerError) {
}
Http::assertSent(fn (Request $request) => ! $request->hasHeader('X-License-Email')
&& ! $request->hasHeader('Authorization')
&& ! $request->hasHeader('X-Device-Id'));
}
public function test_new_device_token_is_stored_even_on_error_responses(): void
{
$this->store()->setLicense('lizenz@firma.de', 'SCHLUESSEL');
Http::fake(['*' => Http::response(['code' => 'license_expired', 'error' => 'abgelaufen'], 403, ['X-Device-Token' => 'rotiert-im-fehler'])]);
try {
app(Channels::class)->client()->check(null);
$this->fail('Fehler erwartet.');
} catch (ServerError $e) {
$this->assertSame('license_expired', $e->errorCode);
}
$this->assertSame('rotiert-im-fehler', (new LicenseStore($this->dir.'/license.json'))->deviceToken());
}
public function test_device_token_from_json_body_is_stored(): void
{
$this->store()->setLicense('lizenz@firma.de', 'SCHLUESSEL');
Http::fake(['*' => Http::response(['sha' => str_repeat('b', 40), 'device_token' => 'aus-dem-json'])]);
$data = app(Channels::class)->client()->version();
$this->assertSame(str_repeat('b', 40), $data['sha']);
$this->assertSame('aus-dem-json', $this->store()->deviceToken());
}
public function test_device_token_from_download_is_stored(): void
{
$this->store()->setLicense('lizenz@firma.de', 'SCHLUESSEL');
Http::fake(['*' => Http::response('PK...', 200, ['X-Device-Token' => 'vom-download'])]);
app(Channels::class)->client()->downloadZip(str_repeat('c', 40), $this->dir.'/x.zip');
$this->assertSame('vom-download', $this->store()->deviceToken());
}
public function test_license_errors_give_messages_and_never_block_the_portal(): void
{
$admin = User::factory()->admin()->create();
$this->store()->setLicense('lizenz@firma.de', 'SCHLUESSEL');
$code = null;
Http::fake(function () use (&$code) {
return Http::response(
['code' => $code, 'error' => 'egal', 'devices_used' => 3, 'devices_max' => 3],
$code === 'rate_limited' ? 429 : 403,
);
});
foreach ([
'license_expired' => 'abgelaufen',
'invalid_key' => 'Lizenzschlüssel ist unbekannt',
'device_limit_reached' => '3 von 3',
'license_revoked' => 'Support',
'device_cloned' => 'kopierten Installation',
'rate_limited' => 'erneut versuchen',
] as $code => $expected) {
$response = $this->actingAs($admin)
->postJson('/admin/update/check')
->assertOk()
->assertJson(['ok' => false, 'code' => $code]);
$this->assertStringContainsString($expected, $response->json('message'));
// Das Portal bleibt uneingeschränkt nutzbar.
$this->actingAs($admin)->get('/')->assertOk();
$this->actingAs($admin)->get('/admin')->assertOk();
$this->actingAs($admin)->get('/admin/aktualisierung')->assertOk();
}
}
public function test_unlimited_license_is_not_treated_as_expired(): void
{
$this->store()->setLicense('lizenz@firma.de', 'SCHLUESSEL');
Http::fake(['*' => Http::response([
'licensing_required' => true,
'license' => ['status' => 'active', 'valid_until' => null, 'unlimited' => true, 'days_remaining' => null, 'expired' => false],
'registered_to' => ['license_email' => 'lizenz@firma.de', 'company' => 'Beispiel GmbH', 'contact_name' => 'Max Muster'],
'devices' => ['used' => 1, 'max' => 2, 'policy' => 'enforce'],
])]);
app(LicenseService::class)->check();
$summary = app(LicenseService::class)->summary();
$this->assertTrue($summary['unlimited']);
$this->assertFalse($summary['expired']);
$this->assertFalse($summary['expires_soon']);
$this->actingAs(User::factory()->admin()->create())
->get('/admin/aktualisierung')
->assertOk()
->assertSee('unbefristet')
->assertSee('Beispiel GmbH')
->assertSee('1 von 2 belegt');
}
public function test_unknown_channel_is_rejected(): void
{
$this->expectException(\InvalidArgumentException::class);
app(Channels::class)->client('nightly');
}
}

View file

@ -0,0 +1,142 @@
<?php
namespace Tests\Feature\Update;
use App\Models\User;
use App\Support\Update\Channels;
use App\Support\Update\Filesystem;
use App\Support\Update\InstalledVersion;
use App\Support\Update\MaintenanceFlag;
use App\Support\Update\UpdateProgress;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;
class UpdateEndpointsTest extends TestCase
{
use RefreshDatabase;
private string $dir;
protected function setUp(): void
{
parent::setUp();
$this->dir = sys_get_temp_dir().'/inhaus-ep-'.bin2hex(random_bytes(4));
mkdir($this->dir);
$this->app->instance(MaintenanceFlag::class, new MaintenanceFlag($this->dir.'/.maintenance'));
$this->app->instance(UpdateProgress::class, new UpdateProgress($this->dir.'/.progress'));
$this->app->instance(InstalledVersion::class, new InstalledVersion($this->dir.'/.version'));
}
protected function tearDown(): void
{
Filesystem::deleteDirectory($this->dir);
parent::tearDown();
}
public function test_update_endpoints_are_admin_only(): void
{
$this->postJson('/admin/update/check')->assertUnauthorized();
$user = User::factory()->create();
foreach (['check', 'install', 'channel', 'migrations'] as $endpoint) {
$this->actingAs($user)->postJson("/admin/update/{$endpoint}")->assertForbidden();
}
$this->actingAs($user)->getJson('/admin/update/progress')->assertForbidden();
$this->actingAs($user)->get('/admin/aktualisierung')->assertForbidden();
}
public function test_maintenance_mode_shows_503_but_keeps_update_pages_reachable(): void
{
$admin = User::factory()->admin()->create();
app(MaintenanceFlag::class)->activate(300);
$this->actingAs($admin)->get('/')
->assertStatus(503)
->assertHeader('Retry-After')
->assertSee('Das Portal wird gerade aktualisiert');
$this->actingAs($admin)->getJson('/admin/update/progress')->assertOk()->assertJson(['step' => 'idle']);
$this->actingAs($admin)->get('/admin/aktualisierung')->assertOk();
$this->get('/up')->assertOk();
app(MaintenanceFlag::class)->deactivate();
$this->actingAs($admin)->get('/')->assertOk();
}
public function test_first_check_of_fresh_installation_remembers_latest_sha(): void
{
Http::fake(['*' => Http::response(['has_update' => false, 'latest_sha' => str_repeat('d', 40), 'version' => '0.2.0'])]);
$this->actingAs(User::factory()->admin()->create())
->postJson('/admin/update/check')
->assertOk()
->assertJson(['ok' => true, 'result' => ['has_update' => false, 'changelog' => []]]);
Http::assertSent(fn ($request) => ! str_contains($request->url(), 'current_sha'));
$this->assertSame(str_repeat('d', 40), app(InstalledVersion::class)->current());
}
public function test_check_shows_changelog_preview_without_commit_texts(): void
{
app(InstalledVersion::class)->save(str_repeat('a', 40));
Http::fake(['*' => Http::response([
'has_update' => true,
'latest_sha' => str_repeat('b', 40),
'version' => '0.3.0',
'versions_behind' => 4,
'changelog_preview' => [
'entries' => [['version' => '0.3.0', 'heading' => '0.3.0', 'text' => "- Neue **Umfragen**\n- <script>x</script>"]],
'complete' => false,
],
])]);
$response = $this->actingAs(User::factory()->admin()->create())
->postJson('/admin/update/check')
->assertOk()
->assertJsonPath('result.has_update', true)
->assertJsonPath('result.version', '0.3.0')
->assertJsonPath('result.latest_short', 'bbbbbbb')
->assertJsonPath('result.versions_behind', 4)
->assertJsonPath('result.changelog_complete', false);
Http::assertSent(fn ($request) => str_contains($request->url(), 'current_sha='.str_repeat('a', 40)));
$this->assertStringContainsString('<strong>Umfragen</strong>', $response->json('result.changelog.0.html'));
$this->assertStringNotContainsString('<script>', $response->json('result.changelog.0.html'));
}
public function test_channel_can_be_changed_and_unknown_channels_are_rejected(): void
{
$admin = User::factory()->admin()->create();
$this->actingAs($admin)->postJson('/admin/update/channel', ['channel' => 'development'])->assertOk();
$this->assertSame('development', app(Channels::class)->active());
$this->actingAs($admin)->postJson('/admin/update/channel', ['channel' => 'nightly'])->assertUnprocessable();
}
public function test_unconfigured_channel_gives_clear_message(): void
{
Http::fake(['*' => Http::response(['code' => 'unknown_tool', 'error' => 'nicht konfiguriert'], 404)]);
$this->actingAs(User::factory()->admin()->create())
->postJson('/admin/update/check')
->assertOk()
->assertJsonPath('code', 'unknown_tool')
->assertJsonPath('message', 'Dieser Update-Kanal ist beim Hersteller noch nicht eingerichtet. Bitte den Kanal „Stabil“ verwenden.');
}
public function test_install_is_refused_while_another_run_is_active(): void
{
app(UpdateProgress::class)->set(50, 'extract', 'läuft');
$this->actingAs(User::factory()->admin()->create())
->postJson('/admin/update/install')
->assertStatus(409);
}
}

View file

@ -0,0 +1,113 @@
<?php
namespace Tests\Feature\Update;
use App\Support\Update\Filesystem;
use App\Support\Update\InstalledVersion;
use App\Support\Update\MaintenanceFlag;
use App\Support\Update\UpdateProgress;
use InvalidArgumentException;
use Tests\TestCase;
class UpdateStateTest extends TestCase
{
private string $dir;
protected function setUp(): void
{
parent::setUp();
$this->dir = sys_get_temp_dir().'/inhaus-state-'.bin2hex(random_bytes(4));
mkdir($this->dir);
}
protected function tearDown(): void
{
Filesystem::deleteDirectory($this->dir);
parent::tearDown();
}
public function test_sha_is_read_and_written(): void
{
$version = new InstalledVersion($this->dir.'/.version');
$this->assertNull($version->current());
$this->assertSame('0.2.0', $version->release());
$this->assertSame('0.2.0', $version->full());
$version->save('A1B2C3D4E5F60718293a4b5c6d7e8f9012345678');
$this->assertSame('a1b2c3d4e5f60718293a4b5c6d7e8f9012345678', $version->current());
$this->assertSame('a1b2c3d', $version->short());
$this->assertSame('0.2.0 (a1b2c3d)', $version->full());
}
public function test_invalid_sha_is_rejected(): void
{
$version = new InstalledVersion($this->dir.'/.version');
foreach (['', 'main', 'a1b2c3d', str_repeat('g', 40), str_repeat('a', 41)] as $invalid) {
try {
$version->save($invalid);
$this->fail("„{$invalid}“ hätte abgelehnt werden müssen.");
} catch (InvalidArgumentException) {
$this->assertNull($version->current());
}
}
file_put_contents($this->dir.'/.version', "kaputt\n");
$this->assertNull($version->current());
}
public function test_maintenance_mode_heals_itself_after_expiry(): void
{
$flag = new MaintenanceFlag($this->dir.'/.maintenance');
$this->assertFalse($flag->isActive());
$flag->activate(600);
$this->assertTrue($flag->isActive());
$flag->deactivate();
$this->assertFalse($flag->isActive());
// Absturz mitten im Update: Flag bleibt liegen, ist aber abgelaufen.
file_put_contents($this->dir.'/.maintenance', json_encode(['since' => time() - 700, 'until' => time() - 100]));
$this->assertFalse($flag->isActive());
$this->assertFileDoesNotExist($this->dir.'/.maintenance');
// Kaputte Datei sperrt ebenfalls nicht.
file_put_contents($this->dir.'/.maintenance', 'Müll');
$this->assertFalse($flag->isActive());
}
public function test_progress_file_including_error_state(): void
{
$progress = new UpdateProgress($this->dir.'/.update-progress');
$this->assertSame(['pct' => 0, 'step' => 'idle', 'text' => '', 'ts' => 0], $progress->get());
$this->assertFalse($progress->isRunning());
$progress->set(20, 'download', 'Lädt …');
$this->assertSame(20, $progress->get()['pct']);
$this->assertSame('Lädt …', $progress->get()['text']);
$this->assertTrue($progress->isRunning());
$progress->fail('Kaputt');
$this->assertSame(-1, $progress->get()['pct']);
$this->assertSame('error', $progress->get()['step']);
$this->assertFalse($progress->isRunning());
}
public function test_stale_run_does_not_block_forever(): void
{
$progress = new UpdateProgress($this->dir.'/.update-progress');
file_put_contents($this->dir.'/.update-progress', json_encode([
'pct' => 50, 'step' => 'extract', 'text' => '', 'ts' => time() - UpdateProgress::STALE_AFTER_SECONDS - 1,
]));
$this->assertFalse($progress->isRunning());
}
}

View file

@ -0,0 +1,193 @@
<?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']);
}
}