<!-- Source: @site/projects/frontline-api-for-laravel/docs/03-keys-and-tiers.md -->
<!-- Canonical: https://docs.pushery.com/frontline-api-for-laravel/keys-and-tiers/ -->

# Keys and tiers

> Where the gateway's keys and tiers come from: the key source, the tier source, the abilities your keys can carry, the limit of your backend, and the in-memory sources for tests.

The package keeps no key and no tier of its own. It asks two sources of your application, writes
what they return into the sheets the gateways read, and publishes again whenever you say that
something changed ([Publishing the sheets](https://docs.pushery.com/frontline-api-for-laravel/publishing.md)). Name the two classes in the published
config, and the package resolves each from the container:

```php
'sources' => [
    'keys' => \App\Frontline\ApiKeys::class,
    'tiers' => \App\Frontline\PlanTiers::class,
],
```

Binding `Pushery\FrontlineApi\Contracts\KeySource` or `Pushery\FrontlineApi\Contracts\TierSource` in
a service provider works as well, and that binding takes the place of the class named there.

## The key source

A key your application issues has the shape the gateway reads:

```text
<product>_<environment>_[<tenant>_]<id>_<secret><checksum>
```

The product is 2 to 10 letters `a`–`z`, the environment `live` or `test`, the optional tenant part 1
to 32 characters of `a`–`z` and `0`–`9`, the id 12 such characters, the secret 43 random letters and
digits, and the checksum the CRC-32 of everything before it in six base-62 digits. The gateway
never sees a key it does not already know by its fingerprint: `sha256:` followed by the lower-case
hex SHA-256 of the whole key. Keep that fingerprint and the id, never the key.

`Pushery\FrontlineApi\Keys\HouseKey` issues and reads keys of this shape, so your application
does not rebuild the rules:

```php
use Pushery\FrontlineApi\Keys\HouseKey;

$key = HouseKey::issue('acme', 'live', 'tenant42');

// Show $key->value once. Store $key->id, $key->fingerprint and $key->tenant.
```

`issue()` draws the id and the secret with `random_int()`, and leaves the tenant out when you pass
none. Whether the id is already taken in your store is for your application to check; issue another
key when it is. `HouseKey::read($value)` takes a value apart by the rules of the format in their
order and throws `InvalidHouseKey` for the first rule it breaks. Its `reason` is a `HouseKeyRefusal`
named as the gateway counts it, such as `checksum_mismatch`, and its message never contains the
value. `HouseKey::matches($value, $fingerprint)` compares in constant time. Where your application
checks a key itself, read it with `HouseKey::bearerFrom($request)`: exactly one `Authorization`
header, the scheme `Bearer` and one space, as the gateway reads it. Laravel's `bearerToken()` also
takes `Basic x, Bearer <key>`, which the gateway refuses.

Implement `Pushery\FrontlineApi\Contracts\KeySource` with two methods. `scopes()` returns the scopes
your keys are kept in: `KeyScope::product()` when one sheet holds every key of the product, or one
`KeyScope::tenant()` per tenant part your keys carry. `keys()` returns every key of one scope that is
issued and not revoked. A revoked key must not be returned: its absence from the sheet is what makes
the gateway refuse it. Both methods may return a generator or a lazy collection, so a scope with
many keys is written one key at a time.

```php
namespace App\Frontline;

use App\Models\ApiKey;
use Pushery\FrontlineApi\Contracts\KeySource;
use Pushery\FrontlineApi\Keys\Key;
use Pushery\FrontlineApi\Keys\KeyRules;
use Pushery\FrontlineApi\Keys\KeyScope;

final class ApiKeys implements KeySource
{
    public function scopes(): iterable
    {
        return [KeyScope::product()];
    }

    public function keys(KeyScope $scope): iterable
    {
        foreach (ApiKey::query()->whereNull('revoked_at')->lazy() as $key) {
            yield new Key(
                id: $key->public_id,
                fingerprint: $key->fingerprint,
                tenant: $key->tenant,
                tier: $key->tier,
                abilities: $key->abilities,
                rules: new KeyRules(cidrs: $key->allowed_ranges),
                notAfter: $key->expires_at,
            );
        }
    }
}
```

| Field | What it holds |
|---|---|
| `id` | the key's id, 12 characters of `a`–`z` and `0`–`9` |
| `fingerprint` | `sha256:` and the SHA-256 of the whole key in lower-case hex |
| `tenant` | the tenant the key acts for, up to 64 characters of `A`–`Z`, `a`–`z`, `0`–`9`, `.`, `_` and `-`, or `null` |
| `tier` | the name of the key's tier |
| `abilities` | the abilities the key holds, each once |
| `rules` | where the key may be used from and on which routes: `KeyRules::none()`, or `new KeyRules(cidrs: [...], routes: [...])` with address ranges such as `203.0.113.0/24` and route names |
| `notAfter` | when the key stops being valid |

A rule left `null` restricts nothing. An empty list would forbid everything and is refused: revoke
a key that may be used nowhere. A value of another form is refused with an exception that names the
field, so a key the gateway would refuse never reaches a sheet.

## The tier source

A tier says, per limit class, how many requests a key, a tenant or both may make, and how high its
callers stand when the gateway is overloaded. Implement `Pushery\FrontlineApi\Contracts\TierSource`
with one method, `tiers()`:

```php
namespace App\Frontline;

use Pushery\FrontlineApi\Contracts\TierSource;
use Pushery\FrontlineApi\Tiers\ClassLimits;
use Pushery\FrontlineApi\Tiers\Counter;
use Pushery\FrontlineApi\Tiers\Tier;

final class PlanTiers implements TierSource
{
    public function tiers(): iterable
    {
        return [
            new Tier('basic', 1,
                new ClassLimits('standard', key: new Counter(perMinute: 600, perSecond: 20, writesPerMinute: 60, concurrency: 8)),
            ),
            new Tier('pro', 5,
                new ClassLimits('standard',
                    key: new Counter(perMinute: 6000, perSecond: 100, writesPerMinute: 600, concurrency: 32),
                    tenant: new Counter(perMinute: 20000, perSecond: 300, writesPerMinute: 2000, concurrency: 64),
                ),
            ),
        ];
    }
}
```

A tier's name is a lower-case letter followed by up to 31 characters of `a`–`z`, `0`–`9` and `_`.
Its priority goes from 0 to 9, and under overload the gateway refuses the requests of the lower
priority first. Each `ClassLimits` names a limit class once, with a counter for each key, one for
each tenant over all its keys, or both; a request is admitted only when every counter it falls under
has room left. A counter allows requests per calendar minute and per calendar second, requests per
minute to routes that write or delete, where 0 refuses them, and requests at the same time.

Every tier names the same limit classes, since a route is counted in one class whatever tier its
caller is on. The product sheet is refused while the tiers disagree, while no tier exists, or while
a route names a class no tier names, and the message says which.

## Abilities

The check of the route declarations holds the ability of every route against the abilities your keys
can carry, so a misspelled ability fails in your own suite instead of locking every key out of the
route ([Declaring routes](https://docs.pushery.com/frontline-api-for-laravel/routes.md)). List them under `abilities` in the published config:

```php
'abilities' => [
    'projects:read',
    'projects:write',
],
```

Where they live elsewhere, bind your own `Pushery\FrontlineApi\Contracts\AbilityCatalog`, whose
`abilities()` returns the list. An ability is up to 64 characters of `a`–`z`, `0`–`9`, `.`, `_`, `:`
and `-`, and starts with a letter or a digit.

## The backend

`frontline-api.backend.max_concurrency` is the most requests the gateway forwards to your application
at once, such as the number of workers of its PHP-FPM pool, 32 by default. The product sheet carries
it to every gateway.

## In tests

`Pushery\FrontlineApi\Testing\InMemoryKeySource` and `Pushery\FrontlineApi\Testing\InMemoryTierSource`
hold keys and tiers you build in a test:

```php
use Pushery\FrontlineApi\Contracts\KeySource;
use Pushery\FrontlineApi\Contracts\TierSource;
use Pushery\FrontlineApi\Keys\Key;
use Pushery\FrontlineApi\Keys\KeyRules;
use Pushery\FrontlineApi\Keys\KeyScope;
use Pushery\FrontlineApi\Testing\InMemoryKeySource;
use Pushery\FrontlineApi\Testing\InMemoryTierSource;
use Pushery\FrontlineApi\Tiers\ClassLimits;
use Pushery\FrontlineApi\Tiers\Counter;
use Pushery\FrontlineApi\Tiers\Tier;

app()->instance(KeySource::class, InMemoryKeySource::make()->with(
    KeyScope::product(),
    new Key('abcdefghijkl', 'sha256:'.hash('sha256', 'acme_test_abcdefghijkl_secret'), null, 'basic', ['projects:read'], KeyRules::none(), now()->addYear()),
));

app()->instance(TierSource::class, new InMemoryTierSource(
    new Tier('basic', 1, new ClassLimits('standard', key: new Counter(perMinute: 60, perSecond: 5, writesPerMinute: 10, concurrency: 2))),
));
```
