Search overview
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,
),
),
];
}
use Lomkit\Access\Controls\HasControl;
use Lomkit\Access\Search\ControlledSearchable;
class Post extends Model
{
use HasControl, ControlledSearchable;
}
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.7andauthor.42for a post of client 7 written by user 42; - each reader has keys:
client.7for a manager of client 7 who reaches the client level,author.42for 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 and 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:
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:
->searchKeys(
name: 'client',
row: fn (Post $post) => $post->client_id,
reader: fn (User $user) => $user->client_id,
)
nameis required: lowercase letters, digits and underscores, unique in the control. Each key is prefixed with it, such asclient.7, so two perimeters never open each other's rows. An invalid name throwsInvalidSearchKeyNameException, a duplicateDuplicateSearchKeyNameException.rowgives the keys of a row, when it is indexed.readergives the keys of a reader, at each search.- Each side returns a value, a list of values or a list of tuples:
[3, 7]givesclient.3andclient.7,[['fr', 7]]givesclient.fr.7. A value is an int, a string or a backed enum; anything else throwsInvalidSearchKeyValueException. nullgives no key, never a key that matchesnull. A reader without any key finds nothing.
Relations
A row callback that reads a relation declares it in load:
->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.
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:
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
rowcallback 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, throwsInvalidSearchKeyReaderException.
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 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:checkreports it asperimeter_without_search_keys.
The boundary
A boundary declared with Boundary::where() gives its search keys from the same declaration. A boundary class declares them in a searchKeys() method:
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
readercallback ofSearchKeys::of()may take theAccessContextas 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
UnsearchableBoundaryExceptionwhen the boundary class has nosearchKeys(). - A reader whose boundary value is
nullfinds 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 alike, so every engine compares it exactly (see Engines). The keys stay readable in the application: the failures of assertSearchAgrees() list them.
Searching
The search of a ControlledSearchable model says whether it is controlled:
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()oruncontrolled()throwsUndeclaredSearchScopeException. Declaring two of them throwsConflictingSearchScopeException. - 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()andcontrolledFor()take no ability: one given after the reader throwsUnsearchableAbilityException. Search, then decide the other abilities on the results withwithAbilities(),Access::preload()orreachableKeys().
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.
- Reindex the documents when the data their keys read changes: Keeping the keys fresh.
- Prove that the search finds the rows of the query:
assertSearchAgrees().
Readers
The reader is the model a decision is made for. Learn about readers of several types, the decision context, and the decisions kept for a request.
Engines
Declare the access attributes in Meilisearch, Typesense, Algolia or Turbopuffer, use the database engine, and combine your own filters with the access filter.