# Policies

Source: https://keyringauth.com/docs/0.x/rust/policies

## Introduction

The **policy** decides what a user must prove to sign in and to confirm sensitive actions. It's `KeyringConfig::policy`, one requirement for everybody:

```rust
use laravel_keyring::{KeyringConfig, Requirement};

laravel::Application::configure().with_config(|config, _| {
    config.section_mut::<KeyringConfig>().policy = Requirement::aal2().if_enrolled().no_downgrade(&["recovery"]);
});
```

The default is `Requirement::aal2().if_enrolled()`, as in the PHP package. Users sign in with their password until they add a second factor, and then they need it too. The rules are the PHP package's, so a user asked for a second factor on one side is asked for it on the other.

## Requirements

A `laravel_keyring::Requirement` counts **distinct categories**, not verifications. The authentication categories are knowledge, possession and inherence, so a password plus a PIN is still one factor. An [email code](https://keyringauth.com/docs/0.x/rust/factors#email-codes) is `Category::Address`, which never counts as a factor.

```rust
use laravel_keyring::{Category, Requirement};

Requirement::aal2(); // two categories, one of them possession
Requirement::factors(3); // three categories of any kind
Requirement::aal2().including(&[Category::Knowledge]).phishing_resistant();
```

Each modifier takes the requirement and returns a new one. The [requirement reference](https://keyringauth.com/docs/0.x/rust/policies#requirement-reference) lists them all.

## Assurance Levels

Keyring works out a level from what the user proved in their session, exactly as the PHP package does. The levels are `laravel_keyring::Assurance`: `None`, `Aal1`, `Aal2` and `Aal3`. The table of what reaches each level, and why, is in the [PHP docs](https://keyringauth.com/docs/0.x/policies#assurance-levels), and holds here.

One difference: an Ed25519 passkey can't be verified by the crate, so it reaches no level here. See [Signature Algorithms](https://keyringauth.com/docs/0.x/rust/passkeys#signature-algorithms).

Without attestation, no session reaches AAL3, and `RequireAssurance::aal3()` sends users to your enrollment page. A phishing-resistant key that stays on its device still counts at AAL2, through `Requirement::aal2().device_bound()` or `RequireAssurance::aal2().device_bound()`.

> [!WARNING]
> A session Keyring calls AAL3 has met NIST's requirements for the authentication. NIST's AAL3 also needs validated cryptography (FIPS 140), which no library supplies. Before you say your application is AAL3, buy validated keys, limit the factor to those models with [`aaguids`](https://keyringauth.com/docs/0.x/rust/passkeys#allowing-only-certain-models), and build on a validated cryptographic module.

The [step-up middleware](https://keyringauth.com/docs/0.x/rust/step-up#raising-assurance) asks for these levels, as in `RequireAssurance::aal2()`.

## Only When Enrolled

`if_enrolled()` applies a requirement as far as the user's authenticators can meet it, as the PHP package's `ifEnrolled()` does. A user who can't meet all of it proves the strongest version they can, and never gets away with one factor while they have a second. Only established authenticators decide what's asked (after `authenticator_changes.established_after`, 7 days by default), except on an account whose new factor took its password to add, where the new factor is asked for straight away. See the [PHP docs](https://keyringauth.com/docs/0.x/policies#only-when-enrolled) for the details, which hold here.

Without `if_enrolled()`, users who can't meet the requirement can't sign in. For a password and an emailed code to be enough, use `Requirement::steps(2)`.

## Requiring a Second Factor

`if_enrolled()` lets users without a second factor carry on with a password. To require one from everyone, which OWASP ASVS 5.0.0 asks for at Level 2 (requirement 6.3.3), append `RequireEnrollment` to the `web` group, the PHP package's `keyring.enrolled`, and point `enrollment_url` at your page for adding one:

```rust
use laravel_keyring::KeyringConfig;
use laravel_keyring::http::RequireEnrollment;

laravel::Application::configure()
    .with_config(|config, _| {
        let keyring = config.section_mut::<KeyringConfig>();
        keyring.enrollment_url = Some("/settings/security".to_owned());
    })
    .with_middleware(|middleware, _| {
        middleware.web(|web| {
            web.append(RequireEnrollment::<Users>::new());
        });
    });
```

Your `with_middleware` runs after the provider's, so it lands after `AuthenticateSession`. It lets guests through, so it's safe in the `web` group. It also works on a route or group of your own, but unlike `RequireFreshVerification`, a request without a session (outside the `web` group) goes straight through rather than failing, so keep it in the `web` group.

`keyring:install` prints this when you name an authenticator app, passkeys or security keys, unless you pass `--optional-second-factor`.

A JSON request gets the `403` `{ "status": "enroll-first", "message", "redirect" }`, with `enrollment_url` as it's set, and a page visit is sent there with the `enroll-first` status, or gets a `403` without one. Recovery codes and email codes don't count. `RequireEnrollment::<Users>::requiring(Requirement::aal3())` asks for an attested key that stays on its device, and `Requirement::aal2().device_bound()` for any key that does, as `keyring.enrolled:aal3` and `keyring.enrolled:aal2,device-bound`.

Guests go through, for the route's own check, and so does a browser impersonating someone. So do Keyring's routes for adding a sign-in method, confirming, sessions and devices, email changes, single sign-on and impersonation, signing out, email verification, changing the password and the `enrollment_url` page. So is your [`password_change_url`](https://keyringauth.com/docs/0.x/rust/protected-changes#requiring-a-password-change) while the user has to choose a new password, since the hold sends every other page, the enrollment page included, there. Name anything else your enrollment page calls in `enrollment_except`, as paths, where the PHP package names routes. Keyring knows its own routes by the handler the request matched, as laravel-rust's routes have no names (see [Differences From PHP](https://keyringauth.com/docs/0.x/rust/differences#requiring-a-second-factor)).

Give one route one `RequireEnrollment`: a route under two with different requirements sends a user who meets the first but not the second to enroll for the second, and the page saved for them only asks for that one.

An admin without a second factor can still impersonate someone, if your `allow_impersonation_when()` lets them, since `RequireEnrollment` doesn't stand in front of Keyring's `POST /impersonate/{user}`. If you require a second factor of admins, check it in `allow_impersonation_when()`.

### Carrying On Afterwards

As in the PHP package, the page a browser navigated to is remembered, with what it needed, and once the user adds a sign-in method that meets it, the `authenticator-added` [status response](https://keyringauth.com/docs/0.x/rust/sign-in-flow#status-responses) carries it as `continue`. Keyring doesn't redirect there itself, because the page may be showing new recovery codes: show a Continue link, as the [starter kit](https://github.com/keyringauth/keyring/blob/main/rust/starter-kit/README.md#requiring-a-second-factor) does. `http::result(&session, Some("continue"))` reads it for a page that isn't JSON.

One difference: the page is saved with `RequireEnrollment`'s own requirement. A `RequireAssurance` on the same route isn't added to it, as the PHP package adds the route's `keyring:aal2`, because laravel-rust doesn't let a middleware see the route's other middleware. A user who enrolls enough for `RequireEnrollment` alone is handed the page, and `RequireAssurance` sends them to enroll again, saving the page with its own requirement.

> [!NOTE]
> Browsers only send `Sec-Fetch-*` headers over HTTPS or to `localhost`. On a plain-HTTP development host, a page that isn't an Inertia visit gets no `continue`. Inertia visits still do.

## No Downgrade

`no_downgrade(except)` stops users with a phishing-resistant authenticator from being talked into a weaker one, as `noDowngrade()` does. Once a user has an [established](https://keyringauth.com/docs/0.x/rust/authenticators#established-authenticators) passkey or security key, the requirement gains `phishing_resistant()`, and "Try another way" offers only their keys plus the factors in `except`.

`except` is always given in Rust. The PHP package's `noDowngrade()` without arguments keeps recovery codes on offer, which here is `no_downgrade(&["recovery"])`. To accept only keys, pass an empty list:

```rust
Requirement::aal2().if_enrolled().no_downgrade(&[])
```

A newer key signs in like any other but doesn't raise the bar until it's established. An explicit `phishing_resistant()` never makes exceptions.

## Deciding Per User and Attempt

To decide for each user and attempt, as `Keyring::require()` takes a closure, give the provider one. It gets the user as your type and a `laravel_keyring::policy::Attempt`, and returns a `Requirement`:

```rust
use laravel_keyring::policy::{Attempt, Device};
use laravel_keyring::{KeyringServiceProvider, Requirement};

KeyringServiceProvider::<Users>::new().policy(|user: &User, attempt: &Attempt| {
    if user.is_admin {
        Requirement::aal2().phishing_resistant()
    } else if attempt.device().is_some_and(Device::is_trusted) {
        Requirement::aal1()
    } else if attempt.risk.as_ref().is_some_and(|risk| risk.is_elevated()) {
        Requirement::aal2()
    } else {
        // An unknown device and risk land here, so keep this the strictest
        // answer you want for an attempt Keyring knows nothing about.
        Requirement::aal2().if_enrolled()
    }
});
```

It takes the place of `KeyringConfig::policy`. The attempt has `purpose`, `verifications`, `remember`, `risk` (the `Risk` the signals found at sign in, or `None`), `step_up`, `device()` (the browser's `Device`, whose `is_trusted()` is "don't ask again on this device", or `None`, as for one signed out meanwhile), `device_id()` and `is_new_device()`. There's no `user()` or `keyring()` on it: the user is the closure's first argument, and the closure is synchronous, as the PHP package's is, so what it looks at is loaded before it's asked. Read anything else you need from the user value.

It's asked when the PHP package asks it: after every factor in a sign in, once the proof is right, with what the attempt has proved so far (the challenge page offers what the last answer decided, and doesn't ask again), when a user removes an authenticator (with no device and no risk), and twice for a fresh verification, about this browser and about one nothing is known of, the stricter answer standing. So cope with a `None` device and risk. Trusted devices do nothing until it reads them, as in the PHP package.

## Checking Requirements in Code

```rust
use laravel_keyring::{Category, Requirement, UserKeyring};

let keyring = UserKeyring::of(&user).await?;

keyring.can_meet(&Requirement::aal2()); // could their authenticators meet it?
keyring.has(Category::Possession); // do they have a possession factor?
```

`UserKeyring` is what the user's sign-in methods were when it was loaded: load it again after changing them. `laravel_keyring::policy::ask(&user, &attempt)` returns what the policy says, as `Keyring::policy()`. `policy::requirement_for(&user, &attempt, reachable)` returns it with `if_enrolled()` and `no_downgrade()` applied, as `Keyring::requirementFor()`.

## Requirement Reference

| Method | Means |
|---|---|
| `Requirement::aal1()` | Any one category. |
| `Requirement::aal2()` | Two categories, one of them possession. |
| `Requirement::aal3()` | `aal2()` with an attested, phishing-resistant key that can't leave its device, by itself or with a password. |
| `Requirement::factors(3)` | That many categories of any kind, and at least one. |
| `Requirement::steps(2)` | That many categories, at least one a factor. A password and an email code will do. |
| `Requirement::for_level(Assurance::Aal2)` | The requirement for an assurance level, as `Requirement::for()`. |
| `Requirement::named("aal2", &["device-bound"])` | The requirement middleware parameters name, as `keyring:aal2,device-bound` does. An error for a name it doesn't know. |
| `.including(&[Category::Possession])` | Those categories must be among those verified. `.including_possession()` is the same for possession. |
| `.phishing_resistant()` | At least one verification must be a passkey or security key. |
| `.device_bound()` | At least one verification must be a phishing-resistant key that can't leave its device. |
| `.attested_key()` | That key must have a [verified attestation](https://keyringauth.com/docs/0.x/rust/passkeys#requiring-attestation). |
| `.if_enrolled()` | Apply the requirement as far as the user's authenticators can meet it. |
| `.no_downgrade(&[...])` | Users with a passkey or security key must use one, or a factor in the list. |
| `.is_met_by(&proved)`, `.would_progress(&proved, &next)`, `.at_least(&other)` | Checks against what was proved, for your own code. |

## How It Works

The policy's effects beyond a single sign in are the PHP package's:

- The policy is asked again after every factor verified in a sign in, so a risk assessment can raise it partway through.
- When a [risk response](https://keyringauth.com/docs/0.x/rust/risk#responding-to-risk) asks for a step-up and the user has enough authenticators, the requirement becomes at least `aal2()`.
- Fresh verification asks for as much as a sign in would, and never less than the account's strongest combination. A [step-up](https://keyringauth.com/docs/0.x/rust/step-up) to a level sets its own requirement.
- [Registration](https://keyringauth.com/docs/0.x/rust/sign-in-flow#registration) doesn't consult the policy. With `registration.reveal_taken`, a new user is signed in with their password alone.
- Users can't remove an authenticator if what's left can't sign in or meet the policy, unless the policy uses `if_enrolled()`. See [Removing Authenticators](https://keyringauth.com/docs/0.x/rust/authenticators#removing-authenticators).
