# Authorization extensions

> Prepare and version row checks, add to the keys of kept decisions, declare gates and narrow the fields of a resource for each user from an extension.

Five kinds act on authorization: `PreparesRowChecks`, `VersionsRowChecks`, `ContributesCacheContext`, `DeclaresGates` and `NarrowsFields`. They decide nothing in place of the policies: the policy still runs for each row whose decision is not kept. They throw `Lomkit\Rest\Exceptions\InvalidAuthorizationExtensionException`, and `NarrowsFields` throws `InvalidFieldExtensionException`. Both name the extension by its name and its registered class. See [Policies](/authorization/policies) and [Decision cache](/authorization/decision-cache).

## Resource hooks

A resource can prepare and version its own row checks. The two extension kinds receive the same objects, after the hook, in name order.

### Preparing row checks

`prepareAuthorization(PendingChecks $checks): void` runs before the policies check a batch of rows. The default does nothing. Use it to read once, for all the rows, data that is not a relation of the row, such as a permission table:

```php [app/Rest/Resources/DocumentResource.php]
use Lomkit\Rest\Authorization\PendingChecks;

public function prepareAuthorization(PendingChecks $checks): void
{
    app(GrantTable::class)->load($checks->user, $checks->ability, $checks->rows->modelKeys());
}
```

- `$checks->resource` is the resource, `$checks->ability` the exact ability that the Gate checks, `$checks->rows` an Eloquent collection of the rows about to be checked for it, and `$checks->user` the user that the policies run for, `null` for a guest, also in `Rest::search()->as($user)`.
- It may run zero or more times per request, each time with a part of the rows. Rows of one resource class at several levels of a page share a call, and a single check is a call with one row.
- Only stored, unchanged rows checked alone reach it. Rows already decided in the request or read from `authorizationCache()`, class-level checks (`viewAny`, `create`), drafts, the `update` checks of a mutation and the link abilities never do.
- It must be idempotent, decide nothing and change none of the rows it receives. Key what it stores by user and row key.
- An exception thrown by it stops the request before any policy of that batch runs.

### Versioning row checks

`versionAuthorization(RowVersions $versions): void` adds to the key of a kept decision the versions of the rows that the decision depends on. When such a row changes, the key changes and the policy runs again, before the decision expires and without `forgetAuthorizations()`. Documents that inherit the permissions of their folder add its `updated_at`:

```php [app/Rest/Resources/DocumentResource.php]
use Lomkit\Rest\Authorization\RowVersions;

public function versionAuthorization(RowVersions $versions): void
{
    $documents = $versions->rows->whereInstanceOf(Document::class);
    $folders = Folder::query()->whereKey($documents->pluck('folder_id')->filter()->unique()->all())->pluck('updated_at', 'id');

    foreach ($documents as $document) {
        $updatedAt = $folders[$document->folder_id ?? 0] ?? null;

        if ($updatedAt !== null) {
            $versions->add($document, 'folder', $updatedAt);
        }
    }
}
```

- `$versions->add($row, 'folder', $version)` adds a `DateTimeInterface`, an integer or a string to the key of the decisions on `$row`. The versions of a row are sorted by key, so the order of the hook and the extensions never shows.
- It runs only to build the key of a kept decision: a stored row, an ability that `authorizationCache()` lists, the cache enabled. It runs once per resource class, ability and user for all the rows of one cache read, before the lookup.
- A `DateTimeInterface` version follows the rule of the row's own `updated_at`: one not before the second in which the request started keeps no decision on that row in this request, and so do two values for one key of a row.
- On a link check of `mutate`, the related row goes to the hook of the related resource, with the ability of the check. In a check that app code makes with `authorizedTo($ability, $model, [$related])`, every model goes to the resource of the check: filter `rows` by class, as above.
- A key that is not 1 to 64 letters, digits or underscores starting with a letter, a version for a model that is not in `rows`, and a change to the rows throw `InvalidResourceException`.
- A version follows Eloquent writes only: a grant written by the query builder that does not touch the folder needs a version of its own, or `Rest::forgetAuthorizations()`.
- Without the hook and without such an extension, nothing runs and the keys do not change.

## Preparing row checks from an extension

`PreparesRowChecks::prepareRowChecks(PendingChecks $checks)` receives the `PendingChecks` of `prepareAuthorization()`, after the hook:

