<!-- Source: @site/projects/frontline-api-for-laravel/docs/05-entrance.md -->
<!-- Canonical: https://docs.pushery.com/frontline-api-for-laravel/entrance/ -->

# The entrance for the gateway

> The middleware that lets only requests the gateway signed reach the API host, where the entrance lives, its safety switch, the gateway as the only proxy, the health probe, and the headers for your tests.

Put `\Pushery\FrontlineApi\Http\Middleware\VerifyFrontlineSignature` on the routes of the API
host. It lets a request through only when the gateway signed it with the secret in
`frontline-api.gateway.secret`, or during a change with `frontline-api.gateway.previous_secret`, at
most five seconds ahead and no longer ago than the route's timeout and five seconds. Every other
request gets the 404 of an unknown path. The package puts the check first in Laravel's middleware
priority, so authentication and the binding of a model never answer a request the gateway did not
sign. Laravel orders only the middleware of that list: name the check first on every route, or a
middleware of your own that answers by itself answers a request that bypassed the gateway.
`RouteDeclarationCheck::problems()` names every route on the API host that runs without the check
or runs another middleware before it.

The secret is the string the gateway signs with: at least 43 characters of `A-Z`, `a-z`, `0-9`,
`-` and `_`, the URL-safe base64 of 32 random bytes without padding. A secret with any other
character, such as the `+`, `/` and `=` of plain base64, is ignored, and outside `local` and
`testing` the health check `signature` fails on it. One way to make one:

```bash
php -r 'echo rtrim(strtr(base64_encode(random_bytes(32)), "+/", "-_"), "="), PHP_EOL;'
```

```php
use Illuminate\Support\Facades\Route;
use Pushery\FrontlineApi\Http\Middleware\VerifyFrontlineSignature;

Route::domain('api.example.com')
    ->middleware(VerifyFrontlineSignature::class)
    ->frontline(limitClass: 'standard')
    ->group(base_path('routes/api.php'));
```

## Where the entrance lives

The gateway forwards each request to an entrance of your application that only the gateway can
reach, over the loopback address or a private network. Nothing between the two may change the
request. The request target stays as the request line had it, and the headers the gateway signs stay
as it sent them: `Host`, the `Frontline-*` headers, `X-Forwarded-For`, `X-Forwarded-Host` and
`X-Forwarded-Proto`. A load balancer, a CDN or the edge of a hosting platform that adds its own
address to `X-Forwarded-For` or sets the host anew breaks every signature, and every request then
gets the 404 of an unknown path. Such a layer belongs in front of the gateway, never behind it.

Inside the entrance, PHP-FPM behind nginx passes the request target on unchanged: nginx keeps
`$request_uri` as the request line had it, and the `REQUEST_URI` of its `fastcgi_params` hands it to
PHP, whatever `try_files` does to `$uri`. An application server that builds `REQUEST_URI` itself,
such as one that keeps your application in memory between requests, serves the entrance only once
it keeps the request target byte for byte.

## The safety switch

The check is a safety switch. `FRONTLINE_API_REQUIRE_SIGNATURE=false` switches it off in the
environments `local` and `testing` only, where your application runs without a gateway. In every
other environment it stays on, whatever the setting says, and a value that is not one of the
spellings for off leaves it on everywhere.

## One route per signature

A signature holds only for the route the gateway checked, named in the `Frontline-Route` header:
a request that Laravel matches to another route gets the same 404. For the same reason the API
host knows no method override. A `POST` that names another method in `X-HTTP-Method-Override` or in
a `_method` parameter, in the query or in a JSON:API document, gets the 404 before any route is
matched. On every other host the override keeps working, so `@method` in your forms is unaffected.

A route is a method and a path. A request whose method no route of its path serves gets the same
404 on the API host, where Laravel would answer `405` and list the methods the path serves, and so
does every `OPTIONS`, which Laravel would answer with `200` and those methods in `Allow`. A request
that reaches the entrance without the gateway learns nothing about your routes that way. On every
other host Laravel answers as it does.

In observe mode the gateway forwards a request that breaks only a rule of your product, so that you
see what it would refuse before it refuses anything. A request that matches no route of the product
sheet then arrives without `Frontline-Route`. Set `FRONTLINE_API_GATEWAY_MODE=observe` the same as the
gateways' `FRONTLINE_MODE`, and such a request reaches the route Laravel matches, within the longest
timeout of the routes on the API host, with your application's own checks as the second line. The
route name `GatewayRequest::of($request)` returns is then empty. In enforce mode, the default, the
request gets the 404 of an unknown path, since the gateway sends none.

