Loheide-eu-mitarbeiterplatt.../tests/Feature/Plugins/PluginSystemTest.php
Friederich Loheide bf68be68f9
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 12m25s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 12m51s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 10m43s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 10m37s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 12m42s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 13m38s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 9m39s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 9m33s
CI / Bekannte Sicherheitslücken in Paketen (pull_request) Successful in 44s
CI / Build-Artefakte aktuell (pull_request) Successful in 1m10s
Schneller und stabiler bei Updates (0.45.0)
- Ladefehler während eines Updates schalten keine Plugins mehr ab: Wartungsmodus
  merkt sich den Update-Zeitraum (+2 min Nachlauf), Plugin-Uploads markieren den
  Dateiaustausch ohne Wartungsmodus; guard/recoverFromCrash prüfen das, betroffene
  Plugins (mit disabled_at im Zeitraum) werden wieder eingeschaltet
- Plugin-Oberflächen werden nach public/plugin-assets kopiert (Webserver statt PHP),
  bei Deaktivieren/Löschen/Neu-Hochladen entfernt; Route bleibt als Rückfall
- RichTextEditor in SDK, Leichte-Sprache-Leiste und Glossar asynchron;
  fehlende Menü-Symbole kuratiert → kein Laden des kompletten Symbolsatzes
- Inertia-Prefetch (hover, 10 s) für Menülinks und Neuigkeiten-Vorschauen;
  Prefetch zählt nicht als Lesen (Reach)

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 14:41:53 +00:00

