diff --git a/app/Controllers/Admin/WebhooksController.php b/app/Controllers/Admin/WebhooksController.php new file mode 100644 index 0000000..0b317ce --- /dev/null +++ b/app/Controllers/Admin/WebhooksController.php @@ -0,0 +1,209 @@ +view('admin/webhooks', [ + 'active' => 'webhooks', + 'page' => Webhook::query()->orderBy('id', 'desc')->paginate($this->page($request), $this->perPage()), + 'groups' => Webhooks::groups(), + 'stats' => WebhookDelivery::stats(), + ], 'Вебхуки'); + } + + public function create(): Response + { + return $this->view('admin/webhook', [ + 'active' => 'webhooks', + 'webhook' => new Webhook(), + 'groups' => Webhooks::groups(), + 'deliveries' => ['items' => [], 'total' => 0, 'page' => 1, 'pages' => 1, 'per_page' => 0], + 'fresh' => '', + ], 'Новая подписка'); + } + + public function store(Request $request): Response + { + $data = $this->validate($request, [ + 'name' => 'nullable|max:191', + 'url' => 'required|url|max:500', + 'secret' => 'nullable|max:191', + ], ['name' => 'Название', 'url' => 'Адрес', 'secret' => 'Секрет']); + + $events = Webhooks::filter((array) $request->input('events', [])); + + if ($events === []) { + $this->flash('Выберите хотя бы одно событие', 'error'); + + return $this->redirect('admin.webhooks.create'); + } + + $webhook = Webhook::add( + (string) ($data['name'] ?? ''), + (string) $data['url'], + $events, + (string) ($data['secret'] ?? '') + ); + + Audit::created('webhook', $webhook->id(), 'подписка «' . (string) $webhook->name . '» на ' . (string) $webhook->url); + + $this->flash('Подписка создана. Секрет пропишите у подписчика'); + + return $this->redirect('admin.webhooks.show', ['id' => $webhook->id()]); + } + + public function show(Request $request, int $id): Response + { + $webhook = $this->webhook($id); + + return $this->view('admin/webhook', [ + 'active' => 'webhooks', + 'webhook' => $webhook, + 'groups' => Webhooks::groups(), + 'deliveries' => WebhookDelivery::query() + ->where('webhook_id', $webhook->id()) + ->orderBy('id', 'desc') + ->paginate($this->page($request), $this->perPage()), + // Новый секрет показываем один раз, сразу после замены + 'fresh' => (string) View::takeStash('webhook_secret', ''), + ], (string) $webhook->name); + } + + public function update(Request $request, int $id): Response + { + $webhook = $this->webhook($id); + + $data = $this->validate($request, [ + 'name' => 'nullable|max:191', + 'url' => 'required|url|max:500', + ], ['name' => 'Название', 'url' => 'Адрес']); + + $events = Webhooks::filter((array) $request->input('events', [])); + + if ($events === []) { + $this->flash('Выберите хотя бы одно событие', 'error'); + + return $this->redirect('admin.webhooks.show', ['id' => $webhook->id()]); + } + + $before = [ + 'name' => (string) $webhook->name, + 'url' => (string) $webhook->url, + 'events' => implode(', ', $webhook->events()), + ]; + + $webhook->forceFill([ + 'name' => (string) ($data['name'] ?? '') !== '' ? (string) $data['name'] : (string) $webhook->name, + 'url' => (string) $data['url'], + 'events' => json_encode($events, JSON_UNESCAPED_UNICODE), + ])->save(); + + Audit::updated('webhook', $webhook->id(), 'подписка «' . (string) $webhook->name . '»', Audit::between($before, [ + 'name' => (string) $webhook->name, + 'url' => (string) $webhook->url, + 'events' => implode(', ', $webhook->events()), + ])); + + $this->flash('Подписка сохранена'); + + return $this->redirect('admin.webhooks.show', ['id' => $webhook->id()]); + } + + /** + * Включить или отключить подписку. + */ + public function toggle(int $id): Response + { + $webhook = $this->webhook($id); + + $active = !(bool) $webhook->active; + + // Включили заново — счётчик неудач больше не повод отключать + $webhook->forceFill(['active' => $active ? 1 : 0, 'failures' => 0])->save(); + + Audit::action('webhook', $webhook->id(), ($active ? 'включена' : 'отключена') . ' подписка «' . (string) $webhook->name . '»'); + + $this->flash($active ? 'Подписка включена' : 'Подписка отключена'); + + return $this->redirect('admin.webhooks.show', ['id' => $webhook->id()]); + } + + /** + * Заменить секрет: старый перестаёт подходить сразу. + */ + public function rotate(int $id): Response + { + $webhook = $this->webhook($id); + + View::stash('webhook_secret', $webhook->rotateSecret()); + + Audit::action('webhook', $webhook->id(), 'заменён секрет подписки «' . (string) $webhook->name . '»'); + + $this->flash('Секрет заменён. Пропишите новый у подписчика — старый больше не подойдёт'); + + return $this->redirect('admin.webhooks.show', ['id' => $webhook->id()]); + } + + /** + * Пробная посылка: уходит очередью, как и настоящие. + */ + public function test(int $id): Response + { + $webhook = $this->webhook($id); + + $delivery = Webhooks::test($webhook); + + Audit::action('webhook', $webhook->id(), 'отправлена пробная посылка подписке «' . (string) $webhook->name . '»'); + + $this->flash('Пробная посылка поставлена в очередь (№' . $delivery->id() . '). Её разберёт воркер'); + + return $this->redirect('admin.webhooks.show', ['id' => $webhook->id()]); + } + + public function delete(int $id): Response + { + $webhook = $this->webhook($id); + + $name = (string) $webhook->name; + + // Журнал доставок без подписки не нужен + WebhookDelivery::query()->where('webhook_id', $webhook->id())->delete(); + + $webhook->delete(); + + Audit::deleted('webhook', $id, 'удалена подписка «' . $name . '»'); + + $this->flash('Подписка удалена'); + + return $this->redirect('admin.webhooks'); + } + + private function webhook(int $id): Webhook + { + /** @var Webhook $webhook */ + $webhook = $this->require(Webhook::find($id), 'admin.webhooks', 'Подписка не найдена'); + + return $webhook; + } +} diff --git a/config/menu.php b/config/menu.php index 750a2bd..46c9e08 100644 --- a/config/menu.php +++ b/config/menu.php @@ -20,6 +20,7 @@ return [ ['key' => 'users', 'label' => 'Пользователи', 'route' => 'admin.users', 'permission' => Permission::USERS_MANAGE], ['key' => 'roles', 'label' => 'Роли', 'route' => 'admin.roles', 'permission' => Permission::ROLES_MANAGE], ['key' => 'tokens', 'label' => 'Ключи API', 'route' => 'admin.tokens', 'permission' => Permission::USERS_MANAGE], + ['key' => 'webhooks', 'label' => 'Вебхуки', 'route' => 'admin.webhooks', 'permission' => Permission::WEBHOOKS_MANAGE], ['key' => 'audit', 'label' => 'Журнал', 'route' => 'admin.audit', 'permission' => Permission::AUDIT_VIEW], ['key' => 'logs', 'label' => 'Логи', 'route' => 'admin.logs', 'permission' => Permission::LOGS_VIEW], ['key' => 'system', 'label' => 'Состояние', 'route' => 'admin.system', 'permission' => Permission::SYSTEM_VIEW], diff --git a/framework/Console/Application.php b/framework/Console/Application.php index 50d319d..baf3e6c 100644 --- a/framework/Console/Application.php +++ b/framework/Console/Application.php @@ -66,6 +66,10 @@ final class Application 'Почта' => [ Commands\MailTestCommand::class, ], + 'Вебхуки' => [ + Commands\WebhookListCommand::class, + Commands\WebhookTestCommand::class, + ], ]; /** @var array Позиционные аргументы */ diff --git a/framework/Console/Commands/WebhookListCommand.php b/framework/Console/Commands/WebhookListCommand.php new file mode 100644 index 0000000..64b09b0 --- /dev/null +++ b/framework/Console/Commands/WebhookListCommand.php @@ -0,0 +1,94 @@ +hasOption('events')) { + return $this->printEvents(); + } + + /** @var array $webhooks */ + $webhooks = Webhook::query()->orderBy('id')->get(); + + if ($webhooks === []) { + $this->line('Подписок нет. Завести: раздел «Вебхуки» в панели'); + + return 0; + } + + $rows = []; + + foreach ($webhooks as $webhook) { + $events = $webhook->events(); + + $rows[] = [ + (string) $webhook->id(), + (string) $webhook->name, + (string) $webhook->url, + in_array(Webhook::ALL_EVENTS, $events, true) ? 'все' : (string) count($events), + (bool) $webhook->active ? 'да' : 'нет', + (int) $webhook->raw('last_status') > 0 ? (string) (int) $webhook->raw('last_status') : '—', + (string) ($webhook->raw('last_sent_at') ?? '—'), + ]; + } + + $this->table(['id', 'Название', 'Адрес', 'События', 'Включена', 'Ответ', 'Последняя посылка'], $rows); + + $stats = WebhookDelivery::stats(); + + $this->line(); + $this->line( + 'Посылки: доставлено ' . (int) ($stats[WebhookDelivery::SENT] ?? 0) + . ', в очереди ' . (int) ($stats[WebhookDelivery::PENDING] ?? 0) + . ', не доставлено ' . (int) ($stats[WebhookDelivery::FAILED] ?? 0) + ); + + return 0; + } + + /** + * Реестр событий: на что вообще можно подписаться. + */ + private function printEvents(): int + { + $rows = []; + + foreach (Webhooks::groups() as $group => $events) { + foreach ($events as $code => $label) { + $rows[] = [$group, $code, $label]; + } + } + + $this->table(['Раздел', 'Событие', 'Что случилось'], $rows); + + return 0; + } +} diff --git a/framework/Console/Commands/WebhookTestCommand.php b/framework/Console/Commands/WebhookTestCommand.php new file mode 100644 index 0000000..45105d1 --- /dev/null +++ b/framework/Console/Commands/WebhookTestCommand.php @@ -0,0 +1,90 @@ + [--queue]'; + } + + public function run(): int + { + $id = (int) $this->arg(0); + + if ($id <= 0) { + $this->fail('Укажите номер подписки: webhook:test 1 (список — webhook:list)'); + + return 1; + } + + $webhook = Webhook::find($id); + + if ($webhook === null) { + $this->fail('Подписка ' . $id . ' не найдена'); + + return 1; + } + + $delivery = Webhooks::test($webhook); + + // По умолчанию отправляем сразу: ждать воркера, чтобы проверить адрес, + // — лишний шаг. С --queue посылка остаётся в очереди + if ($this->hasOption('queue')) { + $this->ok('Посылка №' . $delivery->id() . ' поставлена в очередь «' . Webhooks::queue() . '»'); + + return 0; + } + + try { + (new DeliverWebhookJob())->handle(['delivery_id' => $delivery->id()]); + } catch (Throwable) { + // Ошибку задача уже записала в журнал доставок — печатаем её ниже, + // вместе с остальным по посылке + } + + $delivery = WebhookDelivery::find($delivery->id()); + + if ($delivery === null) { + return 1; + } + + $this->line('Посылка: №' . $delivery->id()); + $this->line('Адрес: ' . (string) $webhook->url); + $this->line('Ответ: ' . ((int) $delivery->raw('response_status') > 0 ? (string) (int) $delivery->raw('response_status') : '—')); + $this->line('Время: ' . (int) $delivery->raw('duration_ms') . ' мс'); + + if ((string) $delivery->raw('status') !== WebhookDelivery::SENT) { + $this->fail('Состояние: ' . $delivery->label() . ' — ' . (string) $delivery->raw('error')); + + return 1; + } + + $this->ok('Доставлена'); + + return 0; + } +} diff --git a/framework/Models/Webhook.php b/framework/Models/Webhook.php index 35830dd..013b0ad 100644 --- a/framework/Models/Webhook.php +++ b/framework/Models/Webhook.php @@ -94,7 +94,8 @@ final class Webhook extends Model */ public function events(): array { - $events = $this->events; + // Читаем raw, а не через приведение: у новой подписки колонки ещё нет + $events = json_decode((string) $this->raw('events'), true); return is_array($events) ? array_map(static fn (mixed $event): string => (string) $event, $events) : []; } diff --git a/framework/Support/Diagnostics.php b/framework/Support/Diagnostics.php index eaa94bd..15cf1f4 100644 --- a/framework/Support/Diagnostics.php +++ b/framework/Support/Diagnostics.php @@ -10,6 +10,8 @@ use Rsgrinko\Proton\Database\Migrator; use Rsgrinko\Proton\Files\Storage; use Rsgrinko\Proton\Models\Setting; use Rsgrinko\Proton\Models\User; +use Rsgrinko\Proton\Models\Webhook; +use Rsgrinko\Proton\Models\WebhookDelivery; use Rsgrinko\Proton\Queue\Queue; use Throwable; @@ -247,9 +249,38 @@ final class Diagnostics 'hint' => '', ]; + $checks[] = self::webhooks(); + return $checks; } + /** + * Подписки на события: сколько их и нет ли недоставленных посылок. + * + * @return array{level: string, title: string, value: string, hint: string} + */ + private static function webhooks(): array + { + try { + if (!Connection::instance()->hasTable('webhooks')) { + return ['level' => self::OK, 'title' => 'Вебхуки', 'value' => 'таблиц нет', 'hint' => '']; + } + + $active = Webhook::query()->where('active', 1)->count(); + $failed = (int) (WebhookDelivery::stats()[WebhookDelivery::FAILED] ?? 0); + + return self::check( + $failed === 0, + 'Вебхуки', + 'подписок ' . $active . ', не доставлено ' . $failed, + 'Посмотрите журнал доставок: кто-то из подписчиков не отвечает', + self::WARN + ); + } catch (Throwable $e) { + return ['level' => self::WARN, 'title' => 'Вебхуки', 'value' => $e->getMessage(), 'hint' => '']; + } + } + /** * @return array{level: string, title: string, value: string, hint: string} */ diff --git a/resources/views/admin/webhook.php b/resources/views/admin/webhook.php new file mode 100644 index 0000000..ffb685b --- /dev/null +++ b/resources/views/admin/webhook.php @@ -0,0 +1,199 @@ +> $groups события по разделам + * @var array{items: array, total: int, page: int, pages: int, per_page: int} $deliveries + * @var string $fresh только что выданный секрет — показывается один раз + */ + +use Rsgrinko\Proton\Models\Webhook; +use Rsgrinko\Proton\Models\WebhookDelivery; +use Rsgrinko\Proton\View\View; + +$isNew = !$webhook->existsInDatabase(); +$action = $isNew ? View::route('admin.webhooks.create') : View::route('admin.webhooks.show', ['id' => $webhook->id()]); +$selected = $webhook->events(); +$all = in_array(Webhook::ALL_EVENTS, $selected, true); +?> +

name) ?>

+ + +
+

Новый секрет

+

Пропишите его у подписчика: старый больше не подойдёт.

+
+

+
+ + +
+
+ + + + + + + + + + +

События

+ + + + $events) { ?> +
+

+ + $label) { ?> + + +
+ + +
+ + К списку +
+
+
+ + +
+

Секрет и состояние

+ + + + + + + + + + + + + + + raw('last_error') !== '') { ?> + + + + + + + + + +
СекретmaskedSecret()) ?>
Состояние + active) { ?> + включена + + отключена + +
Последняя посылка + raw('last_sent_at'))) ?> + raw('last_status') > 0) { ?> + ответ raw('last_status') ?> + +
Последняя ошибкаraw('last_error')) ?>
Неудач подрядraw('failures') ?>
+ +
+
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+
+
+ +
+

