Harden module runtime: audited listener failures and DI-first resolver

This commit is contained in:
2026-03-25 10:02:03 +01:00
parent a721ec0043
commit cb5f7037b2
12 changed files with 314 additions and 79 deletions

View File

@@ -5,6 +5,8 @@ namespace MintyPHP\Tests\Unit\Module;
use MintyPHP\App\AppContainer;
use MintyPHP\App\Module\Contracts\EventListener;
use MintyPHP\App\Module\ModuleEventDispatcher;
use MintyPHP\Http\RequestContext;
use MintyPHP\Service\Audit\SystemAuditService;
use PHPUnit\Framework\TestCase;
final class ModuleEventDispatcherTest extends TestCase
@@ -62,6 +64,8 @@ final class ModuleEventDispatcherTest extends TestCase
public function testDispatchContinuesAfterListenerException(): void
{
RequestContext::resetForTests();
$secondCalled = false;
$failingListener = new class () implements EventListener {
@@ -100,4 +104,64 @@ final class ModuleEventDispatcherTest extends TestCase
self::assertTrue($secondCalled, 'Second listener should be called even after the first one throws');
}
public function testDispatchAuditsListenerFailureWithoutPayloadLeakage(): void
{
RequestContext::resetForTests();
$failingListener = new class () implements EventListener {
public function handle(string $event, array $payload): void
{
throw new \RuntimeException('Do not leak this message');
}
};
$container = new AppContainer();
$container->set($failingListener::class, static fn () => $failingListener);
$systemAuditService = $this->createMock(SystemAuditService::class);
$systemAuditService->expects($this->once())
->method('record')
->with(
'module.listener.failed',
'failed',
$this->callback(static function (array $context): bool {
$metadata = is_array($context['metadata'] ?? null) ? $context['metadata'] : [];
$keys = array_keys($metadata);
sort($keys);
if ($keys !== ['exception_class', 'listener_class', 'listener_method', 'module_event', 'request_id']) {
return false;
}
if (($metadata['module_event'] ?? '') !== 'user.created') {
return false;
}
if (($metadata['exception_class'] ?? '') !== \RuntimeException::class) {
return false;
}
if (($metadata['listener_method'] ?? '') !== 'handle') {
return false;
}
if (!is_string($metadata['request_id'] ?? null) || trim((string) $metadata['request_id']) === '') {
return false;
}
return !array_key_exists('payload', $metadata)
&& !array_key_exists('exception_message', $metadata)
&& !array_key_exists('trace', $metadata);
})
);
$dispatcher = new ModuleEventDispatcher(
['user.created' => [['class' => $failingListener::class, 'method' => 'handle']]],
$container,
$systemAuditService
);
$dispatcher->dispatch('user.created', ['secret' => 'must-not-be-logged']);
}
}