```php [Vendor/Acl/AccessControlExtension.php]
use Lomkit\Rest\Authorization\PendingChecks;
use Lomkit\Rest\Authorization\RowVersions;
use Lomkit\Rest\Extensions\Extension;
use Lomkit\Rest\Extensions\Kinds\PreparesRowChecks;
use Lomkit\Rest\Extensions\Kinds\VersionsRowChecks;

final class AccessControlExtension extends Extension implements PreparesRowChecks, VersionsRowChecks
{
    public function __construct(private readonly GrantTable $grants) {}

    #[\Override]
    public static function name(): string
    {
        return 'acl';
    }

    #[\Override]
    public function prepareRowChecks(PendingChecks $checks): void
    {
        $this->grants->load($checks->user, $checks->resource::class, $checks->ability, $checks->rows->modelKeys());
    }

    #[\Override]
    public function versionRowChecks(RowVersions $versions): void
    {
        $rows = $versions->rows->whereInstanceOf($versions->resource::modelClass());
        $changed = $this->grants->lastChanges($versions->resource::class, $rows->modelKeys());

        foreach ($rows as $row) {
            $versions->add($row, 'grants', $changed[$row->getKey()] ?? 0);
        }
    }
}
```

The same class implements `VersionsRowChecks`, below: one package keeps one name, `acl`, for both kinds.

- The rows are the models that the policy receives, with the columns of `AugmentsQueries`. The rules of the hook apply.
- Loading a relation that was not loaded is allowed. It does not render.
- Changing the rows throws `InvalidAuthorizationExtensionException`: an attribute, compared strictly with its stored value; a relation loaded before the preparation, at any depth, that is replaced, dropped or whose models change; the settings that decide where and how a row is written (`exists`, table, connection, key name, casts, timestamps); or the list of rows. Reading an attribute through a cast is not a change, also when the cast encrypts it again.
- The reference state of each extension is taken after the hook: the hook itself is not checked.
- The check catches mistakes; it does not isolate the extension, which runs in the process with full access. It does not read the attributes of related models: leave them as they are.

## Versioning row checks from an extension

`VersionsRowChecks::versionRowChecks(RowVersions $versions)` receives the `RowVersions` of `versionAuthorization()`, after the hook. The `versionRowChecks()` method of `AccessControlExtension`, above, adds the last change of the grants of each row under the `grants` key.

- Each version goes under `{name}.{key}` in the key of the decisions on its row, here `acl.grants`, next to the row's `updated_at`.
- The rules of the hook apply. A bad key, a version for a model that is not in `rows`, and a change to the rows throw `InvalidAuthorizationExtensionException`.

## Adding to the cache context

`ContributesCacheContext::contributeCacheContext(CacheContributionContext $context)` adds items to the cache key of the kept decisions and metric results of a resource:

```php [Vendor/Tenancy/TenantCacheExtension.php]
use Lomkit\Rest\Extensions\Contexts\CacheContributionContext;
use Lomkit\Rest\Extensions\Extension;
use Lomkit\Rest\Extensions\Kinds\ContributesCacheContext;

final class TenantCacheExtension extends Extension implements ContributesCacheContext
{
    public function __construct(private readonly Tenants $tenants, private readonly RuleVersions $rules) {}

    #[\Override]
    public static function name(): string
    {
        return 'tenant_cache';
    }

    #[\Override]
    public function contributeCacheContext(CacheContributionContext $context): void
    {
        $context->put('id', $this->tenants->current()?->id);
        $context->put('rules', $this->rules->fingerprint());
        $context->shorten('view', 60);
    }
}
```

- `put($key, $value)` stores an integer, a float, a string, a boolean or `null` under `{name}.{key}`, here `tenant_cache.rules`, next to the values of `authorizationCacheContext()`. Another tenant or rules version never reads a kept decision or result.
- `shorten('view', 60)` keeps the decisions of an ability for 60 seconds at most, and `forget('view')` keeps none. The smallest duration of the resource and the extensions wins.
- An extension never adds an ability that `authorizationCache()` does not list, never lengthens a duration, and does not change `cacheFor()` of metrics.
- It runs at most once per resource and acting user per request, only when the resource keeps a decision or a metric key reads its context. Without items, the keys do not change.
- A key that is not 1 to 64 letters, digits or underscores starting with a letter, a float that is not finite, a duration below 1 second and a key that `authorizationCacheContext()` already returns throw.
- A tenant that does not come from the user, such as a subdomain, a header or a job payload, is not in these keys by itself: add it with `put()`.