Посылки

+ + +

Посылок пока не было.

+ +
+ + + + + + + + + + + + + + + + + + + + + + +
№СобытиеСостояниеОтветПопытокВремяКогда
id() ?>raw('event')) ?> + raw('status') === WebhookDelivery::SENT) { ?> + label()) ?> + raw('status') === WebhookDelivery::FAILED) { ?> + label()) ?> + + label()) ?> + + + raw('response_status') > 0 ? (int) $delivery->raw('response_status') : '—' ?> + raw('error') !== '') { ?> +
raw('error')) ?>
+ +
raw('attempts') ?>raw('duration_ms') ?> мсraw('created_at'))) ?>
+
+ + 'admin.webhooks.show', + 'page' => $deliveries['page'], + 'pages' => $deliveries['pages'], + 'params' => ['id' => $webhook->id()], + ]) ?> + +
+ diff --git a/resources/views/admin/webhooks.php b/resources/views/admin/webhooks.php new file mode 100644 index 0000000..c82b062 --- /dev/null +++ b/resources/views/admin/webhooks.php @@ -0,0 +1,109 @@ +, total: int, page: int, pages: int, per_page: int} $page + * @var array> $groups события по разделам + * @var array $stats посылки по состояниям + */ + +use Rsgrinko\Proton\Models\Webhook; +use Rsgrinko\Proton\Models\WebhookDelivery; +use Rsgrinko\Proton\View\View; + +$events = 0; + +foreach ($groups as $group) { + $events += count($group); +} +?> +

