# Step-Up

Source: https://keyringauth.com/docs/0.x/rust/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, in `laravel_keyring::http`:

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

laravel-rust has no middleware names, so they're values on a route or group rather than strings:

```rust
use std::time::Duration;
use laravel::routing::Router;
use laravel_keyring::http::{RequireAssurance, RequireFreshVerification};

fn billing(route: &mut Router) {
    route.middleware(RequireAssurance::<Users>::aal2()).group(|route| {
        route.get("/billing", show_billing);

        route
            .middleware(RequireFreshVerification::<Users>::within(Duration::from_secs(5 * 60)))
            .group(|route| {
                route.delete("/account", delete_account);
            });
    });
}
```

Put them on routes in the `web` group, after the session has started. Without a session they're a server error, not a way past them. A guest gets laravel-rust's `401`, and a browser is sent to the login page.

What the session proved counts only for the user its record belongs to. On a route whose user comes from a request guard (`Authenticate::via()`), put the gate after the guard: a browser session someone else signed in to then proves nothing for the guard's user. See [Second Factors and Step-Up](https://keyringauth.com/docs/0.x/rust/security#second-factors-and-step-up).

## Raising Assurance

`RequireAssurance::<Users>::aal2()` lets the request through at AAL2 or higher, as `keyring:aal2`. `aal1()` and `aal3()` work the same way.

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

Two differences from the PHP package:

- The confirm asks for the whole level afresh, where the PHP package's builds on what still counts toward it.
- `aal1()` takes no recovery code alone, where the PHP package's `keyring:aal1` does. This is deliberate: a recovery code stands in for a lost factor beside another one, never as the whole of what's asked.

