Блокировка адресов, журнал подозрительной активности, срок жизни ключей API

This commit is contained in:
rsgrinko committed 2026-09-15 22:37:47 +03:00
1 parent 3a04ee5bb3
commit 20f3d79552
20 files changed
+1042 -6

No files matched your search

+30
View File
@@ -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)));
}
/**
* Записывает пользователя в сессию.
*
+9
View File
@@ -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;
+3 -1
View File
@@ -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');
}
+24 -1
View File
@@ -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);
}
/**
* Правило на запись не пустило.
*/
+54 -1
View File
@@ -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<int, self>
*/
public static function expiringWithin(int $days): array
{
/** @var array<int, self> $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;
}
/**
* Отмечает использование: по этой дате видно забытые ключи.
*/
+114
View File
@@ -0,0 +1,114 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Models;
use Rsgrinko\Proton\Database\Connection;
use Rsgrinko\Proton\Database\Model\Model;
/**
* Заблокированный адрес: кого не пускать и до какого времени.
*
* Лимит по частоте (`RateLimiter`) тормозит перебор, но не закрывает дверь:
* подождал окно — и снова. Блокировка закрывает совсем, на срок или навсегда.
* Проверяется одним запросом на каждый заход, поэтому таблица маленькая, а
* протухшие записи убирает воркер.
*/
final class BlockedIp extends Model
{
protected static string $table = 'blocked_ips';
protected array $fillable = ['ip', 'reason'];
/**
* Заблокировать адрес. Повторный вызов продлевает и переписывает причину.
*/
public static function block(string $ip, string $reason = '', int $minutes = 60, int $byUserId = 0): self
{
$ip = trim($ip);
/** @var self|null $existing */
$existing = self::query()->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() === '';
}
}
+102
View File
@@ -0,0 +1,102 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Models;
use Rsgrinko\Proton\Database\Connection;
use Rsgrinko\Proton\Database\Model\Model;
use Rsgrinko\Proton\Support\ClientIp;
use Throwable;
/**
* Подозрительное событие: неудачный вход, отказ по правам, негодный ключ.
*
* Отдельно от журнала действий (`audit_log`) нарочно: там записи о том, что
* человек сделал, здесь — о том, что у него не вышло. Смешивать неудобно —
* в аудите начинается шум от перебора паролей.
*
* Запись никогда не роняет то, что её вызвало: у неудачного входа своя судьба.
*/
final class SecurityEvent extends Model
{
protected static string $table = 'security_events';
/** Не сошёлся пароль или логин */
public const LOGIN_FAILED = 'login.failed';
/** Лимит попыток исчерпан */
public const LOGIN_BLOCKED = 'login.blocked';
/** Зашли с закрытого адреса */
public const IP_BLOCKED = 'ip.blocked';
/** Не хватило прав */
public const ACCESS_DENIED = 'access.denied';
/** Ключ API не подошёл */
public const KEY_INVALID = 'key.invalid';
/** @var array<string, string> Подписи для панели */
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();
}
}
@@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Notifications;
use Rsgrinko\Proton\Http\Router;
use Rsgrinko\Proton\Models\ApiToken;
/**
* Ключ API скоро перестанет работать.
*
* Уходит владельцу ключа, а не администратору: чинить интеграцию ему.
* Молчание тут стоит дорого — ключ истекает ночью, а утром «внезапно ничего
* не работает».
*/
final class ApiKeyExpiringNotification extends Notification
{
public function __construct(private ApiToken $token, private int $daysLeft)
{
}
public function type(): string
{
return 'key.expiring';
}
public function title(): string
{
return 'Ключ API «' . (string) $this->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<int, string>
*/
public function channels(): array
{
return [Notify::DATABASE, Notify::MAIL];
}
}
+20
View File
@@ -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(
+4
View File
@@ -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();