From 20f3d795528170b5d24ce97e49e26c9de6ebb590 Mon Sep 17 00:00:00 2001 From: rsgrinko Date: Tue, 15 Sep 2026 22:37:47 +0300 Subject: [PATCH] =?UTF-8?q?=D0=91=D0=BB=D0=BE=D0=BA=D0=B8=D1=80=D0=BE?= =?UTF-8?q?=D0=B2=D0=BA=D0=B0=20=D0=B0=D0=B4=D1=80=D0=B5=D1=81=D0=BE=D0=B2?= =?UTF-8?q?,=20=D0=B6=D1=83=D1=80=D0=BD=D0=B0=D0=BB=20=D0=BF=D0=BE=D0=B4?= =?UTF-8?q?=D0=BE=D0=B7=D1=80=D0=B8=D1=82=D0=B5=D0=BB=D1=8C=D0=BD=D0=BE?= =?UTF-8?q?=D0=B9=20=D0=B0=D0=BA=D1=82=D0=B8=D0=B2=D0=BD=D0=BE=D1=81=D1=82?= =?UTF-8?q?=D0=B8,=20=D1=81=D1=80=D0=BE=D0=BA=20=D0=B6=D0=B8=D0=B7=D0=BD?= =?UTF-8?q?=D0=B8=20=D0=BA=D0=BB=D1=8E=D1=87=D0=B5=D0=B9=20API?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 9 + app/Controllers/Admin/SecurityController.php | 166 +++++++++++++++ app/Controllers/Admin/TokensController.php | 13 +- config/config.php | 14 ++ config/menu.php | 1 + framework/Auth/Auth.php | 30 +++ framework/Database/Model/Model.php | 9 + framework/Database/Model/Query.php | 4 +- framework/Http/Kernel.php | 25 ++- framework/Models/ApiToken.php | 55 ++++- framework/Models/BlockedIp.php | 114 +++++++++++ framework/Models/SecurityEvent.php | 102 ++++++++++ .../ApiKeyExpiringNotification.php | 54 +++++ framework/Queue/Scheduler.php | 20 ++ framework/Queue/Worker.php | 4 + .../20260915230000_create_security_tables.php | 57 ++++++ resources/views/admin/security.php | 189 ++++++++++++++++++ resources/views/admin/tokens.php | 18 ++ routes/admin.php | 8 + tests/SecurityTest.php | 156 +++++++++++++++ 20 files changed, 1042 insertions(+), 6 deletions(-) create mode 100644 app/Controllers/Admin/SecurityController.php create mode 100644 framework/Models/BlockedIp.php create mode 100644 framework/Models/SecurityEvent.php create mode 100644 framework/Notifications/ApiKeyExpiringNotification.php create mode 100644 migrations/20260915230000_create_security_tables.php create mode 100644 resources/views/admin/security.php create mode 100644 tests/SecurityTest.php diff --git a/.env.example b/.env.example index 7549aa1..a40b475 100644 --- a/.env.example +++ b/.env.example @@ -97,6 +97,15 @@ EXPORT_MAX_ROWS=20000 # Загрузка списков из CSV: сколько строк принимаем за раз IMPORT_MAX_ROWS=5000 +# Безопасность: закрытые адреса, автоблокировка перебора, журнал событий +SECURITY_BLOCKLIST=true +SECURITY_AUTOBLOCK_ATTEMPTS=30 +SECURITY_AUTOBLOCK_WINDOW=60 +SECURITY_AUTOBLOCK_MINUTES=60 +SECURITY_KEEP_DAYS=60 +# За сколько дней предупредить владельца, что ключ API скоро истечёт +KEY_EXPIRY_NOTICE_DAYS=7 + # Показатели работы: счётчики запросов и порог «медленного» ответа METRICS_ENABLED=true METRICS_SLOW_MS=1000 diff --git a/app/Controllers/Admin/SecurityController.php b/app/Controllers/Admin/SecurityController.php new file mode 100644 index 0000000..9652634 --- /dev/null +++ b/app/Controllers/Admin/SecurityController.php @@ -0,0 +1,166 @@ +listFilters($request); + + return $this->view('admin/security', [ + 'active' => 'security', + 'page' => $filters->apply(SecurityEvent::query())->paginate($this->page($request), $this->perPage()), + 'filters' => $filters, + 'blocks' => BlockedIp::query()->orderBy('id', 'desc')->limit(100)->get(), + 'authors' => $this->authors(), + 'top' => $this->noisiest(), + ], 'Безопасность'); + } + + public function export(Request $request): Response + { + $filters = $this->listFilters($request); + + return $this->exportCsv($filters->apply(SecurityEvent::query()), [ + 'created_at' => 'Когда', + 'kind' => ['Событие', static fn (SecurityEvent $event): string => SecurityEvent::label((string) $event->raw('kind'))], + 'ip' => 'Адрес', + 'login' => 'Логин', + 'path' => 'Страница', + 'agent' => 'Клиент', + ], 'security', 'security', 'admin.security'); + } + + /** + * Закрыть адрес. Срок в минутах; 0 — навсегда. + */ + public function block(Request $request): Response + { + $data = $this->validate($request, [ + 'ip' => 'required|max:64', + 'reason' => 'nullable|max:191', + 'minutes' => 'nullable|integer', + ], ['ip' => 'Адрес', 'reason' => 'Причина', 'minutes' => 'Срок в минутах']); + + $ip = trim((string) $data['ip']); + + // Свой адрес закрывать не даём: администратор запрёт сам себя + if ($ip === $request->ip()) { + $this->flash('Это ваш собственный адрес — закрывать его нельзя', 'error'); + + return $this->redirect('admin.security'); + } + + $minutes = (int) ($data['minutes'] ?? 60); + + BlockedIp::block($ip, (string) ($data['reason'] ?? ''), $minutes, (int) $request->attribute('user')?->id()); + + Audit::action('security', 0, 'закрыт адрес ' . $ip . ($minutes > 0 ? ' на ' . $minutes . ' мин' : ' навсегда')); + + $this->flash('Адрес ' . $ip . ' закрыт'); + + return $this->redirect('admin.security'); + } + + /** + * Открыть адрес обратно. + */ + public function unblock(Request $request): Response + { + $ip = trim((string) $request->input('ip', '')); + + if ($ip === '' || !BlockedIp::unblock($ip)) { + $this->flash('Такой блокировки нет', 'error'); + + return $this->redirect('admin.security'); + } + + Audit::action('security', 0, 'открыт адрес ' . $ip); + + $this->flash('Адрес ' . $ip . ' открыт'); + + return $this->redirect('admin.security'); + } + + private function listFilters(Request $request): Filters + { + return $this->filters($request, [ + Filter::select('kind', 'Событие', SecurityEvent::LABELS), + Filter::text('ip', 'Адрес', 'ip', '127.0.0.1'), + Filter::search('q', 'Поиск', ['login', 'path'], 'логин или страница'), + Filter::dates('when', 'Когда', 'created_at'), + ])->sortable(['id', 'created_at'], 'id'); + } + + /** + * Логины, которые чаще всего подбирают — по ним видно, ломятся ли + * в конкретную учётную запись. + * + * @return array + */ + private function authors(): array + { + $rows = SecurityEvent::query() + ->select('login', 'COUNT(*) AS total') + ->where('kind', SecurityEvent::LOGIN_FAILED) + ->where('login', '!=', '') + ->groupBy('login') + ->orderBy('total', 'desc') + ->limit(5) + ->rows(); + + $out = []; + + foreach ($rows as $row) { + $out[(string) $row['login']] = (int) $row['total']; + } + + return $out; + } + + /** + * Самые шумные адреса за сутки. + * + * @return array + */ + private function noisiest(): array + { + $rows = SecurityEvent::query() + ->select('ip', 'COUNT(*) AS total') + ->where('created_at', '>=', date('Y-m-d H:i:s', time() - 86400)) + ->where('ip', '!=', '') + ->groupBy('ip') + ->orderBy('total', 'desc') + ->limit(5) + ->rows(); + + $out = []; + + foreach ($rows as $row) { + $out[(string) $row['ip']] = (int) $row['total']; + } + + return $out; + } +} diff --git a/app/Controllers/Admin/TokensController.php b/app/Controllers/Admin/TokensController.php index f968d11..369f540 100644 --- a/app/Controllers/Admin/TokensController.php +++ b/app/Controllers/Admin/TokensController.php @@ -53,7 +53,8 @@ final class TokensController extends Controller 'name' => 'nullable|max:191', 'user_id' => 'required|integer|exists:users', 'ips' => 'nullable|max:500', - ], ['name' => 'Название', 'user_id' => 'Владелец', 'ips' => 'Разрешённые адреса']); + 'days' => 'nullable|integer', + ], ['name' => 'Название', 'user_id' => 'Владелец', 'ips' => 'Разрешённые адреса', 'days' => 'Срок в днях']); $ips = trim((string) ($data['ips'] ?? '')); @@ -65,9 +66,15 @@ final class TokensController extends Controller } } - $issued = ApiToken::issue((string) ($data['name'] ?? ''), (int) $data['user_id'], $ips); + $days = max(0, (int) ($data['days'] ?? 0)); - Audit::created('token', $issued['token']->id(), 'выпущен ключ ' . $issued['token']->mask()); + $issued = ApiToken::issue((string) ($data['name'] ?? ''), (int) $data['user_id'], $ips, $days); + + Audit::created( + 'token', + $issued['token']->id(), + 'выпущен ключ ' . $issued['token']->mask() . ($days > 0 ? ' на ' . $days . ' дн.' : ' без срока') + ); // Ключ показываем один раз — дальше только маска View::stash('api_key', $issued['key']); diff --git a/config/config.php b/config/config.php index 9984a3f..84886c2 100644 --- a/config/config.php +++ b/config/config.php @@ -193,6 +193,20 @@ return [ 'max_rows' => Env::int('EXPORT_MAX_ROWS', 20000), ], + 'security' => [ + // Закрытые адреса проверяются на каждом заходе; выключается, если + // блокировки делает что-то снаружи (nginx, файрвол) + 'blocklist' => Env::bool('SECURITY_BLOCKLIST', true), + // Столько раз упёрся в лимит попыток за окно (минуты) — адрес закрывается + 'autoblock_attempts' => Env::int('SECURITY_AUTOBLOCK_ATTEMPTS', 30), + 'autoblock_window' => Env::int('SECURITY_AUTOBLOCK_WINDOW', 60), + 'autoblock_minutes' => Env::int('SECURITY_AUTOBLOCK_MINUTES', 60), + // Сколько держать журнал подозрительных событий + 'keep_days' => Env::int('SECURITY_KEEP_DAYS', 60), + // За сколько дней предупреждать владельца об истечении ключа API + 'key_expiry_notice_days' => Env::int('KEY_EXPIRY_NOTICE_DAYS', 7), + ], + 'metrics' => [ // Счётчики запросов в кэше: выключаются, если сбор не нужен 'enabled' => Env::bool('METRICS_ENABLED', true), diff --git a/config/menu.php b/config/menu.php index 892ca5d..7e21267 100644 --- a/config/menu.php +++ b/config/menu.php @@ -24,6 +24,7 @@ return [ ['key' => 'settings', 'label' => 'Настройки', 'route' => 'admin.settings', 'permission' => Permission::SETTINGS_MANAGE], ['key' => 'backups', 'label' => 'Копии', 'route' => 'admin.backups', 'permission' => Permission::SYSTEM_MANAGE], ['key' => 'reports', 'label' => 'Отчёты', 'route' => 'admin.reports', 'permission' => Permission::SYSTEM_VIEW], + ['key' => 'security', 'label' => 'Безопасность', 'route' => 'admin.security', 'permission' => Permission::SYSTEM_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/Auth/Auth.php b/framework/Auth/Auth.php index 568c6dc..d55ef30 100644 --- a/framework/Auth/Auth.php +++ b/framework/Auth/Auth.php @@ -7,6 +7,8 @@ namespace Rsgrinko\Proton\Auth; use Rsgrinko\Proton\Access\Viewer; use Rsgrinko\Proton\Http\Response; use Rsgrinko\Proton\Models\RememberToken; +use Rsgrinko\Proton\Models\BlockedIp; +use Rsgrinko\Proton\Models\SecurityEvent; use Rsgrinko\Proton\Models\User; use Rsgrinko\Proton\Models\UserSession; use Rsgrinko\Proton\RateLimit\RateLimiter; @@ -163,6 +165,11 @@ final class Auth $window = max(60, (int) Config::get('auth.attempts_window', 900)); if ($limiter->count($key) >= $max) { + SecurityEvent::record(SecurityEvent::LOGIN_BLOCKED, $credential); + + // Перебор продолжается после исчерпанного лимита — закрываем адрес + self::blockIfPersistent($ip); + return ['user' => null, 'error' => 'Слишком много попыток входа. Попробуйте позже']; } @@ -175,6 +182,8 @@ final class Auth if ($user === null || !$user->verifyPassword($password) || !$user->isActive()) { $limiter->hit($key, time() + $window); + SecurityEvent::record(SecurityEvent::LOGIN_FAILED, $credential); + return ['user' => null, 'error' => 'Неверный логин или пароль']; } @@ -189,6 +198,27 @@ final class Auth return ['user' => $user, 'error' => '']; } + /** + * Закрыть адрес, если перебор не прекращается. Порог и срок задаются + * настройками SECURITY_*; ноль в пороге выключает автоблокировку. + */ + private static function blockIfPersistent(string $ip): void + { + $threshold = (int) Config::get('security.autoblock_attempts', 30); + + if ($threshold <= 0 || $ip === '') { + return; + } + + $window = max(1, (int) Config::get('security.autoblock_window', 60)); + + if (SecurityEvent::countFor($ip, SecurityEvent::LOGIN_BLOCKED, $window) < $threshold) { + return; + } + + BlockedIp::block($ip, 'перебор паролей', max(1, (int) Config::get('security.autoblock_minutes', 60))); + } + /** * Записывает пользователя в сессию. * diff --git a/framework/Database/Model/Model.php b/framework/Database/Model/Model.php index 4118ffc..339416e 100644 --- a/framework/Database/Model/Model.php +++ b/framework/Database/Model/Model.php @@ -131,6 +131,15 @@ abstract class Model implements JsonSerializable return $this->timestamps; } + /** + * Есть ли такая колонка в таблице — нужно массовому обновлению: отметку + * времени нельзя ставить там, где её не предусмотрели схемой. + */ + public function usesColumn(string $column): bool + { + return $this->hasColumn($column); + } + public function softDeletes(): bool { return $this->softDelete; diff --git a/framework/Database/Model/Query.php b/framework/Database/Model/Query.php index 19acb41..c80bef3 100644 --- a/framework/Database/Model/Query.php +++ b/framework/Database/Model/Query.php @@ -180,7 +180,9 @@ final class Query extends Builder { $model = new ($this->model)(); - if ($model->hasTimestamps() && !array_key_exists('updated_at', $data)) { + // Отметку ставим, только если колонка есть: у журналов и событий + // её обычно нет — там только created_at + if ($model->hasTimestamps() && $model->usesColumn('updated_at') && !array_key_exists('updated_at', $data)) { $data['updated_at'] = date('Y-m-d H:i:s'); } diff --git a/framework/Http/Kernel.php b/framework/Http/Kernel.php index dc97158..701199f 100644 --- a/framework/Http/Kernel.php +++ b/framework/Http/Kernel.php @@ -8,6 +8,8 @@ use Rsgrinko\Proton\Access\AccessDenied; use Rsgrinko\Proton\Auth\Auth; use Rsgrinko\Proton\Auth\Csrf; use Rsgrinko\Proton\Database\Model\RecordNotFound; +use Rsgrinko\Proton\Models\BlockedIp; +use Rsgrinko\Proton\Models\SecurityEvent; use Rsgrinko\Proton\Http\Middleware\ApiKey; use Rsgrinko\Proton\Http\Middleware\Authenticate; use Rsgrinko\Proton\Http\Middleware\Can; @@ -55,7 +57,7 @@ final class Kernel Settings::apply(); try { - $response = $this->finish($this->router()->dispatch($request)); + $response = $this->finish($this->blocked($request) ?? $this->router()->dispatch($request)); } catch (AccessDenied $e) { $response = $this->finish($this->denied($request, $e)); } catch (RecordNotFound $e) { @@ -116,6 +118,27 @@ final class Kernel ->withHeader(RequestId::HEADER, RequestId::current()); } + /** + * Закрытый адрес разворачиваем до маршрутов: заблокированному нечего делать + * ни на форме входа, ни в API. Пустой ответ означает «адрес не закрыт». + */ + private function blocked(Request $request): ?Response + { + if (!(bool) Config::get('security.blocklist', true) || !BlockedIp::blocked($request->ip())) { + return null; + } + + SecurityEvent::record(SecurityEvent::IP_BLOCKED, '', $request->path, $request->userAgent()); + + if ($request->wantsJson()) { + return Response::error('Доступ с этого адреса закрыт', 403); + } + + return Response::html(View::render('errors/403', [ + 'message' => 'Доступ с этого адреса закрыт. Если это ошибка, обратитесь к администратору.', + ], 'Доступ закрыт'), 403); + } + /** * Правило на запись не пустило. */ diff --git a/framework/Models/ApiToken.php b/framework/Models/ApiToken.php index f0ea172..1261332 100644 --- a/framework/Models/ApiToken.php +++ b/framework/Models/ApiToken.php @@ -40,7 +40,7 @@ final class ApiToken extends Model * * @return array{token: self, key: string} */ - public static function issue(string $name, int $userId, string $ipList = ''): array + public static function issue(string $name, int $userId, string $ipList = '', int $days = 0): array { $prefix = Str::random(8); $secret = Str::random(40); @@ -55,6 +55,8 @@ final class ApiToken extends Model 'token_hash' => self::hash($key), 'allowed_ips' => $ipList, 'active' => 1, + // Ключ без срока живёт вечно — это осознанный выбор того, кто его выпускал + 'expires_at' => $days > 0 ? date('Y-m-d H:i:s', time() + $days * 86400) : null, 'created_at' => Connection::now(), ])->save(); @@ -92,6 +94,57 @@ final class ApiToken extends Model return $token; } + /** + * До какого времени действует; пусто — без срока. + */ + public function expiresAt(): string + { + return trim((string) $this->raw('expires_at')); + } + + /** + * Сколько дней осталось; -1 — ключ без срока. + */ + public function daysLeft(): int + { + $expires = $this->expiresAt(); + + if ($expires === '') { + return -1; + } + + $time = strtotime($expires); + + return $time === false ? -1 : (int) ceil(($time - time()) / 86400); + } + + public function expired(): bool + { + $expires = $this->expiresAt(); + + return $expires !== '' && strtotime($expires) < time(); + } + + /** + * Действующие ключи, которым осталось не больше стольких дней. По ним + * рассылаются напоминания владельцам. + * + * @return array + */ + public static function expiringWithin(int $days): array + { + /** @var array $tokens */ + $tokens = self::query() + ->where('active', 1) + ->whereNotNull('expires_at') + ->where('expires_at', '>', Connection::now()) + ->where('expires_at', '<=', date('Y-m-d H:i:s', time() + max(1, $days) * 86400)) + ->orderBy('expires_at') + ->get(); + + return $tokens; + } + /** * Отмечает использование: по этой дате видно забытые ключи. */ diff --git a/framework/Models/BlockedIp.php b/framework/Models/BlockedIp.php new file mode 100644 index 0000000..8e1a5b8 --- /dev/null +++ b/framework/Models/BlockedIp.php @@ -0,0 +1,114 @@ +where('ip', $ip)->first(); + + $block = $existing ?? new self(); + + $block->forceFill([ + 'ip' => $ip, + 'reason' => $reason, + 'until' => $minutes > 0 ? date('Y-m-d H:i:s', time() + $minutes * 60) : null, + 'created_by' => $byUserId > 0 ? $byUserId : null, + ]); + + $block->save(); + + return $block; + } + + /** + * Снять блокировку. + */ + public static function unblock(string $ip): bool + { + /** @var self|null $block */ + $block = self::query()->where('ip', trim($ip))->first(); + + return $block !== null && $block->delete(); + } + + /** + * Закрыт ли адрес прямо сейчас. Просроченная запись не считается — + * её уберёт уборка, а держать человека за дверью лишнюю минуту незачем. + */ + public static function blocked(string $ip): bool + { + $ip = trim($ip); + + if ($ip === '') { + return false; + } + + $db = Connection::instance(); + + if (!$db->hasTable('blocked_ips')) { + return false; + } + + $row = $db->selectOne( + 'SELECT until FROM blocked_ips WHERE ip = :ip', + ['ip' => $ip] + ); + + if ($row === null) { + return false; + } + + $until = trim((string) ($row['until'] ?? '')); + + return $until === '' || strtotime($until) > time(); + } + + /** + * Убрать записи, у которых срок вышел. Зовётся уборкой воркера. + */ + public static function purgeExpired(): int + { + return self::query() + ->whereNotNull('until') + ->where('until', '<', Connection::now()) + ->delete(); + } + + /** + * До какого времени закрыт — пусто означает «навсегда». + */ + public function until(): string + { + return trim((string) $this->raw('until')); + } + + public function permanent(): bool + { + return $this->until() === ''; + } +} diff --git a/framework/Models/SecurityEvent.php b/framework/Models/SecurityEvent.php new file mode 100644 index 0000000..8901249 --- /dev/null +++ b/framework/Models/SecurityEvent.php @@ -0,0 +1,102 @@ + Подписи для панели */ + public const LABELS = [ + self::LOGIN_FAILED => 'неудачный вход', + self::LOGIN_BLOCKED => 'перебор паролей', + self::IP_BLOCKED => 'заход с закрытого адреса', + self::ACCESS_DENIED => 'нет прав', + self::KEY_INVALID => 'негодный ключ', + ]; + + /** + * Записать событие. + */ + public static function record(string $kind, string $login = '', string $path = '', string $agent = ''): void + { + try { + $event = new self(); + + $event->forceFill([ + 'kind' => $kind, + 'ip' => ClientIp::fromGlobals(), + 'login' => mb_substr($login, 0, 191), + 'path' => mb_substr($path, 0, 191), + 'agent' => mb_substr($agent, 0, 255), + ]); + + $event->save(); + } catch (Throwable) { + // Журнал безопасности не должен мешать работе: не записалось — и ладно + } + } + + public static function label(string $kind): string + { + return self::LABELS[$kind] ?? $kind; + } + + /** + * Сколько событий такого рода с этого адреса за последние минуты — + * по этому числу решают, не пора ли закрыть адрес. + */ + public static function countFor(string $ip, string $kind, int $minutes): int + { + return self::query() + ->where('ip', $ip) + ->where('kind', $kind) + ->where('created_at', '>=', date('Y-m-d H:i:s', time() - max(1, $minutes) * 60)) + ->count(); + } + + /** + * Уборка старых записей. + */ + public static function purge(int $days): int + { + if ($days <= 0) { + return 0; + } + + return self::query() + ->where('created_at', '<', date('Y-m-d H:i:s', time() - $days * 86400)) + ->delete(); + } +} diff --git a/framework/Notifications/ApiKeyExpiringNotification.php b/framework/Notifications/ApiKeyExpiringNotification.php new file mode 100644 index 0000000..7581be3 --- /dev/null +++ b/framework/Notifications/ApiKeyExpiringNotification.php @@ -0,0 +1,54 @@ +token->name . '» скоро истечёт'; + } + + public function body(): string + { + $days = $this->daysLeft <= 0 ? 'сегодня' : 'через ' . $this->daysLeft . ' дн.'; + + return 'Ключ ' . $this->token->mask() . ' перестанет работать ' . $days + . ' (' . $this->token->expiresAt() . '). Выпустите новый и замените его в интеграции:' + . ' продлить существующий нельзя — в базе лежит только хеш.'; + } + + public function url(): string + { + return Router::absolute('admin.tokens'); + } + + /** + * @return array + */ + public function channels(): array + { + return [Notify::DATABASE, Notify::MAIL]; + } +} diff --git a/framework/Queue/Scheduler.php b/framework/Queue/Scheduler.php index a1c6edb..b8b23c6 100644 --- a/framework/Queue/Scheduler.php +++ b/framework/Queue/Scheduler.php @@ -5,7 +5,11 @@ declare(strict_types=1); namespace Rsgrinko\Proton\Queue; use Rsgrinko\Proton\Backup\BackupJob; +use Rsgrinko\Proton\Models\ApiToken; use Rsgrinko\Proton\Models\Setting; +use Rsgrinko\Proton\Models\User; +use Rsgrinko\Proton\Notifications\ApiKeyExpiringNotification; +use Rsgrinko\Proton\Notifications\Notify; use Rsgrinko\Proton\Support\Config; use Rsgrinko\Proton\Support\Logger; use Rsgrinko\Proton\Support\Monitor; @@ -176,6 +180,22 @@ final class Scheduler }); } + // Ключи API не продлеваются, поэтому владельцу нужно время выпустить + // новый: напоминаем раз в сутки, пока срок не вышел + self::dailyAt('09:00', 'keys:expiring', static function (): void { + $days = max(1, (int) Config::get('security.key_expiry_notice_days', 7)); + + foreach (ApiToken::expiringWithin($days) as $token) { + $owner = User::find((int) $token->raw('user_id')); + + if ($owner === null) { + continue; + } + + Notify::send($owner, new ApiKeyExpiringNotification($token, $token->daysLeft())); + } + }); + // Присмотр за порогами: о беде лучше узнать от приложения, чем от людей if ((bool) Config::get('monitor.enabled', true)) { self::every( diff --git a/framework/Queue/Worker.php b/framework/Queue/Worker.php index 4834120..62f0d19 100644 --- a/framework/Queue/Worker.php +++ b/framework/Queue/Worker.php @@ -6,7 +6,9 @@ namespace Rsgrinko\Proton\Queue; use Rsgrinko\Proton\Cache\Cache; use Rsgrinko\Proton\Models\AuditEntry; +use Rsgrinko\Proton\Models\BlockedIp; use Rsgrinko\Proton\Models\RememberToken; +use Rsgrinko\Proton\Models\SecurityEvent; use Rsgrinko\Proton\Models\Setting; use Rsgrinko\Proton\Models\UserSession; use Rsgrinko\Proton\Models\WebhookDelivery; @@ -233,6 +235,8 @@ final class Worker UserSession::purge((int) Config::get('auth.sessions_keep_days', 60)); AuditEntry::purge((int) Config::get('audit.keep_days', 180)); WebhookDelivery::purge((int) Config::get('webhooks.keep_days', 14)); + SecurityEvent::purge((int) Config::get('security.keep_days', 60)); + BlockedIp::purgeExpired(); Notify::purge(); (new Logger('app'))->purge(); diff --git a/migrations/20260915230000_create_security_tables.php b/migrations/20260915230000_create_security_tables.php new file mode 100644 index 0000000..22e16b6 --- /dev/null +++ b/migrations/20260915230000_create_security_tables.php @@ -0,0 +1,57 @@ +create('blocked_ips', function (Blueprint $table): void { + $table->id(); + $table->string('ip', 64); + $table->string('reason', 191)->default(''); + // Пусто — блокировка без срока, снимается только руками + $table->dateTime('until')->nullable(); + $table->foreignId('created_by')->nullable(); + $table->dateTime('created_at')->nullable(); + $table->dateTime('updated_at')->nullable(); + + $table->unique('idx_blocked_ip', 'ip'); + $table->index('idx_blocked_until', 'until'); + }); + + $this->create('security_events', function (Blueprint $table): void { + $table->id(); + // login.failed, login.blocked, access.denied, key.invalid + $table->string('kind', 32); + $table->string('ip', 64)->default(''); + $table->string('login', 191)->default(''); + $table->string('path', 191)->default(''); + $table->string('agent', 255)->default(''); + $table->dateTime('created_at')->nullable(); + + $table->index('idx_security_kind', 'kind'); + $table->index('idx_security_ip', 'ip'); + $table->index('idx_security_created', 'created_at'); + }); + } + + public function down(): void + { + foreach (['security_events', 'blocked_ips'] as $table) { + $this->drop($table); + } + } +} diff --git a/resources/views/admin/security.php b/resources/views/admin/security.php new file mode 100644 index 0000000..cbab099 --- /dev/null +++ b/resources/views/admin/security.php @@ -0,0 +1,189 @@ +, total: int, page: int, pages: int, per_page: int} $page + * @var \Rsgrinko\Proton\Support\Filters $filters + * @var array $blocks + * @var array $authors логины, которые чаще всего подбирают + * @var array $top самые шумные адреса за сутки + */ + +use Rsgrinko\Proton\Models\SecurityEvent; +use Rsgrinko\Proton\View\View; +?> +