478 lines
19 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\Plugins;
use App\Filament\Pages\Plugins;
use App\Models\User;
use App\Plugins\Hooks;
use App\Plugins\PluginInstaller;
use App\Plugins\PluginManager;
use App\Plugins\PluginState;
use App\Plugins\VersionConstraint;
use App\Support\Navigation;
use App\Support\Update\Filesystem;
use App\Support\Update\MaintenanceFlag;
use App\Support\Update\ZipExtractor;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Schema;
use Livewire\Livewire;
use RuntimeException;
use Tests\TestCase;
use ZipArchive;
class PluginSystemTest extends TestCase
{
use RefreshDatabase;
private string $dir;
protected function setUp(): void
{
parent::setUp();
$this->dir = sys_get_temp_dir().'/inhaus-plugins-'.bin2hex(random_bytes(4));
mkdir($this->dir.'/core', 0777, true);
mkdir($this->dir.'/custom', 0777, true);
$this->app->instance(MaintenanceFlag::class, new MaintenanceFlag($this->dir.'/.maintenance'));
}
protected function tearDown(): void
{
Filesystem::deleteDirectory($this->dir);
Schema::dropIfExists('beispiel_eintraege');
parent::tearDown();
}
/**
* Legt ein Beispiel-Plugin an. $register/$boot werden in die Plugin-Klasse eingesetzt.
*
* @param array<string, mixed> $manifest
*/
private function makePlugin(string $slug, array $manifest = [], string $register = '', string $boot = '', bool $withMigration = false, string $base = 'custom'): string
{
$class = str_replace(' ', '', ucwords(str_replace('-', ' ', $slug)));
$namespace = "Test{$class}".bin2hex(random_bytes(3));
$path = "{$this->dir}/{$base}/{$slug}";
mkdir("{$path}/src", 0777, true);
file_put_contents("{$path}/plugin.json", json_encode(array_merge([
'slug' => $slug,
'name' => "Plugin {$class}",
'version' => '1.0.0',
'namespace' => "{$namespace}\\",
'class' => "{$namespace}\\Plugin",
'requires' => ['core' => '>=0.3.0'],
], $manifest)));
file_put_contents("{$path}/src/Plugin.php", <<<PHP
<?php
namespace {$namespace};
class Plugin extends \App\Plugins\Plugin
{
public function register(): void { {$register} }
public function boot(): void { {$boot} }
public function activate(): void { file_put_contents(\$this->path('activated'), '1'); }
public function uninstall(): void { file_put_contents(sys_get_temp_dir().'/inhaus-uninstalled-{$slug}', '1'); }
}
PHP);
if ($withMigration) {
mkdir("{$path}/database/migrations", 0777, true);
file_put_contents("{$path}/database/migrations/2026_01_01_000000_create_beispiel_eintraege.php", <<<'PHP'
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
public function up(): void { Schema::create('beispiel_eintraege', fn (Blueprint $t) => $t->id()); }
public function down(): void { Schema::dropIfExists('beispiel_eintraege'); }
};
PHP);
}
return $path;
}
private function manager(): PluginManager
{
return new PluginManager($this->app, new PluginState($this->dir.'/state.json'), $this->dir.'/core', $this->dir.'/custom');
}
public function test_version_constraints(): void
{
$this->assertTrue(VersionConstraint::satisfies('0.3.0', '>=0.3.0'));
$this->assertFalse(VersionConstraint::satisfies('0.2.9', '>=0.3'));
$this->assertTrue(VersionConstraint::satisfies('1.4.2', '^1.2'));
$this->assertFalse(VersionConstraint::satisfies('2.0.0', '^1.2'));
$this->assertTrue(VersionConstraint::satisfies('0.3.5', '^0.3'));
$this->assertFalse(VersionConstraint::satisfies('0.4.0', '^0.3'));
$this->assertTrue(VersionConstraint::satisfies('1.4.9', '~1.4'));
$this->assertTrue(VersionConstraint::satisfies('8.3.12', '>=8.3 <9'));
$this->assertTrue(VersionConstraint::satisfies('1.0.0', null));
}
public function test_hooks_run_by_priority(): void
{
$calls = [];
Hooks::on('test.action', function () use (&$calls) {
$calls[] = 'spät';
}, 20);
Hooks::on('test.action', function () use (&$calls) {
$calls[] = 'früh';
}, 5);
Hooks::do('test.action');
Hooks::filter('test.filter', fn (int $v) => $v * 2);
Hooks::filter('test.filter', fn (int $v) => $v + 1, 1);
$this->assertSame(['früh', 'spät'], $calls);
$this->assertSame(8, Hooks::apply('test.filter', 3));
}
public function test_plugins_are_discovered_registered_and_booted_in_dependency_order(): void
{
$this->makePlugin('basis', register: "\$this->app->make(\\App\\Support\\Navigation::class)->add('basis', 'Basis', '/basis', sort: 60);", base: 'core');
$this->makePlugin('erweiterung', ['requires' => ['core' => '>=0.3', 'plugins' => ['basis']]], boot: "\\App\\Plugins\\Hooks::filter('test.boot', fn (\$v) => \$v.'+erweiterung');", base: 'core');
$this->makePlugin('fehlt-abhaengigkeit', ['requires' => ['plugins' => ['gibt-es-nicht']]], base: 'core');
$this->makePlugin('zu-neu', ['requires' => ['core' => '>=99.0']], base: 'core');
$manager = $this->manager();
$manager->registerAll();
$manager->bootAll();
$this->assertSame(['basis', 'erweiterung'], array_keys($manager->loaded()));
$this->assertStringContainsString('gibt-es-nicht', $manager->problem('fehlt-abhaengigkeit'));
$this->assertStringContainsString('benötigt Inhaus >=99.0', $manager->problem('zu-neu'));
$this->assertSame('x+erweiterung', Hooks::apply('test.boot', 'x'));
$labels = array_column(app(Navigation::class)->items(Request::create('/')), 'label');
$this->assertContains('Basis', $labels);
}
public function test_invalid_manifests_are_reported_not_loaded(): void
{
mkdir($this->dir.'/custom/kaputt');
file_put_contents($this->dir.'/custom/kaputt/plugin.json', '{"slug": "Kaputt!"}');
$this->makePlugin('app-namespace', ['namespace' => 'App\\Evil\\', 'class' => 'App\\Evil\\Plugin']);
$manager = $this->manager();
$this->assertSame([], array_keys($manager->all()));
$this->assertStringContainsString('Feld', $manager->problem('kaputt'));
$this->assertStringContainsString('vorbehalten', $manager->problem('app-namespace'));
}
public function test_exception_while_loading_disables_the_plugin_and_keeps_the_portal_running(): void
{
$this->makePlugin('wackelig', register: "throw new \\RuntimeException('Datenbank weg');", base: 'core');
$this->makePlugin('stabil', base: 'core');
$manager = $this->manager();
$manager->registerAll();
$this->assertSame(['stabil'], array_keys($manager->loaded()));
$this->assertFalse($manager->isEnabled('wackelig'));
$this->assertStringContainsString('Datenbank weg', $manager->problem('wackelig'));
}
public function test_missing_class_while_files_are_copied_does_not_disable_the_plugin(): void
{
$path = $this->makePlugin('halbfertig', base: 'core');
rename("{$path}/src/Plugin.php", "{$path}/src/Plugin.php.part");
$manager = $this->manager();
$manager->registerAll();
$this->assertSame([], array_keys($manager->loaded()));
$this->assertTrue($manager->isEnabled('halbfertig'), 'Nur vorübergehend nicht ladbar – bleibt aktiv.');
$this->assertStringContainsString('nicht gefunden', $manager->problem('halbfertig'));
rename("{$path}/src/Plugin.php.part", "{$path}/src/Plugin.php");
$manager = $this->manager();
$manager->registerAll();
$this->assertSame(['halbfertig'], array_keys($manager->loaded()));
}
public function test_plugins_disabled_by_an_earlier_missing_class_are_reenabled(): void
{
$path = $this->makePlugin('geheilt', base: 'core');
$class = json_decode(file_get_contents("{$path}/plugin.json"), true)['class'];
$state = new PluginState($this->dir.'/state.json');
$state->setEnabled('geheilt', false, "Fehler beim Laden: Plugin-Klasse {$class} nicht gefunden.");
$state->setEnabled('echt-kaputt', false, 'Fehler beim Laden: Datenbank weg');
$manager = $this->manager();
$manager->registerAll();
$this->assertSame(['geheilt'], array_keys($manager->loaded()));
$this->assertNull($manager->problem('geheilt'));
}
public function test_leftover_folder_of_a_renamed_core_plugin_is_ignored(): void
{
// Der Updater löscht nie – der alte Ordner liegt nach dem Umbenennen noch da.
$this->makePlugin('dokumente', base: 'core');
$this->makePlugin('ablage', ['replaces' => ['dokumente']], base: 'core');
$this->makePlugin('dokumente-kunde', ['replaces' => ['ablage']]); // Kunden-Plugins ersetzen nichts
$manager = $this->manager();
$manager->registerAll();
$this->assertNull($manager->find('dokumente'));
$this->assertSame(['ablage'], array_keys($manager->loaded()));
}
public function test_fatal_error_during_previous_load_is_detected(): void
{
$this->makePlugin('absturz', base: 'core');
$marker = storage_path('framework/plugins/booting-absturz');
@mkdir(dirname($marker), 0777, true);
file_put_contents($marker, '1');
touch($marker, time() - 120);
$manager = $this->manager();
$manager->registerAll();
$this->assertFalse($manager->isEnabled('absturz'));
$this->assertStringContainsString('Schwerer Fehler', $manager->problem('absturz'));
$this->assertFileDoesNotExist($marker);
}
public function test_customer_plugins_are_inactive_until_activated(): void
{
$path = $this->makePlugin('kunde', withMigration: true);
$this->makePlugin('mitgeliefert', base: 'core');
$manager = $this->manager();
$this->assertFalse($manager->isEnabled('kunde'));
$this->assertTrue($manager->isEnabled('mitgeliefert'));
$manager->activate('kunde');
$this->assertTrue($manager->isEnabled('kunde'));
$this->assertTrue(Schema::hasTable('beispiel_eintraege'));
$this->assertFileExists($path.'/activated');
}
public function test_plugin_with_dependents_cannot_be_deactivated(): void
{
$this->makePlugin('basis', base: 'core');
$this->makePlugin('aufsatz', ['requires' => ['plugins' => ['basis']]], base: 'core');
$this->expectExceptionMessage('Wird noch benötigt von: Plugin Aufsatz');
$this->manager()->deactivate('basis');
}
public function test_delete_with_data_removes_tables_and_files(): void
{
$path = $this->makePlugin('entfernen', withMigration: true);
$manager = $this->manager();
$manager->activate('entfernen');
$manager->delete('entfernen', removeData: true);
$this->assertDirectoryDoesNotExist($path);
$this->assertFalse(Schema::hasTable('beispiel_eintraege'));
$this->assertFileExists(sys_get_temp_dir().'/inhaus-uninstalled-entfernen');
@unlink(sys_get_temp_dir().'/inhaus-uninstalled-entfernen');
}
public function test_core_plugins_cannot_be_deleted(): void
{
$this->makePlugin('kern', base: 'core');
$this->expectExceptionMessage('nur deaktiviert');
$this->manager()->delete('kern', false);
}
public function test_zip_installation(): void
{
$source = $this->makePlugin('hochgeladen', base: 'core');
$zip = $this->zipDirectory($source, 'hochgeladen-1.0.0/');
Filesystem::deleteDirectory($source);
$manager = $this->manager();
$manifest = (new PluginInstaller($manager, new ZipExtractor))->install($zip);
$this->assertSame('hochgeladen', $manifest->slug);
$this->assertFalse($manifest->core);
$this->assertFileExists($this->dir.'/custom/hochgeladen/plugin.json');
$this->assertNotNull($manager->find('hochgeladen'));
// Der Austausch der Dateien zählt als Update-Zeitraum: Ladefehler darin schalten nichts ab
$this->assertFalse(app(MaintenanceFlag::class)->isActive(), 'Die Seite bleibt erreichbar.');
$this->assertTrue(app(MaintenanceFlag::class)->isUpdating());
$this->assertFileDoesNotExist($this->dir.'/.maintenance-quiet');
}
public function test_zip_without_manifest_or_with_core_slug_is_rejected(): void
{
$installer = new PluginInstaller($this->manager(), new ZipExtractor);
$empty = $this->dir.'/leer.zip';
$archive = new ZipArchive;
$archive->open($empty, ZipArchive::CREATE);
$archive->addFromString('README.md', 'kein Plugin');
$archive->close();
try {
$installer->install($empty);
$this->fail('Ohne plugin.json hätte die Installation scheitern müssen.');
} catch (RuntimeException $e) {
$this->assertStringContainsString('kein gültiges Plugin', $e->getMessage());
}
$this->makePlugin('kern', base: 'core');
$copy = $this->makePlugin('kern', base: 'upload');
$this->expectExceptionMessage('gehört zu einem mitgelieferten Plugin');
(new PluginInstaller($this->manager(), new ZipExtractor))->install($this->zipDirectory($copy, 'kern/'));
}
public function test_zip_slip_in_plugin_archive_is_blocked(): void
{
$zip = $this->dir.'/boese.zip';
$archive = new ZipArchive;
$archive->open($zip, ZipArchive::CREATE);
$archive->addFromString('plugin/plugin.json', '{}');
$archive->addFromString('plugin/../../boese.php', '<?php');
$archive->close();
try {
(new PluginInstaller($this->manager(), new ZipExtractor))->install($zip);
$this->fail('Unsicheres Archiv hätte abgelehnt werden müssen.');
} catch (RuntimeException $e) {
$this->assertStringContainsString('Unsicherer Pfad', $e->getMessage());
}
$this->assertFileDoesNotExist(storage_path('boese.php'));
}
public function test_uploads_can_be_disabled(): void
{
config(['inhaus.disallow_file_mods' => true]);
$this->expectExceptionMessage('abgeschaltet');
(new PluginInstaller($this->manager(), new ZipExtractor))->install($this->dir.'/egal.zip');
}
public function test_admin_page_lists_core_plugins_and_is_admin_only(): void
{
$this->actingAs(User::factory()->create())->get('/admin/plugins')->assertForbidden();
$this->actingAs(User::factory()->admin()->create())
->get('/admin/plugins')
->assertOk()
->assertSee('Neuigkeiten')
->assertSee('Termine')
->assertSee('mitgeliefert')
->assertSee('vollen Rechten');
}
public function test_admin_can_upload_a_plugin_through_the_page(): void
{
$source = $this->makePlugin('seite-hochgeladen', base: 'core');
$zip = $this->zipDirectory($source, 'seite-hochgeladen/');
Filesystem::deleteDirectory($source);
$this->app->instance(PluginManager::class, $this->manager());
$this->actingAs(User::factory()->admin()->create());
Livewire::test(Plugins::class)
->set('archive', UploadedFile::fake()->createWithContent('plugin.zip', file_get_contents($zip)))
->call('installArchive')
->assertHasNoErrors();
$this->assertFileExists($this->dir.'/custom/seite-hochgeladen/plugin.json');
}
public function test_upload_form_does_not_use_livewires_reserved_upload_method(): void
{
// $wire.upload() ist Livewires eigene Datei-Upload-Funktion – ein gleichnamiger
// Formular-Handler wird im Browser nie aufgerufen.
$view = file_get_contents(resource_path('views/filament/pages/plugins.blade.php'));
$this->assertStringNotContainsString('wire:submit="upload"', $view);
$this->assertFalse(method_exists(Plugins::class, 'upload'));
}
private function zipDirectory(string $source, string $prefix): string
{
$zip = $this->dir.'/'.basename($source).'-'.bin2hex(random_bytes(2)).'.zip';
$archive = new ZipArchive;
$archive->open($zip, ZipArchive::CREATE);
$files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source, \FilesystemIterator::SKIP_DOTS));
foreach ($files as $file) {
$archive->addFile($file->getPathname(), $prefix.substr($file->getPathname(), strlen($source) + 1));
}
$archive->close();
return $zip;
}
public function test_load_errors_during_an_update_do_not_disable_plugins(): void
{
$this->makePlugin('wackelig', register: "throw new \\RuntimeException('Datei halb kopiert');", base: 'core');
$flag = app(MaintenanceFlag::class);
// Während des Updates und kurz danach: nur diese Anfrage ohne das Plugin
$flag->activate(300);
$manager = $this->manager();
$manager->registerAll();
$this->assertTrue($manager->isEnabled('wackelig'));
$this->assertArrayNotHasKey('wackelig', $manager->loaded());
$this->assertFileDoesNotExist(storage_path('framework/plugins/booting-wackelig'));
$flag->deactivate();
$this->assertTrue($flag->isUpdating());
$manager = $this->manager();
$manager->registerAll();
$this->assertTrue($manager->isEnabled('wackelig'));
// Lange nach dem Update: wirklich defekt → abgeschaltet
file_put_contents($this->dir.'/.maintenance-last', json_encode(['since' => time() - 900, 'until' => time() - 600]));
$this->assertFalse($flag->isUpdating());
$manager = $this->manager();
$manager->registerAll();
$this->assertFalse($manager->isEnabled('wackelig'));
}
public function test_crash_markers_from_an_update_keep_the_plugin_and_old_victims_come_back(): void
{
$this->makePlugin('absturz', base: 'core');
$this->makePlugin('opfer', base: 'core');
file_put_contents($this->dir.'/.maintenance-last', json_encode(['since' => time() - 200, 'until' => time() - 100]));
// Absturz mitten im Update (Markierung aus dem Update-Zeitraum)
$marker = storage_path('framework/plugins/booting-absturz');
@mkdir(dirname($marker), 0777, true);
file_put_contents($marker, '1');
touch($marker, time() - 150);
// Von einer älteren Version während des Updates abgeschaltet
$state = new PluginState($this->dir.'/state.json');
$state->setEnabled('opfer', false, 'Schwerer Fehler beim Laden (das Portal wurde dadurch unterbrochen).');
$data = json_decode(file_get_contents($this->dir.'/state.json'), true);
$data['opfer']['disabled_at'] = time() - 150;
file_put_contents($this->dir.'/state.json', json_encode($data));
$manager = $this->manager();
$manager->registerAll();
$this->assertTrue($manager->isEnabled('absturz'));
$this->assertFileDoesNotExist($marker);
$this->assertTrue($manager->isEnabled('opfer'));
$this->assertArrayHasKey('opfer', $manager->loaded());
}
}