## Declaring gates

`DeclaresGates::gates(GatesContext $context)` adds gates to a resource:

```php [Vendor/Sharing/SharingExtension.php]
use Lomkit\Rest\Extensions\Contexts\GatesContext;
use Lomkit\Rest\Extensions\Extension;
use Lomkit\Rest\Extensions\Kinds\DeclaresGates;

final class SharingExtension extends Extension implements DeclaresGates
{
    #[\Override]
    public static function name(): string
    {
        return 'share';
    }

    #[\Override]
    public function gates(GatesContext $context): array
    {
        return ['share'];
    }
}
```

- It receives the resource class only, no user, with the rules of `gates()`.
- Its gates come after the gates of the resource, in name order, in `/details`, `search.gates` and the OpenAPI document. The policy method `share($user, $model)` answers `authorized_to_share`. A gate that two lists declare is listed once.
- A resource that turns its gates off lists none.
- A misdeclared gate, such as a name that is not camelCase, `viewAny` or a built-in ability, throws when the gates are first read. See [Gates](/authorization/gates).

## Narrowing fields

`NarrowsFields::narrowFields(FieldsContext $context)` narrows the fields of a resource for the user of the request:

```php [Vendor/Payroll/SalaryFieldsExtension.php]
use Lomkit\Rest\Extensions\Contexts\FieldsContext;
use Lomkit\Rest\Extensions\Extension;
use Lomkit\Rest\Extensions\Kinds\NarrowsFields;

final class SalaryFieldsExtension extends Extension implements NarrowsFields
{
    public function __construct(private readonly PayrollAccess $access) {}

    #[\Override]
    public static function name(): string
    {
        return 'payroll';
    }

    #[\Override]
    public function appliesTo(string $resource): bool
    {
        return $resource === EmployeeResource::class;
    }

    #[\Override]
    public function narrowFields(FieldsContext $context): void
    {
        if ($this->access->readsSalaries($context->user)) {
            return;
        }

        $context->hide('salary');
        $context->readOnly('grade');
        $context->unsortable('hired_on');
    }
}
```

- `hide()`, `readOnly()`, `unfilterable()` and `unsortable()` take field names. `$context->declares('salary')` tells whether `fields()` declares a field, for a resource whose fields depend on the user.
- It only takes away, in any extension order. It runs once per request and resource, before any write, also under `Rest::search()->as($user)`. On `operate`, it runs when the body is validated, before the action reads any row. The fields of an action are never narrowed.
- A hidden field is gone from filters at every depth and through relations, sorts, selects, includes, aggregates, rendered rows, `/details`, mutate validation and writes, the searches of actions and metrics, and the grammar of a search engine. A request that names it gets the answer of a field that `fields()` does not declare. Its `rules()`, `createRules()` and `updateRules()` keys no longer apply.
- A read-only, unfilterable or unsortable field behaves as a field that declares `readonly()`, `filterable(false)` or `sortable(false)`. A read-only foreign key is still written by a nested `attach` or `detach` of its relation.
- A field that the user cannot filter or that is hidden is neither groupable nor measurable in [totals](/search/totals).
- The column of a hidden field is still loaded for the policies and gates, also when the client sends `selects`, and never renders.

It refuses, with `InvalidFieldExtensionException`, an unknown name, and hiding the model key, the row version of a `versioned()` resource, a `searchable()` field of a SQL text search, or a field that `ScoutEngine::perimeter()` or `ScoutEngine::indexAttributes()` declares or names. Reading the fields or the text search of the same resource inside `narrowFields()` throws it too: read the declared names with `$context->declares()`.

### What stays visible

- A search engine still matches `search.text` against a hidden value that `toSearchableArray()` indexes: keep it out of the index.
- Metrics, scopes, instructions, `perimeterQuery()` and the callbacks of fields still read every column.
- A visible field derived from a hidden one, through `resolveUsing()` or `requires()`, and `defaultOrderBy()` on a hidden column still show what they read: hide the derived field, and order by a visible column.
- The OpenAPI document is built without a user and lists the declared fields.
