Query extensions
Four kinds act on the SQL queries of the package, and ProvidesPerimeter marks a restriction that is the perimeter. They throw Lomkit\Rest\Exceptions\InvalidQueryExtensionException, which names the extension by its name and its class. See Extensions for registering an extension.
Restricting queries
RestrictsQueries::restrict(RestrictionContext $context) adds where clauses to the perimeter of a resource:
use Lomkit\Rest\Extensions\Contexts\RestrictionContext;
use Lomkit\Rest\Extensions\Extension;
use Lomkit\Rest\Extensions\Kinds\RestrictsQueries;
final class TenantExtension extends Extension implements RestrictsQueries
{
public function __construct(private readonly CurrentTenant $tenant) {}
#[\Override]
public static function name(): string
{
return 'tenant';
}
#[\Override]
public function restrict(RestrictionContext $context): void
{
if ($context->user === null) {
$context->query->whereRaw('0 = 1');
return;
}
$context->query->where($context->query->qualifyColumn('tenant_id'), $this->tenant->id());
}
}
$context->queryis the Eloquent builder of the extension's own where group. The group comes afterperimeterQuery(), inside its own parentheses, and is AND-ed with the perimeter and the other extensions: anorWhere()in it cannot widen the rows.$context->resourceis the restricted resource: the related one on an include, a relation filter, sort or aggregate.$context->useris the user of the request,nullfor a guest: decide the rows of a guest yourself.- Qualify columns with
$context->query->qualifyColumn(): pivot reads join another table. - A restriction may run several times in one request, and again on each attempt of a write transaction: keep it free of side effects.
Where it applies
A restriction applies wherever the perimeter does: searches and includes, through a pivot too, relation filters, sorts and aggregates, metrics and the key of their cache in both scopes, the key lookups of mutate, destroy, restore, forceDestroy and actions, the rows of queued actions, child syncs, attached pivot rows, the records read again after a write and the write gates of rendered rows. It also applies to #[WithoutPerimeter] resources. See Perimeter.
- The key of a cached metric holds the SQL and the bindings of each restricted perimeter, with the user, so a restriction that reads a tenant or a flag never shares a result. Without a restriction, the key does not change.
- Every relation path reads the perimeter through the final
Relation::constrainToPerimeter(). It opens one where group, runsapplyPerimeter()inside it, then adds the restrictions after it: an override ofapplyPerimeter()cannot skip a restriction. A custom relation picks the restricted resource with the protectedperimeterResource(Model $model). - On a search engine, the rows of a page load by key without the restriction: the engine is the proof. Restrict the engine query with
RestrictsEngineQueries, or a text search of the resource throwsInvalidTextSearchExceptionon an engine that does not run SQL. On the Scoutdatabaseandcollectiondrivers, the restriction applies in the SQL of the engine query. - A tenant that does not come from
$context->user, such as a subdomain or a header, is not in the keys of kept decisions: add it withContributesCacheContext.
What it refuses
Only where clauses. A join, order, limit, offset, select, distinct, lock, group, having, union, eager load, other table, before-query or after-query callback, added global scope or removed global scope (withTrashed(), withoutGlobalScope()) throws:
The [tenant] extension Vendor\Tenancy\TenantExtension adds a join to the restriction of App\Rest\Resources\PostResource, which holds only where clauses. Restrict through another table with whereHas() or whereExists().
- The check reads the nested where groups too, at every depth.
- Laravel drops a global scope or an
afterQuery()callback added to the Eloquent builder of a nested group before the check runs: neither is applied. Write where clauses only.
Providing the perimeter
rest:check reports a resource without perimeterQuery() or #[WithoutPerimeter] even when a RestrictsQueries extension restricts it: a tenant extension narrows a perimeter declared elsewhere, it does not stand for it.
An extension whose restriction is the perimeter, such as an access-control extension that decides the rows of each user, implements ProvidesPerimeter, which extends RestrictsQueries and adds no method:
use Lomkit\Rest\Extensions\Kinds\ProvidesPerimeter;
final class AccessControlExtension extends Extension implements ProvidesPerimeter
{
// name() and restrict(), as above
}
rest:checkthen accepts the resources that the extension applies to, with aperimeter from aclline and an entry ofrows.extension_perimeterin--json. Plain restrictions show asrestricted by tenantlines and inrows.restricted. See Checking the application.- It changes nothing at runtime.
rest:checkreads the config of the environment it runs in: where the extension is disabled, or itsappliesTo()leaves a resource out, the problem comes back. Run it with the extensions of production.- A
RestrictsQueriesextension whoseappliesTo()throws for a resource is arowsproblem ofrest:checkthat names it. The extensions that answer are still named for that resource, and the other resources are still checked.
Adding to rendered rows
AugmentsQueries::augment(AugmentationContext $context) loads what the policies and gates of the rendered rows read, in the same query:
use Lomkit\Rest\Extensions\Contexts\AugmentationContext;
use Lomkit\Rest\Extensions\Extension;
use Lomkit\Rest\Extensions\Kinds\AugmentsQueries;
final class LockColumnsExtension extends Extension implements AugmentsQueries
{
#[\Override]
public static function name(): string
{
return 'locks';
}
#[\Override]
public function appliesTo(string $resource): bool
{
return is_a($resource, PostResource::class, true);
}
#[\Override]
public function augment(AugmentationContext $context): void
{
if (! in_array('update', $context->gates, true)) {
return;
}
$context->column('owner_id');
$context->select('locked', Lock::query()->selectRaw('count(*) > 0')->whereColumn('locks.post_id', 'posts.id'));
$context->with('approvals');
}
}
column()adds a column of the model table, as is.select()adds a subquery and returns its alias,{name}__{alias}: herelocks__locked, the attribute that the policy reads. It takes a query builder, an Eloquent builder or a closure that builds the subquery on a fresh query builder, asaddSelect()does.with()eager loads a relation path of public relation methods declared with aRelationreturn type, never past aMorphTo. It takes an optional constraint closure, as Laravel'swith(), which runs when the relation loads and cannot call the context.$context->gateslists the row gates rendered for these rows,[]on an include level that the client did not search.$context->resourceand$context->userare the resource of the level and the user of the request.
Guarantees
- It runs on the rows that a response renders only, at every include level: a search page, the rows of
Rest::search(), the records read after a write and the rows of a search engine page. Never on a count, an action, a metric, an aggregate or a key lookup. fields()alone decides what renders: added columns, subqueries and eager loads never render.- An eager load on a relation that the client includes at that level under its own name is skipped: the policies read the relation as the client filtered and limited it. An include under an alias does not skip it.
- The default
paginate()andPageQuerycount without the augmentation. Apaginate()override that counts with$query->paginate()counts the added columns. - On a query that groups rows, such as a scope with
groupBy(), add only a column that theGROUP BYholds or that depends on its key, or PostgreSQL and MySQL withONLY_FULL_GROUP_BYrefuse the query.
What it refuses
- An alias that is not 1 to 32 lowercase letters or digits starting with a letter, with words joined by single underscores (
a__banda_are refused), longer than 63 characters with its prefix, selected twice or equal to a field name. - A column that is not a column name of the model, a relation path that is not public relation methods, that goes past a
MorphTo, or that two extensions load. - A call to
column(),select()orwith()afteraugment()returned.
Narrowing limits
NarrowsLimits::narrowLimits(LimitsContext $context) narrows the page sizes, the total cap and the include limit of a resource for the user:
use Lomkit\Rest\Extensions\Contexts\LimitsContext;
use Lomkit\Rest\Extensions\Extension;
use Lomkit\Rest\Extensions\Kinds\NarrowsLimits;
final class PlanLimitsExtension extends Extension implements NarrowsLimits
{
#[\Override]
public static function name(): string
{
return 'plan_limits';
}
#[\Override]
public function narrowLimits(LimitsContext $context): void
{
$context->allowSizes([10, 25]);
$context->maxTotal(1000);
$context->includeLimit(10);
}
}
- Never upward, in any extension order.
allowSizes()intersects the sizes oflimits().maxSize()andmaxTotal()drop the larger sizes.maxTotal()andincludeLimit()take the minimum with the resource. - The default page size becomes the largest size left at or below
$defaultLimit, and the include limit the largest size left at or below the smaller include limit. - Validation, paging, includes and
/detailsuse the limits of the current user,$context->user. $context->declaredholds the limits that the resource declares, before any extension:allowed,defaultLimit,includeLimitandmaxTotal.ResourceDefinition::declaredLimits()returns them too.- The OpenAPI document shows the declared limits and never calls
narrowLimits().total_cappedis optional on the pages of a resource that an extension may cap. - A capped count prohibits
search.totalsfor that user.
It refuses a value below 1, a narrowing that leaves no size, no size at or below $defaultLimit or none at or below the include limit, and a read of definition()->limits() of the same resource inside narrowLimits(): read $context->declared. See Limits.
Declaring instructions
DeclaresInstructions::instructions(InstructionsContext $context) adds search instructions to a resource:
use Lomkit\Rest\Extensions\Contexts\InstructionsContext;
use Lomkit\Rest\Extensions\Extension;
use Lomkit\Rest\Extensions\Kinds\DeclaresInstructions;
final class ArchiveInstructionsExtension extends Extension implements DeclaresInstructions
{
#[\Override]
public static function name(): string
{
return 'arc';
}
#[\Override]
public function instructions(InstructionsContext $context): array
{
return is_subclass_of($context->resource, ArchivableResource::class) ? [WithArchivedInstruction::class] : [];
}
}
{
"search": {
"instructions": [{"name": "arc.with-archived"}]
}
}
- It receives the resource class only, no user. Its instructions are read with those of the resource.
- The key of each instruction is the extension name, a dot and its
uriKey():arc.with-archived, in requests,/details, search meta and the OpenAPI document.$instruction->publicUriKey()returns it. - Like any instruction, it runs in its own where group, AND-ed with the rest of the search. See Scopes and instructions.
- It refuses a key that another instruction of the resource or of an extension takes, and the entries that
instructions()of a resource refuses.rest:checkreports both.
Instruction gains the final method publicUriKey(): an instruction that declares a method of that name renames it.Extensions
Add behavior to every resource from one class, registered by an app or a package, with a name, a list of kinds and checks at registration.
Engine extensions
Restrict every search engine query, declare server-only index attributes and lists of strings, and provide the profile of a Scout engine.