Вебхуки

+ +
+

+ Подписка получает событие приложения посылкой POST с подписью в заголовке + X-Proton-Signature. Отправляет их воркер: упавшую посылку + он повторит, а подписчик, молчащий слишком долго, отключится сам. + Событий в реестре: . +

+ +

+ Посылки: доставлено , + в очереди , + не доставлено . +

+ + +
+ +
+

Подписки

+ + +

Подписок пока нет.

+ +
+ + + + + + + + + + + + + + + + + + + + +
НазваниеАдресСобытияСостояниеПоследняя посылка
+ + name) ?> + + url) ?> + events(), true)) { ?> + все + + events()) ?> + + + active) { ?> + включена + + отключена + + + raw('last_sent_at'))) ?> + raw('last_status') > 0) { ?> + (raw('last_status') ?>) + + +
+
+ + +
+
+
+
+ + 'admin.webhooks', + 'page' => $page['page'], + 'pages' => $page['pages'], + 'params' => [], + ]) ?> + +
diff --git a/routes/admin.php b/routes/admin.php index d98ee34..65c0cec 100644 --- a/routes/admin.php +++ b/routes/admin.php @@ -17,6 +17,7 @@ use App\Controllers\Admin\RolesController; use App\Controllers\Admin\SystemController; use App\Controllers\Admin\TokensController; use App\Controllers\Admin\UsersController; +use App\Controllers\Admin\WebhooksController; use Rsgrinko\Proton\Access\Permission; use Rsgrinko\Proton\Http\Router; @@ -51,6 +52,18 @@ return static function (Router $router): void { $router->post('/{id:\d+}/delete', [TokensController::class, 'delete'])->name('admin.tokens.delete'); }); + $router->group(['prefix' => '/webhooks', 'middleware' => 'can:' . Permission::WEBHOOKS_MANAGE], function (Router $router): void { + $router->get('', [WebhooksController::class, 'index'])->name('admin.webhooks'); + $router->get('/new', [WebhooksController::class, 'create'])->name('admin.webhooks.create'); + $router->post('/new', [WebhooksController::class, 'store']); + $router->get('/{id:\d+}', [WebhooksController::class, 'show'])->name('admin.webhooks.show'); + $router->post('/{id:\d+}', [WebhooksController::class, 'update']); + $router->post('/{id:\d+}/test', [WebhooksController::class, 'test'])->name('admin.webhooks.test'); + $router->post('/{id:\d+}/toggle', [WebhooksController::class, 'toggle'])->name('admin.webhooks.toggle'); + $router->post('/{id:\d+}/secret', [WebhooksController::class, 'rotate'])->name('admin.webhooks.rotate'); + $router->post('/{id:\d+}/delete', [WebhooksController::class, 'delete'])->name('admin.webhooks.delete'); + }); + $router->get('/audit', [AuditController::class, 'index']) ->middleware('can:' . Permission::AUDIT_VIEW) ->name('admin.audit'); diff --git a/tests/HttpTest.php b/tests/HttpTest.php index e727d35..b5ec426 100644 --- a/tests/HttpTest.php +++ b/tests/HttpTest.php @@ -19,6 +19,8 @@ use Rsgrinko\Proton\Http\Response; use Rsgrinko\Proton\Models\ApiToken; use Rsgrinko\Proton\Models\Role; use Rsgrinko\Proton\Models\User; +use Rsgrinko\Proton\Models\Webhook; +use Rsgrinko\Proton\Models\WebhookDelivery; /** * Запрос к ядру от лица пользователя (или гостя, если его нет). @@ -94,6 +96,27 @@ function httpUser(): User return $user; } +/** + * Подписка на события для обхода страниц панели. + */ +function httpWebhook(): Webhook +{ + static $webhook = null; + + if ($webhook instanceof Webhook) { + return $webhook; + } + + $webhook = Webhook::add('Подписка для обхода', 'https://example.com/hook', [Webhook::ALL_EVENTS]); + + afterTests(static function () use ($webhook): void { + WebhookDelivery::query()->where('webhook_id', $webhook->id())->delete(); + $webhook->delete(); + }); + + return $webhook; +} + test('http: гостя уводит на вход, а не показывает страницу', function (): void { // Пользователь в базе нужен: пока их нет, всё уводит на первый запуск httpAdmin(); @@ -148,6 +171,7 @@ test('http: все страницы администратора отвечаю '/admin', '/admin/users', '/admin/users/new', '/admin/users/' . httpAdmin()->id(), '/admin/roles', '/admin/roles/new', '/admin/roles/' . (Role::admin()?->id() ?? 1), '/admin/tokens', '/admin/audit', '/admin/logs', '/admin/system', + '/admin/webhooks', '/admin/webhooks/new', '/admin/webhooks/' . httpWebhook()->id(), ]; foreach ($paths as $path) { @@ -156,7 +180,12 @@ test('http: все страницы администратора отвечаю }); test('http: обычный пользователь не попадает в служебные разделы', function (): void { - foreach (['/admin', '/admin/users', '/admin/roles', '/admin/tokens', '/admin/audit', '/admin/logs', '/admin/system'] as $path) { + $closed = [ + '/admin', '/admin/users', '/admin/roles', '/admin/tokens', + '/admin/audit', '/admin/logs', '/admin/system', '/admin/webhooks', + ]; + + foreach ($closed as $path) { assertStatus(403, httpRequest('GET', $path, httpUser()), 'закрытая страница ' . $path); } @@ -215,6 +244,49 @@ test('http: неверные данные возвращают человека assertSame(0, Note::query()->where('title', '')->count()); }); +test('http: подписка на события заводится и проверяется из панели', function (): void { + $response = httpRequest('POST', '/admin/webhooks/new', httpAdmin(), [ + 'name' => 'Через форму', + 'url' => 'https://example.com/hooks/proton', + 'events' => ['user.login'], + 'secret' => 'секрет-из-формы', + ]); + + assertStatus(302, $response); + + /** @var Webhook $webhook */ + $webhook = assertNotNull(Webhook::query()->where('name', 'Через форму')->first()); + + assertSame('секрет-из-формы', $webhook->secret()); + assertSame(['user.login'], $webhook->events()); + + // Пробная посылка только встаёт в очередь — в сеть тесты не ходят + assertStatus(302, httpRequest('POST', '/admin/webhooks/' . $webhook->id() . '/test', httpAdmin())); + + $delivery = assertNotNull( + WebhookDelivery::query()->where('webhook_id', $webhook->id())->orderBy('id', 'desc')->first() + ); + + assertSame(WebhookDelivery::PENDING, (string) $delivery->raw('status')); + + // Событие без подписчиков посылок не создаёт, с подписчиком — создаёт + Rsgrinko\Proton\Webhooks\Webhooks::dispatch('user.logout', ['login' => 'кто-то']); + + assertSame(1, WebhookDelivery::query()->where('webhook_id', $webhook->id())->count(), 'чужое событие не уехало'); + + Rsgrinko\Proton\Webhooks\Webhooks::dispatch('user.login', ['login' => 'кто-то']); + + assertSame(2, WebhookDelivery::query()->where('webhook_id', $webhook->id())->count()); + + // Отключение и удаление — тоже из панели + assertStatus(302, httpRequest('POST', '/admin/webhooks/' . $webhook->id() . '/toggle', httpAdmin())); + assertFalse((bool) assertNotNull(Webhook::find($webhook->id()))->active); + + assertStatus(302, httpRequest('POST', '/admin/webhooks/' . $webhook->id() . '/delete', httpAdmin())); + assertNull(Webhook::find($webhook->id())); + assertSame(0, WebhookDelivery::query()->where('webhook_id', $webhook->id())->count(), 'журнал ушёл вместе с подпиской'); +}); + test('http: неизвестный адрес — 404', function (): void { assertStatus(404, httpRequest('GET', '/нет-такой-страницы', httpAdmin())); });