A route serves `GET`, `HEAD`, `POST`, `PUT`, `PATCH` and `DELETE`, and no other method. A browser's
CORS preflight is an `OPTIONS` request, so it gets the same 404: from the gateway in enforce mode,
and from the package, before Laravel's `HandleCors`, when observe mode forwards it. A page in a
browser on another origin therefore cannot call the API host
with a key in `Authorization` or with a JSON body, because the browser sends a preflight before each
of those. Servers, apps and tools are unaffected, since they send no preflight. People in a browser
never go through the gateway: serve the routes a browser calls from your application's own host.

## The gateway as the only proxy

The gateway is the only proxy of the requests it sends. Before a route is matched, a request from an
address in `frontline-api.gateway.addresses` that carries the gateway's valid signature takes its
client address, its public name and its scheme from `X-Forwarded-For`, `X-Forwarded-Host` and
`X-Forwarded-Proto`, and from no other header. It reaches Laravel's entrance under the entrance's
own name, matches the routes on the public name of the API host, and every URL built while it runs,
a signed URL and a redirect included, names that host with `https`. The package takes this step
right after Laravel's `TrustProxies` in your global middleware, so every middleware after it sees the
public name, and the trust holds to the end of the request; `TrustProxies` sets the proxies your
application trusts anew at the start of the next one. Every other request keeps those proxies, so
the host of your application keeps the proxies it is behind, such as Cloudflare and nginx.
`bootstrap/app.php` needs no entry for the gateway. List only the addresses the gateway connects
from, one IP address each: any other address there could speak for it, and a range, a name or an
address with a port matches no connection, which the health check `signature` names. Where a web
server sits between the gateway and Laravel, its block for the entrance must leave the connection's
address as it is, with no `real_ip_header` and no list of Cloudflare's networks, or no request ever
comes from the gateway's address.

## What the gateway sent

After the check, `\Pushery\FrontlineApi\Http\GatewayRequest::of($request)` returns the request id,
the public identifier of the key, its tenant and the route name the gateway sent.

## The health probe

With `frontline-api.host` set, the package registers the gateway's health probe on that host, at
`frontline-api.gateway.health_path`, behind the same check. It fires Laravel's `DiagnosingHealth`
event, so the listeners of your health check run, and answers 200, or 500 when one of them throws.

In maintenance, Laravel stops every request before it reaches a route. On the API host the package
answers such a request, the health probe among them, with the 503 the gateway reads as maintenance
rather than an outage: an `application/vnd.api+json` document with one error whose code is
`maintenance`, in the format of the gateway's own errors. A prerendered page, a redirect or another
status that `php artisan down` sets applies to your other hosts only. What maintenance lets through
still reaches its route on the API host: a path you except, such as a webhook, and a request with
the bypass cookie. The secret path keeps its redirect that sets the cookie.

## Testing routes on the API host

`\Pushery\FrontlineApi\Testing\GatewayHeaders::for()` returns the headers the gateway sends with a
request, signed with the secret you give it, by the same code the check verifies with. Pass them to
`withHeaders()` before you send that request. Your tests then reach the routes of the API host with
the check on. Set `FRONTLINE_API_HOST` and `FRONTLINE_API_GATEWAY_SECRET` in the environment of
your tests.

```php
use Pushery\FrontlineApi\Testing\GatewayHeaders;

it('lets the gateway through and nobody else', function () {
    $url = 'https://api.example.com/v1/projects';
    $secret = config('frontline-api.gateway.secret');

    $this->withHeaders(GatewayHeaders::for('GET', $url, $secret, keyId: 'abcdefghijkl'))
        ->get($url)
        ->assertOk();

    $this->withHeaders(GatewayHeaders::for('GET', $url, $secret, time: time() - 3600))
        ->get($url)
        ->assertNotFound();

    $this->flushHeaders();

    $this->get($url)->assertNotFound();
});
```

A header you do not name gets the value the gateway would send: a new request id, the current time,
the route Laravel matches for the method and URL, a documentation address as the client, and the
URL's host as the public name. Pass `route: ''` for a request the gateway sends without a route, as
in observe mode.
