# Step-Up

Source: https://keyringauth.com/docs/0.x/step-up

## Introduction

Step-up asks a signed-in user to prove something again before a sensitive action, such as changing their password. Keyring has two middleware for it:

- `keyring:{level}` requires the session to have reached an [assurance level](https://keyringauth.com/docs/0.x/policies#assurance-levels).
- `keyring.fresh:{window}` requires a verification within a time window.

Put them after `auth`, as route middleware or with Laravel's `#[Middleware]` attribute. They check Keyring's guard, so a request with nobody signed in there gets Laravel's usual `AuthenticationException`:

```php
use Illuminate\Routing\Attributes\Controllers\Middleware;

#[Middleware('auth')]
#[Middleware('keyring:aal2')]
class BillingController
{
    #[Middleware('keyring.fresh:15m')]
    public function destroy()
    {
        // ...
    }
}
```

```php
Route::delete('/account', [AccountController::class, 'destroy'])
    ->middleware(['auth', 'keyring.fresh:5m']);
```

## Raising Assurance

`keyring:aal2` lets the request through at AAL2 or higher. `keyring:aal1` and `keyring:aal3` work the same way, and bare `keyring` means `keyring:aal2`. An unknown level throws an `InvalidArgumentException`.

`keyring:aal3` needs a key added with a [verified attestation](https://keyringauth.com/docs/0.x/passkeys#attestation-and-aal3). Without attestation, ask for a named variant of AAL2 instead: `keyring:aal2,device-bound` for a phishing-resistant key that stays on its device, or `keyring:aal2,phishing-resistant` for any passkey or security key. [`keyring.enrolled`](https://keyringauth.com/docs/0.x/policies#requiring-a-second-factor) takes the same names.

The middleware counts what the session has already proved, so it only asks for what's missing. An emailed code counts for nothing here.

A level lapses. At AAL2, it lapses after an hour without a request, or 24 hours overall, as NIST SP 800-63B-4 asks. The next `keyring:aal2` route then asks again. See [Timeouts](https://keyringauth.com/docs/0.x/devices-and-sessions#timeouts), and [Ending a Session With Its Level](https://keyringauth.com/docs/0.x/devices-and-sessions#ending-a-session-with-its-level) to end the session instead. The idle limit is kept by the [session middleware](https://keyringauth.com/docs/0.x/devices-and-sessions#the-session-registry), which is in the `web` group. Routes outside it, such as Sanctum's `api` group, need `keyring.session`. A [risk response](https://keyringauth.com/docs/0.x/risk#checkpoints) can clear a level, and removing an authenticator stops it counting everywhere.

A browser [impersonating](https://keyringauth.com/docs/0.x/impersonation#whats-refused-while-impersonating) the user can't step up as them, and gets a `403` instead of a confirm.

A user without the authenticators for a level is sent to your [`enrollment_url`](https://keyringauth.com/docs/0.x/configuration#account-changes-and-enrollment) with `enroll-first`, as `keyring.enrolled` does. JSON requests get a `403` with that status and the URL. Without an `enrollment_url`, they get a plain `403`.

To check the level in your own code:

```php
use Keyring\Enums\Assurance;
use Keyring\Sessions\SessionAssurance;

app(SessionAssurance::class)->level()->atLeast(Assurance::AAL2);
```

## Fresh Verification

`keyring.fresh:15m` lets the request through when the user verified, within the window, the strongest combination their account can give, and at least what signing in would ask. The window takes any [duration](https://keyringauth.com/docs/0.x/configuration#durations) and defaults to `15m`.

NIST SP 800-63B-4 (Sec. 4.1.2.1) binds a new authenticator at the highest level the account can authenticate at, or at the level the new one will be used at if that's lower. Keyring always asks for the highest level, so what's asked here follows the account, not the sign-in policy:

- Users with only a password confirm with their password, so an account can always add its first sign-in method.
- Users with two factors prove both again, even where the policy would sign them in with one. A stolen session that's no longer fresh, plus one phished factor, can't add, remove or change anything.
- Users with a key that can't leave its device use that key, with its own user verification or their password alongside it. A password and an authenticator app's code isn't enough for them, whatever the policy says. Only an [established](https://keyringauth.com/docs/0.x/authenticators#established-authenticators) key counts here, so a key added from a stolen session isn't the one thing the owner has to prove to remove it.
- Users who have any possession factor (an authenticator app, a passkey or a security key) always use one. An [email code](https://keyringauth.com/docs/0.x/factors#email-codes) isn't a possession factor, so it can't stand in. A user whose only other method is an emailed code proves the password and that code. That's what lets them add a real second factor.

Keyring uses `keyring.fresh:15m` on its own sensitive routes, through the `changes_middleware` option, on top of `auth:{guard}`. Those routes cover managing authenticators, ending sessions, signing out devices, changing the password and starting an email change. The other rules, and the limits on a copy of a just-signed-in session, are in [How It Works](https://keyringauth.com/docs/0.x/step-up#how-it-works).

## Asking From a Controller

An integration, such as an OpenID Connect provider, may need to decide what to ask from parameters like `acr_values` and `max_age`. `Keyring\Login\StepUp` makes the same decision in a controller:

```php
public function unlessMet(Request $request, ?Assurance $level = null, ?DateTimeInterface $since = null): ?Response
```

It returns `null` when the user has already proved what's asked. Otherwise it returns what the middleware would: a redirect to the confirm page, a `423` for JSON, or the enroll-first answer.

- `$level` works like `keyring:{level}`, and the confirm asks only for what's missing. The `device-bound` and `phishing-resistant` names are for the middleware only.
- `$since` works like `keyring.fresh`: the user must have verified the strongest combination at or after that moment. A moment alone doesn't check whether a level lapsed, so pass `$level` too when the current level matters.
- With both, the confirm asks for both at once. If one confirm can't give both, the user is asked in turn: the level first, then the fresh verification.

With nobody signed in to Keyring's guard, `unlessMet` throws an `AuthenticationException`. It throws an `InvalidArgumentException` when asked for nothing, for `Assurance::None`, or for a moment more than `StepUp::CLOCK_LEEWAY` (5) seconds in the future. A moment less than that ahead counts as now, since another of your servers may have a slightly fast clock.

### Passing a Fixed Moment

Once a user confirms, the check is met for any moment before the confirm. Each factor is stamped when proved, though, so a two-step confirm only meets moments up to its first step.

A moment that moves with every request can never be met. If you pass `now()`, the user confirms, comes back a moment later and is asked again. So for `max_age` or `prompt=login`, store the moment the authorization request arrived and pass that:

- `max_age=0` and `prompt=login` ask for a proof made during this authorization, so pass the stored moment.
- Any other `max_age` asks for a proof within `max_age` seconds, so pass the stored moment, or `max_age` seconds before now if that's earlier.

Keep that moment for one authorization request only:

- Store it under an ID that only this request carries, and add the ID to the URL the user returns to. A session-wide key would let an abandoned flow's moment satisfy a later `prompt=login`.
- Store a hash of `client_id`, `redirect_uri`, `state` and `nonce` beside it, and only use it for a request with that hash. Otherwise someone could replay the ID with other parameters.
- Let it expire after a few minutes, keep only a few per session, and forget it when the authorization ends.

Don't put this route behind `auth`. Behind `auth`, the guest signs in before the moment is stored, so `prompt=login` would send them to confirm straight after signing in. The example below stores the moment first.

### Asking Without Starting a Confirm

For requests that must get an answer without showing the user anything, such as `prompt=none`, use `meets`:

```php
public function meets(Request $request, ?Assurance $level = null, ?DateTimeInterface $since = null): bool
```

It takes the same arguments as `unlessMet`, and throws the same `InvalidArgumentException` for ones it can't answer. It returns `true` when `unlessMet` would return `null`. Otherwise it returns `false`, and it never starts a confirm. It throws `AuthenticationException` for a guest, too, so check for a guest first. A silent request stores no moment, so its `max_age` counts back from now.

### An Example

This controller reads `acr_values`, `max_age` and `prompt`, and checks outside values before they reach `unlessMet`, since a negative `max_age` would be a moment in the future. The route isn't behind `auth`, so the controller sends a guest to sign in once the moment is stored.

```php
use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use Keyring\Enums\Assurance;
use Keyring\Facades\Keyring;
use Keyring\Login\StepUp;

class AuthorizeController
{
    public function __invoke(Request $request, StepUp $stepUp)
    {
        $validated = $request->validate([
            'acr_values' => ['nullable', 'string', 'max:255'],
            'max_age' => ['nullable', 'integer', 'min:0', 'max:31536000'],
            'prompt' => ['nullable', 'string', 'max:255'],
            'flow' => ['nullable', 'string', 'max:64'],
            'client_id' => ['required', 'string', 'max:255'],
            'redirect_uri' => ['required', 'string', 'max:2048'],
            'state' => ['nullable', 'string', 'max:1024'],
            'nonce' => ['nullable', 'string', 'max:1024'],
        ]);

        $level = in_array('aal2', explode(' ', $validated['acr_values'] ?? ''), true) ? Assurance::AAL2 : null;
        $maxAge = isset($validated['max_age']) ? (int) $validated['max_age'] : null;
        $freshProof = $maxAge === 0 || in_array('login', explode(' ', $validated['prompt'] ?? ''), true);
        $silent = in_array('none', explode(' ', $validated['prompt'] ?? ''), true);

        // The moment this authorization started, stored under an ID only
        // this authorization request carries, with a hash of the request
        // so the ID can't be replayed with others. prompt=login asks for a
        // proof since then, and max_age takes one since then too, so a slow
        // confirm doesn't send the user round again.
        $hash = hash('sha256', json_encode([
            $validated['client_id'], $validated['redirect_uri'], $validated['state'] ?? null, $validated['nonce'] ?? null,
        ], JSON_THROW_ON_ERROR));
        $flows = collect($request->session()->get('oidc.flows', []))
            ->filter(fn (mixed $flow) => is_array($flow) && $flow['at'] > now()->subMinutes(10)->getTimestamp());

        $flow = $validated['flow'] ?? null;
        $stored = $flow === null ? null : $flows->get($flow);
        $started = $stored !== null && hash_equals($stored['request'], $hash) ? $stored['at'] : null;

        // A silent request can't confirm, so it stores no moment.
        if (($freshProof || $maxAge !== null) && ! $silent && $started === null) {
            $flow = Str::random(40);
            $request->session()->put('oidc.flows', [
                ...$flows->sortByDesc('at')->take(4)->all(),
                $flow => ['at' => now()->getTimestamp(), 'request' => $hash],
            ]);

            return redirect($request->fullUrlWithQuery(['flow' => $flow]));
        }

        // prompt=none mustn't show the user anything, not even the sign-in page.
        if ($silent && Keyring::guard()->guest()) {
            return $this->loginRequired($validated);
        }

        // Signing in comes after the moment, so it counts toward it.
        if (Keyring::guard()->guest()) {
            throw new AuthenticationException(guards: [config('keyring.guard')]);
        }

        // A silent request stores no moment, so it counts from now, when
        // it arrived.
        $arrived = $started ?? now()->getTimestamp();

        $since = match (true) {
            $freshProof => Carbon::createFromTimestamp($arrived),
            $maxAge !== null => Carbon::createFromTimestamp(min($arrived, now()->getTimestamp() - $maxAge)),
            default => null,
        };

        // A silent request only asks meets(), which starts no confirm, so
        // it's never saved as the page to come back to.
        $response = match (true) {
            $level === null && $since === null => null,
            $silent => $stepUp->meets($request, $level, $since) ? null : $this->loginRequired($validated),
            default => $stepUp->unlessMet($request, $level, $since),
        };

        if ($response !== null) {
            return $response;
        }

        if ($started !== null) {
            $request->session()->forget("oidc.flows.{$flow}");
        }

        // Issue the authorization code, with the claims from below...
    }
}
```

A flow ID that's expired, unknown or stored for another request isn't used, so the user confirms again. `validate()` keeps the example short. A real provider sends `invalid_request` back to the client, and `loginRequired()` stands for a `login_required` error. Map outside values to a level yourself, and decide what to do with unknown ones. `Assurance::fromName()` throws for a name it doesn't know.

## Reading What Was Proved

An integration may need to say how the user authenticated, as `amr`, `acr` and `auth_time` in an ID token. Read that from `Keyring\Sessions\SessionAssurance`:

- `level(int $since = 0)` returns the highest `Assurance` the session holds now. Given a Unix timestamp, it counts only what was proved since then.
- `countingToward(Assurance $level, int $since = 0)` returns the verifications that still count toward a level, within its limits. It also takes a timestamp.
- `all()` returns every verification in the session, including ones that no longer count, such as a code proved a day ago. Use `countingToward()` for what you report, or `all()` overstates the session.

Each item is a `Keyring\Login\Verification`, listed under [Verification Properties](https://keyringauth.com/docs/0.x/step-up#verification-properties). `Requirement::isMetBy(array $verifications)` checks a set against a requirement, and `Assurance::of(array $verifications)` returns the highest level it reaches.

Report `auth_time` as the oldest `provedAtIfKnown()` among the verifications behind `amr`, and leave it out if any is `null`. The claim says every method in `amr` was proved at or after `auth_time`. A session that proved a password and an app 20 hours ago, and the password again a minute ago, has `auth_time` 20 hours ago.

With `$since`, build the claims only from what was proved since that moment. Don't recompute the level with `Assurance::of()` from what counts toward a lower level. If AAL2 lapsed and the session is at AAL1, the app proved before the lapse still counts toward AAL1, so `Assurance::of()` would wrongly say AAL2.

For the same reason, report `mfa` only at AAL2 or higher, and at AAL1 report just the factor that holds it:

```php
use Keyring\Enums\Assurance;
use Keyring\Login\Requirement;
use Keyring\Login\Verification;
use Keyring\Sessions\SessionAssurance;

$assurance = app(SessionAssurance::class);
$from = $since?->getTimestamp() ?? 0;

$level = $assurance->level($from);
$proved = $level === Assurance::None ? [] : $assurance->countingToward($level, $from);

// One factor holds AAL1: report the newest, not a second factor that
// stopped counting toward AAL2 when it lapsed.
if ($level === Assurance::AAL1) {
    usort($proved, fn (Verification $a, Verification $b) => $b->at <=> $a->at);
    $proved = [array_find($proved, fn (Verification $verification) => Requirement::for(Assurance::AAL1)->isMetBy([$verification]))];
}

// Null for a verification proved at an unknown time.
$times = array_map(fn (Verification $verification) => $verification->provedAtIfKnown(), $proved);

$claims = [
    'acr' => $level === Assurance::None ? null : strtolower($level->name),
    'amr' => [
        ...array_values(array_unique(array_column($proved, 'factor'))),
        ...($level->atLeast(Assurance::AAL2) ? ['mfa'] : []),
    ],
    // Left out (null) when nothing was proved, or when it was proved at an
    // unknown time.
    'auth_time' => $times === [] || in_array(null, $times, true) ? null : min($times),
];
```

Build the claims in the authorization request, while the browser's session is there, and keep them with the code. The token endpoint has no session.

Keyring's factor keys aren't the registered `amr` values (RFC 8176), so map them yourself. Tell clients to read `acr` for the level, not to derive it from `amr`. An identity provider's own `amr` and `acr` appear as `providerAmr` and `providerAcr`, which Keyring never counts toward the level or `mfa`.

## The Confirm Flow

When a request needs step-up, Keyring starts a confirm attempt and redirects to the confirm page. It works like the [login challenge](https://keyringauth.com/docs/0.x/sign-in-flow#the-challenge-page), with its own routes:

| Method | URI | Name |
|---|---|---|
| `GET` | `/confirm/{factor?}` | `keyring.confirm.challenge` |
| `POST` | `/confirm/{factor}` | `keyring.confirm.verify` |
| `POST` | `/confirm/{factor}/send` | `keyring.confirm.send` |

These need a user signed in to Keyring's guard (`auth:{guard}`). The page is `confirm`, with `purpose: "confirm"` and `canTrustDevice: false`. Visiting `/confirm` with no attempt in progress starts one.

Any single factor except a recovery code satisfies it, provided it was proved recently. A link at a [`never`](https://keyringauth.com/docs/0.x/sso#freshness) identity provider isn't offered on this page. A user with nothing to confirm with is sent to your [`enrollment_url`](https://keyringauth.com/docs/0.x/configuration#account-changes-and-enrollment), or gets a `403`. Identity providers are offered like any other method, except `never` providers, which are only offered toward a level. Their `challenge` prop holds `provider`, `label` and `url`, pointing at `GET /confirm/sso/redirect` (`keyring.sso.confirm`). See [Single Sign-On](https://keyringauth.com/docs/0.x/sso#step-up).

If a page asks again while a confirm for the same requirement is in progress, it continues that attempt, so nothing already proved is lost. Recovery codes are only offered when using one could finish the confirm.

Once the user has verified enough, Keyring:

1. regenerates the session ID and moves the session to a new [registry record](https://keyringauth.com/docs/0.x/devices-and-sessions#the-session-registry), revoking the old one, so a copy of the old session is signed out,
2. records the new verifications, which resets the [level's clocks](https://keyringauth.com/docs/0.x/devices-and-sessions#timeouts),
3. sets Laravel's `auth.password_confirmed_at` (see [below](https://keyringauth.com/docs/0.x/step-up#laravels-password-confirmation)),
4. dispatches `Keyring\Events\Confirmed`,
5. redirects to the intended URL, or `home`.

For a `GET`, the intended URL is the page that needed step-up. For other methods it's the request's `Referer`, when that's on your own origins, so the user returns to the form rather than to a URL they can't `GET` (see [Where They Go Next](https://keyringauth.com/docs/0.x/sign-in-flow#where-they-go-next)). The confirm attempt expires after `pending_logins.keep_for`, and then `keyring::keyring.expired` shows on the next field.

## JSON Requests

A JSON request, which isn't an Inertia visit, gets a `423 Locked` instead of a redirect:

```json
{
  "message": "Please confirm it's you to continue.",
  "page": "confirm",
  "redirect": "https://example.com/confirm"
}
```

Send the user to `redirect` and let them try again. Keyring remembers the page that made the call, so the user returns to it. Protecting the page's own `GET` route with the same middleware asks up front, when the page loads. See [Handling Step-Up in JavaScript](https://keyringauth.com/docs/0.x/frontend#handling-step-up-in-javascript).

## Laravel's Password Confirmation

Confirming through Keyring also satisfies Laravel's `password.confirm` middleware, but not the other way round. Laravel's own password confirmation doesn't count for Keyring's middleware.

Keyring sets `auth.password_confirmed_at` to the latest moment the user really proved one of the factors the confirm added (`Verification::provedAt()`). A sign-in at an identity provider that let them straight through counts from when they signed in there. What the confirm built on confirms nothing. A confirm that only added a round trip to a [`never`](https://keyringauth.com/docs/0.x/sso#freshness) provider leaves the value alone, and the value never moves back.

## Events

`Keyring\Events\Confirmed` is dispatched with `user` and `attempt` when a confirmation completes. `FactorVerified` and `FactorFailed` fire as they do at login, with the `confirm` purpose. See the [verification events](https://keyringauth.com/docs/0.x/sign-in-flow#events).

## Verification Properties

Each `Keyring\Login\Verification` has these public properties:

| Property | Type | Meaning |
|---|---|---|
| `factor` | `string` | The factor's key, such as `password`, `totp`, `passkey` or `recovery`. |
| `authenticator` | `?string` | The stored authenticator's ID, or `null` for a factor with none, such as the password. |
| `categories` | `list<Category>` | What it proved. `Address` is for an emailed code, which isn't an authentication factor. |
| `phishingResistant` | `bool` | Whether it was a passkey or security key. |
| `at` | `int` | When it was verified, as a Unix timestamp. Levels and timeouts go by this. |
| `deviceBound` | `bool` | Whether the key can't leave its device. |
| `attested` | `bool` | Whether the key was added with a verified attestation. |
| `authenticatedAt` | `?int` | When the user really proved it, if earlier than `at`. Set only by an [identity provider](https://keyringauth.com/docs/0.x/sso) sign-in, from `auth_time`. `Verification::UNKNOWN` (`0`) means the provider didn't say, so treat it as unknown, never as recent. `null` when it's the same as `at`. |
| `providerAmr` | `list<string>` | For an [identity provider](https://keyringauth.com/docs/0.x/sso#second-factors-and-policies), the `amr` values its ID token sent, at most 10. Keyring counts none of them. |
| `providerAcr` | `?string` | For an identity provider, the `acr` its ID token sent. Counted toward nothing. |

`provedAt()` returns when the user last proved it: `authenticatedAt`, or `at` when that's `null` or earlier, and freshness goes by it. `provedAtIfKnown()` returns the same, or `null` when unknown. Use it whenever you report a time, so an unknown one can't show as a sign-in on 1 January 1970.

## How It Works

Fresh verification has more rules than the list above:

- A recovery code stands in for a lost key, along with the password. A policy that takes no codes at sign-in (`noDowngrade(except: [])`, or `phishingResistant()`) takes none here either. A code is never the whole of a confirmation, and a user whose only other sign-in method is a set of recovery codes confirms with the password.
- A policy the user can't fully meet yet, such as one that asks for a passkey they haven't added, counts as far as they can go, so they can still add it.
- A policy that asks for more is honoured. A [policy closure](https://keyringauth.com/docs/0.x/policies#deciding-per-user-and-attempt) is asked about the browser the request comes from, and about an attempt nothing is known of, and the stricter answer stands. A trusted device gets no discount, and risk isn't assessed again.
- The window starts at the moment of verification and doesn't slide with activity, so using the app doesn't keep it fresh.
- A sign in counts as a verification. A sign-in with an identity provider whose [`freshness`](https://keyringauth.com/docs/0.x/sso#freshness) is `reauthenticate` counts from when the user last signed in at the provider, as its ID token says (`auth_time`). One without `auth_time` is never fresh, and one with a `never` provider is never fresh. So does [adding a sign-in method](https://keyringauth.com/docs/0.x/authenticators#confirming), for the method that was added. See [Single Sign-On](https://keyringauth.com/docs/0.x/sso#step-up).

Signing in counts, so a copy of a just-signed-in session can act for 15 minutes without proving anything. Keyring limits what that copy can add to an account:

- Adding a second factor to an account with none established takes [the current password](https://keyringauth.com/docs/0.x/authenticators#the-password-for-a-first-second-factor), which a copy of the cookie doesn't have. An account without a password isn't covered.
- A new sign-in method isn't [established](https://keyringauth.com/docs/0.x/authenticators#established-authenticators) for 7 days. Until then, it doesn't make `noDowngrade()` ask for a passkey, so the owner's password and authenticator app still sign them in.
- While the account has a sign-in method that isn't established, it can't remove, rename or replace an established one, or replace established recovery codes. The owner can still remove the new one.
- One such removal or replacement freezes the rest for 7 days too. So a fresh session can do at most one of them, and only when the account had nothing new. It can't take the last second factor, which needs the password.

See [Frozen Sign-In Methods](https://keyringauth.com/docs/0.x/authenticators#frozen-sign-in-methods).