A level lapses on its own clock, as in the PHP package. At AAL2, it lapses after an hour without a request, or 24 hours overall. See [Timeouts](https://keyringauth.com/docs/0.x/rust/devices-and-sessions#timeouts). The idle limit is kept by `AuthenticateSession`, which is in the `web` group. A [risk response](https://keyringauth.com/docs/0.x/rust/risk#checkpoints) can clear a level, and removing an authenticator stops it counting everywhere.

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

A user without the authenticators for a level gets the `403` `enroll-first`, and a browser is sent to your [`enrollment_url`](https://keyringauth.com/docs/0.x/rust/configuration#account-changes-and-enrollment).

To check the level in your own code:

```rust
use laravel_keyring::{Assurance, SessionAssurance};

SessionAssurance::of(&session).level(0).await?.at_least(Assurance::Aal2);
```

## Fresh Verification

`RequireFreshVerification::<Users>::new()` lets the request through when the user verified, in the last 15 minutes, the strongest combination their account can give, and at least what signing in would ask. `within(duration)` gives a route a window of its own, as `keyring.fresh:5m`. What counts as the strongest combination is the PHP package's, as its [docs](https://keyringauth.com/docs/0.x/step-up#fresh-verification) describe.

Keyring asks for this on its own sensitive routes for `changes_fresh_for`, 15 minutes by default, in place of the PHP package's `changes_middleware`. Those routes cover managing authenticators, ending sessions, signing out devices, changing the password and starting an email change. `changes_fresh_for` doesn't reach `RequireFreshVerification` on your own routes, and `None` turns it off on Keyring's.

## 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`. `laravel_keyring::StepUp` makes the same decision in a handler, as the PHP package's `StepUp`:

```rust
use laravel::auth::Auth;
use laravel::http::{IntoResponse, Request, Response};
use laravel::session::Session;
use laravel_keyring::{Assurance, StepUp};

async fn authorize(auth: Auth<User>, session: Session, request: Request) -> laravel::Result<Response> {
    // acr_values=aal2, with the moment this authorization started for
    // max_age, kept from before the user was sent anywhere.
    let started = stored_moment(&session, &request)?;

    if let Some(response) =
        StepUp::<Users>::unless_met(&auth, &session, &request, Some(Assurance::Aal2), Some(started)).await?
    {
        return Ok(response);
    }

    // Issue the authorization code...
    Ok(().into_response())
}
```

It returns `None` 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 `RequireAssurance`, and asks for that level afresh. `since` works like `RequireFreshVerification`.

With nobody signed in, `unless_met()` fails with `abort_with(401)`, where the PHP package throws an `AuthenticationException`. It fails with a plain error when asked for nothing, for `Assurance::None`, or for a moment more than `StepUp::CLOCK_LEEWAY` (5) seconds in the future.

### Passing a Fixed Moment

A moment that moves with every request can never be met. Store the moment the authorization request arrived, for that one request only, and pass it, as the [PHP docs](https://keyringauth.com/docs/0.x/step-up#passing-a-fixed-moment) describe. Their advice on keeping it to one authorization request holds here.

### Asking Without Starting a Confirm

For requests that must get an answer without showing the user anything, such as `prompt=none`, use `StepUp::<Users>::meets()`. It takes the same arguments as `unless_met()` and returns `true` when `unless_met()` would return `None`, without starting a confirm. It fails for a guest, too, so check for a guest first.

### An Example

The [PHP example](https://keyringauth.com/docs/0.x/step-up#an-example) translates directly: read `acr_values`, `max_age` and `prompt`, check outside values before they reach `unless_met()`, store the moment under an ID only this request carries, then call `unless_met()` or `meets()`. `Assurance::from_name()` maps a name such as `aal2` to a level, and fails for one 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 `laravel_keyring::SessionAssurance`:

- `level(since)` returns the highest `Assurance` the session holds now. Given a Unix timestamp, it counts only what was proved since then. `0` counts everything.
- `counting_toward(level, since)` returns the verifications that still count toward a level, within its limits.
- `all()` returns every verification in the session, including ones that no longer count. Use `counting_toward()` for what you report, or `all()` overstates the session.

```rust
use laravel_keyring::{Assurance, SessionAssurance};

let assurance = SessionAssurance::of(&session);
let level = assurance.level(0).await?;
let proved = if level == Assurance::None {
    Vec::new()
} else {
    assurance.counting_toward(level, 0).await?
};

// `auth_time`: the oldest moment behind `amr`, left out when one isn't known.
let auth_time = proved
    .iter()
    .map(|verification| verification.proved_at_if_known())
    .collect::<Option<Vec<i64>>>()
    .and_then(|times| times.into_iter().min());
```

Each item is a `laravel_keyring::Verification`, listed under [Verification Properties](https://keyringauth.com/docs/0.x/rust/step-up#verification-properties). `Requirement::is_met_by(&verifications)` checks a set against a requirement, and `Assurance::of(&verifications)` returns the highest level it reaches. The PHP docs' advice on `auth_time`, `$since` and `mfa` holds here: see [Reading What Was Proved](https://keyringauth.com/docs/0.x/step-up#reading-what-was-proved).

## 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/rust/sign-in-flow#the-challenge-page), with its own routes, under a session key of its own (`keyring.attempt.confirm`), so options a sign in was given never answer a confirm:

| Method | URI |
|---|---|
| `GET` | `/confirm/{factor?}` |
| `POST` | `/confirm/{factor}` |
| `POST` | `/confirm/{factor}/send` |

The page is `confirm`, with `purpose: "confirm"`. Visiting `/confirm` with no attempt in progress asks for one factor. Each factor is a page of its own (`202` `{ "status": "challenge", "page": "confirm" }` between), and a passkey that verified the user is both.

Once the user has verified enough, Keyring answers `200` `{ "status": "authenticated", "redirect" }`, moves the browser to a new session ID and record (a copy of the session from before is signed out), records what it proved, raises the record's level, and dispatches `Confirmed`. Its `redirect` is where the step-up was asked for: the page itself for a `GET` that isn't for JSON, otherwise the last page the session visited when it's on this site, or `home`. The page a step-up goes back to is checked against the request's origin and `APP_URL`'s.

## JSON Requests

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

```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. See [Handling Step-Up in JavaScript](https://keyringauth.com/docs/0.x/rust/frontend#handling-step-up-in-javascript).

## Laravel's Password Confirmation

Confirming through Keyring sets `auth.password_confirmed_at` in the session, as in the PHP package, for anything of yours that reads it. laravel-rust has no `password.confirm` middleware of Laravel's to satisfy.

## Events

`laravel_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 [Events](https://keyringauth.com/docs/0.x/rust/events).

## Verification Properties

Each `laravel_keyring::Verification` has these public fields:

| Field | Type | Meaning |
|---|---|---|
| `factor` | `String` | The factor's key, such as `password`, `totp`, `passkey` or `recovery`. |
| `authenticator` | `Option<String>` | The stored authenticator's ID, or `None` for a factor with none, such as the password. |
| `categories` | `Vec<&'static str>` | What it proved, such as `possession`. |
| `user_verified` | `bool` | Whether a key verified the user. |
| `phishing_resistant` | `bool` | Whether it was a passkey or security key. |
| `at` | `i64` | When it was verified, as a Unix timestamp. |
| `device_bound` | `bool` | Whether the key can't leave its device. |
| `attested` | `bool` | Whether the key was added with a verified attestation. |
| `authenticated_at` | `Option<i64>` | When the user really proved it, if earlier than `at`, from an identity provider's `auth_time`. `Verification::UNKNOWN` means the provider didn't say. |
| `provider_amr`, `provider_acr` | `Vec<String>`, `Option<String>` | What an identity provider's ID token sent. Counted toward nothing. |

`proved_at()` returns when the user last proved it, and freshness goes by it. `proved_at_if_known()` returns the same, or `None` when unknown. Use it whenever you report a time.

## How It Works

Fresh verification's other rules are the PHP package's, as its [How It Works](https://keyringauth.com/docs/0.x/step-up#how-it-works) describes: recovery codes stand in for a lost key beside the password, never alone; a policy the user can't fully meet yet counts as far as they can go; a policy closure is asked about this browser and about one nothing is known of; the window doesn't slide with activity; and a sign in counts as a verification. The limits on what a copy of a just-signed-in session can add to an account (the password for a first second factor, established authenticators and the freeze) are the same. See [Frozen Sign-In Methods](https://keyringauth.com/docs/0.x/rust/authenticators#frozen-sign-in-methods).
