From 3a04ee5bb31fd66f2cd04095f13342eec72b2586 Mon Sep 17 00:00:00 2001 From: rsgrinko Date: Tue, 15 Sep 2026 22:25:58 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9F=D1=80=D0=B0=D0=B2=D0=B8=D0=BB=D0=B0=20?= =?UTF-8?q?=D0=B4=D0=BE=D1=81=D1=82=D1=83=D0=BF=D0=B0=20=D0=BD=D0=B0=20?= =?UTF-8?q?=D0=B7=D0=B0=D0=BF=D0=B8=D1=81=D1=8C=20=D0=B8=20=D0=BF=D0=BE?= =?UTF-8?q?=D0=B4=D0=BF=D0=B8=D1=81=D0=B0=D0=BD=D0=BD=D1=8B=D0=B5=20=D1=81?= =?UTF-8?q?=D1=81=D1=8B=D0=BB=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controllers/Web/NotesController.php | 38 +++++- config/policies.php | 42 ++++++ framework/Access/AccessDenied.php | 26 ++++ framework/Access/Policy.php | 118 +++++++++++++++++ framework/Http/Controller.php | 16 +++ framework/Http/Kernel.php | 19 ++- framework/Http/Middleware/Signed.php | 35 +++++ framework/Support/SignedUrl.php | 152 ++++++++++++++++++++++ framework/View/View.php | 9 +- resources/views/notes/form.php | 10 +- resources/views/notes/index.php | 2 +- resources/views/notes/show.php | 11 +- routes/web.php | 6 + tests/PolicyTest.php | 164 ++++++++++++++++++++++++ 14 files changed, 638 insertions(+), 10 deletions(-) create mode 100644 config/policies.php create mode 100644 framework/Access/AccessDenied.php create mode 100644 framework/Access/Policy.php create mode 100644 framework/Http/Middleware/Signed.php create mode 100644 framework/Support/SignedUrl.php create mode 100644 tests/PolicyTest.php diff --git a/app/Controllers/Web/NotesController.php b/app/Controllers/Web/NotesController.php index 85c9eb1..15af502 100644 --- a/app/Controllers/Web/NotesController.php +++ b/app/Controllers/Web/NotesController.php @@ -5,9 +5,11 @@ declare(strict_types=1); namespace App\Controllers\Web; use App\Models\Note; +use Rsgrinko\Proton\Access\Policy; use Rsgrinko\Proton\Access\Scope; use Rsgrinko\Proton\Access\Viewer; use Rsgrinko\Proton\Database\Model\Query; +use Rsgrinko\Proton\Database\Model\RecordNotFound; use Rsgrinko\Proton\Events\Events; use Rsgrinko\Proton\Files\Storage; use Rsgrinko\Proton\Http\Controller; @@ -179,9 +181,13 @@ final class NotesController extends Controller public function edit(int $id, Scope $scope): Response { + $note = $this->find($id, $scope); + + $this->authorize('note.edit', $note); + return $this->view('notes/form', [ 'active' => 'notes', - 'note' => $this->find($id, $scope), + 'note' => $note, ], 'Правка заметки'); } @@ -189,6 +195,8 @@ final class NotesController extends Controller { $note = $this->find($id, $scope); + $this->authorize('note.edit', $note); + $data = $this->validate($request, [ 'title' => 'required|max:191', 'body' => 'nullable|max:20000', @@ -197,6 +205,12 @@ final class NotesController extends Controller $before = ['title' => $note->title, 'body' => $note->body, 'pinned' => $note->raw('pinned')]; + // Закрепление — отдельное правило: у кого его нет, у того в форме нет + // и галочки, и молчаливо открепить заметку такая форма не должна + if (Policy::denies('note.pin', $note)) { + unset($data['pinned']); + } + $note->fill($data); $this->attachFile($request, $note); @@ -220,6 +234,8 @@ final class NotesController extends Controller { $note = $this->find($id, $scope); + $this->authorize('note.delete', $note); + // Мягкое удаление: запись остаётся в базе с отметкой времени $note->delete(); @@ -252,6 +268,26 @@ final class NotesController extends Controller ); } + /** + * Тот же файл, но по подписанной ссылке: вход не нужен, потому что право + * на скачивание доказывает сама подпись. Ссылку выдаёт карточка заметки, + * срок жизни — сутки. + */ + public function sharedFile(int $id): Response + { + /** @var Note|null $note */ + $note = Note::query()->where('id', $id)->first(); + + if ($note === null || !$note->hasFile() || !Storage::exists((string) $note->raw('file_path'))) { + throw new RecordNotFound('Файла нет'); + } + + return Response::download( + Storage::read((string) $note->raw('file_path')), + (string) $note->raw('file_name') + ); + } + /** * Заметка с оглядкой на область видимости: чужая для обычного пользователя * просто не существует. diff --git a/config/policies.php b/config/policies.php new file mode 100644 index 0000000..cdd30de --- /dev/null +++ b/config/policies.php @@ -0,0 +1,42 @@ + …); + * $this->authorize('note.edit', $note); // в контроллере + * View::can('note.edit', $note) // в шаблоне + */ + +use App\Models\Note; +use Rsgrinko\Proton\Access\Policy; +use Rsgrinko\Proton\Access\Viewer; + +// Свою заметку правит тот, кто может править заметки вообще; чужую — только +// тот, кому видны чужие записи (право data.all) +Policy::define('note.edit', static function (Viewer $viewer, mixed $note): bool { + if (!$viewer->can('notes.manage')) { + return false; + } + + return Policy::owns($viewer, $note) || $viewer->isAdmin(); +}); + +// Удаление строже правки: чужое удаляет только полный доступ +Policy::define('note.delete', static function (Viewer $viewer, mixed $note): bool { + if (!$viewer->can('notes.manage')) { + return false; + } + + return Policy::owns($viewer, $note) || $viewer->isAdmin(); +}); + +// Закрепить заметку наверху списка может только тот, кто видит все: иначе +// каждый закрепит своё и список перестанет что-либо значить +Policy::define('note.pin', static fn (Viewer $viewer, mixed $note): bool => $viewer->isAdmin()); diff --git a/framework/Access/AccessDenied.php b/framework/Access/AccessDenied.php new file mode 100644 index 0000000..edd64a4 --- /dev/null +++ b/framework/Access/AccessDenied.php @@ -0,0 +1,26 @@ + $context + */ + public function __construct(string $message = 'Нет доступа', array $context = []) + { + parent::__construct($message, $context, 403); + } +} diff --git a/framework/Access/Policy.php b/framework/Access/Policy.php new file mode 100644 index 0000000..bddfb41 --- /dev/null +++ b/framework/Access/Policy.php @@ -0,0 +1,118 @@ + + * (int) $note->raw('user_id') === $viewer->id()); + * + * Policy::allows('note.edit', $note); // в коде + * $this->authorize('note.edit', $note); // в контроллере, 403 при отказе + * View::can('note.edit', $note) // в шаблоне + * + * Право (`Permission`) отвечает на вопрос «пускать ли в раздел», политика — на + * вопрос «можно ли трогать именно эту запись». Права проверяет прослойка у + * группы маршрутов, политику — контроллер там, где у него уже есть запись. + * + * Правила живут в коде (`config/policies.php`), в базе их нет: иначе после + * выкладки нового раздела правила пришлось бы досыпать вручную. + */ +final class Policy +{ + /** @var array|null */ + private static ?array $rules = null; + + /** + * Правило: кому и что можно с записью. + * + * @param callable(Viewer, mixed): bool $rule + */ + public static function define(string $ability, callable $rule): void + { + self::boot(); + + self::$rules[$ability] = $rule; + } + + /** + * Есть ли правило — нужно тем, кто хочет отличить «запрещено» от «правила нет». + */ + public static function has(string $ability): bool + { + self::boot(); + + return isset(self::$rules[$ability]); + } + + /** + * Можно ли. Правила нет — решает право с тем же именем: так политику можно + * добавить позже, не переписывая места вызова. + */ + public static function allows(string $ability, mixed $subject = null, ?Viewer $viewer = null): bool + { + self::boot(); + + $viewer ??= Auth::viewer(); + + if (!isset(self::$rules[$ability])) { + return $viewer->can($ability); + } + + // Полный доступ (право data.all) снимает вопрос о чужих записях — но + // только если правило само не решило иначе для своей записи + return (bool) (self::$rules[$ability])($viewer, $subject); + } + + /** + * Обратное — читается лучше, чем отрицание в условии. + */ + public static function denies(string $ability, mixed $subject = null, ?Viewer $viewer = null): bool + { + return !self::allows($ability, $subject, $viewer); + } + + /** + * Хозяин записи: одинаковая проверка почти для всех правил приложения. + */ + public static function owns(Viewer $viewer, mixed $subject, string $column = 'user_id'): bool + { + if (!$subject instanceof Model) { + return false; + } + + return (int) $subject->raw($column) === $viewer->id(); + } + + /** + * Забыть правила — нужно тестам. + */ + public static function reset(): void + { + self::$rules = null; + } + + /** + * Правила приложения. Файла нет — работают одни права. + */ + private static function boot(): void + { + if (self::$rules !== null) { + return; + } + + self::$rules = []; + + $file = APP_ROOT . '/config/policies.php'; + + if (is_file($file)) { + require $file; + } + } +} diff --git a/framework/Http/Controller.php b/framework/Http/Controller.php index f540d23..b88b005 100644 --- a/framework/Http/Controller.php +++ b/framework/Http/Controller.php @@ -4,6 +4,8 @@ declare(strict_types=1); namespace Rsgrinko\Proton\Http; +use Rsgrinko\Proton\Access\AccessDenied; +use Rsgrinko\Proton\Access\Policy; use Rsgrinko\Proton\Database\Model\Model; use Rsgrinko\Proton\Database\Model\RecordNotFound; use Rsgrinko\Proton\Database\Query\Builder; @@ -93,6 +95,20 @@ abstract class Controller return Validator::make($request->all(), $rules, $labels)->validate(); } + /** + * Правило на запись: можно ли этому человеку трогать именно её. + * Нельзя — 403, дальше код не идёт. + * + * Право у группы маршрутов решает, пускать ли в раздел; здесь решается + * судьба конкретной строки, поэтому вызов стоит рядом с ней. + */ + protected function authorize(string $ability, mixed $subject = null): void + { + if (Policy::denies($ability, $subject)) { + throw new AccessDenied('С этой записью так нельзя'); + } + } + /** * Запись обязана быть, иначе — «не найдено» с возвратом в список. * diff --git a/framework/Http/Kernel.php b/framework/Http/Kernel.php index 03ba430..dc97158 100644 --- a/framework/Http/Kernel.php +++ b/framework/Http/Kernel.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Rsgrinko\Proton\Http; +use Rsgrinko\Proton\Access\AccessDenied; use Rsgrinko\Proton\Auth\Auth; use Rsgrinko\Proton\Auth\Csrf; use Rsgrinko\Proton\Database\Model\RecordNotFound; @@ -12,6 +13,7 @@ use Rsgrinko\Proton\Http\Middleware\Authenticate; use Rsgrinko\Proton\Http\Middleware\Can; use Rsgrinko\Proton\Http\Middleware\Guest; use Rsgrinko\Proton\Http\Middleware\Install; +use Rsgrinko\Proton\Http\Middleware\Signed; use Rsgrinko\Proton\Http\Middleware\Throttle; use Rsgrinko\Proton\Http\Middleware\VerifyCsrf; use Rsgrinko\Proton\Support\Config; @@ -54,6 +56,8 @@ final class Kernel try { $response = $this->finish($this->router()->dispatch($request)); + } catch (AccessDenied $e) { + $response = $this->finish($this->denied($request, $e)); } catch (RecordNotFound $e) { $response = $this->finish($this->notFound($request, $e)); } catch (ValidationException $e) { @@ -91,7 +95,8 @@ final class Kernel ->middleware('can', new Can()) ->middleware('api', new ApiKey()) ->middleware('throttle', new Throttle()) - ->middleware('install', new Install()); + ->middleware('install', new Install()) + ->middleware('signed', new Signed()); foreach ((array) Config::get('routes', ['routes/web.php']) as $file) { $router->load(APP_ROOT . '/' . ltrim((string) $file, '/')); @@ -111,6 +116,18 @@ final class Kernel ->withHeader(RequestId::HEADER, RequestId::current()); } + /** + * Правило на запись не пустило. + */ + private function denied(Request $request, AccessDenied $e): Response + { + if ($request->wantsJson()) { + return Response::error($e->getMessage(), 403); + } + + return Response::html(View::render('errors/403', ['message' => $e->getMessage()], 'Нет доступа'), 403); + } + private function notFound(Request $request, RecordNotFound $e): Response { if ($request->wantsJson()) { diff --git a/framework/Http/Middleware/Signed.php b/framework/Http/Middleware/Signed.php new file mode 100644 index 0000000..bf3a292 --- /dev/null +++ b/framework/Http/Middleware/Signed.php @@ -0,0 +1,35 @@ +wantsJson()) { + return Response::error('Ссылка недействительна или устарела', 403); + } + + return Response::html(View::render('errors/403', [ + 'message' => 'Ссылка недействительна или устарела. Попросите её заново.', + ], 'Ссылка не работает'), 403); + } +} diff --git a/framework/Support/SignedUrl.php b/framework/Support/SignedUrl.php new file mode 100644 index 0000000..9b52240 --- /dev/null +++ b/framework/Support/SignedUrl.php @@ -0,0 +1,152 @@ + 5], 3600); // на час + * $url = SignedUrl::absolute('report.download', ['id' => 7], 86400); + * + * Нужна там, где человеку надо что-то отдать без входа: файл из письма, + * готовую выгрузку, подтверждение действия. Подпись считается от пути и всех + * параметров ключом приложения (APP_KEY), поэтому подобрать её нельзя, а + * поменять хоть один параметр — значит сломать. + * + * Проверяет ссылку прослойка `signed`. Срок жизни хранится прямо в адресе: + * своей таблицы у таких ссылок нет, и отзывать по одной их нельзя — смена + * APP_KEY обнуляет разом все. + */ +final class SignedUrl +{ + /** Имена служебных параметров в адресе */ + public const EXPIRES = 'expires'; + public const SIGNATURE = 'signature'; + + /** + * Подписанный путь. Срок в секундах; 0 — без срока (ссылка живёт, пока + * не сменится ключ приложения). + * + * @param array $params + */ + public static function to(string $route, array $params = [], int $lifetime = 3600): string + { + $params = self::withExpiry($params, $lifetime); + + return self::signUrl(Router::url($route, $params)); + } + + /** + * То же с доменом — для писем: путь без домена там не кликается. + * + * @param array $params + */ + public static function absolute(string $route, array $params = [], int $lifetime = 3600): string + { + $params = self::withExpiry($params, $lifetime); + + return self::signUrl(Router::absolute($route, $params)); + } + + /** + * Цела ли подпись и не вышел ли срок. + */ + public static function valid(Request $request): bool + { + $query = $request->query; + $signature = (string) ($query[self::SIGNATURE] ?? ''); + + if ($signature === '') { + return false; + } + + unset($query[self::SIGNATURE]); + + $expires = (int) ($query[self::EXPIRES] ?? 0); + + if ($expires > 0 && $expires < time()) { + return false; + } + + return Str::secureEquals(self::sign(self::canonical($request->path, $query)), $signature); + } + + /** + * Дописывает подпись к готовому адресу. + * + * Подписываем ровно то, что увидит проверяющий: путь (в нём уже сидят + * параметры маршрута вроде {id}) и query-строку. Считать подпись от + * исходного массива параметров нельзя — часть из них ушла в путь. + */ + private static function signUrl(string $url): string + { + $path = (string) parse_url($url, PHP_URL_PATH); + + parse_str((string) parse_url($url, PHP_URL_QUERY), $query); + + return $url . (str_contains($url, '?') ? '&' : '?') + . self::SIGNATURE . '=' . self::sign(self::canonical($path, $query)); + } + + /** + * Строка, которую подписываем: путь и параметры в одном порядке всегда. + * + * @param array $params + */ + private static function canonical(string $path, array $params): string + { + $values = []; + + foreach ($params as $key => $value) { + if ($key === self::SIGNATURE) { + continue; + } + + $values[(string) $key] = is_scalar($value) ? (string) $value : ''; + } + + // Порядок параметров в адресе произвольный, а подпись должна сходиться + ksort($values); + + return rtrim($path, '/') . '|' . http_build_query($values); + } + + private static function sign(string $payload): string + { + return hash_hmac('sha256', $payload, self::secret()); + } + + /** + * Ключ подписи — тот же, что у кук и шифрования: своего заводить незачем, + * а его смена разом обнуляет все выданные ссылки. + */ + private static function secret(): string + { + $key = (string) Config::get('app.key', ''); + + if ($key === '') { + throw new ProtonException('Не задан APP_KEY: подписывать ссылки нечем'); + } + + return $key; + } + + /** + * @param array $params + * + * @return array + */ + private static function withExpiry(array $params, int $lifetime): array + { + if ($lifetime > 0) { + $params[self::EXPIRES] = time() + $lifetime; + } + + return $params; + } +} diff --git a/framework/View/View.php b/framework/View/View.php index 146056d..65d9b76 100644 --- a/framework/View/View.php +++ b/framework/View/View.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Rsgrinko\Proton\View; +use Rsgrinko\Proton\Access\Policy; use Rsgrinko\Proton\Access\Viewer; use Rsgrinko\Proton\Auth\Auth; use Rsgrinko\Proton\Auth\Csrf; @@ -186,9 +187,13 @@ final class View * но полагаться на это нельзя: доступ закрывает прослойка, разметка лишь * не дразнит. */ - public static function can(string $permission): bool + public static function can(string $permission, mixed $subject = null): bool { - return self::viewer()->can($permission); + // С записью спрашиваем политику: «править свою заметку» — это не право, + // а правило на конкретную строку + return $subject === null + ? self::viewer()->can($permission) + : Policy::allows($permission, $subject, self::viewer()); } /** diff --git a/resources/views/notes/form.php b/resources/views/notes/form.php index 0cc8835..c3b0c01 100644 --- a/resources/views/notes/form.php +++ b/resources/views/notes/form.php @@ -31,10 +31,12 @@ $action = $isNew - + + +