# Laravel Access Control 1.x: full documentation > Laravel Access Control (lomkit/laravel-access-control) is a Laravel package that declares in one control who can see and change each Eloquent model: its perimeters drive the policies, the query scopes and the Scout searches. This file holds every page of Laravel Access Control 1.x, the current version (latest release 1.0.0). It requires PHP 8.3+ and Laravel 13 and installs with `composer require lomkit/laravel-access-control`. # Introduction ## What it is Laravel Access Control decides who can see and change which rows of your Eloquent models. For each model, you write one **control**. Its **perimeters** say which users reach which rows, for each ability: `view`, `update`, `delete`, or a business ability such as `approve`. ```php [app/Access/Controls/PostControl.php] namespace App\Access\Controls; use App\Access\Perimeters\ClientPerimeter; use App\Access\Perimeters\OwnPerimeter; use App\Models\Post; use App\Models\User; use Illuminate\Database\Eloquent\Builder; use Lomkit\Access\Ability; use Lomkit\Access\Controls\Control; use Lomkit\Access\Perimeters\Levels; class PostControl extends Control { protected string $model = Post::class; protected function perimeters(): array { return [ Levels::of( ClientPerimeter::new() ->allowed(fn (User $user, Ability $ability) => $user->client_id !== null && $user->can("{$ability} client posts")) ->query(function (Builder $query, User $user): void { $query->where('client_id', $user->client_id); }), OwnPerimeter::new() ->allowed(fn (User $user, Ability $ability) => $user->can("{$ability} own posts")) ->should(fn (User $user, Post $post) => $post->author_id === $user->id) ->query(function (Builder $query, User $user): void { $query->where('author_id', $user->id); }), ), ]; } } ``` Each perimeter answers up to three questions: - `allowed()` is the **permission**: does this perimeter apply to the user, for this ability? A user who may update the posts of their client reaches the client perimeter for `update`. - `query()` gives the **rows** of the perimeter in SQL, for the lists. - `should()`, optional, checks **one row** in memory: when a user may only see their own posts, `should()` checks that the post at hand is theirs. `ClientPerimeter` has none: the package checks its rows through its `query()`, in one SQL query. The client perimeter refuses a user without a client in `allowed()`, so that a `null` client never matches the posts without one. See [Perimeters](https://laravel-access-control.lomkit.com/essentials/perimeters). The same control then answers everywhere: ```php $user->can('update', $post); // the policy Post::query()->controlled()->paginate(); // the posts the signed-in user may view Post::controlled('update')->count(); // the posts they may update Post::search('budget')->controlled()->get(); // a Laravel Scout search, with the same rules ``` The search needs search keys on the perimeters and the `ControlledSearchable` trait on the model, as the [Search](https://laravel-access-control.lomkit.com/search/overview) section shows. ## Why use it - **One place for each rule.** The policy behind `$user->can()`, the `controlled()` scope of your queries, the filter of your Scout searches and the row restriction of your laravel-rest-api resources all read the same control. A rule changed in the control changes everywhere. - **Fails closed.** A query without a signed-in user, a user that no perimeter allows, or a boundary without a value gives no row. A missing or wrong declaration throws an exception instead of opening rows. - **Built for real access models.** [Levels](https://laravel-access-control.lomkit.com/essentials/levels) apply the highest level a user reaches. A [boundary](https://laravel-access-control.lomkit.com/essentials/boundaries) keeps every row inside the user's tenant or workspace. A [parent](https://laravel-access-control.lomkit.com/essentials/parents) gives a comment the access of its post. - **Checked.** `php artisan access:check` reports in CI what would throw, open or hide rows. Test assertions prove that the policy, the queries and the search agree on your test data. ## How it fits Laravel - **Policies.** `Access::registerPolicies()` gives every controlled model a policy built on its control, unless the model has a policy of its own. `can()`, `@can`, `authorize()` and `Gate::inspect()` work as usual. See [Policies](https://laravel-access-control.lomkit.com/essentials/policies). - **Eloquent.** `controlled()`, `controlledFor()` and `uncontrolled()` are local scopes of the `HasControl` trait. A query is controlled only when it says so: no global scope changes your other queries. See [Queries](https://laravel-access-control.lomkit.com/essentials/queries). - **Laravel Scout.** `ControlledSearchable` indexes each document with the keys that open it, and a controlled search keeps the documents that the user may view, in one engine query. - **Laravel Rest Api.** With [laravel-rest-api](https://laravel-rest-api.lomkit.com) 3.6 or higher, an extension applies your controls to every resource of a controlled model, with no perimeter to write in the resources. ## When to use it Laravel Access Control fits an application where users reach only some rows of a model: the rows of their tenant, of their client, of their team, or their own rows, with rights that differ by ability. It suits list screens, exports and searches that must show exactly the rows that the policy allows. ### When it does not fit - **Storing roles and permissions.** The package does not store roles or permissions. Your `allowed()` callbacks read them from your application, such as `$user->can()` with a permission package or your own tables. - **Hiding columns.** A control decides which rows a user reaches, not which attributes of a row they see. - **Every user sees every row.** When access depends on the ability alone, never on the row, a plain Laravel policy is enough. ### Requirements Laravel Access Control requires PHP 8.3 or higher and Laravel 13. Laravel Scout and laravel-rest-api are optional, see [Installation](https://laravel-access-control.lomkit.com/getting-started/installation). ## How it compares - **Laravel policies and query scopes.** A [Laravel policy](https://laravel.com/docs/authorization) authorizes an action for a model or resource, and a local scope filters a query: written by hand, they are two places to keep in agreement. Laravel Access Control builds the policy and the `controlled()` scope from the same control, and gives the same rules to Laravel Scout. - **spatie/laravel-permission.** [spatie/laravel-permission](https://spatie.be/docs/laravel-permission) manages user permissions and roles in a database. Laravel Access Control does not store them: its `allowed()` callbacks can read the permissions that spatie/laravel-permission manages, so the two packages work together. With teams, put the current team in the [decision context](https://laravel-access-control.lomkit.com/essentials/readers#the-decision-context). - **PostgreSQL row-level security.** [Row security policies](https://www.postgresql.org/docs/current/ddl-rowsecurity.html) restrict, per database user, which rows a table returns or changes, for every query that reaches it, from Laravel or from any other client. Laravel Access Control works in the application: it filters only the queries that call `controlled()` or `controlledFor()`, and the same control drives the policy and the Scout search, which the database does not reach. ## Meet Lomkit Lomkit is an organization dedicated to the Laravel community. We offer a collection of open source packages for developers, and we keep them up to date with the latest practices of the framework. Community contributions are welcome. Explore our packages on [GitHub](https://github.com/lomkit), open an issue or send a pull request. ## Next steps - [Install the package](https://laravel-access-control.lomkit.com/getting-started/installation). - [Control your first model](https://laravel-access-control.lomkit.com/getting-started/quick-start). # Installation ## Requirements - PHP **8.3** or higher - Laravel **13** Optional: - [Laravel Scout](https://laravel.com/docs/scout) **11**, for controlled searches. - [Laravel Rest Api](https://laravel-rest-api.lomkit.com) **3.6** or higher, for its extension, which applies your controls to every rest-api resource. > **Note:** Applications on Laravel 12 can use version [0.7](https://github.com/Lomkit/laravel-access-control/releases/tag/v0.7.0), the last 0.x release. Moving an application from 0.x to 1.x is covered in the [upgrade guide](https://laravel-access-control.lomkit.com/getting-started/upgrade-guide). ## Installing Laravel Access Control Install the package with Composer: ```bash composer require lomkit/laravel-access-control ``` Laravel discovers the service provider of the package. There is no configuration file to publish: everything is declared in your controls. # Quick start [Install the package](https://laravel-access-control.lomkit.com/getting-started/installation) first. Take a `Post` model with a `client_id` and an `author_id`, and a `User` model with a `client_id`. Three kinds of users read posts: administrators read every post, managers read the posts of their client, authors read their own posts. ## 1. Declare who reaches which posts Create one perimeter class per kind of access, and the control of the model: ```bash php artisan make:perimeter GlobalPerimeter php artisan make:perimeter ClientPerimeter php artisan make:perimeter OwnPerimeter php artisan make:control PostControl ``` The [perimeter classes](https://laravel-access-control.lomkit.com/essentials/perimeter-classes) land in `app/Access/Perimeters` and the control in `app/Access/Controls`. `make:control` names the model after the control, `App\Models\Post` here. Declare the rules of each perimeter in the control: ```php [app/Access/Controls/PostControl.php] namespace App\Access\Controls; use App\Access\Perimeters\ClientPerimeter; use App\Access\Perimeters\GlobalPerimeter; use App\Access\Perimeters\OwnPerimeter; use App\Models\Post; use App\Models\User; use Illuminate\Database\Eloquent\Builder; use Lomkit\Access\Ability; use Lomkit\Access\Controls\Control; use Lomkit\Access\Perimeters\Levels; class PostControl extends Control { protected string $model = Post::class; protected function perimeters(): array { return [ Levels::of( GlobalPerimeter::new() ->allowed(fn (User $user, Ability $ability) => $user->can("{$ability} all posts")) ->unrestricted(), ClientPerimeter::new() ->allowed(fn (User $user, Ability $ability) => $user->client_id !== null && $user->can("{$ability} client posts")) ->should(fn (User $user, Post $post) => $post->client_id === $user->client_id) ->query(function (Builder $query, User $user): void { $query->where('client_id', $user->client_id); }), OwnPerimeter::new() ->allowed(fn (User $user, Ability $ability) => $user->can("{$ability} own posts")) ->should(fn (User $user, Post $post) => $post->author_id === $user->id) ->query(function (Builder $query, User $user): void { $query->where('author_id', $user->id); }), ), ]; } } ``` - `allowed()` is the permission: whether the perimeter applies to the user for an ability. `view client posts` or `update own posts` are permission names of your application, checked here with `$user->can()`: define them with `Gate::define()` or a permission package. Any boolean check works. - `query()` gives the rows of the perimeter in SQL, for the lists. - `should()` checks one row in memory, for the policy. It must describe the same rows as `query()`. It is kept here because users create posts through these perimeters, and a post about to be created can only be judged in memory. It also saves one query per check. - `unrestricted()` reaches every post, for the administrators. The three perimeters form a `Levels::of()` group, widest first: for each ability, only the highest level that the user reaches applies. A manager who also holds `view own posts` reaches the client level for `view`, and the own level is not evaluated. See [Perimeters](https://laravel-access-control.lomkit.com/essentials/perimeters) and [Levels](https://laravel-access-control.lomkit.com/essentials/levels). The client perimeter refuses a user without a client in `allowed()`, so a `null` client never matches the posts without a client. > **Note:** `GlobalPerimeter` reaches the posts of every client. When clients are tenants, keep each user inside theirs with a [boundary](https://laravel-access-control.lomkit.com/essentials/boundaries). ## 2. Link the model Add the `HasControl` trait to the model: ```php [app/Models/Post.php] namespace App\Models; use Illuminate\Database\Eloquent\Model; use Lomkit\Access\Controls\HasControl; class Post extends Model { use HasControl; } ``` The package finds `PostControl` in `app/Access/Controls` through its `$model` property. A control kept in another directory is named on the model with `#[ControlledBy(PostControl::class)]`. See [Controls](https://laravel-access-control.lomkit.com/essentials/controls). ## 3. Register the policies Call `Access::registerPolicies()` in the `boot()` method of a service provider: ```php [app/Providers/AppServiceProvider.php] use Lomkit\Access\Access; public function boot(): void { Access::registerPolicies(); } ``` Every controlled model that has no policy of its own now gets one, built on its control. See [Policies](https://laravel-access-control.lomkit.com/essentials/policies). ## 4. Use it ```php Post::query()->controlled()->paginate(); // the posts the signed-in user may view Post::query()->controlled('update')->paginate(); // the posts the signed-in user may update Post::controlledFor($user)->get(); // for a named user, in jobs and commands $user->can('update', $post); // the policy, from the same perimeters ``` A query is controlled only when it says so: `Post::query()->get()` still reads every row. A controlled query without a signed-in user returns no row. See [Queries](https://laravel-access-control.lomkit.com/essentials/queries). ## Next steps - **Search.** With Laravel Scout, give each perimeter that restricts rows its search keys and use `ControlledSearchable` on the model: `Post::search('budget')->controlled()` then keeps the posts the user may view. The [Search](https://laravel-access-control.lomkit.com/search/overview) section covers the keys, the engines and the reindexing. - **Testing.** Run `php artisan access:check` in CI, and prove in your tests that the policy, the queries and the search agree with the assertions of `InteractsWithAccess`. The [Testing and tooling](https://laravel-access-control.lomkit.com/testing-and-tooling/testing) section covers both. - **Essentials.** Read [Controls](https://laravel-access-control.lomkit.com/essentials/controls) and the pages that follow, in order. # Upgrade guide ## Upgrading to 1.0 from 0.x Version 1.0 requires PHP 8.3 and Laravel 13. Applications that stay on Laravel 12 can use version [0.7](https://github.com/Lomkit/laravel-access-control/releases/tag/v0.7.0), the last 0.x release. This page sums up the main changes, area by area, each with the page that explains the new way. The [upgrade guide on GitHub](https://github.com/Lomkit/laravel-access-control/blob/1.x/UPGRADE.md) lists every breaking change, with before and after examples, and ends with a table that maps each removed call to its replacement. Go through the sections of the features that your application uses. ### Coming from 0.6 Version 0.7 already changed several things. If you upgrade from 0.6, apply the [0.7.0 checklist](https://github.com/Lomkit/laravel-access-control/releases/tag/v0.7.0) first, then the 1.0 guide. ## Configuration and controls - **No configuration file.** `config/access-control.php` and its `methods` map are gone: delete your published file. A custom `methods` map becomes an override of [`abilityFor()`](https://laravel-access-control.lomkit.com/essentials/policies#abilities) on the control. - **Linking a model.** A control is [discovered](https://laravel-access-control.lomkit.com/essentials/controls#discovery) in `app/Access/Controls` by its `$model`, or named on the model with `#[ControlledBy]`. `addControl()`, `addControls()` and `Access::$controlDiscoveryPaths` are replaced by the attribute and `Access::discoverControlsIn()`, which adds directories. - **The `Access` facade.** `Access::controlForModel()` becomes [`Access::controlFor()`](https://laravel-access-control.lomkit.com/essentials/controls#the-access-facade), which throws `MissingControlException`, with `Access::hasControl()` to check first. `Access::flush()` is removed. - **Pure perimeter lists.** A control builds its perimeters once per process: read the user and the request in the callbacks, never in `perimeters()`. See [Pure perimeter lists](https://laravel-access-control.lomkit.com/essentials/controls#pure-perimeter-lists). - **Cache.** Run `php artisan access:cache` again after upgrading, or `php artisan optimize` in your deployment. See [Cache and about](https://laravel-access-control.lomkit.com/testing-and-tooling/cache-and-about). ## Queries > **Warning:** **A query is controlled only when it says so.** `queries.enabled_by_default` is gone: plain queries, relations, `whereHas()` subqueries, eager and lazy loads and route model binding now read every row unless they call `controlled()`. Add `controlled()` to every query that must be filtered, and authorize a model bound to a route through its policy. See [Queries](https://laravel-access-control.lomkit.com/essentials/queries). - `controlled('update')` and `controlledFor($user, 'approve')` list the rows of another ability. - `withAbilities()`, `Access::preload()` and `reachableKeys()` replace the helpers that collected the editable keys. See [Batched decisions](https://laravel-access-control.lomkit.com/digging-deeper/batched-decisions). ## Perimeters - **Abilities.** `allowed()` receives an [`Ability`](https://laravel-access-control.lomkit.com/digging-deeper/abilities) instead of a string: type the parameter `Ability $ability` and compare with `$ability->is('update')`. - **Callbacks.** A `query()` callback constrains the builder it receives, and an empty or joined one throws. A perimeter without `should()` checks a saved row in SQL through its `query()`: remove the `should()` callbacks that only repeated it, and keep those of the perimeters through which users create rows. See [Perimeters](https://laravel-access-control.lomkit.com/essentials/perimeters). - **Every row.** A global perimeter becomes `unrestricted()`. See [Unrestricted perimeters](https://laravel-access-control.lomkit.com/essentials/perimeters#unrestricted-perimeters). - **Combining.** Perimeters that stopped at the first allowed one become a [`Levels::of()`](https://laravel-access-control.lomkit.com/essentials/levels) group, widest first, and `OverlayPerimeter` becomes a plain perimeter outside the group. - **Classes.** The overridden `apply*Callback()` methods become the protected hooks `allows()`, `includes()` and `scope()`, which receive an `AccessContext`. See [Perimeter classes](https://laravel-access-control.lomkit.com/essentials/perimeter-classes). - **Immutable.** Each fluent method returns a new perimeter, and a second declaration of a callback throws. ## Boundaries and parents - **Boundaries.** A condition that every row must meet, such as the tenant, moves from an override of `applies()` or `applyQueryControl()` to [`boundary()`](https://laravel-access-control.lomkit.com/essentials/boundaries) on the control. - **Parents.** A child whose `query()` called `whereHas()` on its parent becomes a [`ThroughParent`](https://laravel-access-control.lomkit.com/essentials/parents), which delegates only `view` by default. ## Policies - **Automatic policies.** An empty `ControlledPolicy` subclass is replaced by [`Access::registerPolicies()`](https://laravel-access-control.lomkit.com/essentials/policies#automatic-policies). - **Responses.** The policy methods return a `Response` with a [refusal code](https://laravel-access-control.lomkit.com/essentials/policies#refusals), and a row of another tenant answers `404`. - **Drafts.** Authorize a creation with the model about to be created: `authorize('create', [Post::class, $draft])`. An overridden `create()` takes `create(Model $user, ?Model $draft = null): Response`, or PHP throws a fatal error. See [Drafts](https://laravel-access-control.lomkit.com/essentials/policies#drafts). - **Stored values.** The policy decides a saved row on its stored values: a row changed with `fill()` is decided on what the database holds, so check new values through a draft. A model that is not saved is refused with `unsaved`, for every ability but `viewAny` and `create`. See [Decisions on the stored row](https://laravel-access-control.lomkit.com/essentials/policies#decisions-on-the-stored-row). - **Business abilities.** A method that called the control by hand calls `decideByControl()`. See [Business abilities](https://laravel-access-control.lomkit.com/essentials/policies#business-abilities). - **Decision context.** What `allowed()` reads besides the reader, such as the current team, goes in [`Access::decisionContextUsing()`](https://laravel-access-control.lomkit.com/essentials/readers#the-decision-context). ## Search - **The model.** `Searchable` becomes `ControlledSearchable`, and every search says `controlled()`, `controlledFor()` or `uncontrolled()`. See [Search overview](https://laravel-access-control.lomkit.com/search/overview). - **Search keys.** `scoutQuery()` and `scoutScope()` are replaced by [`searchKeys()`](https://laravel-access-control.lomkit.com/search/overview#search-keys). A controlled search now gives the union of the perimeters, with the boundary. - **Engines.** Declare `_access` and `_boundary` as filterable, then reindex every controlled model. The `collection` engine is refused: use `database`. See [Engines](https://laravel-access-control.lomkit.com/search/engines). - **Freshness.** A listener that reindexed documents becomes `reindexWhen()` or the `ReindexesSearch` pivot trait. See [Keeping the keys fresh](https://laravel-access-control.lomkit.com/search/keeping-the-keys-fresh). - **Browser search.** A token whose filter was written by hand becomes `Access::searchToken()`, or a route that calls `Access::guardSearch()`. See [Search from the browser](https://laravel-access-control.lomkit.com/search/from-the-browser). ## laravel-rest-api - An application that uses laravel-rest-api upgrades it to 3.6 or later first: 1.0 conflicts with earlier versions, so Composer refuses the upgrade until then. - `AccessControlExtension` restricts the rows, filters the text searches and preloads the row checks of every controlled resource: remove the `perimeterQuery()` and `prepareAuthorization()` overrides that applied the control. See [laravel-rest-api](https://laravel-access-control.lomkit.com/integrations/laravel-rest-api). ## Testing and tooling - **Checks.** Run [`php artisan access:check`](https://laravel-access-control.lomkit.com/testing-and-tooling/access-check) in CI, with the Scout driver of production. - **Assertions.** A test that compared `can()` with `controlled()` by hand becomes `assertControlAgrees()`. Remove the `Access::flush()` calls: each test gets a new registry. See [Testing](https://laravel-access-control.lomkit.com/testing-and-tooling/testing). - **Generators.** `make:perimeter --overlay` is removed. Publish your stubs again if you published them. See [Generators](https://laravel-access-control.lomkit.com/testing-and-tooling/generators). # Controls ## Writing a control A control is a class that extends `Lomkit\Access\Controls\Control`. It names its model and lists its perimeters: ```php [app/Access/Controls/PostControl.php] namespace App\Access\Controls; use App\Access\Perimeters\OwnPerimeter; use App\Models\Post; use App\Models\User; use Illuminate\Database\Eloquent\Builder; use Lomkit\Access\Ability; use Lomkit\Access\Controls\Control; class PostControl extends Control { protected string $model = Post::class; protected function perimeters(): array { return [ OwnPerimeter::new() ->allowed(fn (User $user, Ability $ability) => $user->can("{$ability} own posts")) ->query(function (Builder $query, User $user): void { $query->where('author_id', $user->id); }), ]; } } ``` - `$model` is the Eloquent model that the control decides on, declared as the default value of the property. A `$model` that is missing, is not a class or is not an Eloquent model throws `InvalidControlModelException`. - `perimeters()` lists the [perimeters](https://laravel-access-control.lomkit.com/essentials/perimeters): loose perimeters, which add up, and [`Levels::of()`](https://laravel-access-control.lomkit.com/essentials/levels) groups. - `boundary()`, optional, declares a condition that every row must meet, such as the tenant of the user. See [Boundaries](https://laravel-access-control.lomkit.com/essentials/boundaries). The model uses the `HasControl` trait, which adds the [controlled queries](https://laravel-access-control.lomkit.com/essentials/queries): ```php [app/Models/Post.php] use Lomkit\Access\Controls\HasControl; class Post extends Model { use HasControl; } ``` ## Generating a control ```bash php artisan make:control PostControl ``` The command writes `app/Access/Controls/PostControl.php`. Its options: - `--model` (`-m`) names the model: `--model=Post` for `App\Models\Post`, or a fully qualified class such as `--model='Domain\Blog\Post'`. Without it, the model is named after the control, `App\Models\Post` for `PostControl`. The command refuses, and writes nothing, when the model is not an Eloquent model class. - `--perimeters` (`-p`), repeatable, lists perimeter classes of `app/Access/Perimeters`. The control gets an `allowed()`, `should()` and `query()` callback for each one, which refuse everything until you write them, except the callbacks of the [hooks](https://laravel-access-control.lomkit.com/essentials/perimeter-classes#rules-in-the-class) that the class overrides. The perimeters are listed as loose perimeters: group the levels of a hierarchy in `Levels::of()` yourself. - `--parent`, repeatable, writes a [`ThroughParent`](https://laravel-access-control.lomkit.com/essentials/parents) entry for a `belongsTo` relation of the model, such as `--parent=post`. ```bash php artisan make:control PostControl --model=Post --perimeters=GlobalPerimeter --perimeters=OwnPerimeter ``` ## Finding the control of a model The package links a model to its control in two ways. ### Discovery The controls in `app/Access/Controls` are discovered: the package reads their `$model`. A model without anything more is linked to the discovered control whose `$model` it is. Add directories with `Access::discoverControlsIn()`, in the `boot()` method of a service provider: ```php use Lomkit\Access\Access; public function boot(): void { Access::discoverControlsIn([app_path('Domain/*/Controls')]); } ``` - The calls add up: each module can add its own directory from its provider. `app/Access/Controls` is always scanned, and no call removes a directory. - The paths accept glob patterns. Pass absolute paths (`app_path()`, `base_path()`, `__DIR__`), since a relative path depends on the working directory. - The same directory given twice is scanned once. ### The `#[ControlledBy]` attribute A model can name its control itself. A control outside the discovered directories is only found this way: ```php [app/Models/Post.php] use App\Access\Controls\PostControl; use Lomkit\Access\Attributes\ControlledBy; use Lomkit\Access\Controls\HasControl; #[ControlledBy(PostControl::class)] class Post extends Model { use HasControl; } ``` ### One control per model A model has a single control. Two controls for the same model, two discovered controls or a discovered control and the one the attribute names, throw `DuplicateControlException`, which names both, whatever the order. Put the variations, such as what administrators see, in the perimeters of the single control. A model with neither a discovered control nor the attribute has no control: its controlled queries throw `MissingControlException`, and `Access::registerPolicies()` gives it no policy. ## The Access facade `Lomkit\Access\Access` reaches the controls: ```php use Lomkit\Access\Access; if (Access::hasControl($model)) { $control = Access::controlFor($model); } ``` - `Access::controlFor($model)` returns the control of a model, given as an instance or a class name, or throws `MissingControlException`. `Access::hasControl($model)` checks first. - `Access::control(PostControl::class)` and `PostControl::new()` return the instance of that control. There is one instance per control class, resolved through the container, so a control can take constructor dependencies. There is no runtime list of the controls: `#[ControlledBy]` is resolved model by model. Guard with `Access::hasControl()` on the model at hand. ## Pure perimeter lists A control builds its perimeters and its boundary once, and keeps them for the whole process: a request, a queue worker or an Octane worker that serves many requests. `perimeters()` and `boundary()` must therefore return the same declarations every time. Read the user, the request, the tenant, the configuration of the moment or the clock in the callbacks, which receive the user, never while building the list: ```php // Wrong: the client of the first user is kept for the whole worker protected function perimeters(): array { $client = auth()->user()->client_id; return [ ClientPerimeter::new() ->allowed(fn (User $user) => $user->client_id !== null) ->query(fn (Builder $query) => $query->where('client_id', $client)), ]; } // Right protected function perimeters(): array { return [ ClientPerimeter::new() ->allowed(fn (User $user) => $user->client_id !== null) ->query(fn (Builder $query, User $user) => $query->where('client_id', $user->client_id)), ]; } ``` In debug mode and in tests, the package builds the list again each time it hands out a control and throws `ImpurePerimetersException` when the result differs. The check compares the classes, the callbacks and the values they capture: it catches a user, a date or a configuration value read at build time, but not the state hidden inside a service. ## Caching the controls In production, cache the control of each model: ```bash php artisan access:cache ``` `php artisan optimize` runs it, and `php artisan access:clear` removes the cache. Run it again in every deployment, after adding, moving or deleting a control. `php artisan access:check` builds every control and reports what would throw, open or hide rows. See [access\:check](https://laravel-access-control.lomkit.com/testing-and-tooling/access-check). # Perimeters ## The three callbacks A perimeter declares one access rule: which users it applies to, and which rows it reaches. ```php use App\Access\Perimeters\OwnPerimeter; use App\Models\Post; use App\Models\User; use Illuminate\Database\Eloquent\Builder; use Lomkit\Access\Ability; OwnPerimeter::new() ->allowed(fn (User $user, Ability $ability) => $user->can("{$ability} own posts")) ->should(fn (User $user, Post $post) => $post->author_id === $user->id) ->query(function (Builder $query, User $user): void { $query->where('author_id', $user->id); }); ``` | Callback | Question | Used by | | ----------- | ---------------------------------------------------------------------------- | ------------------------------------------------------------- | | `allowed()` | Does the perimeter apply to this user, for this ability? The **permission**. | everything | | `query()` | Which rows does it reach? Constraints on the query, for the **lists**. | `controlled()`, and the row check when there is no `should()` | | `should()` | Is this row one of them? The **row check**, in memory. Optional. | the policy, and the rows about to be created (drafts) | Take a user who may only see their own posts. `allowed()` says that they hold the `view own posts` permission. `should()` checks, in the policy, that the post at hand belongs to them. `query()` gives their posts for the lists. `query()` and `should()` are two rules you write, so they must describe the same rows. `assertControlAgrees()` proves it on your test data, see [Testing](https://laravel-access-control.lomkit.com/testing-and-tooling/testing#the-decisions). The user that the callbacks receive is the **reader**: any Eloquent model, such as a `User` or an API client. A perimeter whose callbacks type the reader, such as `fn (User $user, ...)`, applies only to the readers of that type. See [Readers](https://laravel-access-control.lomkit.com/essentials/readers#readers-of-several-types). ### `allowed()` ```php ->allowed(fn (User $user, Ability $ability) => $user->client_id !== null && $user->can("{$ability} client posts")) ``` - It receives the user and the ability. The ability converts to its name in a string: `"{$ability} client posts"` reads `view client posts`, `update client posts`, `approve client posts`. - It must return a boolean: any other value throws `PerimeterCallbackResultException`. - It never sees a row. A condition on the row goes in `should()` and `query()`, or in the [boundary](https://laravel-access-control.lomkit.com/essentials/boundaries). - It runs at most once per reader, ability and decision context until the next write, whatever the number of rows, and the policy, the queries and the search share its answer. See [Readers](https://laravel-access-control.lomkit.com/essentials/readers#kept-decisions). ### `query()` ```php ->query(function (Builder $query, User $user, Ability $ability): void { $query->where('client_id', $user->client_id); }) ``` - It constrains the builder it receives and returns nothing. An arrow function that returns that same builder works too. - Laravel turns `where('client_id', null)` into `IS NULL`. Refuse in `allowed()` a reader without the value, as above, so that a `null` never matches the rows without one. - Returning another builder, such as `Post::query()->where(...)`, throws `QueryCallbackReturnedAnotherBuilderException`. - A callback that adds no `where`, or only orders, limits or skips its constraint under a condition, throws `EmptyQueryCallbackException`. For every row, use [`unrestricted()`](https://laravel-access-control.lomkit.com/essentials/perimeters#unrestricted-perimeters). For a user who reaches no row, refuse them in `allowed()`, or add `$query->whereRaw('0=1')`. - A join throws `JoinInPerimeterException`, since Laravel drops the joins of a nested `where` group. Use `whereHas()` or an `exists` subquery. - The ability, the third parameter, is optional. The controlled queries pass the ability they list: `view`, unless `controlled('update')` names another one. ### `should()` ```php ->should(fn (User $user, Post $post, Ability $ability) => $post->author_id === $user->id) ``` - It receives the user, the row and, optionally, the ability, and must return a boolean. - It is optional. Without it, the policy checks a saved row through `query()`, in one SQL query on the row's key. With it, the row is checked in memory, without a query. - A row about to be created, a **draft**, is not in the database: only `should()` can judge it. Keep `should()` on the perimeters through which users create rows. See [Policies](https://laravel-access-control.lomkit.com/essentials/policies#drafts). - The policy passes the row as it is stored: after `fill()`, `should()` receives the original values. See [Policies](https://laravel-access-control.lomkit.com/essentials/policies#decisions-on-the-stored-row). Drop a `should()` that only repeats its `query()` when no user creates rows through the perimeter and the extra query per check does not matter: the row is then checked in SQL. ## The ability Each callback receives a `Lomkit\Access\Ability`, an immutable value object: ```php use Lomkit\Access\Ability; Ability::view(); // also create(), update(), delete(), restore(), forceDelete() Ability::of('approve'); // any business ability $ability->is('view'); // compare by name, with a string or an Ability $ability->name(); // 'view' "{$ability} posts"; // 'view posts' ``` - Type the ability parameter `Ability $ability`. An untyped parameter, or one typed `string`, throws `AbilityParameterTypeException` when the perimeter is declared. `?Ability`, `Stringable`, `object`, `mixed` and unions that contain `Ability` are accepted. - Compare with `is()`, never with `===`: two abilities with the same name are two objects. - A callback that does not need the ability leaves the parameter out: `fn (User $user) => $user->is_editor`. The policy method `viewAny` maps to `view`, the other standard methods to themselves, and any other method to `Ability::of($method)`. See [Policies](https://laravel-access-control.lomkit.com/essentials/policies#abilities). A perimeter can reach the posts of the user's client for `view`, and only the user's own posts of that client for the other abilities: ```php ClientPerimeter::new() ->allowed(fn (User $user, Ability $ability) => $user->client_id !== null && $user->can("{$ability} client posts")) ->should(fn (User $user, Post $post, Ability $ability) => $ability->is('view') ? $post->client_id === $user->client_id : $post->client_id === $user->client_id && $post->author_id === $user->id) ->query(function (Builder $query, User $user, Ability $ability): void { $query->where('client_id', $user->client_id); if (! $ability->is('view')) { $query->where('author_id', $user->id); } }); ``` ## Unrestricted perimeters A perimeter that reaches every row, such as an administrator's, is declared with `unrestricted()`: ```php GlobalPerimeter::new() ->allowed(fn (User $user, Ability $ability) => $user->can("{$ability} all posts")) ->unrestricted(); ``` - It takes only `allowed()`. Declaring `query()`, `should()` or search keys with it throws `UnrestrictedPerimeterCallbackException`. - When it applies to the reader, the controlled queries get no perimeter constraint, the policy grants the row without any `should()`, and no other perimeter narrows it. - The [boundary](https://laravel-access-control.lomkit.com/essentials/boundaries) of the control still applies. > **Note:** Without a boundary, an unrestricted perimeter reaches the rows of every tenant. When your rows belong to tenants, keep each user inside theirs with a [boundary](https://laravel-access-control.lomkit.com/essentials/boundaries). Never write a perimeter for every row as a `query()` that adds nothing: it throws `EmptyQueryCallbackException`. ## Perimeter classes `OwnPerimeter`, `ClientPerimeter` and `GlobalPerimeter` above are classes of your application that extend `Lomkit\Access\Perimeters\Perimeter`, generated with `php artisan make:perimeter`. A class can also hold its rules itself, in protected hooks, and take a value for each use. See [Perimeter classes](https://laravel-access-control.lomkit.com/essentials/perimeter-classes). ## Perimeters are immutable `allowed()`, `should()`, `query()`, `searchKeys()` and `unrestricted()` return a new perimeter and leave the one they are called on unchanged. Chain the declarations, or keep the returned perimeter: ```php // Lost: the perimeter in $own has no callback $own = OwnPerimeter::new(); $own->allowed(fn (User $user, Ability $ability) => $user->can("{$ability} own posts")); // Kept $own = OwnPerimeter::new() ->allowed(fn (User $user, Ability $ability) => $user->can("{$ability} own posts")); ``` Each callback is declared once: a second `allowed()`, `should()`, `query()` or `searchKeys()` on one perimeter throws `DuplicatePerimeterCallbackException`. Write one callback that checks both conditions. ## Search keys A perimeter of a searchable model also declares how it is searched, with `searchKeys()`, at the end of its chain. See [Search keys](https://laravel-access-control.lomkit.com/search/overview#search-keys). # Perimeter classes ## Generating a perimeter class A perimeter is an instance of a class that extends `Lomkit\Access\Perimeters\Perimeter`: ```bash php artisan make:perimeter ClientPerimeter ``` The class lands in `app/Access/Perimeters`, empty: ```php [app/Access/Perimeters/ClientPerimeter.php] namespace App\Access\Perimeters; use Lomkit\Access\Perimeters\Perimeter; class ClientPerimeter extends Perimeter {} ``` Its rules are the callbacks that the control declares, `allowed()`, `should()` and `query()`, as [Perimeters](https://laravel-access-control.lomkit.com/essentials/perimeters) shows. The class names the rule, in `access:check` and in the errors. ## Rules in the class A rule shared by several controls can live in the class instead, in three protected hooks: ```bash php artisan make:perimeter EditorialPerimeter --hooks ``` ```php [app/Access/Perimeters/EditorialPerimeter.php] namespace App\Access\Perimeters; use App\Models\User; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Lomkit\Access\AccessContext; use Lomkit\Access\Perimeters\Perimeter; class EditorialPerimeter extends Perimeter { protected function allows(AccessContext $context): bool { $reader = $context->reader(); return $reader instanceof User && $reader->client_id !== null && $reader->can("{$context->ability()} editorial posts"); } protected function includes(Model $row, AccessContext $context): bool { $reader = $context->reader(); return $reader instanceof User && $row->client_id === $reader->client_id; } protected function scope(Builder $query, AccessContext $context): void { $reader = $context->reader(); $query->where('client_id', $reader instanceof User ? $reader->client_id : 0); } } ``` | Hook | Callback it replaces | | ----------------------------------------------------- | -------------------- | | `allows(AccessContext $context): bool` | `allowed()` | | `includes(Model $row, AccessContext $context): bool` | `should()` | | `scope(Builder $query, AccessContext $context): void` | `query()` | - Each hook receives an `AccessContext`: `reader()` gives the reader, typed `Model`, so check its class with `instanceof`; `ability()` gives the ability. - `allows()` refuses a reader without a client, so that `includes()` and `scope()` never compare with a `null` client. - `--hooks` generates the three hooks, which refuse everything until you write them. Remove `includes()` to check the rows in SQL. - A rule is written once: declaring in the control the callback of a hook that the class overrides throws `OverriddenPerimeterHookException`. - The control lists the class with `EditorialPerimeter::new()`, and may still add `allowed()` when the class does not override `allows()`. ## Variants of a class A class that needs a value for each use, such as the kind of document, keeps it as private state that every hook reads. A required value goes in a constructor with `readonly` promoted properties, behind a named static constructor: ```php [app/Access/Perimeters/OwnedDocuments.php] namespace App\Access\Perimeters; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Lomkit\Access\AccessContext; use Lomkit\Access\Perimeters\Perimeter; final class OwnedDocuments extends Perimeter { private function __construct(private readonly string $kind) {} public static function ofKind(string $kind): self { return new self($kind); } protected function includes(Model $row, AccessContext $context): bool { return $row->kind === $this->kind && $row->owner_id === $context->reader()->getKey(); } protected function scope(Builder $query, AccessContext $context): void { $query->where('kind', $this->kind)->where('owner_id', $context->reader()->getKey()); } } ``` ```php OwnedDocuments::ofKind('invoice') ->allowed(fn (User $user, Ability $ability) => $user->can("{$ability} own invoices")); ``` - Call the named constructor first: the fluent methods clone the perimeter and keep its state. - `X::new()` on a class whose constructor requires arguments, or is not public, throws `UnbuildablePerimeterException`. - Build the state from constants, never from the request or the user: the control keeps its perimeters for the whole process. See [Controls](https://laravel-access-control.lomkit.com/essentials/controls#pure-perimeter-lists). - Never narrow a class with a second `query()`, or by wrapping it in another perimeter: the package reads only what each perimeter of the list declares. # Levels ## A hierarchy of perimeters Most access models are a hierarchy: administrators see every post, managers the posts of their client, authors their own posts. Declare it in a `Levels::of()` group, **widest level first**: ```php use Lomkit\Access\Perimeters\Levels; protected function perimeters(): array { return [ Levels::of( GlobalPerimeter::new() ->allowed(fn (User $user, Ability $ability) => $user->can("{$ability} all posts")) ->unrestricted(), ClientPerimeter::new() ->allowed(fn (User $user, Ability $ability) => $user->client_id !== null && $user->can("{$ability} client posts")) ->query(fn (Builder $query, User $user) => $query->where('client_id', $user->client_id)), OwnPerimeter::new() ->allowed(fn (User $user, Ability $ability) => $user->can("{$ability} own posts")) ->query(fn (Builder $query, User $user) => $query->where('author_id', $user->id)), ), ]; } ``` For each ability, only the **highest level the user reaches** applies: the first level whose `allowed()` returns `true`. The levels below it are neither evaluated nor added to the SQL, in the policy and in the controlled queries alike. The level is chosen for each ability. A user who holds `view client posts` and `update own posts` is at the client level for `view` and at the own level for `update`: they read the posts of their client and edit only their own. ## Levels nest A level contains the levels below it: a user who reaches the client level must see at least the rows of the own level. Since the lower levels are not evaluated, a row that only a lower level reaches would vanish for the users of a higher level. A perimeter that does not nest belongs outside the group. `assertLevelsNest()` checks the nesting on your test data, see [Testing](https://laravel-access-control.lomkit.com/testing-and-tooling/testing#the-levels). ## Loose perimeters add up Every perimeter outside a group adds up with the others, with an OR, wherever it is written: ```php protected function perimeters(): array { return [ Levels::of( GlobalPerimeter::new()->allowed(...)->unrestricted(), ClientPerimeter::new()->allowed(...)->query(...), OwnPerimeter::new()->allowed(...)->query(...), ), SharedPerimeter::new()->allowed(...)->query(...), // outside the group: adds up ]; } ``` A user reaches the rows of the level they reach in the group, plus the rows of each loose perimeter that allows them: an author also sees the posts shared with them. - A control may declare several groups next to loose perimeters. Each group gives its own level, and they all add up. - The order of the perimeters and their classes never change how they combine: only the groups do. - When an [unrestricted](https://laravel-access-control.lomkit.com/essentials/perimeters#unrestricted-perimeters) perimeter applies, in a group or outside, the user reaches every row of the [boundary](https://laravel-access-control.lomkit.com/essentials/boundaries): no other perimeter narrows it. ## Errors - `Levels::of()` without a level throws `EmptyLevelsException`. - A group given as a level of another group throws `NestedLevelsException`. # Boundaries ## A condition on every row A tenant, a workspace or a company is not one more perimeter: it is a condition that every row must meet, whatever the perimeter that grants it. Declare it once in the `boundary()` method of the control: ```php [app/Access/Controls/PostControl.php] use Lomkit\Access\Boundaries\Boundary; protected function boundary(): Boundary { return Boundary::where('workspace_id', fn (User $user) => $user->current_workspace_id); } ``` The boundary applies as an **AND** around the perimeters: - in the controlled queries and in the policy alike, for every ability; - before the [levels](https://laravel-access-control.lomkit.com/essentials/levels): a user reaches the level of their perimeters, inside their workspace; - even for an [unrestricted](https://laravel-access-control.lomkit.com/essentials/perimeters#unrestricted-perimeters) perimeter: an administrator who sees every post sees every post of their workspace. So the perimeters never repeat the condition, and none of them can forget it. Without `boundary()`, a control has no boundary, as with `Boundary::none()`. ## `Boundary::where()` `Boundary::where($column, $readerValue)` keeps the rows whose column equals the value that the closure reads from the reader, an int or a string. The same declaration gives the SQL of the controlled queries and the check of the policy, in memory, without a query. The boundary fails closed: - A reader value of `null`, such as a user without a current workspace, closes the boundary: the user reads no row, and the policy refuses every ability, `create` included. The SQL never compares with `IS NULL`. - A reader whose type the closure does not accept, such as an API client for `fn (User $user)`, is refused the same way. - Any other value than an int, a string or `null` throws `InvalidBoundaryValueException`. ### Read-only rows `Boundary::where(...)->readOnlyWhenNotNull($column)` keeps a row readable while the column is not null, and refuses it to every other ability. The method exists only on the boundary that `Boundary::where()` returns: for another boundary, write a [boundary class](https://laravel-access-control.lomkit.com/essentials/boundaries#boundary-classes) whose `scope()` and `includes()` refuse the abilities other than `view` on such rows. ```php protected function boundary(): Boundary { return Boundary::where('workspace_id', fn (User $user) => $user->current_workspace_id) ->readOnlyWhenNotNull('archived_at'); } ``` An archived post stays in `controlled()` and its `view` is granted, but `update`, `delete` and business abilities such as `approve` are refused, and `controlled('update')` leaves it out. ## Refusals The policy tells two refusals of the boundary apart: | Code | When | Status | | ------------------ | ---------------------------------------------------------------------------------------------------------- | ------ | | `outside_boundary` | The row is outside the boundary for this ability, but the user may still view it, such as an archived post | 403 | | `not_found` | The boundary also refuses `view`, such as a post of another workspace | 404 | A row of another workspace answers like a row that does not exist, so its existence is never revealed. See [Policies](https://laravel-access-control.lomkit.com/essentials/policies#refusals). ## Boundary classes A condition that one column cannot express is a class that extends `Lomkit\Access\Boundaries\Boundary`: ```php [app/Access/Boundaries/TeamBoundary.php] namespace App\Access\Boundaries; use App\Models\User; use Illuminate\Database\Eloquent\Builder; use Lomkit\Access\AccessContext; use Lomkit\Access\Boundaries\Boundary; class TeamBoundary extends Boundary { protected function scope(Builder $query, AccessContext $context): void { $reader = $context->reader(); $query->whereIn('team_id', $reader instanceof User ? $reader->teams()->select('teams.id') : []); if (! $context->ability()->is('view')) { $query->where('locked', false); } } } ``` ```php protected function boundary(): Boundary { return new TeamBoundary; } ``` - `scope()` is required: the condition in SQL, for the controlled queries. It receives the `AccessContext`, with the reader and the ability. A join throws `JoinInPerimeterException`: use `whereHas()` or an `exists` subquery. - `includes(Model $row, AccessContext $context): bool`, optional, checks a row in memory. Without it, the policy checks the boundary with one `exists` query on the row, even for an unrestricted perimeter, and refuses every [draft](https://laravel-access-control.lomkit.com/essentials/policies#drafts), since a row about to be created is not in the database. - `admits(AccessContext $context): bool`, optional, is the boundary without a row. When it returns `false`, the reader reaches nothing for that ability: `controlled()` lists no row, and the policy refuses with `no_perimeter`, `viewAny` and `create` included. `boundary()` follows the rule of `perimeters()`: it is built once per process, so it never reads the user, the request or the tenant while it builds the boundary. Read them in `scope()` and `includes()`, from the context. See [Controls](https://laravel-access-control.lomkit.com/essentials/controls#pure-perimeter-lists). ## Good to know - A controlled search applies the boundary too: `Boundary::where()` gives its search keys, and a boundary class declares them in a `searchKeys()` method. See [Search overview](https://laravel-access-control.lomkit.com/search/overview#the-boundary). - A `Gate::before()` callback that returns `true` grants before any policy runs, so it bypasses the boundary too, as it bypasses every policy in Laravel. - The boundary holds one value per reader. When one list spans several brands or companies, the brand belongs to the perimeters, not to the boundary: see [Several brands](https://laravel-access-control.lomkit.com/digging-deeper/several-brands). # Parents ## A child with the access of its parent A child row often has the access of its parent: a comment is visible to whoever may view its post. Declare it with `ThroughParent` in the control of the child: ```php [app/Access/Controls/CommentControl.php] use Lomkit\Access\Perimeters\ThroughParent; class CommentControl extends Control { protected string $model = Comment::class; protected function perimeters(): array { return [ ThroughParent::belongsTo('post', inverse: 'comments'), ]; } } ``` - `belongsTo()` names the `belongsTo` relation from the child to its parent. - The control of the parent decides, for the same reader: its perimeters, its levels and its boundary. The child's own boundary still applies to the child. - It works in the policy, in `controlled()`, in the row checks and in the batched decisions. A row check is one `exists` query through `whereHas()`, with the global scopes of the parent. - `inverse` names the `hasMany` from the parent to its children. The search needs it to reindex the children when the parent changes, so a searchable child requires it. Elsewhere it is optional, and checked when given. `php artisan make:control CommentControl --parent=post` writes the entry. > **Warning:** Never write the parent by hand, as a `query()` with `whereHas('post', ...)`: that callback runs without the control of the parent unless it calls `controlledFor()` itself, and opens every comment of every post once that call is forgotten. ## Delegated abilities **Only `view` is delegated by default.** Reusing every ability would let whoever may update a post delete any comment on it. `delegates()` replaces the default with the abilities it lists: ```php ThroughParent::belongsTo('post')->delegates(['view', 'update', 'create' => 'view']); ``` - A list item delegates the same ability: `update` on the comment asks for `update` on the post. - A string key maps an ability of the child to an ability of the parent: creating a comment asks for `view` on the post. - For an ability it does not delegate, the perimeter does not apply. Compare the abilities one by one: delegating `delete` to the parent's `update` lets every editor of a post delete its comments. ## A permission of the child (AND) A child is often reachable when the reader holds a permission of the child itself **and** reaches the parent. Declare that permission with `allowed()` on the `ThroughParent`: ```php ThroughParent::belongsTo('post', inverse: 'comments') ->delegates(['view', 'create' => 'view']) ->allowed(fn (User $user, Ability $ability) => $user->can("{$ability} comments")); ``` - An ability that the perimeter does not delegate is refused first, without calling `allowed()`. - When `allowed()` returns `false`, the parent is not touched: no query. - Otherwise the parent decides. `allowed()` receives the ability of the child, `create` above, not the parent's `view`. It can only narrow what the parent grants. ## Other rows (OR) A perimeter next to the `ThroughParent` grants other rows, such as the comments the reader wrote, whatever the post: ```php protected function perimeters(): array { return [ ThroughParent::belongsTo('post', inverse: 'comments'), AuthorPerimeter::new() ->allowed(fn (User $user, Ability $ability) => $user->can("{$ability} own comments")) ->query(fn (Builder $query, User $user) => $query->where('author_id', $user->id)), ]; } ``` `ThroughParent` takes no other callback: `should()`, `query()`, `searchKeys()`, `reindexWhen()`, `unrestricted()` and `ThroughParent::new()` throw `ThroughParentCallbackException`. So: | You need | Write | | ------------------------------------------------ | -------------------------------------------------------------------------------------------- | | A permission of the reader, on top of the parent | `allowed()` on the `ThroughParent` | | A condition on the child row | the [boundary](https://laravel-access-control.lomkit.com/essentials/boundaries) of the child | | Other rows | a perimeter next to the `ThroughParent` | A `ThroughParent` adds up like any loose perimeter, so two parents add up too, and it can be a level of a `Levels::of()` group. Parents nest: the post can itself inherit from its project. ## The parent's control, not its policy The control of the parent decides; the parent's **policy** is never called. A rule that the parent's policy adds on top of its control, such as an update allowed on drafts only, is not inherited, and delegating that ability would grant more than the Gate does on the parent. Move such a rule into the control of the parent, usually its boundary: `Boundary::where(...)->readOnlyWhenNotNull('closed_at')`, or a [boundary class](https://laravel-access-control.lomkit.com/essentials/boundaries#boundary-classes) whose `scope()` and `includes()` refuse the abilities other than `view` on such rows. The parent's own lists become right too. `assertControlAgrees()` on the parent fails while its policy adds a rule. ## Drafts A comment about to be created is not in the database. With `create` delegated, the draft loads its parent by the foreign key, in one query, and the control of the parent decides on that stored parent: ```php $draft = new Comment(['post_id' => $post->id, 'body' => $body]); $user->can('create', [Comment::class, $draft]); // asks the post's control, for the mapped ability ``` A draft without a parent key, or whose parent does not exist, is refused. A relation loaded on the draft is ignored: only the foreign key counts. ## Decisions without a row `viewAny`, and `create` without a draft, have no row to check. A `ThroughParent` counts for them only when it delegates the ability, its own `allowed()` accepts, and the reader reaches at least one perimeter of the parent for the mapped ability. A reader who holds the permission of the child but reaches nothing on the parent, and no other perimeter of the child, gets a 403 `no_perimeter` on `viewAny`, not an empty list. A reader who reaches the parent without rows there gets an empty list. Where the child must be listable, grant the parent ability too. ## Errors The control checks its `ThroughParent` perimeters when it builds its perimeters, before any query: | Mistake | Exception | | ------------------------------------------------------------------------------------- | ------------------------------------- | | The relation does not exist, or is not a `belongsTo` | `InvalidParentRelationException` | | `inverse` is not the `hasMany` of the parent on the same keys | `InvalidParentRelationException` | | The parent model has no control | `MissingParentControlException` | | The parents lead back to the child | `ParentCycleException` | | `delegates()` gets an empty list, an ability twice, or something else than an ability | `InvalidDelegationException` | | The relation method runs a query while it builds the relation | `RelationInspectionQueryException` | | A second `allowed()` | `DuplicatePerimeterCallbackException` | ## Parents of several types `ThroughParent` follows a `belongsTo` relation. A child readable through any of several parents, such as a note linked to contracts and customers by a `note_links` table, takes a perimeter checked in SQL that reaches each type of parent through its control: ```php LinkedSubjectsPerimeter::new() ->allowed(fn (User $user, Ability $ability): bool => $ability->is('view') && $user->can('view notes')) ->query(function (Builder $query, User $user): void { $query->whereHas('links', fn (Builder $links) => $links->whereHasMorph( 'subject', [Contract::class, Customer::class], fn (Builder $subjects) => $subjects->controlledFor($user), )); }), ``` A note is readable when the reader may view at least one of its subjects, each decided by its own control. Keep each part of this recipe: - `$ability->is('view')` in `allowed()`: `controlledFor($user)` checks each parent for `view`, whatever the ability decided on the note, so without it every reader of a parent may update and delete the note. - `controlledFor($user)` with the reader that the callback receives, and nothing else in that closure: never `controlled()`, which reads the signed-in user. - The listed types, never `'*'`: with `'*'`, the types come from the link table, and any controlled type that a row names would open the note. - No `should()`: the policy and the lists then decide with this same query. - A permission of the child in `allowed()`: without a row, `viewAny` is granted to every reader whom `allowed()` accepts, whether they reach a parent or not, where a `ThroughParent` asks the control of the parent. The perimeter declares no search keys, grants no draft and checks no cycle. Keep such a model out of the search engine, or search it with Scout's `database` driver. # Policies ## Automatic policies Call `Access::registerPolicies()` in the `boot()` method of a service provider: ```php [app/Providers/AppServiceProvider.php] use Lomkit\Access\Access; public function boot(): void { Access::registerPolicies(); } ``` Every controlled model that has no policy then gets a `Lomkit\Access\Policies\ControlledPolicy` for its control. `can()`, `@can`, `authorize()`, `Gate::allows()` and `Gate::inspect()` work as usual: ```php $user->can('view', $post); $this->authorize('update', $post); Gate::inspect('delete', $post)->code(); // null when granted, or a refusal code ``` A model keeps its own policy when it has one: registered with `Gate::policy()`, declared with `#[UsePolicy]` on the model or a parent class, or found by Laravel's naming convention. The policies are resolved when the Gate asks for them, through `Gate::guessPolicyNamesUsing()`: if your application sets its own guesser, set it before `Access::registerPolicies()`. ## How a decision runs The policy maps each method to an ability, and asks the control: | Policy method | Ability | Row | | ---------------------------------------------------- | ---------------------- | ---------------------------------------------------------------------------------------- | | `viewAny` | `view` | none | | `view`, `update`, `delete`, `restore`, `forceDelete` | the same | the stored row | | `create` | `create` | none, or a [draft](https://laravel-access-control.lomkit.com/essentials/policies#drafts) | | any other method, through `decideByControl()` | `Ability::of($method)` | a row, a draft or none | - **Without a row**, such as `viewAny` or `create` without a draft, the ability is granted when one `allowed()` returns `true` and the boundary admits the reader. A `Boundary::where()` whose reader value is `null`, or a boundary class whose `admits()` returns `false`, refuses with `no_perimeter`. It means "somewhere". - **With a row**, the row must also be inside the [boundary](https://laravel-access-control.lomkit.com/essentials/boundaries) and inside one of the perimeters that allow the reader. The row is checked in memory by the perimeters that have a `should()` callback or an `includes()` hook, and by an unrestricted one. The other perimeters check it in SQL: one query on the row's key, constrained by the OR of their `query()`. The in-memory checks run first, and the SQL only when none of them grants, so the number of queries never depends on loaded relations. ## Refusals Each method returns an `Illuminate\Auth\Access\Response`. A refusal carries a code and a translated message, checked in this order: | Code | Refusal | Status | | ------------------ | ----------------------------------------------------------------------------------------------------------- | ------ | | `unsaved` | The model is not saved, for any ability but `create` with a draft | 403 | | `no_perimeter` | No perimeter allows the reader for this ability | 403 | | `outside_boundary` | The row is outside the boundary for this ability, but the reader may still view it, such as an archived row | 403 | | `not_found` | The row is outside the boundary for this ability and for `view`, such as a row of another tenant | 404 | | `outside_rows` | No perimeter that allows the reader contains the row | 403 | ```php $response = Gate::inspect('update', $post); $response->allowed(); // false $response->code(); // 'outside_rows' $response->message(); // 'You are not allowed to perform this action on this record.' ``` The messages ship in English and French. Publish them to translate or change them, then edit `lang/vendor/access-control/{locale}/refusals.php`: ```bash php artisan vendor:publish --tag=access-control-lang ``` ## Drafts `create` without a row means "allowed to create somewhere": only the `allowed()` callbacks run. To check **where** the new row lands, pass the model about to be created, the draft: ```php $draft = new Post($request->validated()); $this->authorize('create', [Post::class, $draft]); $draft->save(); ``` The draft must land inside the boundary and inside one of the reader's perimeters. A user who may only create their own posts cannot create one for another author or another client, whatever the validation lets through. A draft is not in the database, so only the in-memory checks judge it: - the `should()` callback or the `includes()` hook of a perimeter, an unrestricted perimeter, and a [`ThroughParent`](https://laravel-access-control.lomkit.com/essentials/parents#drafts) that delegates `create`; - the in-memory form of the boundary: `Boundary::where()`, or the `includes()` hook of a boundary class. A perimeter checked in SQL cannot grant a draft, and a boundary without an in-memory form refuses every draft. Give a `should()` callback to the perimeters through which users create rows. `php artisan access:check` notes the controls that can grant no draft. laravel-rest-api always passes the draft: it checks `create` on the class, then on the draft of each row it creates. ## Decisions on the stored row The policy decides a saved row on the values it has in the database. After `fill()`, `should()` and the boundary receive a copy built from the original attributes: ```php $post->fill(['author_id' => $user->id]); $user->can('update', $post); // decided on the stored author, not the new one ``` Check new values through a draft, never by authorizing the modified row. A model that is not saved is refused with `unsaved` for `view`, `update`, `delete`, `restore`, `forceDelete` and every business ability: decide `viewAny` and `create` without a row, or with a draft. ## Business abilities A policy declares a business ability, such as `approve` or `export`, by calling the protected `decideByControl()` helper with the name of its method. Extend `ControlledPolicy` and name the control: ```php [app/Policies/PostPolicy.php] namespace App\Policies; use App\Access\Controls\PostControl; use App\Models\Post; use App\Models\User; use Illuminate\Auth\Access\Response; use Lomkit\Access\Decisions\Draft; use Lomkit\Access\Policies\ControlledPolicy; class PostPolicy extends ControlledPolicy { protected string $control = PostControl::class; public function approve(User $user, Post $post): Response { return $this->decideByControl(__FUNCTION__, $user, $post); } public function export(User $user): Response { return $this->decideByControl(__FUNCTION__, $user); } public function duplicate(User $user, Post $post, Post $copy): Response { return $this->decideByControl(__FUNCTION__, $user, Draft::of($copy)); } } ``` The perimeters receive `Ability::of('approve')`, so a permission such as `"{$ability} client posts"` reads `approve client posts`. Laravel finds `PostPolicy` by its naming convention, and it replaces the automatic policy for `Post`. - `$control` names the control of the model. Without it, a row is decided by the control of its model, but `viewAny`, `create` without a draft and a business ability without a row throw `MissingPolicyControlException`. A `$control` that is not the control of the model throws `PolicyControlMismatchException`. - A business ability on a row about to be created takes `Draft::of($row)`, like `duplicate` above, and is judged in memory like a `create` draft. Passing the unsaved model itself is refused with `unsaved`. - The standard methods of `ControlledPolicy` need no declaration. `decideByControl` and `declaredControl` are the only names that a policy cannot use for an ability. ### Abilities The control maps a policy method to an ability with `abilityFor()`. Override it on the control to change the mapping: ```php use Lomkit\Access\Ability; public function abilityFor(string $policyMethod): Ability { return match ($policyMethod) { 'viewAny' => Ability::of('list'), default => parent::abilityFor($policyMethod), }; } ``` The controlled queries use the same mapping: `controlled('viewAny')` lists the `list` rows here. ## Keep the rules in the control An overridden method keeps the parameters of `ControlledPolicy`, typed `Model`, and returns a `Response`: ```php use Illuminate\Database\Eloquent\Model; public function update(Model $user, Model $post): Response { if ($post->locked_at !== null) { return Response::deny('This post is locked.'); } return parent::update($user, $post); } ``` It works, but the rule lives in the policy only: `controlled('update')` still lists the locked posts, and a [`ThroughParent`](https://laravel-access-control.lomkit.com/essentials/parents#the-parents-control-not-its-policy) child does not inherit it. Prefer the control, here its boundary, which keeps a locked post readable and refuses it every other ability: ```php protected function boundary(): Boundary { return Boundary::where('workspace_id', fn (User $user) => $user->current_workspace_id) ->readOnlyWhenNotNull('locked_at'); } ``` Without a column to bound the rows by, write a [boundary class](https://laravel-access-control.lomkit.com/essentials/boundaries#boundary-classes) whose `scope()` and `includes()` refuse the abilities other than `view` on locked rows. The policy, the lists and the search then agree, which `assertControlAgrees()` checks. A `Gate::before()` callback that returns `true` grants before the policy runs, whatever the control says. # Queries ## Controlled queries The `HasControl` trait adds three local scopes to the model: ```php Post::controlled()->paginate(); // the posts the signed-in user may view Post::controlledFor($user)->get(); // the posts a named reader may view Post::uncontrolled()->count(); // every post, on purpose ``` `controlled()` reads the signed-in user, with `Auth::user()`, when the query is built. The control adds the constraints of the perimeters that the user reaches, and of the boundary, in SQL, in one nested `where`. **A query is controlled only when it says so.** `Post::query()->get()` reads every row: the trait registers no global scope. Add `controlled()` to every query that must be filtered. ### Guests see nothing Without a signed-in user, `controlled()` reads no row, whatever the ability. So does `controlledFor(null)`: a missing reader never means every row. A user that no perimeter allows reads no row either: the query gets `0=1`. ## Listing another ability Both scopes list the `view` rows by default. Pass another ability, as a name or an `Ability`, to list the rows the reader may act on: ```php use Lomkit\Access\Ability; Post::controlled('update')->paginate(); Post::controlledFor($user, Ability::delete())->count(); Post::controlledFor($user, 'approve')->get(); ``` The list follows the policy for that ability: the perimeters that allow the reader for it, the level reached for it in each group, the boundary checked for it, and the abilities a parent delegates. A post archived under [`readOnlyWhenNotNull('archived_at')`](https://laravel-access-control.lomkit.com/essentials/boundaries#read-only-rows) stays in the `view` list and leaves the `update` list. - A name goes through `abilityFor()`: `viewAny` lists `view`, and a business ability such as `approve` lists its rows. - `create` throws `UnlistableAbilityException`, since the policy judges it on a draft only. - One ability per scope: a second argument, such as `controlled('view', 'update')`, throws `IgnoredArgumentException`. The list is what the control grants. A rule that an overridden policy method adds, or a `Gate::before()`, does not change it: keep the rules in the control, see [Policies](https://laravel-access-control.lomkit.com/essentials/policies#keep-the-rules-in-the-control). ## Named readers `controlledFor($reader)` applies the control for a reader you name. Use it where no user is signed in, such as jobs, listeners and commands, or to act for another user: ```php class SendDigest implements ShouldQueue { public function __construct(public User $recipient) {} public function handle(): void { $posts = Post::controlledFor($this->recipient)->latest()->limit(10)->get(); // ... } } ``` The reader can be any Eloquent model, such as a `User` or an API client. See [Readers](https://laravel-access-control.lomkit.com/essentials/readers). ## Combining with your own conditions The constraints of the control form one group, so a condition chained **before** `controlled()` stays an AND: ```php Post::where('published', true)->orWhere('featured', true)->controlled()->get(); // where (published = 1 or featured = 1) and (the control) ``` A condition chained **after** `controlled()` is joined to the whole query, like any Eloquent `orWhere()`: an `orWhere()` there would bring rows from outside the control. Group your conditions in a closure: ```php Post::controlled()->where(fn (Builder $query) => $query->where('published', true)->orWhere('featured', true))->get(); ``` To narrow a list with a rule of your own, such as the posts of one author, intersect it with the controlled list: the control stays inside, so the rule can only narrow it. ```php Post::controlledFor($user, 'update')->where(fn (Builder $query) => $query->whereBelongsTo($author, 'author')); ``` ## Relations and subqueries Relations, `whereHas()` subqueries, eager loads, lazy loads and route model binding are **not controlled** unless they say so. Each scope works on a relation or a subquery: ```php $user->posts()->controlled()->get(); Project::whereHas('posts', fn (Builder $posts) => $posts->controlled())->get(); User::with(['posts' => fn ($posts) => $posts->controlled()])->get(); Comment::whereIn('post_id', Post::controlledFor($user, 'update')->select('id'))->get(); ``` A model bound to a route is loaded without control: authorize it through its policy. ```php public function show(Post $post) { $this->authorize('view', $post); // ... } ``` ## Uncontrolled queries `uncontrolled()` adds nothing: it states that a query reads every row on purpose, for statistics, seeders or a back office. It reads like `Post::query()`, and tells a reviewer that the missing control is a choice. ## Deciding the rows of a page A page that checks `@can('update', $post)` on each row runs one query per row and ability for the perimeters checked in SQL. Decide the whole page in the query that loads it with `withAbilities()`, after `controlled()` or `controlledFor()`: ```php $posts = Post::controlled() ->withAbilities(['view', 'update', 'delete']) ->paginate(); ``` The query decides each row for each ability, and `can()`, `@can` and `authorize()` then answer without SQL. The extra columns never show in `toArray()` or the JSON. `withAbilities()` without `controlled()` or `controlledFor()` before it throws `MissingControlledReaderException`. `controlled()` does not decide `view` by itself: list `view` in `withAbilities()` when the page checks it. [Batched decisions](https://laravel-access-control.lomkit.com/digging-deeper/batched-decisions) covers the others, `Access::preload()` and `reachableKeys()`. ## Good to know - `controlled()` reads `Auth::user()` when it runs: do not call it from an event of the user model that the guard fires while it retrieves the user, such as `retrieved`. - A Laravel Scout search has its own `controlled()`, `controlledFor()` and `uncontrolled()`, and must call one of them. See [Search overview](https://laravel-access-control.lomkit.com/search/overview#searching). # Readers ## Who is the reader Every decision is made for a **reader**: the signed-in user for `controlled()` and the policy, or the model you name with `controlledFor()`. A reader is any Eloquent model: a `User`, an API client, a member of another guard. | Where | Reader | | ----------------------------------------------- | -------------------------------------- | | `controlled()`, a Scout search's `controlled()` | `Auth::user()`, or none for a guest | | `controlledFor($reader)` | the model you pass, or none for `null` | | `$user->can()`, `Gate::forUser($user)` | that user | | `$this->authorize()`, `@can`, `Gate::allows()` | the signed-in user | Without a reader, the controlled queries read no row. The perimeter callbacks receive the reader as their first parameter (`allowed()`, `should()`) or second (`query()`), and the hooks of a perimeter class read it with `$context->reader()`. ## Readers of several types A control can serve several types of readers. A perimeter whose callbacks type the reader applies only to the readers of that type, and the others skip it: ```php protected function perimeters(): array { return [ OwnPerimeter::new() ->allowed(fn (User $user, Ability $ability) => $user->can("{$ability} own posts")) ->query(fn (Builder $query, User $user) => $query->where('author_id', $user->id)), ClientAppPerimeter::new() ->allowed(fn (ApiClient $client, Ability $ability) => $client->client_id !== null && $ability->is('view')) ->query(fn (Builder $query, ApiClient $client) => $query->where('client_id', $client->client_id)), ]; } ``` A `User` reaches only `OwnPerimeter`, an `ApiClient` only `ClientAppPerimeter`, and any other reader no perimeter, so no row. The same goes for a [boundary](https://laravel-access-control.lomkit.com/essentials/boundaries) declared with `Boundary::where()`: a reader whose type its closure does not accept is refused everything. - A class, a nullable class, an interface, a union or an intersection narrows the readers. - An untyped parameter, `Model`, `object` or `mixed` accepts every reader. - Type every callback of a perimeter with the same reader type: the perimeter is skipped when any of them refuses the reader. ## The decision context Some decisions depend on more than the reader: the current team of a permission package, the brand or the tenant that the request works in. Declare these values once, in the `boot()` method of a service provider: ```php use Lomkit\Access\Access; public function boot(): void { Access::decisionContextUsing(fn (): array => ['team' => Team::current()?->id]); } ``` - The resolver returns an array of strings, ints, booleans or nulls, keyed by name. Anything else, such as a model, throws `InvalidDecisionContextException`. - The hooks of a perimeter or boundary class read it with `$context->decisionContext()`. - Without a resolver, the context is empty. The package files the decisions it keeps under this context, so a decision made for one team is never reused for another. **Everything `allowed()` reads besides the reader belongs in the decision context**, such as the team that `setPermissionsTeamId()` sets, a tenant or a guard chosen during the request. ## Kept decisions Within a request, a queued job or a console command, the package keeps what it decided: - the perimeters a reader reaches: what each `allowed()` answered, and the level reached in each group, for each reader, ability and decision context; - the SQL check of each row, for each reader, decision context and ability. So an `allowed()` that queries runs once per reader, ability and context, not once per row, and the policy, the controlled queries and the search filter share its answer: they always agree within a request. The in-memory checks, `should()` and the boundary, run on every decision. Everything kept is forgotten at once: - after any SQL statement that is not a read, on any connection: Eloquent saves and deletes, mass updates, `attach()`, `DB::table()` and `DB::statement()` writes included, with or without model events. The writes of Laravel's own tables, such as the cache, the sessions and the queues, are the exception, see [Laravel's own tables](https://laravel-access-control.lomkit.com/digging-deeper/decisions#laravels-own-tables); - when a transaction rolls back, once a request is handled, and at the end of each job; - when you call `Access::forgetDecisions()`. A reader that is not saved, or has no key, is never kept: its perimeters are evaluated on every decision. Call `Access::forgetDecisions()` yourself when a decision changes without a write through Laravel: - in a long console command, at the start of each unit of work, such as each tenant, since it never sees a permission revoked by another process; - in a test, after `Gate::define()` changes a permission between two checks. The tests need no reset: each test starts with no kept decision. ## What Digging deeper covers These pages keep to what most applications need. The Digging deeper section covers the rest: - [the batched decisions](https://laravel-access-control.lomkit.com/digging-deeper/batched-decisions), `Access::preload()` and `reachableKeys()`, next to [`withAbilities()`](https://laravel-access-control.lomkit.com/essentials/queries#deciding-the-rows-of-a-page); - [the writes of Laravel's own tables](https://laravel-access-control.lomkit.com/digging-deeper/decisions#laravels-own-tables), such as the cache, the sessions and the queues, which do not forget the kept decisions; - [lists that span several brands](https://laravel-access-control.lomkit.com/digging-deeper/several-brands), and [a parent decided in the context of the child row](https://laravel-access-control.lomkit.com/digging-deeper/row-context). # Search overview ```php [app/Access/Controls/PostControl.php] protected function perimeters(): array { return [ Levels::of( GlobalPerimeter::new() ->allowed(fn (User $user, Ability $ability) => $user->can("{$ability} all posts")) ->unrestricted(), ClientPerimeter::new() ->allowed(fn (User $user, Ability $ability) => $user->client_id !== null && $user->can("{$ability} client posts")) ->query(fn (Builder $query, User $user) => $query->where('client_id', $user->client_id)) ->searchKeys( name: 'client', row: fn (Post $post) => $post->client_id, reader: fn (User $user) => $user->client_id, ), OwnPerimeter::new() ->allowed(fn (User $user, Ability $ability) => $user->can("{$ability} own posts")) ->query(fn (Builder $query, User $user) => $query->where('author_id', $user->id)) ->searchKeys( name: 'author', row: fn (Post $post) => $post->author_id, reader: fn (User $user) => $user->id, ), ), ]; } ``` ```php [app/Models/Post.php] use Lomkit\Access\Controls\HasControl; use Lomkit\Access\Search\ControlledSearchable; class Post extends Model { use HasControl, ControlledSearchable; } ``` ```php Post::search('budget')->controlled()->paginate(25); ``` A controlled search is **one query to the search engine**, with all the filtering inside it: - each document is indexed with the keys that open it: `client.7` and `author.42` for a post of client 7 written by user 42; - each reader has keys: `client.7` for a manager of client 7 who reaches the client level, `author.42` for user 42 at the own level; - the search keeps the documents that share at least one key with the reader. The keys of every perimeter the reader reaches add up, so one filter gives the union of the perimeters, with the [levels](https://laravel-access-control.lomkit.com/essentials/levels) and the [boundary](https://laravel-access-control.lomkit.com/search/overview#the-boundary) applied as in SQL. ## The model Use `ControlledSearchable` instead of Scout's `Searchable`: the trait includes it. `toSearchableArray()` does not change: the keys are added to each document as Scout metadata, the way Scout adds `__soft_deleted`. A model that overrides `makeSearchableUsing()` returns `$this->withAccessKeys($models)`, or its documents carry no keys and no controlled search finds them: ```php public function makeSearchableUsing(Collection $models): Collection { return $this->withAccessKeys($models->load('tags')); } ``` Calling `controlled()` on the search of a model that still uses `Searchable` throws `MissingControlledSearchableException`. ## Search keys Each perimeter that restricts rows declares its keys with `searchKeys()`, at the end of its chain: ```php ->searchKeys( name: 'client', row: fn (Post $post) => $post->client_id, reader: fn (User $user) => $user->client_id, ) ``` - `name` is required: lowercase letters, digits and underscores, unique in the control. Each key is prefixed with it, such as `client.7`, so two perimeters never open each other's rows. An invalid name throws `InvalidSearchKeyNameException`, a duplicate `DuplicateSearchKeyNameException`. - `row` gives the keys of a row, when it is indexed. `reader` gives the keys of a reader, at each search. - Each side returns a value, a list of values or a list of tuples: `[3, 7]` gives `client.3` and `client.7`, `[['fr', 7]]` gives `client.fr.7`. A value is an int, a string or a backed enum; anything else throws `InvalidSearchKeyValueException`. - `null` gives no key, never a key that matches `null`. A reader without any key finds nothing. ### Relations A `row` callback that reads a relation declares it in `load`: ```php ->searchKeys( name: 'shared', row: fn (Post $post) => $post->sharedWith->modelKeys(), reader: fn (User $user) => $user->id, load: ['sharedWith:id'], ) ``` The relations are loaded once per indexed batch, on a copy of the rows, and the keys are computed with lazy loading disabled: a relation read without `load` throws `UndeclaredSearchKeyRelationException`. When that relation changes, the documents must be indexed again: see [Keeping the keys fresh](https://laravel-access-control.lomkit.com/search/keeping-the-keys-fresh). ### The decision context The `reader` callback may take the `AccessContext` as its second parameter, the object that the hooks of a perimeter class receive. A key that depends on the brand of the request reads it from the [decision context](https://laravel-access-control.lomkit.com/essentials/readers#the-decision-context): ```php use Lomkit\Access\AccessContext; ->searchKeys( name: 'author', row: fn (Post $post) => [[$post->brand_id, $post->author_id]], reader: fn (User $user, AccessContext $context) => [[$context->decisionContext()['brand'], $user->id]], ) ``` - The ability of this context is always `view`: a search finds the rows the reader may view. - The `row` callback never receives a context, since rows are indexed outside any request. The context part of a row key comes from a column of the row. - A second parameter that cannot receive an `AccessContext`, or a third parameter without a default value, throws `InvalidSearchKeyReaderException`. ### Levels and unrestricted perimeters - In a `Levels::of()` group, only the highest level the reader reaches gives its keys, as in the queries. - An [unrestricted](https://laravel-access-control.lomkit.com/essentials/perimeters#unrestricted-perimeters) perimeter gives no key filter: the search keeps every document inside the boundary. It takes no search keys: declaring them throws `UnrestrictedPerimeterCallbackException`. - A perimeter that applies to the reader but declares no search keys adds no row to the search, which is then narrower than the query, never wider. `php artisan access:check` reports it as `perimeter_without_search_keys`. ## The boundary A [boundary](https://laravel-access-control.lomkit.com/essentials/boundaries) declared with `Boundary::where()` gives its search keys from the same declaration. A boundary class declares them in a `searchKeys()` method: ```php [app/Access/Boundaries/TenantBoundary.php] use Illuminate\Database\Eloquent\Model; use Lomkit\Access\Search\SearchKeys; class TenantBoundary extends Boundary { protected function searchKeys(): ?SearchKeys { return SearchKeys::of( name: 'tenant', row: fn (Model $row) => $row->tenant_id, reader: fn (User $user) => $user->tenant_id, ); } // scope() and includes() as on the Boundaries page } ``` - The `reader` callback of `SearchKeys::of()` may take the `AccessContext` as its second parameter too, so a boundary that reads the brand of the request finds the same rows in SQL and in a search. - A controlled search on an engine that stores documents throws `UnsearchableBoundaryException` when the boundary class has no `searchKeys()`. - A reader whose boundary value is `null` finds nothing. ## The documents Each document carries two more attributes: | Attribute | Content | | ----------- | ----------------------------------------------------------------- | | `_access` | the keys of the row for every perimeter that declares search keys | | `_boundary` | the keys of the row for the boundary | A document is found when it shares a key with the reader in `_access`, unless the reader is unrestricted, and in `_boundary`, when the control has a boundary. The engine never receives a key as you declare it: each key leaves the application as a digest of 32 lowercase hexadecimal characters, in the documents, in the filters and in the [browser tokens](https://laravel-access-control.lomkit.com/search/from-the-browser) alike, so every engine compares it exactly (see [Engines](https://laravel-access-control.lomkit.com/search/engines#why-digests)). The keys stay readable in the application: the failures of [`assertSearchAgrees()`](https://laravel-access-control.lomkit.com/testing-and-tooling/testing#the-search) list them. ## Searching The search of a `ControlledSearchable` model says whether it is controlled: ```php Post::search('budget')->controlled()->paginate(25); // the posts the signed-in user may view Post::search('budget')->controlledFor($user)->get(); // for a named reader: jobs, listeners, commands Post::search('budget')->uncontrolled()->paginate(25); // every post, on purpose: back office, exports Post::search('budget')->paginate(25); // throws UndeclaredSearchScopeException ``` - A search that runs without `controlled()`, `controlledFor()` or `uncontrolled()` throws `UndeclaredSearchScopeException`. Declaring two of them throws `ConflictingSearchScopeException`. - Without a signed-in user, with `controlledFor(null)`, or for a reader that no perimeter allows, a controlled search returns an empty page without calling the engine. - A search always finds the rows the reader may **view**. `controlled()` and `controlledFor()` take no ability: one given after the reader throws `UnsearchableAbilityException`. Search, then decide the other abilities on the results with [`withAbilities()`, `Access::preload()` or `reachableKeys()`](https://laravel-access-control.lomkit.com/digging-deeper/batched-decisions). A search callback, such as `Post::search('budget', fn ($client, $query, $options) => ...)`, receives the options that hold the access filter: pass them on to the engine, never rebuild them. ## Next steps - Declare the two attributes in the settings of your engine: [Engines](https://laravel-access-control.lomkit.com/search/engines). - Reindex the documents when the data their keys read changes: [Keeping the keys fresh](https://laravel-access-control.lomkit.com/search/keeping-the-keys-fresh). - Prove that the search finds the rows of the query: [`assertSearchAgrees()`](https://laravel-access-control.lomkit.com/testing-and-tooling/testing#the-search). # Engines ## Index settings Declare `_access` and `_boundary` as filterable in the settings of each searchable model. `Access::searchFilterables()` returns `['_access', '_boundary']`: ```php [Meilisearch] // config/scout.php 'meilisearch' => [ 'index-settings' => [ Post::class => [ 'filterableAttributes' => [...Access::searchFilterables(), 'status'], ], ], ], ``` ```php [Typesense] // config/scout.php 'typesense' => [ 'model-settings' => [ Post::class => [ 'collection-schema' => [ 'fields' => [ // your fields ['name' => '_access', 'type' => 'string[]'], ['name' => '_boundary', 'type' => 'string[]'], ], ], ], ], ], ``` ```php [Algolia] // config/scout.php 'algolia' => [ 'index-settings' => [ Post::class => [ 'attributesForFaceting' => ['filterOnly(_access)', 'filterOnly(_boundary)'], ], ], ], ``` ```php [Turbopuffer] // config/scout.php, the schema that Scout sends with each write 'turbopuffer' => [ 'model-settings' => [ Post::class => [ 'schema' => [ '_access' => ['type' => '[]string', 'filterable' => true], '_boundary' => ['type' => '[]string', 'filterable' => true], ], ], ], ], ``` Then push the settings and index the documents: ```bash php artisan scout:sync-index-settings php artisan scout:import "App\Models\Post" ``` Turbopuffer sets the type of an attribute on its first write and cannot change it: declare the schema before the first write, or delete the namespace (`scout:flush`) and import it again. ### Why digests Each key leaves the application as a digest of 32 lowercase hexadecimal characters. Search engines do not compare indexed strings verbatim: Typesense drops symbols such as `.` and `_` and cuts values at 100 characters, so `author.1.23` would match `author.12.3`, and Meilisearch cuts a stored value at 468 bytes. A digest has a fixed length and no symbol, so every engine compares it exactly, and the engines need no setting for it: no `symbols_to_index` or `token_separators` on Typesense. ## Supported engines | Engine | Controlled search | | ------------------------------- | ------------------------------------------------------- | | Algolia, Meilisearch, Typesense | Filtered with `whereIn` on `_access` and `_boundary` | | Turbopuffer | Filtered with its native `ContainsAny` operator | | `database` | The control's SQL inside the search query, without keys | | `null` | Accepted: it finds nothing | | `collection` | Refused: it paginates before it filters | | Any other engine | Refused, unless you trust it | The package checks the engines with `instanceof`, so a subclass of a supported engine is trusted as it is. > **Warning:** A subclass keeps the duties of a [trusted engine](https://laravel-access-control.lomkit.com/search/engines#trusting-another-engine): it sends the options it receives, the access filter included, on every read path, as `...$options` does in the [multi-search engine](https://laravel-access-control.lomkit.com/search/engines#readers-with-many-keys) below. The package does not check what a subclass overrides. ### The `database` engine The `database` engine searches with SQL: a controlled search applies the control's SQL inside the search query, through Scout's `query()` callback, which still runs the callback you pass to `query()`. No keys are computed for it. It is also the engine for your tests: the `collection` engine throws `UnsupportedSearchEngineException` on a controlled search. ### Trusting another engine Any other engine throws `UnsupportedSearchEngineException`: an engine that ignored `whereIn` would return every document. When your engine filters correctly, trust it in the `boot()` method of a service provider: ```php Access::trustSearchEngine(ElasticsearchEngine::class); ``` A trusted engine must: - render `whereIn` on an array attribute as "at least one element in common", and AND the fields together, `_boundary` with `_access`; - compare each value as a whole string; - apply the `whereIns` of the search on every read path: `get()`, `paginate()`, `simplePaginate()`, `keys()`, `raw()` and `cursor()`; - write `scoutMetadata()` with each document, as the Meilisearch and Typesense engines do, or no key is indexed; - for laravel-rest-api, have an engine profile that implements `MatchesStringLists`, or its searches throw `UnsupportedRestSearchException`. It needs nothing for a reader who reaches nothing: the package never calls the engine for them. ## Your own filters Your `where()` and `whereIn()` clauses narrow a controlled search on every engine. Filters passed through `options()` behave differently on each engine: - **Typesense.** A `filter_by` from `options()` or `typesenseSearchParameters()` is combined with the access filter as `() && ()`, on every read path and in a search callback, so it can only narrow the results. Your filter must end on its own: a filter that is not a string, or that leaves a backtick-quoted value, a geo filter, a reference or an object filter open, throws `UncombinableSearchFilterException`. - **Meilisearch and Algolia.** Scout sends its own filter, built from the `where()` and `whereIn()` clauses and the access filter, in place of the `filter` (Meilisearch) or `filters` (Algolia) of `options()`. Put your conditions in `where()` and `whereIn()`. Algolia still ANDs the `facetFilters` and `numericFilters` of `options()`. - **Turbopuffer.** The access filter is added to the native filters of `options['filters']`, joined with `And`, and applied again when the search runs, so a later `options()` or `whereIn()` cannot remove it. Some engine features would show documents that the filter does not keep, so a controlled search turns them off: - Typesense: `filter_curated_hits` is always `true`, so pinned hits and curated documents go through the filter. Natural-language search (`nl_query`) throws `NaturalLanguageSearchException`; do not use a preset that turns it on for a controlled model. - Algolia: `enableRules` and `enableABTest` are always `false`, since a rule can promote records whatever the filters and an A/B test can answer from another index. An unrestricted reader without a boundary has no access filter: their search is sent as you wrote it, with these features on. ## Readers with many keys A reader with many keys sends a long filter. Scout's Typesense engine searches with a GET request, and Typesense refuses a query string longer than 4,000 encoded characters with HTTP 400: the search fails, it never shows a row too many. Each key costs about 36 encoded characters, so a search holds about 100 keys, `_boundary` and `_access` together. The keys through a [parent](https://laravel-access-control.lomkit.com/search/through-a-parent) multiply. When your readers hold more, search through Typesense's `multi_search` endpoint, which takes the filter in a POST body, with a subclass of Scout's engine registered under the `typesense` driver. It needs Scout 11.7 or later: ```php use Laravel\Scout\Builder; use Laravel\Scout\EngineManager; use Laravel\Scout\Engines\TypesenseEngine; use Typesense\Client; use Typesense\Documents; class MultiSearchTypesenseEngine extends TypesenseEngine { protected function executeSearch(Builder $builder, Documents $documents, array $options): mixed { $results = $this->typesense->getMultiSearch()->perform([ 'searches' => [[...$options, 'collection' => $builder->index ?? $builder->model->searchableAs()]], ]); $result = $results['results'][0] ?? []; if (isset($result['error'])) { throw $this->marshalMultiSearchException($result); } return $result; } } // In the boot() method of a service provider resolve(EngineManager::class)->extend('typesense', fn () => new MultiSearchTypesenseEngine( new Client(config('scout.typesense.client-settings')), config('scout.typesense.max_total_results', 1000), config('scout.typesense'), )); ``` The subclass is trusted without `Access::trustSearchEngine()`, since it passes the options it receives, the access filter included, to the engine. Its browser tokens keep working, and it covers the searches of laravel-rest-api too. Algolia accepts at most 1,000 filters in a query, so a reader with more keys than that cannot search an Algolia index. ## The engine is the only barrier A controlled search shows what the index says. An index that lags behind can show a row that just left the reader's perimeters until the row is indexed again, and documents keep the keys of a former rule until they are reindexed. [Keeping the keys fresh](https://laravel-access-control.lomkit.com/search/keeping-the-keys-fresh) covers what reindexes them. # Keeping the keys fresh The keys of a document are computed when it is indexed. Scout indexes a document again when its own model is saved. When a key reads **another model**, such as the client of the project of a post, a change of that model leaves the documents with their former keys: a former key can show a document to a reader who lost access. ## `reindexWhen()` Declare what reindexes the documents on the perimeter whose keys read the other model, after `searchKeys()`: ```php ClientPerimeter::new() ->allowed(fn (User $user, Ability $ability) => $user->client_id !== null && $user->can("{$ability} client posts")) ->query(fn (Builder $query, User $user) => $query->whereRelation('project', 'client_id', $user->client_id)) ->searchKeys( name: 'client', row: fn (Post $post) => $post->project->client_id, reader: fn (User $user) => $user->client_id, load: ['project:id,client_id'], ) ->reindexWhen(Project::class, changed: ['client_id'], rows: fn (Project $project) => $project->posts()), ``` When a project changes client, a job reindexes its posts, in chunks, after the commit. - The rows are reindexed when a `Project` is updated and one of the `changed` attributes changed, as Eloquent's `wasChanged()` compares them, and when a `Project` is created, deleted, soft deleted, force deleted or restored. A save that changes no listed attribute queues nothing. - `rows` receives the project and returns a query or a relation of the controlled model. The rows of the project's previous state are reindexed too, which matters when the watched model holds the link, such as an assignment moved from one post to another. - A perimeter may watch several models, with one `reindexWhen()` each. ### The job - It is queued after the commit, always, whatever Scout's `after_commit` option, on Scout's queue connection and queue (`scout.queue`). Without a queue, it runs synchronously after the commit. A rolled back transaction queues nothing. - It reindexes the rows in chunks of `scout.chunk.searchable`, through Scout, and removes from the index the rows whose `shouldBeSearchable()` is now `false`. - It carries no full copy of the watched model: its key, and for an update the previous values of the `changed` attributes. For a deleted model, it carries its attributes without the `$hidden` columns, so a `rows` callback must not read a hidden attribute. - Inside `withoutSyncingToSearch()` of the controlled model, nothing is queued. ### Discovery A queue worker that only updates a project must know that posts depend on it, without building `PostControl`. The package listens to the `created`, `updated`, `deleted` and `restored` events of every model and looks up the controls that watch it: about a microsecond for a model that nobody watches. - A control that declares `reindexWhen()` must be [discovered](https://laravel-access-control.lomkit.com/essentials/controls#discovery), in `app/Access/Controls` or a directory passed to `Access::discoverControlsIn()`. A control linked only by `#[ControlledBy]` throws `UnwatchableReindexException` when it is built. - So does a control whose model does not use `ControlledSearchable`, unless a searchable child inherits its keys: see [Searching through a parent](https://laravel-access-control.lomkit.com/search/through-a-parent). - `php artisan access:cache` caches the watched models with the controls, and the cache is used as it is: run it in every deployment, which `php artisan optimize` does. A stale cache throws `UnwatchableReindexException` when a control whose `reindexWhen()` it does not know is built. ### Errors | Mistake | Exception | | --------------------------------------------------------------------------------------------------------------------- | ----------------------------------- | | `reindexWhen()` before `searchKeys()` on the perimeter, or without it | `ReindexWithoutSearchKeysException` | | A class that is not an Eloquent model | `InvalidReindexModelException` | | An empty or blank attribute in `changed` | `InvalidReindexAttributesException` | | A `rows` callback that does not accept the model, or returns anything but a query or relation of the controlled model | `InvalidReindexRowsException` | | The same model watched twice, or a parent or child class of a watched model | `DuplicateReindexException` | ## Pivots A key that reads a many-to-many relation, such as the users a post is shared with, is kept fresh by a custom pivot that uses the `ReindexesSearch` trait: ```php use Illuminate\Database\Eloquent\Relations\Pivot; use Lomkit\Access\Search\ReindexesSearch; class PostShare extends Pivot { use ReindexesSearch; } ``` ```php [app/Models/Post.php] public function sharedWith(): BelongsToMany { return $this->belongsToMany(User::class)->using(PostShare::class); } ``` ```php [app/Models/User.php] public function sharedPosts(): BelongsToMany { return $this->belongsToMany(Post::class)->using(PostShare::class); } ``` - `attach()`, `detach()`, `sync()`, `toggle()` and `updateExistingPivot()` on a relation that uses the pivot fire its events, and each event reindexes the linked models that use `ControlledSearchable`. - Declare `->using(PostShare::class)` on **both sides** of the relation: otherwise `attach()` and `detach()` from the other side write the pivot table with a plain query, fire no event, and the documents keep stale keys. `access:check` reports a relation that reaches the table without it (`pivot_without_using`). - The job is unique per document and queued after the commit: fifty attaches queue one job per post. Without a queue, the jobs run as the pivots are written, so wrap a bulk change in `DB::transaction()` to reindex each document once. - A pivot written outside its relation, such as `PostShare::create([...])`, does not know the models it links: the write throws `UnresolvablePivotException` before it reaches the database. A pivot that links no `ControlledSearchable` model throws `MissingControlledSearchableException`. - The pivot keys must reference the primary keys of the models: a relation with a custom `parentKey` or `relatedKey` is not supported. ## What Eloquent cannot see A write without Eloquent events reindexes nothing. Reindex the rows yourself, through Scout: ```php Post::where('project_id', $id)->update(['author_id' => $newAuthor]); // a mass update fires no event Post::where('project_id', $id)->searchable(); // Scout reindexes them in chunks $post->sharedWith()->attach($user); // a plain pivot, without ReindexesSearch $post->searchable(); ``` The same goes for `DB::table()` writes, `Model::withoutEvents()`, `withoutSyncingToSearch()`, pivot queries such as `newPivotStatement()`, and cascades or `SET NULL` done by the database. ## The document's own model The model of the document needs nothing: Scout reindexes it when it is saved. When the model overrides `searchIndexShouldBeUpdated()` and it returns `false`, the package compares the keys of the row before and after the save, after the commit, each state with its own `load` relations, and reindexes the document when they differ. Keep your override for the other attributes. Turn on Scout's `after_commit` option, so that Scout's own indexing never writes the keys of a change that is rolled back: ```php [config/scout.php] 'after_commit' => true, ``` ## After a deployment Reindex each time the `row` side of a key or the boundary changes, as after a change of `toSearchableArray()`: ```bash php artisan scout:sync-index-settings php artisan scout:import "App\Models\Post" ``` - `scout:import` updates the documents in place, and until it has run they keep the keys of the former rule. When you narrow a rule to close an access, run it right away; to close it at once, run `scout:flush` before `scout:import`. - With Typesense, delete the collection first (`php artisan scout:delete-index posts`) when its schema changes, so that it is created again with the new fields. - A change of the `reader` side needs no reindex: the keys of a reader are computed at each search. ## The window Freshness has a limit: between a change and the end of its job, the documents keep their former keys. Without a queue, the window closes right after the commit. With one, it lasts as long as the backlog of the queue, and a failed job leaves the keys stale until it is retried or the rows are reindexed. # Exceptions and dates ## Keys only add rows A document is found when it shares a key with the reader, and nothing in the filter removes a document that a key found. There is **no negative key**: a rule with an exception, such as a stand-in who sees the posts of the author they stand in for except some sectors or some posts, becomes a positive key. A `whereNotIn` would not do: a reader sees the union of what each of their perimeters grants, and a global `whereNotIn` would also remove the rows that another perimeter grants. A negation also fails open: a document indexed before its exclusion, or whose exclusion is not reindexed yet, does not carry the excluded value and passes a `NOT IN`. A missing positive key hides the row instead. ### An exception on a dimension of the row When the exception is on a finite dimension of the row, such as a sector, a category or a status, the reader gets the complement of their exclusions: one key per sector they may see. ```php StandInPerimeter::new() // allowed() and query() with the exclusions, as in SQL ->searchKeys( name: 'stand_in', row: fn (Post $post) => [[$post->author_id, $post->sector_id]], reader: fn (User $user) => $user->standingInFor->flatMap( fn (StandIn $standIn) => array_map(fn (int $sector): array => [$standIn->principal_id, $sector], $standIn->allowedSectorIds()), )->all(), ), ``` `standingInFor` stands for the stand-ins the reader holds, and `allowedSectorIds()` for every sector of your application minus the ones the stand-in excludes. Nothing is reindexed when an exclusion changes, since the keys of a reader are computed at each search. ### An exception on specific rows When the exception is on specific rows, such as a table of excluded posts, each row lists the readers who see it through the perimeter, and the reader has one key, their own id: ```php StandInPerimeter::new() // allowed() and query() with the exclusions, as in SQL ->searchKeys( name: 'stand_in', row: fn (Post $post) => $post->author->standIns ->reject(fn (StandIn $standIn) => $standIn->excludes($post)) ->pluck('stand_in_id') ->all(), reader: fn (User $user) => $user->id, load: ['author.standIns.exclusions'], ) ->reindexWhen(StandIn::class, changed: ['principal_id', 'stand_in_id'], rows: fn (StandIn $standIn) => Post::where('author_id', $standIn->principal_id)) ->reindexWhen(StandInExclusion::class, changed: ['post_id'], rows: fn (StandInExclusion $exclusion) => Post::whereKey($exclusion->post_id)), ``` A new stand-in reindexes the posts of the author, an exclusion reindexes one post. Until its job has run, the stand-in who excludes the post still finds it: see [the window](https://laravel-access-control.lomkit.com/search/keeping-the-keys-fresh#the-window). When neither form fits, such as an exclusion that depends on the time, keep the model in SQL: search it with the `database` engine or with a controlled query. ### Testing the exceptions Check the recipe with [`assertSearchAgrees()`](https://laravel-access-control.lomkit.com/testing-and-tooling/testing#the-search) on a stand-in and rows that cover each case: rows of an excluded sector, an excluded row, and an excluded row that another perimeter grants, such as a post of a sector that the stand-in also manages. That last row must be found: it proves that the search keeps the union of the perimeters. ## Rights that depend on the date The keys of a row are computed when it is indexed, the keys of a reader at each search. **Read the clock in `reader`, never in `row`.** A row key computed from `now()`, such as the users whose loan of a vehicle is active, stays in the index after the loan ends, and is missing before it starts, until the row is indexed again. When the period ties the reader to something the row names without a date, such as a loan, an assignment to a site or a delegation from an author, key the row by that thing, and give the reader the ones whose period is active now: ```php LoanPerimeter::new() ->allowed(fn (User $user, Ability $ability) => $user->can("{$ability} borrowed vehicles")) ->query(fn (Builder $query, User $user) => $query->whereHas('loans', fn (Builder $loans) => $loans ->whereBelongsTo($user) ->where('starts_at', '<=', now()) ->where(fn (Builder $end) => $end->whereNull('ends_at')->orWhere('ends_at', '>=', now())))) ->searchKeys( name: 'loan', row: fn (Vehicle $vehicle) => $vehicle->getKey(), reader: fn (User $user) => Loan::query() ->whereBelongsTo($user) ->where('starts_at', '<=', now()) ->where(fn (Builder $end) => $end->whereNull('ends_at')->orWhere('ends_at', '>=', now())) ->pluck('vehicle_id') ->all(), ), ``` The document carries only the key of the vehicle, neither the user nor the dates, and nothing is reindexed when a period starts or ends. Write the same condition in `query()` and in `reader`, and compare with `now()` from PHP rather than the database's `NOW()`: a database clock in another time zone, or on another server, makes the SQL and the keys disagree. ### What keeps an answer longer The keys of a reader follow the clock wherever they are computed at each search: `controlled()`, `controlledFor()`, a [guarded search](https://laravel-access-control.lomkit.com/search/from-the-browser#through-a-route-of-the-application), laravel-rest-api and `Access::indexReaderKeys()`. Three things keep an answer longer: - A [browser search token](https://laravel-access-control.lomkit.com/search/from-the-browser) keeps the keys of the instant it was issued until it expires. Keep its expiry short. - laravel-rest-api files a kept decision under the `updated_at` of the row, which the end of a period does not touch: leave the abilities that a period decides out of `authorizationCache()`, or shorten their duration. - A long-running console command keeps its [decisions](https://laravel-access-control.lomkit.com/digging-deeper/decisions) for its whole run. Call `Access::forgetDecisions()` at the start of each unit of work. ### When the period belongs to the row When the period belongs to the row and many readers share it, such as the publication window of each post, the reader cannot list the rows: keep the model in SQL, with the `database` engine or a controlled query. A window that only opens, such as an embargo lifted at a date, has a recipe of its own: a scheduled job writes the state into a column when the date passes, `row` and `query()` read that column, and the job reindexes the rows, through the save of the model or a `reindexWhen()` on the model it writes. A job that runs late keeps the rows closed a little longer, never open. ### Testing the periods Test with [`assertSearchAgrees()`](https://laravel-access-control.lomkit.com/testing-and-tooling/testing#the-search) before, during and after each period, and one second on each side of its bounds, with `$this->travelTo()`. The documents do not depend on the clock, so the rows of the test are indexed once. `assertSearchAgrees()` and `assertIndexKeysAgree()` fail when the keys of a row read the clock. # Searching through a parent ```php [app/Access/Controls/CommentControl.php] protected function perimeters(): array { return [ ThroughParent::belongsTo('post', inverse: 'comments'), ]; } ``` ```php [app/Models/Comment.php] class Comment extends Model { use HasControl, ControlledSearchable; } ``` A searchable child declared with [`ThroughParent`](https://laravel-access-control.lomkit.com/essentials/parents) is found through its parent with the rule of the SQL: the parent's boundary **and** the parent's access keys must both open the parent for the reader. `Comment::search('typo')->controlled()` then finds the comments of the posts the reader may view. ## The keys The child's own filter is `_boundary` AND `_access`, and `_access` is a union, so each pair of a parent boundary key and a parent access key becomes one composite key in the child's `_access`: | Keys of the parent | Keys of the child | | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | | Boundary `workspace_id.1`; access `author.7`, `client.3` | `through.post.2.workspace_id.1`, `through.post.2.workspace_id.1.author.7`, `through.post.2.workspace_id.1.client.3` | | No boundary; access `client.3` | `through.post.0`, `through.post.0.client.3` | The reader builds the same keys from the parent's filter: `through.post.2.workspace_id.1.author.7` for an author, and the boundary key alone, `through.post.2.workspace_id.1`, for a reader that the parent does not restrict. - The number after the relation counts the parts of the boundary key, `0` without a boundary, so a key always splits back into one boundary key and one access key. - Nested parents compose: a reply through its thread through its forum carries `through.thread.0.through.forum.0.client.3`. - A child carries, for each parent, the parent's boundary keys times its access keys plus one: usually one key more than the parent has. - `through` is reserved: a perimeter of a control with a `ThroughParent` that names its keys `through` throws `DuplicateSearchKeyNameException`. - Each key is stored as its digest, like every key. The relation is loaded with the parent's own `load` relations when the child is indexed. A soft-deleted parent is not loaded, so its children lose the keys they inherit from it. ## Requirements On a searchable child, the control throws `UnsearchableThroughParentException` when it is built: - when a `ThroughParent` has no `inverse`, or a parent further up the chain has none; - when it delegates `view` to another ability of the parent: a search only knows the keys that open the parent for `view`; - when the parent's boundary has no search form. The control of a searchable child watches its parent and the models its parent watches, so it must be [discovered](https://laravel-access-control.lomkit.com/essentials/controls#discovery), like a control that declares `reindexWhen()`. ## Following the parent The children follow their parent through jobs queued after the commit, unique and in chunks, as for [`reindexWhen()`](https://laravel-access-control.lomkit.com/search/keeping-the-keys-fresh#reindexwhen): - **The parent's keys change.** On each update of the parent, the package compares the parent's keys before and after it, and reindexes the children through `inverse` when they differ. An update that leaves the keys unchanged queues nothing, and creating a parent queues nothing. - **The parent is reindexed by its own `reindexWhen()`.** When a grandparent changes, the children of the rows that the parent's rule reindexes are reindexed too, through every level. The parent needs neither to be searchable nor to be discovered: a control whose model does not use `ControlledSearchable` may declare `reindexWhen()` when a searchable child inherits its keys through a `ThroughParent` with `inverse`. - **The parent is deleted, soft deleted or restored.** Its children are reindexed, and lose or regain the keys they inherit. - **A child moves to another parent.** Scout reindexes the child itself, as any saved model. A foreign key that the database sets to `null` on its own, without an Eloquent event, is not seen: reindex those children yourself. ## Children of several brands The `through` keys carry nothing of the child's own brand. When the control of the parent reads the brands of the request, decide the parent in the brand of each child row with `decidedInRowContext()`: the keys then hold the value of the row after the relation, such as `through.post.in.1.2.workspace_id.1.author.7`. See [Row context](https://laravel-access-control.lomkit.com/digging-deeper/row-context#searching-through-the-parent). ## Testing [`assertSearchAgrees()`](https://laravel-access-control.lomkit.com/testing-and-tooling/testing#the-search) compares the search with the SQL on a searchable child as on any model: ```php $this->assertSearchAgrees(CommentControl::class, readers: [$this->author, $this->manager, $this->admin]); ``` # Search from the browser A front end reaches Meilisearch, Typesense or Algolia in one of two ways: it queries the engine directly with a signed token, or it goes through a route of your application, which adds the reader's filter on the server. Declare which one, once, in the `boot()` method of a service provider: ```php use Lomkit\Access\Access; Access::searchTokens(direct: true); // browsers query the engine with a token from Access::searchToken() Access::searchTokens(direct: false); // browsers go through a route that calls Access::guardSearch() ``` - An application makes one choice: a second declaration that differs from the first throws `ConflictingSearchTokensException`. The same declaration twice is accepted. - `Access::searchToken()` throws `UndeclaredSearchTokensException` until one is declared, and `ProxiedSearchTokenException` under `direct: false`. ## Direct search with a token `direct: true` is safe only on the engine versions below, which keep the filter of the token apart from the filter that the browser sends. The package cannot check the version of your servers: the declaration is your statement that every engine your browsers query meets this table. | Engine | `direct: true` needs | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Typesense | The first release that includes typesense/typesense#3111 (expected 31.0). Older servers do not isolate the filter of the browser from the filter of a scoped key: use `direct: false` with them. | | Meilisearch | 1.0 or later. The filter of a tenant token is applied apart from the filter of the browser. | | Algolia | Not verified by the package. Algolia documents that the browser cannot change the parameters of a secured API key; use `direct: false` for a guarantee that the package verifies. | `Access::searchToken()` signs the reader's filter into a key derived from a search-only key: ```php [app/Http/Controllers/PostSearchTokenController.php] use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Lomkit\Access\Access; use Lomkit\Access\Search\Tokens\SearchTokenKey; class PostSearchTokenController { public function __invoke(Request $request): JsonResponse { $token = Access::searchToken( reader: $request->user(), model: Post::class, key: SearchTokenKey::meilisearch(uid: config('services.meilisearch.search_key_uid'), key: config('services.meilisearch.search_key')), expiresAt: now()->addMinutes(15), ); return response()->json($token); // {"token": "...", "index": "posts", "expires_at": "..."} } } ``` - The token is built for the engine the model searches with: a tenant token for Meilisearch, a scoped search key for Typesense, a secured API key for Algolia. Pass the key of that engine, `SearchTokenKey::meilisearch(uid:, key:)`, `SearchTokenKey::typesense(key:)` or `SearchTokenKey::algolia(key:)`, or `MismatchedSearchTokenKeyException` is thrown. - The filter in the token is the one `controlled()` applies, in the syntax of the engine. A reader that `controlled()` would show an empty page gets a token whose filter asks for a key that no document carries. An unrestricted reader without a boundary gets a token with no filter, over the whole index of the model. - The token keeps the keys of its reader until it expires: a permission change reaches the browser with the next token. The expiry is required, and one that is not in the future throws `PastSearchTokenExpiryException`. Keep it short, from a few minutes to an hour. - `scout.prefix` is part of the index name. `index()` on the token returns the prefixed name, for the front end to query. - On the engine versions of the table above, the browser can narrow its search with its own filter, never widen it. ### The search-only key Never sign with the admin key: a key equal to the one Scout uses (`scout.meilisearch.key`, `scout.typesense.client-settings.api_key`, `scout.algolia.secret`) throws `AdminSearchTokenKeyException`. Create a search-only key for each engine, and read it from your own configuration, such as `config/services.php`: - **Meilisearch:** `POST /keys` with the master key and `{"actions": ["search"], "indexes": ["posts"], "expiresAt": null}`, naming the index of the model with its `scout.prefix`. Pass the `uid` and the `key` it returns. The token is limited to the index of the model. - **Typesense:** `POST /keys` with the admin key and `{"description": "Search posts", "actions": ["documents:search"], "collections": ["posts"]}`, naming the collection of the model with its `scout.prefix`. Pass the `value`, which Typesense returns only once. A scoped key cannot narrow the collections of its parent key, so limit the parent key to the collection of the model. - **Algolia:** in the dashboard, under API Keys, create a key with the `search` ACL and the index of the model, with its `scout.prefix`, or use the search-only API key. The token is limited to the index of the model. Meilisearch and Typesense sign with their official client, `meilisearch/meilisearch-php` or `typesense/typesense-php`, which Scout already needs; without it, `MissingSearchClientException` names the package. Algolia keys are signed by the package. ### Good to know - With `scout.soft_delete` on, the filter of a token leaves out the deleted rows of a model that uses `SoftDeletes`. Declare `__soft_deleted` as an `int32` field of the Typesense collection, or every search of a token fails. - A Typesense token embeds `filter_curated_hits: true`, and an Algolia token with a filter embeds `enableRules=false` and `enableABTest=false`, which the browser cannot turn back on. - Typesense runs its natural-language model before it applies the parameters of a scoped key: do not configure a natural-language search model on a Typesense server that browsers query with tokens. - The `database`, `collection` and `null` engines, Turbopuffer and the engines passed to `Access::trustSearchEngine()` have no browser token: `UnsupportedSearchTokenEngineException`. - `filter()` on the token returns the rendered filter, for logs and tests. Its JSON form holds the token, the index and the expiry only. ## Through a route of the application With `direct: false`, the front end sends the body of its multi-search to a route of your application. The route authenticates the reader, passes the body to `Access::guardSearch()`, and forwards the body it returns to the engine, with a search-only key that stays on the server: ```php [app/Http/Controllers/SearchController.php] use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Http; use Lomkit\Access\Access; class SearchController { public function __invoke(Request $request): JsonResponse { $body = json_decode($request->getContent(), true); $guarded = Access::guardSearch(is_array($body) ? $body : [], $request->user()); $response = Http::baseUrl(config('services.typesense.url')) ->withHeaders(['X-TYPESENSE-API-KEY' => config('services.typesense.search_key')]) ->post('/multi_search', $guarded); return response()->json($response->json(), $response->status()); } } ``` ```php [routes/web.php] Route::post('/search', SearchController::class)->middleware('auth'); ``` Give the search client of the front end, the InstantSearch adapter of your engine, the URL of that route instead of the engine's. - Read the raw body, as above: Laravel's `TrimStrings` and `ConvertEmptyStringsToNull` middlewares rewrite `$request->json()`. - Forward the guarded body only, never the query string or the headers of the browser: a Typesense `preset` in the query string, for instance, replaces the whole body. One exception: with `union: true`, Typesense reads the pagination of the union (`page`, `per_page`, `offset`, `limit` and `limit_hits`) from the query string. Forward those five, as integers, and nothing else. - Return the status of the engine, so that a search the engine rejects stays a client error. - The filter is computed at each request, so a permission change applies at the next search. | Engine | Body | Forward to | Key | | -------------------------- | --------------------- | --------------------------- | ---------------------------------------------------------- | | Typesense | `{"searches": [...]}` | `POST /multi_search` | `X-TYPESENSE-API-KEY` header | | Meilisearch (1.1 or later) | `{"queries": [...]}` | `POST /multi-search` | `Authorization: Bearer` header | | Algolia | `{"requests": [...]}` | `POST /1/indexes/*/queries` | `X-Algolia-Application-Id` and `X-Algolia-API-Key` headers | ### What the guard checks `Access::guardSearch(array $body, ?Model $reader): array` is pure: it calls no engine. - The field that lists the searches tells the engine. A body with none of them, or several, throws `InvalidSearchBodyException`. - Each search names its index (`collection`, `indexUid` or `indexName`), which must be the index of a `ControlledSearchable` model whose control is [discovered](https://laravel-access-control.lomkit.com/essentials/controls#discovery). Any other index throws `UnknownSearchIndexException`, an Algolia replica or a Typesense alias included. Two discovered models searched in the same index throw `AmbiguousSearchIndexException`. - The model must search with the engine of the body, or `InvalidSearchBodyException` is thrown. The engines that have no token throw `UnguardableSearchEngineException`. - The reader's filter is the one `controlled()` applies, added to the filter of the browser: | Engine | Filter of the browser | Sent to the engine | Forced | | ----------- | ------------------------------------------------------------ | ---------------------------------------------------------------- | ------------------------------------------- | | Typesense | `filter_by`, a string that ends on its own | `() && ()` | `filter_curated_hits: true` | | Meilisearch | `filter`, a string or a list of strings and lists of strings | `[, ...]` | | | Algolia | `filters`, a string without backslash that ends on its own | ` AND `, with parentheses around an `OR` | `enableRules: false`, `enableABTest: false` | - The guard accepts only the parameters that narrow, page, rank or format the documents the reader may see, listed below. Any other parameter, including one that differs by its case only, refuses the whole body with `RefusedSearchParameterException`. A filter it cannot combine throws `RefusedSearchFilterException`. A forced parameter replaces whatever the browser sends. - `InvalidSearchBodyException`, `UnknownSearchIndexException`, `RefusedSearchParameterException` and `RefusedSearchFilterException` are HTTP exceptions: Laravel answers `422` with their message and does not report them. - With `scout.soft_delete` on, the filter of a model that uses `SoftDeletes` also leaves out its deleted rows. The parameters left out let the browser choose a key, stored settings (presets, curations, rules, A/B tests), documents that the engine adds to a search, a language model, or the history of another user: set them on the server instead. Typesense natural-language search (`nl_query`) is refused, and so are the rule contexts and curation tags that an InstantSearch `QueryRuleContext` widget sends. Algolia analytics parameters are accepted, so that the InstantSearch insights middleware keeps working: the browser chooses the `userToken`, so do not let Algolia personalization rank a guarded search by it. **Accepted parameters** **Typesense.** Each search: `collection`, `q`, `query_by`, `query_by_weights`, `prefix`, `infix`, `max_extra_prefix`, `max_extra_suffix`, `pre_segmented_query`, `split_join_tokens`, `text_match_type`, `num_typos`, `min_len_1typo`, `min_len_2typo`, `typo_tokens_threshold`, `drop_tokens_threshold`, `drop_tokens_mode`, `enable_typos_for_numerical_tokens`, `enable_typos_for_alpha_numerical_tokens`, `synonym_prefix`, `synonym_num_typos`, `enable_synonyms`, `demote_synonym_match`, `synonym_sets`, `stopwords`, `filter_by`, `filter_curated_hits`, `enable_lazy_filter`, `max_filter_by_candidates`, `validate_field_names`, `hidden_hits`, `sort_by`, `prioritize_exact_match`, `prioritize_token_position`, `prioritize_num_matching_fields`, `facet_by`, `facet_query`, `facet_query_num_typos`, `max_facet_values`, `facet_strategy`, `facet_sample_percent`, `facet_sample_threshold`, `facet_sample_slope`, `facet_return_parent`, `group_by`, `group_limit`, `group_missing_values`, `group_max_candidates`, `page`, `per_page`, `offset`, `limit`, `limit_hits`, `include_fields`, `exclude_fields`, `highlight_fields`, `highlight_full_fields`, `highlight_affix_num_tokens`, `highlight_start_tag`, `highlight_end_tag`, `snippet_threshold`, `exhaustive_search`, `search_cutoff_ms`, `max_candidates`, `use_cache`, `cache_ttl`, `vector_query`, `rerank_hybrid_matches`, `remote_embedding_timeout_ms`, `remote_embedding_num_tries`, `voice_query`. The body takes `searches`, `union` and `remove_duplicates`. A reference to another collection (`$name(...)`) in `filter_by`, a `$` in `include_fields`, `exclude_fields`, `sort_by`, `facet_by` or `group_by`, and a `vector_query` with an `id` are refused. **Meilisearch.** Each search: `indexUid`, `q`, `offset`, `limit`, `page`, `hitsPerPage`, `attributesToRetrieve`, `attributesToCrop`, `cropLength`, `cropMarker`, `attributesToHighlight`, `highlightPreTag`, `highlightPostTag`, `showMatchesPosition`, `filter`, `sort`, `distinct`, `facets`, `matchingStrategy`, `attributesToSearchOn`, `rankingScoreThreshold`, `locales`, `hybrid`, `vector`, `retrieveVectors`, `media`, `personalize`, `showRankingScore`, `showRankingScoreDetails`, `showPerformanceDetails`, and `federationOptions` with `weight` and `queryPosition`. The body takes `queries` and `federation`, with `limit`, `offset`, `page`, `hitsPerPage`, `facetsByIndex`, `mergeFacets`, `distinct`, `showPerformanceDetails` and `personalize`. **Algolia.** Each request: `query`, `similarQuery`, `filters`, `facetFilters`, `optionalFilters`, `numericFilters`, `tagFilters`, `sumOrFiltersScores`, `restrictSearchableAttributes`, `facets`, `facetingAfterDistinct`, `maxValuesPerFacet`, `sortFacetValuesBy`, `facetQuery`, `maxFacetHits`, `page`, `hitsPerPage`, `offset`, `length`, `aroundLatLng`, `aroundLatLngViaIP`, `aroundRadius`, `aroundPrecision`, `minimumAroundRadius`, `insideBoundingBox`, `insidePolygon`, `naturalLanguages`, `queryLanguages`, `ignorePlurals`, `removeStopWords`, `decompoundQuery`, `attributesToRetrieve`, `attributesToHighlight`, `attributesToSnippet`, `highlightPreTag`, `highlightPostTag`, `snippetEllipsisText`, `restrictHighlightAndSnippetArrays`, `minWordSizefor1Typo`, `minWordSizefor2Typos`, `typoTolerance`, `allowTyposOnNumericTokens`, `disableTypoToleranceOnAttributes`, `queryType`, `removeWordsIfNoResults`, `advancedSyntax`, `advancedSyntaxFeatures`, `optionalWords`, `disableExactOnAttributes`, `exactOnSingleWordQuery`, `alternativesAsExact`, `distinct`, `getRankingInfo`, `synonyms`, `replaceSynonymsInHighlight`, `minProximity`, `responseFields`, `percentileComputation`, `attributeCriteriaComputedByMinProximity`, `relevancyStrictness`, `analytics`, `analyticsTags`, `clickAnalytics`, `userToken`, `enableRules` and `enableABTest`, as fields of the request or in its `params` query string, not both. A request also takes `indexName`, `type` and `facet`; the body takes `requests` and `strategy`. A parameter twice in `params`, whatever its case, is refused. ## Stored settings that skip the filter - Meilisearch search rules that pin documents (Enterprise Edition, Meilisearch Cloud) are not verified by the package: do not pin the documents of a controlled model. - Do not declare Meilisearch `foreignKeys` from or to the index of a controlled model: Meilisearch replaces the keys with the documents of the other index. These apply to controlled searches, tokens and guarded searches alike. # Your own search client ## Four ways An application that queries the engine with its own client keeps the access filter in one of four ways: | You need | Use | | ----------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | A multi-search, a vector search or an option that Scout does not expose, on the index of a `ControlledSearchable` model | A search callback: `Post::search('budget', fn ($client, $query, $options) => ...)->controlled()` | | A search that your server proxies for a front end | [`Access::guardSearch()`](https://laravel-access-control.lomkit.com/search/from-the-browser#through-a-route-of-the-application) in your route | | One index per model, written by your own client | A Scout engine of your application: a subclass of Scout's Algolia, Meilisearch, Typesense or Turbopuffer engine, or an engine passed to [`Access::trustSearchEngine()`](https://laravel-access-control.lomkit.com/search/engines#trusting-another-engine) | | An index that is not the index of one Scout model | [`Access::indexKeysOf()` and `Access::indexReaderKeys()`](https://laravel-access-control.lomkit.com/search/your-own-client#an-index-of-your-own) | - The options that a search callback receives hold the access filter of the reader for the index of this model: pass them on to your client, never rebuild them, and never apply them to another index, where keys of the same name may have another meaning. In a multi-search, each model takes the filter of its own search. - Never combine a filter of the package with yours by hand: `filter()` on a [browser token](https://laravel-access-control.lomkit.com/search/from-the-browser) is for logs and tests. - With your own Scout engine, the documents, their freshness, `access:check` and `assertSearchAgrees()` follow as for any engine. ## An index of your own An index that is not the index of one Scout model, such as a collection shared by several models, chunks of documents for a semantic search or an ingestion pipeline, takes its values from two read-only methods: - `Access::indexKeysOf($rows)` gives the values to store on the documents of each row; - `Access::indexReaderKeys($reader, $model)` gives the values that the search of a reader filters on. A common use keeps the list in SQL with `controlledFor()` and asks the engine only for the rows that their content finds, filtered by the keys of the reader so that the documents the reader may not view do not take the top results: ```php use Lomkit\Access\Access; // Indexing: the rows of one model at a time $posts = Post::query()->whereKey($ids)->get(); foreach (Access::indexKeysOf($posts) as $id => $keys) { foreach ($chunks[$id] as $chunk) { $index->upsert([...$chunk, '_access' => $keys['_access'], '_boundary' => $keys['_boundary']]); } } // Searching $keys = Access::indexReaderKeys($request->user(), Post::class); if ($keys->isClosed()) { return []; } $hits = $index->search($query, filters: [ ['_access', 'in', $keys->values()['_access']], ['_boundary', 'in', $keys->values()['_boundary']], ]); ``` `$index` stands for the client of your engine. Declare `_access` and `_boundary` as arrays of strings that the engine filters on, compared as whole values. ### `indexKeysOf()` - It takes the saved rows of one model, as a collection or any iterable, and returns, by the key of each row, `['_access' => [...], '_boundary' => [...]]`. A string key written as a decimal integer, such as `"123"`, comes back as the int `123`, as in any PHP array. - It loads the `load` relations of the keys once for all the rows, and never loads lazily. - It throws `InvalidIndexRowException` for rows of two models, a value that is not a model, an unsaved, deleted or soft-deleted row, and a key that is not an int or a string. ### `indexReaderKeys()` - It returns a `Lomkit\Access\Search\IndexReaderKeys`, with `model()`, `isClosed()` and `values()`, the values of `_access` and `_boundary` as two lists of strings. - The keys of the reader are the ones `controlledFor()` lists the rows with: for `view`, in the current [decision context](https://laravel-access-control.lomkit.com/essentials/readers#the-decision-context). It takes no ability: one given after the model throws `UnsearchableAbilityException`. - A reader that `controlled()` would show an empty page (no reader, no perimeter that allows them, no key, or a `null` boundary value) is **closed**: `isClosed()` is `true`, and each field holds one value that no document carries, so a filter that ignores `isClosed()` still finds nothing. Skip the engine when it is `true`. ### Matching A document matches a reader when it shares at least one value with the reader in `_access` **and** at least one in `_boundary`. - Every open reader has values in both fields, and every document in `_access`, so a filter on both fields is always right: an unrestricted reader holds the value that every document of the model carries, and a model without a boundary gives the same `_boundary` value to its documents and its readers. - The `_boundary` of a document is empty when its row has no boundary value: no reader finds it. - The values are digests of 32 lowercase hexadecimal characters. The morph class of the model is part of each digest, so one collection holds several models without a field of its own: the values of one model never match another model's. A model whose morph class names another model, as a child model of single table inheritance does, throws `SharedMorphClassException`: give it a morph class of its own. - The values never match the documents of a `ControlledSearchable` model, even of the same model: never store or filter one kind with the other. - A change of the morph alias, or the rename of a class without one, changes every value: write the documents again. ### Requirements The model needs a control, not `ControlledSearchable`. Both methods throw: - `MissingControlException` without a control; - `UnsearchableBoundaryException` when the boundary class has no `searchKeys()`; - `PerimeterWithoutSearchKeysException` when a perimeter that is neither unrestricted nor a `ThroughParent` declares no search keys, in the control or in the control of a parent, since the rows it grants would be missing from the index; - `UnsearchableThroughParentException` for a `ThroughParent` that delegates `view` to another ability of the parent, or whose parent has a boundary without a search form. The relation needs no `inverse` on a model that is not `ControlledSearchable`. `access:check` does not check a model indexed only by your own pipeline: call both methods in a test, as [`assertIndexKeysAgree()`](https://laravel-access-control.lomkit.com/testing-and-tooling/testing#an-index-of-your-own) does. ### Freshness The package reindexes nothing outside Scout. A document keeps the values it was written with, and a stale value can show a row to a reader who lost access until the document is written again. Compute the values again and rewrite the documents when what the keys read changes: - the columns that the `row` callbacks and the boundary read, and the models they load through `load`; - the models that a `reindexWhen()` watches, the parent of a `ThroughParent` and what changes its keys, and the pivots that a key reads; - the rules themselves, after a deployment, and the writes that Eloquent does not see. Delete the documents of a row when it is deleted or soft deleted, and write them again when it is restored; a parent deleted or restored changes the keys of its children. [Keeping the keys fresh](https://laravel-access-control.lomkit.com/search/keeping-the-keys-fresh) lists what the package does for a Scout model in each case: your pipeline does the same for its index. The reader side needs nothing, since `indexReaderKeys()` computes the keys at each call. # laravel-rest-api ```php [app/Rest/Resources/PostResource.php] use Lomkit\Rest\Text\ScoutEngine; use Lomkit\Rest\Text\TextSearch; class PostResource extends Resource { public static string $model = Post::class; public function text(): ?TextSearch { return ScoutEngine::make()->withoutPerimeter(); } } ``` With [laravel-rest-api](https://laravel-rest-api.lomkit.com) 3.6 or higher installed, the package registers `Lomkit\Access\Integrations\RestApi\AccessControlExtension` on its own. It applies to every rest-api resource whose model has a control, and leaves the others alone: nothing to write in the resources, no `perimeterQuery()` that calls `controlled()`. The package conflicts with laravel-rest-api before 3.6, which has no extensions. The extension is named `access_control`. ## Rows The rows of a resource are the rows that `controlledFor($user)` finds for `view`, wherever rest-api applies a perimeter: - searches, includes, relation filters, sorts and aggregates; - metrics and the keys of their cache; - the key lookups of `mutate`, `destroy`, `restore`, `forceDestroy` and actions, the rows of queued actions and the rows read again after a write. A guest finds no row, as with `controlled()`. A user that is not an Eloquent model throws `InvalidRestReaderException`, which names its class. `php artisan rest:check` accepts a controlled resource without `perimeterQuery()` or `#[WithoutPerimeter]`: the extension provides its perimeter, shown as `perimeter from access_control`. It also reports a control that cannot be built. rest-api itself still reports a model without a policy: call [`Access::registerPolicies()`](https://laravel-access-control.lomkit.com/essentials/policies) or give the model a policy. ### Conditions that are not access rules Keep the conditions that are not access rules, such as a published flag, in `perimeterQuery()` for the SQL lists and in the perimeter of `ScoutEngine` for the text searches. rest-api applies both, and the extension adds its restriction to them: ```php use Illuminate\Contracts\Database\Eloquent\Builder; use Lomkit\Rest\Fields\Boolean; use Lomkit\Rest\Text\Engine\EngineQuery; use Lomkit\Rest\Text\ScoutEngine; use Lomkit\Rest\Text\TextSearch; class PostResource extends Resource { public function perimeterQuery(Builder $query): Builder { return $query->where('published', true); } public function text(): ?TextSearch { return ScoutEngine::make() ->perimeter(fn (EngineQuery $query) => $query->where('published', '=', true)) ->indexAttributes([Boolean::make('published')]); } } ``` ## Text search rest-api builds its own Scout query, so `controlled()` never runs there: the extension is the access filter of these searches. A resource searched through `ScoutEngine` declares `withoutPerimeter()`, or a perimeter for its other conditions, as above. - On the Scout `database` and `collection` drivers, the rows are restricted in the SQL of the search, with an exact total. - On another engine, the model uses `ControlledSearchable`, and the extension keeps the documents that share a key with the reader in `_access` and `_boundary`, as `controlled()` does. A guest or a reader that no perimeter reaches gets an empty page without calling the engine. Declare the two attributes in the [index settings](https://laravel-access-control.lomkit.com/search/engines#index-settings). - The search throws `UnsupportedRestSearchException` when the model does not use `ControlledSearchable`, when the engine is not supported or trusted, and when the rest-api profile of the engine matches no list of strings. A boundary without a search form throws `UnsearchableBoundaryException`. `rest:check` reports the first two cases and the boundary, with the Scout driver of its environment. The engine is the only barrier: rest-api loads the rows of the page by key, without the SQL restriction, so a row that a stale index still matches is shown until it is indexed again. [Keep the keys fresh](https://laravel-access-control.lomkit.com/search/keeping-the-keys-fresh). ## Row checks Before the policies check rows for an ability, the extension preloads their decisions with [`Access::preload()`](https://laravel-access-control.lomkit.com/digging-deeper/batched-decisions#preloading-loaded-rows), so the gates of a page cost one query per ability, not one per row and ability. It decides nothing itself: the policy still decides each row. The ability goes through `abilityFor()` of the control, so a business gate such as `approve` is preloaded too. rest-api checks `create` on the class, then on the [draft](https://laravel-access-control.lomkit.com/essentials/policies#drafts) of each row that `mutate` creates. A draft is judged in memory only: a perimeter with a `should()` callback or an `includes()` hook, an unrestricted perimeter, or a `ThroughParent` that delegates `create` can grant it. A control whose perimeters are all checked in SQL refuses every creation, and so does a boundary without an in-memory form, such as a boundary class without `includes()`. ## Kept decisions rest-api keeps the decisions of the abilities that a resource lists in [`authorizationCache()`](https://laravel-rest-api.lomkit.com/authorization/decision-cache), filed under the `updated_at` of the row. - The extension adds a hash of the [decision context](https://laravel-access-control.lomkit.com/essentials/readers#the-decision-context) to their key, so a decision kept for one tenant is never read for another. - For an ability that a `ThroughParent` delegates, it adds the `updated_at` of the parent, and of each parent above it, with one query per level for the rows of a page. When a parent changes, the decisions on its children are made again. A parent without `updated_at` keeps no decision on its children. - A parent written with `DB::table()` or inside `Model::withoutTimestamps()` keeps its `updated_at`, and the old decisions stay until the duration runs out. - A perimeter whose `query()` reads another table, or a right that holds during a [period](https://laravel-access-control.lomkit.com/search/exceptions-and-dates#rights-that-depend-on-the-date), changes no `updated_at`: leave these abilities out of `authorizationCache()`, shorten their duration, or call `Rest::forgetAuthorizations()` when that table changes. ## Columns rest-api loads the columns of the fields and of `alwaysSelect()`, and a policy that reads another column throws `MissingColumnException`. List in `alwaysSelect()` the columns that the control reads in memory: the column and the read-only columns of the boundary, the columns of the `should()` callbacks, and `updated_at` for the kept decisions. ```php public function alwaysSelect(): array { return ['workspace_id', 'archived_at', 'author_id', 'updated_at']; } ``` ## Turning it off List the extension in `disabled_extensions` of `config/rest.php`: rest-api then leaves the rows to `perimeterQuery()` and the decisions to the policies alone. ```php [config/rest.php] 'disabled_extensions' => [ \Lomkit\Access\Integrations\RestApi\AccessControlExtension::class, ], ``` > **Warning:** Without the extension, nothing restricts the rows of a controlled resource but its own `perimeterQuery()`. A resource whose `perimeterQuery()` was removed because the extension applied the control reads every row once the extension is disabled. `rest:check` then reports again every resource without a perimeter: give each of them a `perimeterQuery()` before you disable the extension. `AccessControlExtension` is final, so that no subclass can drop the restriction of the rows, the filter of the search engines or the decision context of the kept decisions. To replace the access rules of rest-api, disable it and register an extension of your own: the package then restricts nothing in rest-api, preloads no row check and adds nothing to the key of the kept decisions. `php artisan about` shows whether the extension is enabled: see [Cache and about](https://laravel-access-control.lomkit.com/testing-and-tooling/cache-and-about#the-about-command). # Testing ```php [tests/Feature/PostControlTest.php] namespace Tests\Feature; use App\Access\Controls\PostControl; use App\Models\Post; use App\Models\User; use Illuminate\Foundation\Testing\RefreshDatabase; use Lomkit\Access\Testing\InteractsWithAccess; use Tests\TestCase; class PostControlTest extends TestCase { use InteractsWithAccess, RefreshDatabase; public function test_its_rules_agree(): void { // Give each reader the permissions your application gives it. $admin = User::factory()->create(['client_id' => 1]); // "... all posts" $manager = User::factory()->create(['client_id' => 1]); // "... client posts" $author = User::factory()->create(['client_id' => 1]); // "... own posts" $other = User::factory()->create(['client_id' => 2]); // "... own posts" Post::factory()->create(['client_id' => 1, 'author_id' => $author->id]); Post::factory()->create(['client_id' => 1, 'author_id' => $manager->id]); Post::factory()->create(['client_id' => 2, 'author_id' => $other->id]); $readers = [$admin, $manager, $author, $other]; foreach ($readers as $reader) { $this->assertControlAgrees(PostControl::class, $reader, Post::uncontrolled()->get()); } $this->assertLevelsNest(PostControl::class, readers: $readers); $this->assertSearchAgrees(PostControl::class, readers: $readers); // with Laravel Scout } } ``` The `Lomkit\Access\Testing\InteractsWithAccess` trait adds assertions that compare the ways of deciding with each other, for the readers and the rows of your test. > **Warning:** **A reader without permissions proves nothing.** A reader that no perimeter allows sees no row on every path, so every assertion passes. Give each reader the permissions your application gives it, and seed the rows that each perimeter reaches: the assertions prove the agreement on the rows of the test only. ## The decisions `assertControlAgrees()` checks that every way of deciding gives the same answer, for each ability and each row: ```php $this->assertControlAgrees(PostControl::class, $reader, Post::uncontrolled()->get()); $this->assertControlAgrees(PostControl::class, $reader, $posts, ['view', 'update', 'approve']); ``` It compares four paths: - the Gate, row by row, with no decision kept; - the Gate after `Access::preload()`; - the Gate after `withAbilities()`; - whether `controlledFor($reader, $ability)` lists the row. The abilities default to `view`, `update` and `delete`; pass others as the fourth argument. `create` is compared through the Gate only, since it is judged on drafts, and `viewAny` too, since it decides without a row. The rows must be saved rows of the control's model. A failure names the reader, then each row key and ability that disagree, with the answer of each path: `granted`, a refusal code, or `denied without a code` when no policy decided. The usual causes: - a `should()` callback or an `includes()` hook that describes other rows than its `query()`; - a policy method that adds its own rule, such as an `update()` override that refuses some rows: the Gate then grants fewer rows than `controlled('update')` lists. Move the rule into the control, see [Policies](https://laravel-access-control.lomkit.com/essentials/policies#keep-the-rules-in-the-control). ## The levels `assertLevelsNest()` checks, for each reader and each pair of adjacent levels of every `Levels::of()` group, that no row of the lower level, inside the boundary, is missing from the upper level: ```php $this->assertLevelsNest(PostControl::class, readers: [$author, $manager, $admin]); ``` It reads the rows of the `query()` callbacks for `view`, not the `allowed()` callbacks, and compares them with `not exists` on the key, so a `NULL` in a column cannot hide a missing row. Seed the rows that each level reaches. See [Levels](https://laravel-access-control.lomkit.com/essentials/levels#levels-nest). ## The search `assertSearchAgrees()` checks, for each reader, that the rows the search keys find are the rows of the controlled query: ```php $this->assertSearchAgrees(PostControl::class, readers: [$admin, $manager, $author]); ``` - It computes the keys of the rows and of the readers from the same declarations as the indexing, without any engine, and compares their digests, as the engine receives them. It proves the logic of your keys, not the behaviour of the engine. - A failure lists the readable keys of the reader and of each row in disagreement, the first ten of each list. - A perimeter that applies to the reader without search keys makes it fail: the search would be narrower than the SQL. ### The clock check Before comparing, the assertion checks that each row gets the same keys at any instant, since an index keeps the keys of the instant the row was written. It computes the keys of the rows of the test at the current instant, and again with the clock frozen 400 days earlier and 400 days later, and fails when the keys of a row differ. - The failure names the row, the field and the key rules: a `row` callback that reads the clock, or one that gives other keys each time, such as `first()` on a relation without an order. See [Rights that depend on the date](https://laravel-access-control.lomkit.com/search/exceptions-and-dates#rights-that-depend-on-the-date). - It sees what reads Laravel's clock: `now()`, `Date::now()`, `Illuminate\Support\Carbon::now()`, `Carbon\Carbon::now()` and `Carbon\CarbonImmutable::now()`. It does not see PHP's `time()`, `date()` or `new DateTimeImmutable()`, nor a database `NOW()`. - It catches a clock read only when the keys of a test row change between these instants: give the rows of the test a period that starts or ends within 400 days of the instant of the test. - The clock is set back afterwards, also after a failure: a test that froze it with `travelTo()` keeps its instant. A test that runs controlled searches uses the `database` engine, not `collection`, which refuses them: ```xml [phpunit.xml] ``` ## An index of your own `assertIndexKeysAgree()` checks the same for an [index of your own](https://laravel-access-control.lomkit.com/search/your-own-client#an-index-of-your-own), on a model with or without `ControlledSearchable`: for each reader, `null` included, the rows whose `Access::indexKeysOf()` values meet the `Access::indexReaderKeys()` values in each field must be the rows of `controlledFor()`: ```php $this->assertIndexKeysAgree(PostControl::class, readers: [null, $admin, $manager, $author]); ``` It runs the same clock check as `assertSearchAgrees()`. ## Several brands `assertRowContextAgrees()` checks a parent decided in the context of the child row, with `decidedInRowContext()`. See [Row context](https://laravel-access-control.lomkit.com/digging-deeper/row-context#testing-the-switch). ## Kept decisions in tests The tests need no reset trait: the [kept decisions](https://laravel-access-control.lomkit.com/essentials/readers#kept-decisions) live in a scoped instance of the container, so each test starts with none, and every write through a Laravel connection forgets them, `attach()` and writes under `Event::fake()` included, as long as the connection was opened before `Event::fake()`: a connection opened after it sends its events to the fake and forgets nothing. After a permission changed in memory, such as a `Gate::define()` between two checks, call `Access::forgetDecisions()` before the next check: ```php Gate::define('update own posts', fn (User $user) => false); Access::forgetDecisions(); $this->assertFalse($author->can('update', $post)); ``` ## Pure perimeter lists in tests In tests, the package builds the perimeters of a control again each time it hands it out, and throws `ImpurePerimetersException` when they differ: see [Controls](https://laravel-access-control.lomkit.com/essentials/controls#pure-perimeter-lists). With Laravel Scout installed and without `access:cache`, the first Eloquent write of a test, such as a factory in `setUp()`, builds the control of every discovered `ControlledSearchable` model, to know which writes reindex which documents. Set what `perimeters()` and `boundary()` read before that first write, or read it in the callbacks. # access:check ```bash SCOUT_DRIVER=meilisearch php artisan access:check ``` `access:check` builds every discovered control, declares and verifies its perimeters whatever the environment, and reports what would throw, open or hide rows, or leave search documents stale, before production meets it. Run it in CI with the Scout driver of production: the engine checks use the driver of the environment the command runs in. ```txt controls 2 built from app/Access/Controls cache ................................................................. not cached models ................................................ 2 scanned in app/Models scout driver ........................ meilisearch, from the config of this environment pivots ............ 1 BelongsToMany relation with a declared return type scanned App\Access\Controls\PostControl App\Models\Post #1.1 GlobalPerimeter ........................................ memory, unrestricted #1.2 ClientPerimeter .................................... sql, search keys client #2 SharedPerimeter .................................................... memory boundary ...................... Lomkit\Access\Boundaries\ColumnBoundary, memory, searchable search ................ ControlledSearchable on Laravel\Scout\Engines\MeilisearchEngine policy ................................................ App\Policies\PostPolicy, controlled App\Access\Controls\CommentControl App\Models\Comment #1 ThroughParent [post] ....... sql, update from the parent's update, view from the parent's view boundary ...................................................................... none search ................................................................ not searchable policy ............................. Lomkit\Access\Policies\AutomaticPolicy, automatic problems .................................................................. 1 FAILED ⇂ The [App\Access\Perimeters\SharedPerimeter] perimeter at #2 of the [App\Access\Controls\PostControl] control declares no search keys, so a reader that only this perimeter reaches finds none of its [App\Models\Post] rows in a controlled text search. Declare searchKeys() on the perimeter, or unrestricted() if it reaches every row notes ........................................................................ none ERROR 1 problem found. ``` Each control is listed with its model, its perimeters by position (`#1.2` is the second level of the first group), the mode of each perimeter (`memory` with a `should()` callback, `sql` without), its boundary, its `ThroughParent` relations and their delegated abilities, the search engine of a `ControlledSearchable` model, and its policy: | Policy form | Meaning | | -------------- | ------------------------------------------------ | | `controlled` | A policy that extends `ControlledPolicy` | | `automatic` | Registered by `Access::registerPolicies()` | | `own` | A policy that does not extend `ControlledPolicy` | | `none` | No policy | | `unresolvable` | The Gate throws while it resolves the policy | The command exits with `1` when it finds a problem, `0` otherwise. Notes never change the exit code. ## Problems | Kind | Reported when | | ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `control_failure` | Building a control, its declaration or the verification of its perimeters throws: impure perimeters, empty or nested levels, a `ThroughParent` on a missing relation, a cycle, a parent without control, an invalid delegation, a duplicate search key name, a control without model. The message quotes the exception. | | `duplicate_control` | Two discovered controls, or a discovered control and `#[ControlledBy]`, declare the same model. | | `uncontrolled_model` | A model of the scanned directories uses `HasControl` and has no control. | | `invalid_controlled_by` | `#[ControlledBy]` names a class that is not a control, or the control of another model. | | `stale_control_cache` | The cache maps the models to other controls than the discovered ones. | | `stale_watch_cache` | The controls are cached, and the cache of the watched models is missing, unreadable, or lists other models than the `reindexWhen()` rules of the controls. | | `unresolvable_policy` | The Gate throws while it resolves the policy of a controlled model. | | `policy_without_control` | The policy of a controlled model extends `ControlledPolicy` without `$control`. | | `policy_for_another_control` | That policy names another control than the one of its model. | | `plain_searchable` | A controlled model uses Scout's `Searchable` instead of `ControlledSearchable`. | | `unsupported_search_engine` | The engine of a `ControlledSearchable` model cannot filter a controlled search: not supported nor trusted, the `collection` engine, or an engine that throws when it is built. | | `unsearchable_boundary` | On an engine that stores documents, the boundary has no search form. | | `perimeter_without_search_keys` | On an engine that stores documents, a perimeter that is neither unrestricted nor a `ThroughParent` declares no search keys. The problem names the position of the perimeter. | | `search_freshness` | Something would leave documents stale: Scout's `after_commit` off, `makeSearchableUsing()` overridden without `withAccessKeys()`, a relation that the search keys read and that nothing reindexes. | | `pivot_without_using` | A `BelongsToMany` relation reaches the table of a pivot that uses `ReindexesSearch` without `->using()` it. | | `unreadable_relation` | A relation that the command reads throws when it is read without a database connection. | ## Notes | Kind | Reported when | | ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `inherited_memory_perimeters` | Two discovered controls or more inherit `perimeters()` from a base class whose perimeters have a `should()` callback. | | `policy_outside_control` | The policy of a controlled model does not extend `ControlledPolicy`, so the package cannot check that it names the model's control. | | `model_without_policy` | No policy is registered for a controlled model. | | `ungrantable_drafts` | No perimeter of a control can grant a [draft](https://laravel-access-control.lomkit.com/essentials/policies#drafts): none has a `should()` callback or an `includes()` hook, none is unrestricted, and no `ThroughParent` delegates `create`. | | `boundary_refusing_drafts` | The boundary of a control has no in-memory form, so it refuses every draft. | When a kind has more than five notes, the human output prints them on one line, with their count, the base classes they share and the first three subjects. Problems are never grouped, and `--json` lists every note. No attribute, interface or option silences a note: fix what it reports, or read it in the JSON. ## Options | Option | Effect | | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `--json` | Prints the same report as one JSON document. | | `--only=App\Models\Post` | Checks only these controls, given by model or control class, repeatable. The discovery, the cache and the pivots are always checked. A name that matches no control exits with `2`. | | `--models=app/Domain/Models` | Sets the directories scanned for models that use `HasControl` or `#[ControlledBy]`, `app/Models` by default, repeatable. Globs are accepted, such as `--models='modules/*/src/Models'`, resolved from the working directory. | The scan of `--models` adds what discovery cannot see: the models that use `HasControl` without a control, the controls that a scanned model names with `#[ControlledBy]` outside the discovered directories, which are then checked like the others, and the `BelongsToMany` relations of the scanned models, for `pivot_without_using`. The models of the discovered controls are always checked, wherever they live. ### The JSON report `--json` gives: - `passed`; - `discovery`: `paths`, `cached`, `models`, `scanned`, `scout_driver`; - `controls`: each with `control`, `model`, `perimeters` (`position`, `perimeter`, `mode`, `unrestricted`, `search_keys`, `parent` with `relation`, `delegates` and `allowed`), `boundary` (`boundary`, `mode`, `searchable`), `search` (`searchable`, `engine`) and `policy` (`policy`, `form`); - `pivots`: `relations`; - `problems`: `kind`, `subject`, `position` and `message`; - `notes`: `kind`, `subject` and `message`. There is no runtime list of the controls: for an inventory, in CI or in a review, read `controls[].model` and `controls[].control`, with `--models` covering every directory that holds a controlled model. ## What it does not do The command is read-only: it never writes the cache, runs no query and dispatches no job. It builds the controls, resolves the policies and the Scout engines, and reads the relations without a database connection. - It cannot tell whether a `should()` callback describes the same rows as its `query()`, or reads a relation: [`assertControlAgrees()`](https://laravel-access-control.lomkit.com/testing-and-tooling/testing#the-decisions) proves the first on your test data. - The pivot check only sees the public relation methods that declare a `BelongsToMany` return type, or a subclass such as `MorphToMany`. - A minor release may add problems and notes, so a CI that passed may fail after it, as with the new rules of a linter. # Cache and about ## Caching the controls ```bash php artisan access:cache php artisan access:clear ``` `access:cache` writes the control of each discovered model, and the models that the `reindexWhen()` rules of the controls watch, into `bootstrap/cache`. `access:clear` removes both files. - `php artisan optimize` runs `access:cache`, and `php artisan optimize:clear` runs `access:clear`. - The cache is used as it is, the way Laravel uses its route and event caches: run it again in every deployment, after adding, moving or deleting a control, or adding a `reindexWhen()`. - It runs once every service provider has booted, so it caches the controls of every directory passed to [`Access::discoverControlsIn()`](https://laravel-access-control.lomkit.com/essentials/controls#discovery). - A cached control class that was deleted since is skipped. - `access:check` reports a stale cache: `stale_control_cache` for the controls, `stale_watch_cache` for the watched models. See [access\:check](https://laravel-access-control.lomkit.com/testing-and-tooling/access-check#problems). Without the cache, the package discovers the controls when a model first asks for its control. With Laravel Scout installed, the first Eloquent write of a process also builds the control of every discovered `ControlledSearchable` model, to know which writes reindex which documents: the cache spares that work in production. ## The about command `php artisan about` prints an "Access Control" section: ```bash php artisan about --only=access_control ``` ```txt Access Control ................................................................ Automatic policies ................................................. registered Cache .............................................................. not cached Controls ................................................................... 12 Discovery paths .................................................. app/Access/Controls Scout ...................................................... installed, meilisearch driver Version ........................................................................ 1.0.0 laravel-rest-api ............................... installed, AccessControlExtension enabled ``` | Row | Value | | -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Version` | The installed version of the package. | | `Controls` | The number of controls, read from the cache when it exists, else from the discovery paths. No control is built. When discovery fails, the row reads `discovery failed:` and the first line of the error. | | `Discovery paths` | Every directory the controls are discovered in, relative to the base path: `app/Access/Controls` first, then the ones added with `Access::discoverControlsIn()`. | | `Cache` | `cached` when `access:cache` wrote its file, `not cached` otherwise. | | `Automatic policies` | `registered` after `Access::registerPolicies()`, `not registered` otherwise, or when the application replaced the policy guesser afterwards. | | `Scout` | `not installed`, or the driver of the environment. | | `laravel-rest-api` | `not installed`, `AccessControlExtension enabled`, or `AccessControlExtension listed in rest.disabled_extensions`. | - `--json` gives the same rows under the `access_control` key. - The section is registered when the application runs in the console. - An empty value prints `none`, and a row that cannot be read prints `unavailable:` with the first line of the error: the section never makes `about` fail. Add this section when you report an issue. # Generators ```bash php artisan make:perimeter ClientPerimeter php artisan make:perimeter EditorialPerimeter --hooks php artisan make:control PostControl --model=Post --perimeters=ClientPerimeter --perimeters=EditorialPerimeter php artisan make:control CommentControl --parent=post ``` ## `make:control` Writes a control into `app/Access/Controls`. | Option | Effect | | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `--model`, `-m` | The model of the control: `--model=Post` for `App\Models\Post`, or a fully qualified class such as `--model='Domain\Blog\Post'`. Without it, the model is named after the control: `App\Models\Post` for `PostControl`. | | `--perimeters`, `-p` | A perimeter class of `app/Access/Perimeters`, repeatable. The control gets an `allowed()`, `should()` and `query()` callback for each one, which refuse everything until you write them, except the callbacks of the hooks that the class overrides. | | `--parent` | A `belongsTo` relation of the model, repeatable: writes a [`ThroughParent`](https://laravel-access-control.lomkit.com/essentials/parents) entry for it. | - The command refuses, and writes nothing, when the model is not an Eloquent model class. - The perimeters are listed as loose perimeters, which add up: group the levels of a hierarchy in [`Levels::of()`](https://laravel-access-control.lomkit.com/essentials/levels) yourself. - A perimeter class whose constructor requires arguments, or is not public, is left out with a warning: list it in the control with its named constructor. - The control declares no boundary: add a [`boundary()`](https://laravel-access-control.lomkit.com/essentials/boundaries) method when the model needs one. See [Controls](https://laravel-access-control.lomkit.com/essentials/controls#generating-a-control). ## `make:perimeter` Writes a perimeter class into `app/Access/Perimeters`. - Without option, the class is empty: its rules are the callbacks declared in the control. - `--hooks` generates the protected hooks `allows()`, `includes()` and `scope()`, which refuse everything until you write them, for a rule shared by several controls. Remove `includes()` to check the rows in SQL. See [Perimeter classes](https://laravel-access-control.lomkit.com/essentials/perimeter-classes). ## Stubs Publish the stubs to change what the commands write: ```bash php artisan stub:publish ``` | Stub | Used by | | ---------------------------- | ------------------------ | | `stubs/control.stub` | `make:control` | | `stubs/perimeter.plain.stub` | `make:perimeter` | | `stubs/perimeter.hooks.stub` | `make:perimeter --hooks` | A published stub replaces the one of the package. After an upgrade, publish them again with `php artisan stub:publish --force`, or apply the changes of the package to your copies. # Abilities ```php use Lomkit\Access\Ability; Ability::view(); // also create(), update(), delete(), restore(), forceDelete() Ability::of('approve'); // any business ability $ability->is('view'); // compare by name, with a string or an Ability $ability->name(); // 'view' "{$ability} posts"; // 'view posts' ``` Every decision is made for an ability: what the reader wants to do with the rows. `Lomkit\Access\Ability` is an immutable value object, open to any business ability, that every perimeter callback and hook receives. ## The value object - `Ability::of()` throws `InvalidAbilityException` for an empty name, a name with whitespace, or a name that is not valid UTF-8. - Compare with `is()`, never with `===`: two abilities with the same name are two objects, and an ability restored by `unserialize()` is a new one. - It converts to its name in a string, so a permission reads `"{$ability} client posts"`: `view client posts`, `approve client posts`. - laravel-rest-api has its own `Lomkit\Rest\Authorization\Ability` enum, closed to its standard actions. It is a different type: import the one of the package you call. How the callbacks receive it, and how to type their parameter, is on the [Perimeters](https://laravel-access-control.lomkit.com/essentials/perimeters#the-ability) page. ## From a policy method to an ability The control maps each policy method to an ability with `abilityFor()`: | Policy method | Ability | | ------------------------------------------------------ | ---------------------- | | `viewAny`, `view` | `view` | | `create`, `update`, `delete`, `restore`, `forceDelete` | the same | | any other method, such as `approve` | `Ability::of($method)` | The same mapping serves everywhere a name is given: the [policy](https://laravel-access-control.lomkit.com/essentials/policies), `controlled('update')` and `controlledFor($user, 'approve')`, `withAbilities()`, `Access::preload()`, the abilities of `assertControlAgrees()`, and the row checks of laravel-rest-api. A name that the control cannot map throws `InvalidAbilityException`. To change the mapping, override `abilityFor()` on the control, as [Policies](https://laravel-access-control.lomkit.com/essentials/policies#abilities) shows: the perimeters, the policy and the controlled queries then follow the new mapping, while `controlled()` without an ability still lists `view`. ## Business abilities A business ability, such as `approve`, `export` or `publish`, is decided by the same perimeters as the standard ones: `allowed()` receives `Ability::of('approve')`, so a permission such as `"{$ability} client posts"` reads `approve client posts`. - In a policy, a method that calls `decideByControl()` declares it, with `Draft::of($row)` for a row about to be created: see [Policies](https://laravel-access-control.lomkit.com/essentials/policies#business-abilities). - In a query, list its rows with `Post::controlledFor($user, 'approve')`, and decide a page with `withAbilities(['approve'])`. - A perimeter that grants `view` but not `approve` refuses it in `allowed()`, or narrows its rows in `query()` and `should()` with `$ability->is('approve')`. Without a row, a business ability means "somewhere": only the `allowed()` callbacks run. A policy method that receives a draft passes it on as it is; it never wraps a model in `Draft::of()` itself, or a saved row changed with `fill()` would be judged on its new values. ## Deciding in code Outside a policy, the control decides directly: ```php use Lomkit\Access\Ability; use Lomkit\Access\Access; use Lomkit\Access\Decisions\Draft; $control = Access::controlFor(Post::class); $control->applies($user, Ability::update(), $post); // bool $control->decide($user, $control->abilityFor('approve'), $post); // Illuminate\Auth\Access\Response $control->applies($user, Ability::create(), Draft::of($newPost)); // a draft, judged in memory $control->applies($user, Ability::create()); // without a row: "somewhere" ``` `decide()` returns the same `Response` as the policy, with its [refusal code](https://laravel-access-control.lomkit.com/essentials/policies#refusals). Both ignore the policies, `Gate::before()` included: they give what the control grants. Prefer the Gate in your application code, so that a policy of your own still applies. # Kept decisions Within a request, a queued job or a console command, the package keeps what it decided, so that an `allowed()` that queries runs once per reader, ability and [decision context](https://laravel-access-control.lomkit.com/essentials/readers#the-decision-context), not once per row. The [Readers](https://laravel-access-control.lomkit.com/essentials/readers#kept-decisions) page gives the essentials; this page gives the details. ## What is kept Two kinds of answers, each capped at 10,000 entries, the oldest dropped first: - **The perimeters a reader reaches**, under the reader (its morph class, connection and key), the decision context, the control and the ability: what every `allowed()` callback and `allows()` hook answered, what the boundary's `admits()` answered, the level reached in each group, and, for a `ThroughParent`, the perimeters the reader reaches on the parent, kept the same way under the parent's control. - **The SQL check of each row**, under the reader, the decision context, the model, the key of the row and the ability. The [batched decisions](https://laravel-access-control.lomkit.com/digging-deeper/batched-decisions) fill it too. The policy, `controlled()`, `controlledFor()`, the batches, the search filter and `applicablePerimeters()` read the same kept perimeters, so they always agree within a request. The in-memory checks, `should()`, `includes()` and the in-memory form of the boundary, run on every decision, on the row as stored. A reader without a key, or not saved, is never kept: its perimeters are evaluated again on every decision. ## What forgets them Everything kept is forgotten at once: - after any SQL statement that is not a read, on any connection; - when a transaction rolls back; - once Laravel has handled a request, so two requests of one test share nothing; - at the end of each queued job; - when the application calls `Access::forgetDecisions()`. A **read** is a single statement that starts with `select` or `show`, after spaces and opening parentheses. Every other statement forgets: Eloquent saves and deletes, with or without events (`saveQuietly()`, `withoutEvents()`, and `Event::fake()` on a connection opened before it), mass updates and deletes, `attach()`, `detach()` and `sync()`, `DB::table()`, `DB::statement()` and `DB::unprepared()`. So do the statements that might write without starting with a write: `with`, `explain`, `pragma`, `call`, `set`, a statement that starts with a comment, the schema statements, and a `select` followed by `;` and another statement. ## Laravel's own tables The writes that Laravel makes to its own tables do not forget, so a cache entry, a lock, the rate limiter, a session or a queued job costs no query in production, where these drivers write to the database: - the `table` of each cache store whose driver is `database`, and its `lock_table` (`cache_locks` when unset); - `session.table`, when `session.driver` is `database`; - the `table` of each queue connection whose driver is `database`; - `queue.failed.table`, when its driver is `database` or `database-uuids`; - `queue.batching.table` (`job_batches` when unset), unless batching uses DynamoDB. The package reads them from the configuration, each on the connection it names, the default one when it is `null`. A write is one of them only when it is a single `insert`, upsert, `update` that reads no other table, `delete` or SQL Server `merge` on one of these tables, quoted the way the query builder quotes it. - An application table with the name and the connection of one of them, such as a `Job` model on the `jobs` table that `config/queue.php` declares, never forgets: give it another name or connection. - The list cannot be extended. Write a log of each row after the response (`defer()`, `dispatch()->afterResponse()`), not while the page renders: each write would forget the batched decisions of the page. ## Calling `forgetDecisions()` Call `Access::forgetDecisions()` when a decision changes without a write through a Laravel connection: - a write through another PDO handle, or a database client outside Laravel; - a write by another process, such as a queue worker, a scheduled command or another application, that the current request or job must see; - a write hidden in a statement read as a `select`, such as a function that writes, or `select ... into` in PostgreSQL and SQL Server; - a permission changed without any write, such as a `Gate::define()` in a test. A statement that fails after writing part of its rows does not forget. An attribute of the reader changed in memory, without saving it, does not change what was kept either. ### Long console commands A console command keeps its decisions for its whole run, and never sees a permission revoked by another process. Call `Access::forgetDecisions()` at the start of each unit of work: ```php foreach (Tenant::all() as $tenant) { Access::forgetDecisions(); // ... } ``` The same goes for a right on a period: an `allowed()` that compares with `now()`, and the SQL check of a row through a `query()` that does, keep the answer of the instant they ran. The lists still run `query()` at each call, and the searches compute the reader keys at each call. ### Jobs A queue worker starts each job with no kept decision. A job run with the `sync` connection or `dispatchSync()` shares the kept decisions of the request that runs it. ## The decision context Everything that `allowed()` reads besides the reader belongs in the [decision context](https://laravel-access-control.lomkit.com/essentials/readers#the-decision-context): the current team of a permission package, a tenant or a guard set during the request. A value that changes without being in it reuses the answer given for the previous value until the next flush. laravel-rest-api files the decisions that `authorizationCache()` keeps under the same context: see [laravel-rest-api](https://laravel-access-control.lomkit.com/integrations/laravel-rest-api#kept-decisions). # Batched decisions A page that checks `@can('update', $post)` on each row runs one query per row and ability for the perimeters checked in SQL. Three tools decide many rows at once, and keep the answers for the request, so that `can()`, `@can`, `authorize()` and `Gate::inspect()` then answer without SQL. | You have | Use | | ------------------------------------------ | ------------------- | | A query that loads the page | `withAbilities()` | | Rows already loaded | `Access::preload()` | | Rows already loaded, and you need the keys | `reachableKeys()` | ## `withAbilities()` ```php $posts = Post::controlled() ->withAbilities(['view', 'update', 'delete']) ->paginate(); ``` For each ability, the query selects one `CASE` that returns the verdict of the row: the boundary when it has no in-memory form, then the perimeters checked in SQL. The answers are kept under the reader chosen by `controlledFor()`, or the signed-in user for `controlled()`, and under the current decision context. - It works with `get()`, `first()`, `paginate()`, `simplePaginate()`, `cursorPaginate()`, `chunk()`, `lazy()`, `cursor()` and the eager loads of a controlled relation: ```php User::with(['posts' => fn ($posts) => $posts->controlled()->withAbilities(['update'])])->get(); ``` - It comes after `controlled()` or `controlledFor()`, or throws `MissingControlledReaderException`. - The abilities are names or `Ability` objects. A name goes through [`abilityFor()`](https://laravel-access-control.lomkit.com/digging-deeper/abilities#from-a-policy-method-to-an-ability), and one the control cannot map throws `InvalidAbilityException`. - `controlled()` does not decide `view` by itself: Laravel only groups the conditions of the scope, so an `orWhere()` added after it could bring rows from outside the perimeters. List `view` when the page checks it. - Select the columns with `select()`: the columns passed to `get()` are ignored once `withAbilities()` adds its own. - The extra columns use reserved aliases and are removed from every model right after the query: they never show in `getAttributes()`, `toArray()` or the JSON. To page through the rows a reader may act on, list them with `controlledFor($user, 'update')`, then decide the other abilities on the same rows: ```php $editable = Post::controlledFor($user, 'update') ->withAbilities(['view', 'delete']) ->paginate(); ``` ## Preloading loaded rows ```php use Lomkit\Access\Ability; use Lomkit\Access\Access; Access::preload($user, 'update', $posts); Access::preload($user, Ability::delete(), $posts); ``` `Access::preload($reader, $ability, $rows)` runs one query per ability and per model, in chunks of 1,000 keys, and keeps the answers the same way. - The rows can belong to several controlled models. - Unsaved rows are skipped, since they are refused as `unsaved` without SQL. - A reader without a key, or not saved, is never kept, so preloading for it runs no query. The [laravel-rest-api extension](https://laravel-access-control.lomkit.com/integrations/laravel-rest-api#row-checks) preloads the row checks of each page this way. ## `reachableKeys()` ```php use Lomkit\Access\Ability; use Lomkit\Access\Access; $editable = Access::controlFor(Post::class)->reachableKeys($user, Ability::update(), $posts); ``` `reachableKeys()` returns, in one query, the keys of the rows the reader may act on, in the order of `$rows`. Use it to filter rows that are already loaded, such as the results of a [search](https://laravel-access-control.lomkit.com/search/overview#searching), which always finds the rows the reader may view. ## What a batch holds A batch holds only what the SQL decides, under the perimeters kept for the reader. The in-memory checks still run on every decision, on the row as stored: the in-memory form of the boundary, and the perimeters with a `should()` callback or an `includes()` hook. A perimeter checked in memory can grant a row that the batch answered `outside_rows`, so a batched answer is always the answer of the row-by-row decision. [`assertControlAgrees()`](https://laravel-access-control.lomkit.com/testing-and-tooling/testing#the-decisions) checks it on your test data. With a boundary that has no in-memory form, `withAbilities(['view', ...])` or a preload of `view` also gives the `not_found` answers of the other abilities without a query. A batch is worth its query only while nothing forgets the [kept decisions](https://laravel-access-control.lomkit.com/digging-deeper/decisions#what-forgets-them): a write for each row while the page renders, such as an access log, forgets them, and the next checks query again. # Row checks ## How a row is checked The policy checks a saved row in a fixed order: 1. the in-memory form of the boundary: `Boundary::where()`, or the `includes()` hook of a boundary class; 2. the perimeters that check in memory: a `should()` callback, an `includes()` hook, or `unrestricted()`; 3. only when none of them grants, one SQL query on the row's key, constrained by the OR of the `query()` of every other perimeter the reader reaches, with the boundary inside it when it has no in-memory form. | The reader reaches | Queries for one row | | -------------------------------------------------------------------------------- | ---------------------------------------------------------- | | No perimeter | None: `no_perimeter` | | An unrestricted perimeter, with no boundary or a boundary with an in-memory form | None | | A perimeter with an in-memory form that contains the row | None, or one on the boundary when it has no in-memory form | | Only perimeters without an in-memory form | One, with the boundary in it when it has no in-memory form | The mode never depends on the state of the moment, such as loaded relations, so a decision costs the same number of queries in tests and in production. The SQL check of each row is [kept](https://laravel-access-control.lomkit.com/digging-deeper/decisions) for the request, and the [batched decisions](https://laravel-access-control.lomkit.com/digging-deeper/batched-decisions) decide many rows in one query. A draft is not in the database: only the in-memory forms judge it, and a perimeter checked in SQL never grants it. See [Drafts](https://laravel-access-control.lomkit.com/essentials/policies#drafts). ## Which perimeters apply Inside a control, the protected `applicablePerimeters($reader, $ability)` lists the perimeters that apply to a reader for an ability: the level reached in each group, then the loose perimeters that allow the reader, or an unrestricted perimeter alone. ```php use Illuminate\Database\Eloquent\Model; use Lomkit\Access\Ability; use Lomkit\Access\Perimeters\Perimeter; class PostControl extends Control { public function grantingPerimeter(Model $reader, Post $post): ?Perimeter { foreach ($this->applicablePerimeters($reader, Ability::update()) as $perimeter) { if ($perimeter->admits($reader, Ability::update(), $post)) { return $perimeter; } } return null; } } ``` - It reads the [kept perimeters](https://laravel-access-control.lomkit.com/digging-deeper/decisions#what-is-kept) of the reader, so it agrees with the policy and the queries. - It does not check the boundary against a row: the policy does. - `applicablePerimeters()` is final. Give the methods you add to a control distinctive names, since a minor release may add methods to `Control`. ## Which perimeter grants a row `$perimeter->admits($reader, $ability, $row)` tells whether a perimeter applies to the reader for the ability and contains the row: - in memory, through its `should()` callback or its `includes()` hook; - otherwise with one `exists` query on the stored row, through its `query()`; - never for an unsaved row, which only the in-memory checks judge. `$perimeter->checksInMemory()` tells which of the two it uses, and `checksInMemory()` on a boundary tells whether the boundary has an in-memory form. Never call the hooks of another perimeter, `allows()`, `includes()` or `scope()`, even though PHP lets a perimeter class do it: they skip the admission of the reader by the type of the callbacks and by the `reader` callback of the search keys. Call `admits()`. # Several brands A decision runs under one [decision context](https://laravel-access-control.lomkit.com/essentials/readers#the-decision-context): the one the resolver returns when the decision is made. This page covers the lists that span several brands, companies or tenants in one query. Replace "brand" with the dimension of your application. ## The brand is a value of the row Do not build such a list by switching the decision context between `controlledFor()` calls joined with `orWhere()`. Only the list would follow each branch: `withAbilities()`, the policy, the kept decisions, `Access::preload()` and the row checks of laravel-rest-api run under the context in force, not under the brand of each row. A post of brand B listed through the rights of brand B would be decided for `update` with the rights of brand A, and kept so. When one list spans several brands, the brand is a value of the row, not of the request. Write perimeters that read the brand of the row and filter by the brands where the reader holds the right: ```php [app/Access/Controls/PostControl.php] protected function perimeters(): array { return [ BrandPerimeter::new() ->allowed(fn (User $user, Ability $ability): bool => $user->brandsWhere("{$ability} brand posts") !== []) ->should(fn (User $user, Post $post, Ability $ability): bool => in_array($post->brand_id, $user->brandsWhere("{$ability} brand posts"), true)) ->query(function (Builder $query, User $user, Ability $ability): void { $query->whereIn('brand_id', $user->brandsWhere("{$ability} brand posts")); }), OwnPerimeter::new() ->allowed(fn (User $user, Ability $ability): bool => $user->brandsWhere("{$ability} own posts") !== []) ->should(fn (User $user, Post $post, Ability $ability): bool => $post->author_id === $user->id && in_array($post->brand_id, $user->brandsWhere("{$ability} own posts"), true)) ->query(function (Builder $query, User $user, Ability $ability): void { $query->whereBelongsTo($user, 'author')->whereIn('brand_id', $user->brandsWhere("{$ability} own posts")); }), ]; } ``` `brandsWhere()` stands for a method of your application that returns the brands where the user holds a permission. `Post::controlled()` then lists the posts of every brand of the reader in one query, and the policy, `withAbilities()` and `Access::preload()` decide each row from its own brand, whatever the current one. - **Keep these perimeters out of `Levels::of()`.** A group applies only the highest level the reader reaches, in any brand: a reader who sees every post of brand A and only their own posts of brand B would lose their posts of brand B. Loose perimeters add up, each filtered by its own brands. - **Keep the brand out of the boundary.** `Boundary::where()` holds one value per reader, so a boundary that reads the current brand cuts the list to that brand. Keep in the boundary what is the same for every row the reader may reach, such as the tenant. - Check the result with [`assertControlAgrees()`](https://laravel-access-control.lomkit.com/testing-and-tooling/testing#the-decisions) on posts of several brands. ### One level per brand The loose perimeters already give each brand its own level: in each brand, their union is the highest level the reader reaches there. Never wrap a group, or its levels, in a perimeter that picks the level brand by brand: the package reads only what each perimeter of the list declares. To keep what a group saves, the lower levels left out of the SQL, filter each lower level by the brands where no higher level applies: ```php OwnPerimeter::new() ->allowed(fn (User $user, Ability $ability): bool => $user->brandsOnlyWhere("{$ability} own posts", above: ["{$ability} brand posts"]) !== []) ->should(fn (User $user, Post $post, Ability $ability): bool => $post->author_id === $user->id && in_array($post->brand_id, $user->brandsOnlyWhere("{$ability} own posts", above: ["{$ability} brand posts"]), true)) ->query(function (Builder $query, User $user, Ability $ability): void { $query->whereBelongsTo($user, 'author')->whereIn('brand_id', $user->brandsOnlyWhere("{$ability} own posts", above: ["{$ability} brand posts"])); }), ``` `brandsOnlyWhere()` stands for `brandsWhere()` of the first permission minus the brands of every higher level, whose permissions `above` lists, so each brand is read by one level only. ### Search keys On a searchable model, key these perimeters by the brand of the row and the brands where the reader holds the `view` right: ```php BrandPerimeter::new() // allowed(), should() and query() as above ->searchKeys( name: 'brand', row: fn (Post $post) => $post->brand_id, reader: fn (User $user) => $user->brandsWhere('view brand posts'), ), OwnPerimeter::new() // allowed(), should() and query() as above ->searchKeys( name: 'own', row: fn (Post $post) => [[$post->brand_id, $post->author_id]], reader: fn (User $user) => array_map(fn (int $brand): array => [$brand, $user->id], $user->brandsWhere('view own posts')), ), ``` The key of an own post holds its brand with its author: an author key alone would find the reader's posts in every brand, even one where they hold no right. `Post::search()->controlled()` finds the posts of every brand of the reader, and laravel-rest-api serves the lists and the searches of several brands under one decision context, with its extension as it is. Check with [`assertSearchAgrees()`](https://laravel-access-control.lomkit.com/testing-and-tooling/testing#the-search) on posts of several brands. ## A child read through its parent A [`ThroughParent`](https://laravel-access-control.lomkit.com/essentials/parents) decides its parent under the decision context of the request, and never reads the brand of the child row. With the perimeters above, which read the brand of the row and never the current brand, that changes nothing: a comment is readable wherever its post is. A condition on the comment's own brand and the reader's rights goes in the comment's boundary. It is different when the control of the parent reads the brands from the decision context, such as `['brands' => '1,2']` for a headquarters that reads two brands. The parent is then decided under the whole context, and being readable in any one of its brands is enough. Take a post P readable only in brand B, and a comment of brand A on P under a comment boundary that keeps the brands of the request: under A and B, the comment is listed and granted, since P is readable in B, though neither brand alone grants it. Every path agrees on this wide answer, so the assertions cannot catch it. `decidedInRowContext()` decides the parent, for each child row, within the brand that the row holds: see [Row context](https://laravel-access-control.lomkit.com/digging-deeper/row-context). ### Without the row context Without `decidedInRowContext()`, serve the children of such a parent one brand at a time, with a boundary on the child that keeps its rows to the brand of the request. To show several brands on one page, run one query per brand, switch the decision context between them, and decide everything the page needs on those rows, `withAbilities()`, every `can()` and the API resources that check them, while the context of their brand is in force. Never join those queries with `orWhere()`. laravel-rest-api decides under the context of the request, so there one brand at a time means one brand per request. # Row context A [`ThroughParent`](https://laravel-access-control.lomkit.com/essentials/parents) decides its parent under the decision context of the request. When the control of the parent reads several brands from that context, a child row can be opened by a parent readable only in another brand than its own: [Several brands](https://laravel-access-control.lomkit.com/digging-deeper/several-brands#a-child-read-through-its-parent) shows the case. `decidedInRowContext()` decides the parent, for each child row, within the value that the row holds. Replace "brand" with the dimension of your application. ## Declaring the switch Declare once, in the `boot()` method of a service provider and next to `Access::decisionContextUsing()`, the values that the request covers and how the application acts in one of them. `Brands` stands for the state of your application: ```php [app/Providers/AppServiceProvider.php] use Closure; use Lomkit\Access\Access; public function boot(): void { Access::decisionContextUsing(fn (): array => ['brands' => Brands::requested()->sort()->implode(',')]); Access::rowContextUsing( values: fn (): array => Brands::requested()->all(), within: fn (int|string $brand, Closure $decide): mixed => Brands::actingIn([$brand], $decide), ); } ``` ```php public static function actingIn(array $brands, Closure $callback): mixed { $previous = self::$requested; self::$requested = $brands; try { return $callback(); } finally { self::$requested = $previous; } } ``` - `values` returns the values that the request covers, ints or non-empty strings, exactly as stored in the column of the child rows; an empty list reaches nothing. It must read the same state as the decision context. - `within` switches the application to the single value it receives, every state that the parent reads included (the brands, the team of a permission package, a tenant), calls `$decide` exactly once, and restores the previous state in a `finally` block. - Keep both cheap: they run once per value for each list, and for the first row check of a reader, ability and context in a request. - Only the PHP state is switched: `within` runs while the package builds the SQL, and the query runs after it returns. Keep out of the rules of the parent a state that the database reads, such as a session variable or a row-level security policy. Then name, on the `ThroughParent`, the column of the child row that holds the value: ```php [app/Access/Controls/CommentControl.php] ThroughParent::belongsTo('post', inverse: 'comments') ->decidedInRowContext('brand_id'), ``` ## What it changes The SQL gets one branch per value of the request, each built while `within()` runs for its value: ```sql where ( (comments.brand_id = 'A' and exists (select * from posts where posts.id = comments.post_id and ())) or (comments.brand_id = 'B' and exists (select * from posts where posts.id = comments.post_id and ())) ) ``` - A child row whose value is `null`, or not one of `values`, has no branch: the `ThroughParent` refuses it. Reach such rows through another perimeter. - The policy, the row checks, `withAbilities()`, `Access::preload()` and `reachableKeys()` use the same branches. - A decision without a row is granted when there is a value of the request in which the `allowed()` of the `ThroughParent` accepts and the parent reaches a perimeter. - A draft reads the column from its attributes, like the foreign key. - The decisions on the parent are kept under the context of each value, the same key as a request of that value alone. - `access:check` prints `row context brand_id` on the line of the `ThroughParent`, and `--json` gives `parent.row_context`. Each row gets the answer of its own value alone. That narrows the wide answer only when the rules of the parent grow with the brands: each rule that reads the brands filters the rows by them, and each `allowed()` that reads them accepts as soon as the reader holds the right in one of them. A rule that grants more for fewer brands would open, within one value, a parent that the whole request does not open. No assertion checks it. ## Searching through the parent A searchable child whose `ThroughParent` is `decidedInRowContext('brand_id')` writes the value of the child row after the relation: `through.post.in.1.2.workspace_id.1.author.7` for a comment of brand 1. A child without a value carries no key through that parent. The reader gets, for each value of the request where the `allowed()` of the `ThroughParent` accepts, the keys of the parent computed within that value. See [Searching through a parent](https://laravel-access-control.lomkit.com/search/through-a-parent). ## Errors | Mistake | Exception | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- | | `decidedInRowContext()` without `Access::rowContextUsing()` | `MissingRowContextException`, when the control is built | | `values` returns something else than a list of ints and non-empty strings | `InvalidRowContextValuesException` | | `within` does not call `$decide` exactly once, leaves the decision context changed, decides under the context of the whole request or of another value, or switches two values to the same context | `RowContextSwitchException` | | The column is not a plain column name | `InvalidRowContextColumnException` | | `decidedInRowContext()` twice on one `ThroughParent` | `DuplicatePerimeterCallbackException` | | The `ThroughParent` is a level of `Levels::of()` | `RowContextInLevelsException`: declare it next to the group | ## Testing the switch `assertRowContextAgrees()` compares each row with a request of its value alone, which the test sets up itself through `alone`, without the `within` closure under test: ```php public function test_the_brand_switch_is_complete(): void { foreach ([$this->headquarters, $this->brandManager] as $reader) { $this->assertRowContextAgrees( CommentControl::class, $reader, Comment::uncontrolled()->get(), alone: fn (int|string $brand, Closure $check): mixed => $this->asBrandRequest($brand, $check), ); } } ``` - `alone` receives a value and a callback, sets up every state of a real request of that value alone, calls the callback and restores the state. `asBrandRequest()` stands for that helper of your tests. - For each row whose value is one of the request, the assertion compares the answer under the request with the answer inside `alone`, through the Gate and through `controlledFor()`, for `view`, `update` and `delete` by default (pass others as `abilities`). - It catches a `within` that forgets a state the parent reads, and a perimeter or boundary of the child that reads the brands of the request instead of the brand of the row. It does not check that the rules of the parent grow with the brands. - The control declares exactly one column with `decidedInRowContext()`, and at least one row holds a value of the request. # What is public in 1.x The releases of 1.x follow semantic versioning for what this documentation and the [upgrade guide](https://github.com/Lomkit/laravel-access-control/blob/1.x/UPGRADE.md) describe, and do not mark `@internal`. ## Covered - The classes, and their public and protected methods, that the documentation shows an application calling, extending, implementing or overriding. - The exception classes and the classes they extend, thrown in the cases the documentation gives. Their messages, and the way they are built, are not covered. - The refusal codes of the policies, `unsaved`, `no_perimeter`, `outside_boundary`, `not_found` and `outside_rows`, and the names of the search attributes, `_access` and `_boundary`. - The artisan commands, their options, their exit codes and the JSON of `access:check`. A minor release may add problems and notes to `access:check`, so a CI that passed may fail after it, as with the new rules of a linter. - The assertions of `InteractsWithAccess`, whose signatures do not change in 1.x. A minor release may add checks to them, so a test that passed may fail after it, when the new check reveals a disagreement. - `Access::searchTokens()` and `Access::guardSearch()`, with the bodies the guard accepts and the parameters it forces. A release, even a patch, may refuse a parameter or a filter that turns out to widen what a reader finds: the guard fails closed rather than keep an opening. - `Access::indexKeysOf()`, `Access::indexReaderKeys()`, `IndexReaderKeys` with its `model()`, `isClosed()` and `values()`, and the `assertIndexKeysAgree()` assertion, with the behaviour that [Your own search client](https://laravel-access-control.lomkit.com/search/your-own-client) gives: both fields for each document and each reader, digests of 32 lowercase hexadecimal characters, never an empty list for an open reader nor in the `_access` of a document, and, for a closed reader, one value in each field that is not a digest and that no document carries. The values themselves change as the keys do. ## The classes you extend Your application extends `Perimeter`, `Control` and `Boundary`. A minor release may add methods to them, and a method of the same name in your subclass would then clash: **give the methods you add to your subclasses distinctive names.** Their covered members: | Class | Covered members | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `Perimeter` | `new()`, `allowed()`, `should()`, `query()`, `searchKeys()`, `reindexWhen()`, `unrestricted()`, `admits()` and `checksInMemory()`; the protected hooks `allows()`, `includes()` and `scope()` | | `Control` | `new()`, `abilityFor()`, `decide()`, `applies()` and `reachableKeys()`; the protected `perimeters()`, `boundary()` and `applicablePerimeters()`, and the protected `$model` property, declared by its default value and never assigned elsewhere | | `Boundary` | `where()`, `none()` and `checksInMemory()`; the protected hooks `scope()`, `includes()`, `searchKeys()` and `admits()`; `readOnlyWhenNotNull()` on the boundary that `where()` returns | `ControlledPolicy` gets no new method in 1.x, since the methods of your policy are named after your abilities: it keeps the seven standard abilities, the protected `decideByControl()` and `declaredControl()`, and nothing else. ## Not covered - A class or a method marked `@internal` may change or disappear in any release, whatever its PHP visibility, and so may a public or protected method that the documentation does not describe. Do not call, extend, implement, override or type against them. - The classes behind the artisan commands, the control registry, and the search keys and filters, such as `SearchKeyValues`, `SearchDocuments`, `SearchRules` and `SearchFilter`, are internal. - `AccessServiceProvider` is registered by package discovery: list it in `bootstrap/providers.php` if your application turns the discovery off, and do not extend it. - Calling the protected hooks of another perimeter from a perimeter class is not supported: call [`admits()`](https://laravel-access-control.lomkit.com/digging-deeper/row-checks#which-perimeter-grants-a-row). - The access keys, and their digests in your search indexes, are not an API. They live in your indexes, though: a release that changes them says so in its upgrade notes, with the reindex it needs, even a minor one. `ControlledSearchBuilder` is the builder that `search()` returns on a `ControlledSearchable` model: its `controlled()`, `controlledFor()` and `uncontrolled()` are public. # Use with AI Laravel Access Control 1.0 changed most of its API: controls linked by discovery, levels, boundaries, search keys. A coding assistant that learned from code written for an earlier version can write controls that no longer work. The sources on this page give it the current documentation. ## Laravel Boost skill The package ships a skill for [Laravel Boost](https://laravel.com/docs/boost): a `SKILL.md` file that a coding agent loads when it works on your controls, perimeters, policies or controlled searches. ### Installing the skill The skill is named `laravel-access-control`. It lives in the package at `resources/boost/skills/laravel-access-control/SKILL.md`, so Laravel Boost finds it in `vendor/lomkit/laravel-access-control` once both packages are installed: ```bash composer require laravel/boost --dev php artisan boost:install ``` Select the skill during the installation. After an update of the package, run `php artisan boost:update` so that the agent reads the skill of the installed version. See the [Laravel Boost documentation](https://laravel.com/docs/boost) for its commands and for replacing a package skill with your own. ### What the skill covers The skill applies when a task touches a policy that should be centralized, row-level filtering of Eloquent queries, a child model with the access of its parent, the `make:control`, `make:perimeter` and `access:*` commands, or the classes of the `Lomkit\Access\` namespace. It describes: - controls, their discovery and `#[ControlledBy]`, and the `Access` facade; - perimeters, their callbacks and hooks, levels, boundaries and `ThroughParent`; - the policies, their refusal codes, drafts and business abilities; - the controlled queries and the batched decisions; - the Laravel Scout search: search keys, engines, freshness, browser tokens and an index of your own; - the laravel-rest-api extension, `access:check` and the test assertions; - the pitfalls to flag when reviewing or writing code. ## llms.txt and Markdown pages The site publishes its pages in formats that assistants read directly: | URL | Content | | --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | [`/llms.txt`](https://laravel-access-control.lomkit.com/llms.txt) | The list of every page, with a description and a link to its Markdown copy | | [`/llms-full.txt`](https://laravel-access-control.lomkit.com/llms-full.txt) | Every page in one Markdown file | | `/raw/.md` | The Markdown copy of one page, such as [`/raw/essentials/perimeters.md`](https://laravel-access-control.lomkit.com/raw/essentials/perimeters.md) | Both files cover 1.x only. Give an assistant `llms.txt` and let it open the pages it needs, or give it `llms-full.txt` when it can read a long file. The **Copy page** button at the top of each page copies its Markdown. Its menu copies the link to the Markdown copy, opens it, or opens ChatGPT or Claude with a prompt that points to it. ## GitMCP [GitMCP](https://gitmcp.io) serves a GitHub project as a remote MCP server. Its address for this site, `https://lomkit.gitmcp.io/laravel-access-control-doc`, reads the `llms.txt` of the site, and its tools let the assistant search the docs and fetch the Markdown copy of any page. Add the server to your assistant: ```bash [Claude Code] claude mcp add --transport http laravel-access-control https://lomkit.gitmcp.io/laravel-access-control-doc ``` ```json [Cursor: .cursor/mcp.json] { "mcpServers": { "laravel-access-control": { "url": "https://lomkit.gitmcp.io/laravel-access-control-doc" } } } ``` ```json [VS Code: .vscode/mcp.json] { "servers": { "laravel-access-control": { "type": "http", "url": "https://lomkit.gitmcp.io/laravel-access-control-doc" } } } ``` ## Context7 [Context7](https://context7.com) indexes the documentation of libraries and serves it to coding assistants through its MCP server and its `ctx7` command. Laravel Access Control is listed as [`/lomkit/laravel-access-control-doc`](https://context7.com/lomkit/laravel-access-control-doc), which indexes the 1.x pages of this site. Set it up with `npx ctx7 setup`, then name the library in your prompt: ```txt Show only their own posts to authors, and every post of their client to managers. use library /lomkit/laravel-access-control-doc ```