# Risk

Source: https://keyringauth.com/docs/0.x/risk

## Introduction

Risk signals look for things that make a sign-in or a session look suspicious, such as a new device, a new country, or a session cookie turning up in another browser. Each signal that fires adds a score. The scores add up, to at most 100, to a **level**, and you decide what to do at each level.

## Choosing Signals

You pick signals in your `KeyringServiceProvider`. `keyring:install` writes this list:

```php
use Keyring\Facades\Keyring;
use Keyring\Risk\Signals;

Keyring::risk()->signals([
    Signals\SessionFingerprintChanged::class,
    // These two read the security log: Features::securityLog().
    Signals\RepeatedFactorFailures::class,
    Signals\SuccessAfterFailures::class,
    // These two go by an account's devices: Features::devices().
    Signals\NewDevice::class,
    Signals\InactiveAccount::class,
    // Signals\RecentlyChangedRecovery::class,
    // Signals\CredentialStuffing::class,
    // Signals\BreachedPassword::class,
    // Signals\NewCountry::class,
    // Signals\ImpossibleTravel::class,
]);
```

A signal whose feature is off stays commented out, ready to turn on with it. The rest are off until you turn them on:

- `BreachedPassword` calls Have I Been Pwned at every sign-in. It [holds](https://keyringauth.com/docs/0.x/risk#requiring-a-new-password) a user whose password turns up in a breach.
- `NewCountry` and `ImpossibleTravel` need a [locator](https://keyringauth.com/docs/0.x/devices-and-sessions#locations). Without one, they never fire.
- `RecentlyChangedRecovery` needs `Features::emailChanges()`.
- `CredentialStuffing` counts failures per IP address. See [Built-in Signals](https://keyringauth.com/docs/0.x/risk#built-in-signals) before you turn it on.

If your application doesn't use the published provider, it has no signals until you call `Keyring::risk()->signals([...])`.

The starting set can't refuse a user who has only a password. For that user, `NewDevice`, `InactiveAccount` and `SuccessAfterFailures` add up to 75, below the 90 that refuses a sign-in. Adding `RecentlyChangedRecovery` or `CredentialStuffing`, or raising a score, can push a password-only user over 90. For example, with `CredentialStuffing` on, `InactiveAccount` (30), `SuccessAfterFailures` (30) and `CredentialStuffing` (40) add up to 100 without any new device. Check the sums whenever you change the list.

## Responding to Risk

Without your own responder, Keyring answers by level. The thresholds are the `risk.levels` config option:

```php
'risk' => [
    'levels' => ['medium' => 30, 'high' => 60, 'critical' => 90],
],
```

A total of 30 or more is `Level::Medium`, 60 or more is `Level::High`, and 90 or more is `Level::Critical`. Anything less is `Level::Low`. Keyring's own response then does this:

| Level | Keyring's Response |
|---|---|
| `Low` | `Action::allow()` |
| `Medium` | `Action::stepUp()` |
| `High` | `Action::stepUp()->notify()` |
| `Critical` | `Action::deny()->revokeAllSessions()->notify()` |

`Level::Critical` is a plain deny, so a user with a second factor is refused too, not asked for one.

Four findings get an answer at any level. Three add a notice (`SuccessAfterFailures`, `InactiveAccount` and `CredentialStuffing`, see [Telling the User](https://keyringauth.com/docs/0.x/risk#telling-the-user)), and `BreachedPassword` adds a password hold (see [Requiring a New Password](https://keyringauth.com/docs/0.x/risk#requiring-a-new-password)).

To set your own response, add a responder in your `KeyringServiceProvider`:

```php
use Keyring\Facades\Keyring;
use Keyring\Risk\Action;
use Keyring\Risk\Checkpoint;
use Keyring\Risk\Level;
use Keyring\Risk\Risk;
use Keyring\Risk\Signals\ImpossibleTravel;
use Keyring\Risk\Signals\NewCountry;
use Keyring\Risk\Signals\NewDevice;
use Keyring\Risk\Signals\SessionFingerprintChanged;

Keyring::risk()->signals([NewDevice::class, NewCountry::class, ImpossibleTravel::class, SessionFingerprintChanged::class])
    ->respond(fn (Risk $risk, Checkpoint $at) => match ($risk->level) {
        Level::Low => Action::allow(),
        Level::Medium => Action::stepUp(),
        Level::High => Action::stepUp()->notify(),
        Level::Critical => Action::deny()->revokeAllSessions()->lockFor('1h')->notify(),
    });
```

The responder receives the `Risk` and the `Checkpoint` it was assessed at, so it can act differently at login and mid-session. To change only the response and keep the signals, call `Keyring::risk()->respond()` on its own.

A `Risk` has a `score`, a `level` and `findings`. Each finding is a `Keyring\Risk\Finding` with `signal`, `score` and `reason`. `has($signal)` checks for one signal, `reasons()` lists the reasons, and `isElevated()` is true above low.

### Telling the User

OWASP ASVS 5.0.0 (6.3.5) asks that users hear about a sign-in after a long quiet period, or after several failures. On their own, those findings only reach `Level::Medium`, which sends nothing. So Keyring's own response sends a `suspicious_activity` email, whatever the level, when `SuccessAfterFailures`, `InactiveAccount` or `CredentialStuffing` turns up. The email lists the reasons, such as "The first sign-in for 120 days."

If you write your own responder, keep the email by notifying for those findings:

```php
use Keyring\Facades\Keyring;
use Keyring\Risk\Action;
use Keyring\Risk\Checkpoint;
use Keyring\Risk\Level;
use Keyring\Risk\Risk;
use Keyring\Risk\Signals\CredentialStuffing;
use Keyring\Risk\Signals\InactiveAccount;
use Keyring\Risk\Signals\SuccessAfterFailures;

Keyring::risk()->respond(function (Risk $risk, Checkpoint $at) {
    $action = match ($risk->level) {
        Level::Low => Action::allow(),
        Level::Medium => Action::stepUp(),
        Level::High => Action::stepUp()->notify(),
        Level::Critical => Action::deny()->revokeAllSessions()->notify(),
    };

    return $risk->has(InactiveAccount::FINDING) || $risk->has(SuccessAfterFailures::FINDING) || $risk->has(CredentialStuffing::FINDING)
        ? $action->notify()
        : $action;
});
```

The email is sent unless you've set the `suspicious_activity` notification to `null` in your app.

## Actions

Build an action from a static constructor, then chain any extras. The table shows what each one does at login, and on a signed-in request.

| Action | At Login | On a Signed-In Request |
|---|---|---|
| `Action::allow()` | Nothing. | Nothing. |
| `Action::stepUp()` | Asks for a second factor, if the user has one (the requirement becomes at least AAL2). | Forgets what the session has proved, so step-up asks again. |
| `Action::reauthenticate()` | Nothing. | Signs the session out. |
| `Action::deny()` | Refuses the sign-in with the usual "these credentials don't match" error. | Signs the session out. |
| `->revokeAllSessions()` | Ignored, even from your own responder, so anyone with only the password can't sign the owner out. | Signs out every session, this one included, changes the "remember me" token, stops trusting devices, and cancels any pending email change. |
| `->lockFor('1h')` | Refuses sign-ins for that long. Trusted devices stay trusted. | Refuses sign-ins for that long, from now, and stops trusting devices. |
| `->notify()` | Sends the `suspicious_activity` email. | The same. |
| `->requirePasswordChange()` | Holds the user until they choose a new password. The sign-in goes ahead unless the action also denies it. | Holds them from this request on. |

Locks are kept in the cache store named by `risk.store` (your default store when `null`). Clearing that store lifts every lock, so `php artisan cache:clear` does too. Where that matters, use a persistent store such as the database or Redis. The `octane` store loses every lock on restart, along with [other things](https://keyringauth.com/docs/0.x/security#octanes-cache-store).

A locked user gets the usual generic error on every sign-in, and a "remember me" cookie is signed out instead of let back in. Sessions already signed in carry on. A password reset lifts the lock, so the owner can always get back in.

### Requiring a New Password

NIST SP 800-63B-4 (Sec. 3.1.1.2) only changes a password when there's evidence it was compromised. A step-up, notice or lock doesn't do that, since the password someone else knows is still the password. `requirePasswordChange()` holds the user on your change-password page until they choose another, so use it for signals about the password itself.

Keyring does this for `BreachedPassword`. Turn the signal on, and tell Keyring where your change-password form is:

```php
// app/Providers/KeyringServiceProvider.php
use Keyring\Facades\Keyring;
use Keyring\Risk\Signals\BreachedPassword;

Keyring::risk()->push(BreachedPassword::class);
```

```php
// config/keyring.php
'password_change_url' => '/settings/password',
```

A user who signs in with a breached password is then held until they choose another. The sign-in goes ahead as the level says, and the hold is logged as `risk_password_change`. Without `password_change_url`, a held user gets a `403` on every page, so set it first.

If you write your own responder, answer for the finding:

```php
use Keyring\Facades\Keyring;
use Keyring\Risk\Action;
use Keyring\Risk\Level;
use Keyring\Risk\Risk;
use Keyring\Risk\Signals\BreachedPassword;

Keyring::risk()
    ->push(BreachedPassword::class)
    ->respond(fn (Risk $risk) => match (true) {
        $risk->has(BreachedPassword::FINDING) => Action::stepUp()->requirePasswordChange()->notify(),
        $risk->level === Level::Critical => Action::deny()->revokeAllSessions()->notify(),
        $risk->isElevated() => Action::stepUp(),
        default => Action::allow(),
    });
```

A user with no password is never held, so a responder can ask for this without checking. For what a held user can reach, and how the hold ends, see [Requiring a Password Change](https://keyringauth.com/docs/0.x/protected-changes#requiring-a-password-change).

## Checkpoints

Signals run at one or both checkpoints, from `Keyring\Risk\Checkpoint`:

- **`Login`** runs once per login, after the first factor is verified. Every signal that lists it runs.
- **`Request`** runs on every signed-in request, from the [session middleware](https://keyringauth.com/docs/0.x/devices-and-sessions#the-session-middleware). Only signals that list it run, so keep them cheap. When one does, the responder is called on every request, even at `Level::Low`. A custom responder should return `Action::allow()` for low risk.

`SessionFingerprintChanged` runs at `Request`. With the default response, a session whose browser changes is asked to verify again, and the owner is emailed, on every switch. To end such a session instead, answer `Action::reauthenticate()` at `Checkpoint::Request`.

A request-time step-up gives the session a new record and revokes the old one, so only the request that noticed the change carries on, and an older cookie copy is signed out. The new record counts as used by that request, so the session's idle time starts over from it. With [`sessions.end_on_lapse`](https://keyringauth.com/docs/0.x/devices-and-sessions#ending-a-session-with-its-level) on, a request-time step-up signs the session out instead.

## Configuring Signals

`signals([...])` replaces the list, and `push()` adds to it. Both take class names or instances, so you can change a score:

```php
use App\Keyring\ListedIp;
use Keyring\Facades\Keyring;
use Keyring\Risk\Signals\BreachedPassword;
use Keyring\Risk\Signals\NewDevice;
use Keyring\Risk\Signals\RepeatedFactorFailures;

Keyring::risk()->push(BreachedPassword::class, ListedIp::class);

Keyring::risk()->signals([
    new NewDevice(score: 20),
    app()->make(RepeatedFactorFailures::class, ['threshold' => 3, 'within' => '1h']),
    BreachedPassword::class,
]);
```

Use `app()->make()` for signals with dependencies: `RepeatedFactorFailures`, `SuccessAfterFailures`, `CredentialStuffing`, `InactiveAccount`, `RecentlyChangedRecovery` and `BreachedPassword`. `within` and `after` are [durations](https://keyringauth.com/docs/0.x/configuration#durations):

| Signal | Options | Defaults |
|---|---|---|
| Every signal | `score` | See [Built-in Signals](https://keyringauth.com/docs/0.x/risk#built-in-signals). |
| `ImpossibleTravel` | `maxKph`, `minKm` | `900`, `500` |
| `RepeatedFactorFailures` | `threshold`, `within` | `5`, `15m` |
| `SuccessAfterFailures` | `threshold`, `within` | `5`, `1h` |
| `CredentialStuffing` | `threshold`, `within` | `5`, `1h` |
| `InactiveAccount` | `after` | `90d` |

```php
use Keyring\Facades\Keyring;
use Keyring\Risk\Signals\InactiveAccount;
use Keyring\Risk\Signals\SuccessAfterFailures;

Keyring::risk()->push(
    app()->make(InactiveAccount::class, ['after' => '180d']),
    app()->make(SuccessAfterFailures::class, ['threshold' => 3, 'within' => '24h']),
);
```

## Built-in Signals

The built-in signals are in `Keyring\Risk\Signals`:

| Signal | Fires When | Score | Runs At |
|---|---|---|---|
| `NewDevice` | The browser hasn't signed in before. | 15 | login |
| `NewCountry` | The request comes from a country none of the user's active devices have been seen in. Needs a locator. | 30 | login |
| `ImpossibleTravel` | The last located sign-in was 500 km or more away, and getting here since means travelling faster than 900 km/h. Needs a locator with coordinates. | 60 | login |
| `RepeatedFactorFailures` | Five or more second factors failed after a correct password (or an identity provider sign-in) in 15 minutes. Ten or more doubles the score. | 25 | login |
| `RecentlyChangedRecovery` | The email address changed, or was changed back, within `risk.recent_change` (7 days). | 25 | login |
| `InactiveAccount` | The last sign-in was 90 days ago or more, and none of the account's sessions has been used since. An impersonated session doesn't count. | 30 | login |
| `SuccessAfterFailures` | The first factor was right after five or more failed attempts on the account in the last hour, counted since it last signed in. | 30 | login |
| `CredentialStuffing` | The first factor was right, and five or more other accounts failed a factor from the same IP address in the last hour. The published provider leaves it off. | 40 | login |
| `SessionFingerprintChanged` | A signed-in session now comes from a different browser or platform. IP changes alone don't count. | 60 | every request |
| `BreachedPassword` | The password used to sign in appears in a public breach list. It calls the network at sign-in, so the published provider leaves it off. | 40 | login |

`CredentialStuffing` goes by IP address, so it can fire on the sign-ins of people who share an address with an attacker. It's off in the published provider for that reason.

> [!WARNING]
> Many people share one address, such as an office, a school or a mobile network. The same happens to everyone when Laravel doesn't [trust your proxies](https://keyringauth.com/docs/0.x/security#trusted-proxies), or when a frontend posts logins for its users. So five ordinary mistakes from one office in an hour can fire this signal for the rest. Raise `threshold`, or leave the signal off, if your users share addresses like that.

## Writing a Signal

To write one, extend `Keyring\Risk\Signals\Signal` and implement `assess()`. It returns a `Keyring\Risk\Finding` with a name, a score and a reason, or `null` when nothing's wrong. `has()` looks for the name, and the reason goes in the `suspicious_activity` email. Register the class with `push()` or `signals()`, and the container builds it.

A signal runs at login unless `checkpoints()` says otherwise. Return `[Checkpoint::Request]` to run on every signed-in request, and keep those signals cheap. An exception from `assess()` isn't caught, so the sign-in fails with it.

`assess()` receives an `Assessment` with `checkpoint`, `request`, `user`, `attempt` (at login), `session` (on a request), and `location()`, which is the request's location from the locator or `null`.

### Allowed and Blocked Countries

This signal goes by the country in the request's [location](https://keyringauth.com/docs/0.x/devices-and-sessions#locations), and returns `null` when there isn't one:

```php
namespace App\Keyring;

use Keyring\Risk\Assessment;
use Keyring\Risk\Finding;
use Keyring\Risk\Signals\Signal;

class CountryRules extends Signal
{
    /**
     * @param  list<string>  $allowed  Country codes to allow. Empty allows any not blocked.
     * @param  list<string>  $blocked  Country codes never to allow.
     */
    public function __construct(
        protected array $allowed = [],
        protected array $blocked = [],
        protected int $score = 90,
    ) {}

    public function assess(Assessment $assessment): ?Finding
    {
        $country = $assessment->location()['country'] ?? null;

        if (! is_string($country)) {
            return null;
        }

        $refused = in_array($country, $this->blocked, true)
            || ($this->allowed !== [] && ! in_array($country, $this->allowed, true));

        return $refused
            ? new Finding('country_not_allowed', $this->score, "Signing in from a country that isn't allowed ({$country}).")
            : null;
    }
}
```

```php
use App\Keyring\CountryRules;
use Keyring\Facades\Keyring;

Keyring::risk()->push(new CountryRules(allowed: ['GB', 'IE']));
```

At the default score of 90, a sign-in from elsewhere reaches `Level::Critical` on its own, so this works as a block, and the owner is emailed. With a lower score, such as 30, the user is asked for a second factor instead. A request the locator can't place gets through, and so does anyone who can pick their country through a VPN or a [header the locator trusts](https://keyringauth.com/docs/0.x/devices-and-sessions#locations).

### IP Reputation

This signal asks a list of bad addresses, such as Tor exit nodes, about the request's address. The list and its client are yours, so bind your client to an interface:

```php
namespace App\Keyring;

interface IpReputation
{
    /** Whether the address is listed, or null when the list can't be reached. */
    public function isListed(string $ip): ?bool;
}
```

```php
namespace App\Keyring;

use Illuminate\Support\Facades\Cache;
use Keyring\Risk\Assessment;
use Keyring\Risk\Finding;
use Keyring\Risk\Signals\Signal;

class ListedIp extends Signal
{
    public function __construct(
        protected IpReputation $reputation,
        protected int $score = 40,
    ) {}

    public function assess(Assessment $assessment): ?Finding
    {
        $ip = $assessment->request->ip();

        if ($ip === null) {
            return null;
        }

        $listed = Cache::get('ip-reputation:'.$ip);

        if ($listed === null) {
            $listed = $this->reputation->isListed($ip);

            // Only a real answer is kept, so an outage isn't remembered.
            if ($listed !== null) {
                Cache::put('ip-reputation:'.$ip, $listed, now()->addHour());
            }
        }

        return $listed === true
            ? new Finding('listed_ip', $this->score, 'Signing in from an address on an abuse list.')
            : null;
    }
}
```

```php
// In your KeyringServiceProvider
use App\Keyring\IpReputation;
use App\Keyring\ListedIp;
use App\Keyring\TorExitList; // Your client for the list.
use Keyring\Facades\Keyring;

$this->app->bind(IpReputation::class, TorExitList::class);

Keyring::risk()->push(ListedIp::class);
```

A lookup is a network call, so the answer is cached for an hour. The signal checks `$request->ip()`, the real address, at login. An exception fails the sign-in, so give your client a short timeout and return `null` when the list is unreachable. Caching that as "not listed" would let every address through for the next hour.

## Running Risk Yourself

To assess risk elsewhere, such as in a pipeline step of your own, use the `Keyring\Risk\RiskEngine` that `Keyring::risk()` returns:

```php
use Keyring\Facades\Keyring;
use Keyring\Risk\Assessment;
use Keyring\Risk\Checkpoint;

$engine = Keyring::risk();
$risk = $engine->assess(new Assessment(Checkpoint::Login, $request, $user, $attempt));
$action = $engine->enforce($user, $risk, Checkpoint::Login);
```

`enforce()` asks the responder and does what doesn't depend on where you are: it dispatches `RiskAssessed`, revokes sessions (never at login), places the lock, and places the password hold. Denying, stepping up and signing out are up to you, using the returned `Action`. `decide()` only asks the responder, and drops any revocation at login. `signalsFor()` lists the signals at a checkpoint.

## Using Risk in Your Policy

At login, Keyring assesses risk before it asks the policy, so a [policy closure](https://keyringauth.com/docs/0.x/policies#deciding-per-user-and-attempt) can read the result:

```php
Keyring::require(fn (User $user, Attempt $attempt) => $attempt->risk?->has('new_country')
    ? Requirement::aal2()
    : Requirement::aal2()->ifEnrolled());
```

## Events and Logging

When an action does anything, Keyring dispatches `Keyring\Events\RiskAssessed`, with `user`, `risk`, `action` and `checkpoint`. The `checkpoint` is `Checkpoint::Login` or `Checkpoint::Request`.

Keyring logs the event under the strongest thing the action did: `risk_denied`, `risk_reauthenticate`, `risk_locked`, `risk_password_change`, `risk_step_up`, `risk_revoked_sessions` or `risk_notified`. Each entry records the checkpoint (`login` or `request`), the score and the reasons.

## How It Works

Each built-in signal was chosen for a reason, and these are the reasons.

`RepeatedFactorFailures` ignores wrong passwords. Anyone can type a wrong password for a known address, and counting those would let a stranger raise the owner's risk and lock them out. So only failures after a correct password count.

`SuccessAfterFailures` counts every failed attempt on the account, wrong passwords included. That's what tells a guessed password from a known one. Anyone who knows a username can cause those failures, so the signal can't say whose sign-in it is, only that someone has been trying. Its score asks for a second factor and no more.

`CredentialStuffing` counts accounts, not attempts. Ten failures on one account count once, and the user's own failures don't count, since `SuccessAfterFailures` covers those. A wrong confirm password counts too. Failures for names nobody has can't be told apart, so together they count as one account, and someone retyping a mistyped address doesn't look like a list.

`InactiveAccount` reads the account's devices and sessions. It says nothing about an account with no sign-in on record, so turning it on doesn't flag every existing user's next sign-in. Devices unseen for `devices.keep_unseen_for` (a year) are pruned, and after that a returning browser counts as a new device again, which `NewDevice` and the `new_device` email cover.
