Loheide-eu-mitarbeiterplatt.../tests/Feature/Update/LicenseTest.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
7.2 KiB
PHP

<?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');
}
}