Loheide-eu-mitarbeiterplatt.../tests/Feature/Plugins/PluginSystemTest.php
Friederich Loheide 28ef1e4a20 Plugin-System; Neuigkeiten und Termine als mitgelieferte Plugins
- Plugins nach WordPress-Prinzip: plugin.json-Manifest mit Versions- und
  Abhängigkeitsprüfung, eigenes PSR-4-Autoloading, register()/boot(),
  activate()/deactivate()/uninstall(), Migrationen, Routen und Views je Plugin
- plugins-core/ (mitgeliefert, aktiv bis zur Deaktivierung) und plugins/
  (Kunden-Plugins, geschützt vor Updates, inaktiv bis zur Aktivierung)
- Zustand in storage/app/plugins.json – Laden ohne Datenbankabfrage
- Wiederherstellungsmodus: Ausnahmen und Fatal Errors beim Laden
  deaktivieren das Plugin, das Portal bleibt erreichbar
- Hooks (Actions/Filter mit Prioritäten) und Registries für Navigation,
  Startseiten-Kacheln, Rechte und Admin-Seiten (Filament-Discovery)
- Admin-Seite „Plugins“: aktivieren, deaktivieren, per ZIP installieren
  (ZIP-Slip-Schutz), löschen mit oder ohne Daten; abschaltbar per
  INHAUS_DISALLOW_FILE_MODS
- Startseite komplett aus Kacheln; Plugin-Seiten als „slug::Seite“
- Version 0.3.0

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

360 lines
14 KiB
PHP

<?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\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);
}
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_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'));
}
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('upload')
->assertHasNoErrors();
$this->assertFileExists($this->dir.'/custom/seite-hochgeladen/plugin.json');
}
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;
}
}