Безопасность

+ +
+
+

Закрыть адрес

+ +
+ + +
+ + + + + +
+ +
+ + 0 минут — навсегда, пока не откроете руками +
+
+
+ +
+

Кого подбирают

+ + +

Пока тихо.

+ +
+ + $count) { ?> + + + + + +
попыток
+
+ + +

Шумные адреса за сутки

+ +
+ + $count) { ?> + + + + + + +
+
+ + + + + +
+
+
+ + +
+
+ +
+

Закрытые адреса

+ + +

Ни один адрес не закрыт.

+ +
+ + + + + + + + + + + + + + + + +
АдресПричинаДо
raw('ip')) ?>raw('reason') ?: '—') ?> + permanent()) { ?> + навсегда + + until())) ?> + + +
+ + + +
+
+
+ +
+ + $filters, + 'route' => 'admin.security', + 'total' => $page['total'], + 'export' => 'admin.security.export', +]) ?> + +
+

Что происходило

+ + +

Событий нет.

+ +
+ + + + + + + + + + + + + + + + + + + + +
$filters, 'route' => 'admin.security', 'column' => 'created_at', 'label' => 'Когда']) ?>СобытиеАдресЛогинСтраница
raw('created_at'))) ?>raw('kind'))) ?>raw('ip')) ?>raw('login') ?: '—') ?>raw('path') ?: '—') ?> + raw('ip') !== '') { ?> +
+ + + + + +
+ +
+
+ + 'admin.security', + 'page' => $page['page'], + 'pages' => $page['pages'], + 'params' => $filters->params(), + ]) ?> + +
diff --git a/resources/views/admin/tokens.php b/resources/views/admin/tokens.php index 25c8d5c..1d88d74 100644 --- a/resources/views/admin/tokens.php +++ b/resources/views/admin/tokens.php @@ -50,6 +50,11 @@ use Rsgrinko\Proton\View\View; Разрешённые адреса (через запятую, можно сети) + +
@@ -74,6 +79,7 @@ use Rsgrinko\Proton\View\View; Владелец Адреса Состояние + Срок Использован @@ -91,6 +97,18 @@ use Rsgrinko\Proton\View\View; отключён + + daysLeft(); ?> + + без срока + expired()) { ?> + истёк + + осталось дн. + + expiresAt(), 'd.m.Y')) ?> + + raw('last_used_at'))) ?>
diff --git a/routes/admin.php b/routes/admin.php index d5b7580..b23822d 100644 --- a/routes/admin.php +++ b/routes/admin.php @@ -16,6 +16,7 @@ use App\Controllers\Admin\DashboardController; use App\Controllers\Admin\LogsController; use App\Controllers\Admin\ReportsController; use App\Controllers\Admin\RolesController; +use App\Controllers\Admin\SecurityController; use App\Controllers\Admin\SettingsController; use App\Controllers\Admin\SystemController; use App\Controllers\Admin\TokensController; @@ -89,6 +90,13 @@ return static function (Router $router): void { $router->get('/export', [ReportsController::class, 'export'])->name('admin.reports.export'); }); + $router->group(['prefix' => '/security', 'middleware' => 'can:' . Permission::SYSTEM_MANAGE], function (Router $router): void { + $router->get('', [SecurityController::class, 'index'])->name('admin.security'); + $router->get('/export', [SecurityController::class, 'export'])->name('admin.security.export'); + $router->post('/block', [SecurityController::class, 'block'])->name('admin.security.block'); + $router->post('/unblock', [SecurityController::class, 'unblock'])->name('admin.security.unblock'); + }); + $router->get('/audit', [AuditController::class, 'index']) ->middleware('can:' . Permission::AUDIT_VIEW) ->name('admin.audit'); diff --git a/tests/SecurityTest.php b/tests/SecurityTest.php new file mode 100644 index 0000000..6631724 --- /dev/null +++ b/tests/SecurityTest.php @@ -0,0 +1,156 @@ +forceFill(['until' => date('Y-m-d H:i:s', time() - 60)])->save(); + + assertFalse(BlockedIp::blocked('203.0.113.20'), 'срок вышел — дверь открыта'); + + assertSame(1, BlockedIp::purgeExpired()); + assertSame(0, BlockedIp::query()->count()); + + // Блокировка без срока уборкой не снимается + BlockedIp::block('203.0.113.21', 'навсегда', 0); + + assertSame(0, BlockedIp::purgeExpired()); + assertTrue(BlockedIp::blocked('203.0.113.21')); + }); +}); + +test('блокировка: закрытый адрес не пускают даже на форму входа', function (): void { + withOwnDatabase(static function (): void { + Factory::of(User::class)->create(); + + assertStatus(200, get('/login')); + + // Тесты ходят с адреса, который отдаёт Request::create + $ip = Rsgrinko\Proton\Http\Request::create('GET', '/login')->ip(); + + BlockedIp::block($ip, 'проверка', 60); + + $response = get('/login'); + + assertStatus(403, $response); + assertSee('Доступ с этого адреса закрыт', $response); + + // И заход попал в журнал + assertTrue(SecurityEvent::query()->where('kind', SecurityEvent::IP_BLOCKED)->count() > 0); + + BlockedIp::unblock($ip); + + assertStatus(200, get('/login')); + }); +}); + +test('журнал: неудачный вход записывается с логином и адресом', function (): void { + withOwnDatabase(static function (): void { + /** @var User $user */ + $user = Factory::of(User::class)->create(); + + $before = SecurityEvent::query()->count(); + + $response = post('/login', ['login' => (string) $user->login, 'password' => 'не тот пароль']); + + assertStatus(302, $response); + assertSame($before + 1, SecurityEvent::query()->count()); + + /** @var SecurityEvent $event */ + $event = assertNotNull(SecurityEvent::query()->orderBy('id', 'desc')->first()); + + assertSame(SecurityEvent::LOGIN_FAILED, (string) $event->raw('kind')); + assertSame((string) $user->login, (string) $event->raw('login')); + }); +}); + +test('журнал: считает события одного адреса за окно', function (): void { + withOwnDatabase(static function (): void { + foreach (['ivan', 'ivan', 'petr'] as $login) { + SecurityEvent::record(SecurityEvent::LOGIN_FAILED, $login); + } + + $ip = SecurityEvent::query()->orderBy('id', 'desc')->first()?->raw('ip'); + + assertSame(3, SecurityEvent::countFor((string) $ip, SecurityEvent::LOGIN_FAILED, 60)); + assertSame(0, SecurityEvent::countFor('203.0.113.99', SecurityEvent::LOGIN_FAILED, 60)); + + // Старое за окно не попадает + SecurityEvent::query()->update(['created_at' => date('Y-m-d H:i:s', time() - 7200)]); + + assertSame(0, SecurityEvent::countFor((string) $ip, SecurityEvent::LOGIN_FAILED, 60)); + }); +}); + +test('ключи: срок задаётся при выпуске и закрывает доступ по истечении', function (): void { + withOwnDatabase(static function (): void { + /** @var User $owner */ + $owner = Factory::of(User::class)->create(); + + $issued = ApiToken::issue('на неделю', $owner->id(), '', 7); + + /** @var ApiToken $token */ + $token = $issued['token']; + + assertTrue($token->expiresAt() !== '', 'срок записан'); + assertSame(7, $token->daysLeft()); + assertFalse($token->expired()); + assertNotNull(ApiToken::match($issued['key']), 'пока не истёк — работает'); + + // Отматываем срок назад + $token->forceFill(['expires_at' => date('Y-m-d H:i:s', time() - 60)])->save(); + + assertTrue(ApiToken::find($token->id())?->expired()); + assertNull(ApiToken::match($issued['key']), 'истёкший ключ не подходит'); + + // Ключ без срока живёт всегда + $forever = ApiToken::issue('без срока', $owner->id()); + + assertSame(-1, $forever['token']->daysLeft()); + assertNotNull(ApiToken::match($forever['key'])); + }); +}); + +test('ключи: в напоминание попадают только те, кому осталось немного', function (): void { + withOwnDatabase(static function (): void { + /** @var User $owner */ + $owner = Factory::of(User::class)->create(); + + ApiToken::issue('скоро', $owner->id(), '', 3); + ApiToken::issue('не скоро', $owner->id(), '', 90); + ApiToken::issue('без срока', $owner->id()); + + $expiring = ApiToken::expiringWithin(7); + + assertCount(1, $expiring); + assertSame('скоро', (string) $expiring[0]->name); + }); +});