# Policies

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

## Introduction

The **policy** decides what a user must prove to sign in and to confirm sensitive actions. It's a function given to `Require`, as `Keyring::require()` takes a closure:

```go
k := keyring.New[models.User]().Require(func(ctx context.Context, user *models.User, attempt keyring.Attempt) keyring.Requirement {
    return keyring.AAL2.Requirement().IfEnrolled().NoDowngrade()
})
```

The default is `keyring.AAL2.Requirement().IfEnrolled()`, as in the PHP package. Users sign in with their password until they add a second factor, and then they need it too. The zero `keyring.Requirement` is the default too. There's no fixed requirement setting beside `Require`: a function that returns one requirement does the same. 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 `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/go/factors#email-codes) is `keyring.Address`, which never counts as a factor.

```go
keyring.AAL2.Requirement()  // two categories, one of them possession
keyring.RequireFactors(3)   // three categories of any kind
keyring.AAL2.Requirement().Including(keyring.Knowledge).PhishingResistant()
```

Each method returns a changed copy. The [requirement reference](https://keyringauth.com/docs/0.x/go/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 `keyring.Level`: `keyring.AAL1`, `keyring.AAL2` and `keyring.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.

Keyring for Go doesn't check attestation yet, so no session reaches AAL3, and `RequireAssurance[U]{Level: keyring.AAL3}` sends users to your enrollment page. A passkey that can't sync still counts as device bound at AAL2, through `keyring.AAL2.Requirement().DeviceBound()` or `RequireAssurance[U]{DeviceBound: true}`.

> [!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.

The [step-up middleware](https://keyringauth.com/docs/0.x/go/step-up#raising-assurance) asks for these levels, as in `keyring.RequireAssurance[models.User]{}`, which is AAL2.

## Only When Enrolled

`IfEnrolled()` 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 `Config.EstablishedAfter`, 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 `IfEnrolled()`, users who can't meet the requirement can't sign in. For a password and an emailed code to be enough, use `keyring.RequireSteps(2)`.

## Requiring a Second Factor

`IfEnrolled()` 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 `Config.EnrollmentURL` at your page for adding one:

```go
func Options() laravel.Options {
    k := keyring.New[models.User](func(cfg *keyring.Config) {
        cfg.EnrollmentURL = "/settings/security"
    })

    return laravel.Options{
        Packages: []laravel.Package{k},
        Middleware: func(m *laravel.Middleware, _ *config.Config) {
            m.Web.Append(keyring.RequireEnrollment[models.User]{})
        },
        // ...
    }
}
```

A package's middleware goes in ahead of the application's, so yours 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, inside the web group: without the session it fails closed with a `500`, as `RequireAssurance` does, where the PHP package's lets the request through.

`keyring:install` prints this, with `EnrollmentURL` set to `/settings/security`, when you name an authenticator app or passkeys (`--factor=totp` or `--factor=passkeys`), unless you pass `--optional-second-factor`. Security keys aren't in Keyring for Go.

A JSON request gets the `403` `{ "status": "enroll-first", "message", "redirect" }`, with `EnrollmentURL` 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[U]{PhishingResistant: true}` asks for a passkey, and `RequireEnrollment[U]{DeviceBound: true}` for one that can't sync, as `keyring.enrolled:aal2,phishing-resistant` and `keyring.enrolled:aal2,device-bound`.

Guests go through, for the route's own check. So do Keyring's own routes, signing out (`logout`), email verification (`verification.*`), changing the password (`user-password.update`) and the `EnrollmentURL` page. Name anything else your enrollment page calls in `Config.EnrollmentExcept`, by route name, with `*` as a wildcard, as the PHP package's `enrollment_except`.

A user held until they choose a new password is let through to `Config.PasswordChangeURL`'s page too: the hold comes first. In the PHP package such a user with no second factor goes round in a loop between the two pages.

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.

A browser that's [impersonating](https://keyringauth.com/docs/0.x/go/impersonation) someone goes through as well, as in the PHP package: enrolling isn't the impersonator's to do.

An admin without a second factor can still impersonate someone, if your `AllowImpersonationWhen` lets them and `Impersonation.Middleware` doesn't ask for AAL2, since `RequireEnrollment` doesn't stand in front of Keyring's `POST /impersonate/{user}`. If you require a second factor of admins, check it in `AllowImpersonationWhen`.

### 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/go/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/go/starter-kit/README.md#requiring-a-second-factor) does. A page that isn't JSON finds it in the `keyring.result` flash, which `keyring.FlashedResult(r)` reads (see [Flash Messages and Alerts](https://keyringauth.com/docs/0.x/go/frontend#flash-messages-and-alerts)). The starter kit's `resources/js/pages/settings/security.tsx` shows the link once the recovery codes it showed are saved.

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 Go doesn't tell a middleware the values of the route's other middleware. So give `RequireEnrollment` the same options as the route's `RequireAssurance`. Otherwise a user who enrolls enough for `RequireEnrollment` alone is handed the page, and `RequireAssurance` sends them to enroll again. See [Requiring a Second Factor](https://keyringauth.com/docs/0.x/go/differences#requiring-a-second-factor).

> [!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

`NoDowngrade()` 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/go/authenticators#established-authenticators) passkey, the requirement gains `PhishingResistant()`, and "Try another way" offers only their keys plus recovery codes, the way back when the key is lost.

`NoDowngradeExcept(factors...)` names the exceptions instead, as `noDowngrade(except: [...])`. To accept only keys, name none:

```go
keyring.AAL2.Requirement().IfEnrolled().NoDowngradeExcept()
```

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

## Deciding Per User and Attempt

The function given to `Require` gets the request's context, the user as your type and a `keyring.Attempt`, and returns a `Requirement`:

```go
k.Require(func(ctx context.Context, user *models.User, attempt keyring.Attempt) keyring.Requirement {
    switch {
    case user.IsAdmin:
        return keyring.AAL2.Requirement().PhishingResistant()
    case attempt.Device() != nil && attempt.Device().IsTrusted(ctx):
        return keyring.AAL1.Requirement()
    case attempt.Risk != nil && attempt.Risk.IsElevated():
        return keyring.AAL2.Requirement()
    default:
        // An unknown device and risk land here, so keep this the strictest
        // answer you want for an attempt Keyring knows nothing about.
        return keyring.AAL2.Requirement().IfEnrolled()
    }
})
```

The attempt has `Purpose` (`keyring.PurposeLogin` or `keyring.PurposeConfirm`), `Verifications`, `Remember`, `Risk` (the `*keyring.Risk` the signals found at sign in, or nil), `StepUp`, `Device()` (the browser's `*keyring.Device`, whose `IsTrusted(ctx)` is "don't ask again on this device", or nil, as for one signed out meanwhile), `DeviceID()` and `IsNewDevice()`. There's no `user()` or `keyring()` on it: the user is the function's second argument, and `keyring.From[models.User](ctx)` reaches Keyring. The context is there for `IsTrusted`, which reads the application's clock.

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 nil device and risk. Once the risk signals have run, a sign in's attempt always has a `Risk`, empty when nothing was found. Trusted devices do nothing until the policy reads them, as in the PHP package.

The contract app's [policy](https://github.com/keyringauth/keyring/blob/main/go/contract-app/policies/policies.go) reads both a trusted device and the risk.

## Checking Requirements in Code

There's no `UserKeyring`. Ask Keyring instead:

```go
k := keyring.From[models.User](r)
attempt := keyring.Attempt{Purpose: keyring.PurposeLogin}

// What the policy says, as Keyring::policy().
asked := k.Policy(r, user, attempt)

// With IfEnrolled and NoDowngrade applied to their sign-in methods.
required, err := k.RequirementFor(r, user, attempt, false)
if err != nil {
    return web.Fail(err)
}

// Do these verifications meet it?
met := required.IsMetBy(attempt.Verifications)

// Do they have a second factor? Recovery codes don't count.
methods, err := k.SignInMethods(r, user)
if err != nil {
    return web.Fail(err)
}
hasSecondFactor := methods.HasSecondFactor
```

`RequirementFor` with `reachable` true limits a policy the user can't fully meet to what they can, as if it said `IfEnrolled()`, as `Keyring::requirementFor(..., reachable: true)`. What risk asked for at sign in isn't added. `SignInMethods` is what the user's sign-in methods are when it's called: call it again after changing them.

## Requirement Reference

| Method | Means |
|---|---|
| `keyring.AAL1.Requirement()` | Any one category. |
| `keyring.AAL2.Requirement()` | Two categories, one of them possession. |
| `keyring.AAL3.Requirement()` | AAL2 with an attested, phishing-resistant key that can't leave its device, by itself or with a password. Nothing meets it yet. |
| `keyring.RequireFactors(3)` | That many categories of any kind, and at least one. |
| `keyring.RequireSteps(2)` | That many categories, at least one a factor. A password and an email code will do. |
| `.Including(keyring.Possession)` | Those categories must be among those verified. |
| `.PhishingResistant()` | At least one verification must be a passkey. |
| `.DeviceBound()` | At least one verification must be a phishing-resistant key that can't leave its device. |
| `.AttestedKey()` | That key must have a verified attestation. Nothing meets it yet. |
| `.IfEnrolled()` | Apply the requirement as far as the user's authenticators can meet it. |
| `.NoDowngrade()` | Users with a passkey must use one, or a recovery code. |
| `.NoDowngradeExcept(factors...)` | Users with a passkey must use one, or a factor in the list. |
| `.IsMetBy(verifications)` | Whether the verifications meet it as it stands, for your own code. |

A level under AAL1 is AAL1's, and one over AAL3 is AAL3's. There's no `Requirement::named()`: the middleware take fields rather than parameters.

## 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/go/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/go/step-up) to a level sets its own requirement.
- [Registration](https://keyringauth.com/docs/0.x/go/sign-in-flow#registration) doesn't consult the policy. With `Registration.RevealTaken`, 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 `IfEnrolled()`. See [Removing Authenticators](https://keyringauth.com/docs/0.x/go/authenticators#removing-authenticators).
