# Risk

Source: https://keyringauth.com/docs/0.x/rust/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, as in the PHP package. 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. The signals, scores, findings and reasons are the PHP package's.

## Choosing Signals

Pick signals in `risk.signals`, which starts empty, as an application without the PHP package's published provider has none. Each is a struct whose fields are its options, with the PHP package's defaults:

```rust
use std::sync::Arc;
use laravel_keyring::KeyringConfig;
use laravel_keyring::risk::signals::{
    InactiveAccount, NewDevice, RepeatedFactorFailures, SessionFingerprintChanged, SuccessAfterFailures,
};

laravel::Application::configure().with_config(|config, _| {
    config.section_mut::<KeyringConfig>().risk.signals = vec![
        Arc::new(SessionFingerprintChanged::default()),
        // These two read the security log: security_log.enabled.
        Arc::new(RepeatedFactorFailures::default()),
        Arc::new(SuccessAfterFailures::default()),
        // These two go by an account's devices: features.devices.
        Arc::new(NewDevice::default()),
        Arc::new(InactiveAccount::default()),
    ];
});
```

That's the PHP installer's starting set. The rest, `RecentlyChangedRecovery`, `CredentialStuffing`, `BreachedPassword`, `NewCountry` and `ImpossibleTravel`, are off until you add them, for the reasons the [PHP docs](https://keyringauth.com/docs/0.x/risk#choosing-signals) give. `NewCountry` and `ImpossibleTravel` need a [locator](https://keyringauth.com/docs/0.x/rust/devices-and-sessions#locations).

## Responding to Risk

Keyring's own response answers by level, as in the PHP package: medium steps up, high steps up and notifies, critical denies, revokes every session and notifies, `SuccessAfterFailures`, `InactiveAccount` and `CredentialStuffing` notify at any level, and `BreachedPassword` holds for a new password. `risk::default_response(&risk)` is it, to build on.

`risk.respond` replaces it with a function of the `Risk` and the `Checkpoint`:

```rust
use std::time::Duration;
use laravel_keyring::risk::{Action, Checkpoint, Level};

config.section_mut::<KeyringConfig>().risk.respond = Some(|risk, at| match (risk.level, at) {
    (Level::Low, _) => Action::allow(),
    (_, Checkpoint::Request) => Action::reauthenticate().notify(),
    (Level::Critical, _) => Action::deny().lock_for(Duration::from_secs(60 * 60)).notify(),
    _ => Action::step_up().notify(),
});
```

It's a plain `fn(&Risk, Checkpoint) -> Action`, which can't capture anything, where the PHP package takes a closure.

### Telling the User

As in the PHP package, Keyring's own response sends the `suspicious_activity` email for `SuccessAfterFailures`, `InactiveAccount` and `CredentialStuffing` whatever the level, as OWASP ASVS 5.0.0 (6.3.5) asks. A response of your own keeps that by notifying for those findings:

```rust
use laravel_keyring::risk::signals::{CredentialStuffing, InactiveAccount, SuccessAfterFailures};
use laravel_keyring::risk::{self, Action};

config.section_mut::<KeyringConfig>().risk.respond = Some(|risk, _| {
    let action = risk::default_response(risk);

    if risk.has(InactiveAccount::FINDING) || risk.has(SuccessAfterFailures::FINDING) || risk.has(CredentialStuffing::FINDING) {
        action.notify()
    } else {
        action
    }
});
```

## Actions

Build an action from a constructor, then chain any extras. What each does is the PHP package's, as its [table](https://keyringauth.com/docs/0.x/risk#actions) shows:

| Rust | PHP |
|---|---|
| `Action::allow()` | `Action::allow()` |
| `Action::step_up()` | `Action::stepUp()` |
| `Action::reauthenticate()` | `Action::reauthenticate()` |
| `Action::deny()` | `Action::deny()` |
| `.revoke_all_sessions()` | `->revokeAllSessions()` |
| `.lock_for(Duration)` | `->lockFor('1h')` |
| `.notify()` | `->notify()` |
| `.require_password_change()` | `->requirePasswordChange()` |

`.without_revoking_sessions()` takes back a revocation. The fields (`step_up`, `deny`, `lock_seconds` and the rest) are public, and `does_something()` says whether it does anything.

Locks are kept in the default cache store. There's no `risk.store`. Clearing the store lifts every lock, so use a persistent one where that matters. 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. A password reset lifts the lock, and so does `laravel_keyring::unlock(&user)`.

### Requiring a New Password

As in the PHP package: Keyring holds a user whose password turns up in a breach, with `BreachedPassword` on and `password_change_url` set:

```rust
use std::sync::Arc;
use laravel_keyring::risk::signals::BreachedPassword;

let keyring = config.section_mut::<KeyringConfig>();
keyring.risk.signals.push(Arc::new(BreachedPassword::default()));
keyring.password_change_url = Some("/settings/password".to_owned());
```

`BreachedPassword` asks Have I Been Pwned's range API through laravel-rust's HTTP client, as Laravel's `NotPwnedVerifier` does (padding asked for, `timeout` 30 seconds, an answer that doesn't come taken as not breached). A response of your own answers for its finding with `.require_password_change()`, and a user with no password is never held. See [Requiring a Password Change](https://keyringauth.com/docs/0.x/rust/protected-changes#requiring-a-password-change).

## Checkpoints

Signals run at one or both checkpoints, `laravel_keyring::risk::Checkpoint`:

- **`Login`** runs once per sign in, once the first factor (a password, a passkey or an identity provider) is right, in the pipeline's `EnsureNotRiskLocked` and `AssessRisk` steps.
- **`Request`** runs on every signed-in request, in `AuthenticateSession`. Only signals that list it run, so keep them cheap.

At sign in, a denial is the usual "credentials" `422`, counted against the account's limits but no `FactorFailed`, and a step-up raises the requirement to at least a second factor the user can give, whatever a policy closure answers. Nothing is ever revoked from a sign in. On a request, a denial, re-authentication or revocation signs the session out (`risk`), and a step-up forgets what the session proved and moves it to a new record, as the PHP package's `reregisterQuietly()`. The new record counts as used by that request, so the session's idle time starts over from it. An impersonated session isn't assessed.

## Configuring Signals

An option is a field, with `..Default::default()` for the rest:

```rust
use std::time::Duration;
use laravel_keyring::risk::signals::{InactiveAccount, NewDevice, RepeatedFactorFailures};

keyring.risk.signals = vec![
    Arc::new(NewDevice { score: 20 }),
    Arc::new(RepeatedFactorFailures { threshold: 3, ..Default::default() }),
    Arc::new(InactiveAccount { after: Duration::from_secs(180 * 24 * 60 * 60), ..Default::default() }),
];
```

Durations are `Duration`s rather than strings like `'180d'`, and a reason names a duration in the largest unit it's a whole number of (`15m`, `1h`, `180d`), where the PHP package writes the config's text as given. There's no `push()`: push onto the `Vec`. `risk.levels` sets the scores at which risk is medium, high and critical (30, 60, 90).

## Built-in Signals

The built-in signals are in `laravel_keyring::risk::signals`, with the PHP package's findings, scores and checkpoints, as its [table](https://keyringauth.com/docs/0.x/risk#built-in-signals) lists: `NewDevice` (15), `NewCountry` (30), `ImpossibleTravel` (60), `RepeatedFactorFailures` (25), `RecentlyChangedRecovery` (25), `InactiveAccount` (30), `SuccessAfterFailures` (30), `CredentialStuffing` (40), `SessionFingerprintChanged` (60, every request) and `BreachedPassword` (40). A sign in with an identity provider is assessed as one with a password is.

## Writing a Signal

A signal of your own implements `laravel_keyring::risk::Signal`. `assess()` gets the `Assessment`, with the request, the user as your type (`assessment.user::<User>()`), their ID and type, the attempt at sign in, whether it's a new device, the session on a request, and `location()`, and returns a `Finding` or `None`. Its `score` is a `u32`:

```rust
use laravel_keyring::risk::{Assessing, Assessment, Finding, Signal};

#[derive(Debug)]
struct CountryRules {
    blocked: Vec<String>,
}

impl Signal for CountryRules {
    fn assess<'a>(&'a self, assessment: &'a Assessment<'a>) -> Assessing<'a> {
        Box::pin(async move {
            let country = assessment.location().await
                .and_then(|location| location.get("country")?.as_str().map(str::to_owned));

            Ok(country.filter(|country| self.blocked.contains(country)).map(|country| {
                Finding::new("country_not_allowed", 90, format!("Signing in from a country that isn't allowed ({country})."))
            }))
        })
    }
}
```

Add it with the others, as `Arc::new(CountryRules { blocked: vec!["XX".into()] })`. A signal runs at sign in unless `checkpoints()` returns `&[Checkpoint::Request]`, which runs it on every signed-in request. An error from `assess()` fails the sign in, or the request, with it.

### Allowed and Blocked Countries

`CountryRules` above is this section's blocked list. For an allowed list, find the country the other way round. See the [PHP docs](https://keyringauth.com/docs/0.x/risk#allowed-and-blocked-countries) for the scores to give each.

### IP Reputation

The PHP example binds a client to an interface. In Rust, keep the client on the signal itself, and cache its answers as the PHP example does:

```rust
use std::sync::Arc;
use std::time::Duration;
use laravel_keyring::risk::{Assessing, Assessment, Finding, Signal};

trait IpReputation: std::fmt::Debug + Send + Sync + 'static {
    /// Whether the address is listed, or None when the list can't be reached.
    fn is_listed(&self, ip: &str) -> impl std::future::Future<Output = Option<bool>> + Send;
}

#[derive(Debug)]
struct ListedIp<L> {
    reputation: Arc<L>,
    score: u32,
}

impl<L: IpReputation> Signal for ListedIp<L> {
    fn assess<'a>(&'a self, assessment: &'a Assessment<'a>) -> Assessing<'a> {
        Box::pin(async move {
            let ip = assessment.request.ip().to_string();
            let key = format!("ip-reputation:{ip}");

            let listed = match laravel::cache::get::<bool>(&key).await? {
                Some(listed) => Some(listed),
                None => {
                    let listed = self.reputation.is_listed(&ip).await;

                    // Only a real answer is kept, so an outage isn't remembered.
                    if let Some(listed) = listed {
                        laravel::cache::put(&key, listed, Duration::from_secs(60 * 60)).await?;
                    }

                    listed
                }
            };

            Ok((listed == Some(true)).then(|| {
                Finding::new("listed_ip", self.score, "Signing in from an address on an abuse list.")
            }))
        })
    }
}
```

Add it as `Arc::new(ListedIp { reputation: Arc::new(TorExitList), score: 40 })`, where `TorExitList` is your client. An error fails the sign in, so give your client a short timeout and return `None` when the list is unreachable. See the [PHP docs](https://keyringauth.com/docs/0.x/risk#ip-reputation) for the rest.

## Running Risk Yourself

`risk::assess()` and `risk::enforce()` are public, for a pipeline step that replaces `AssessRisk`, as the PHP package's `RiskEngine`. One that replaces it does what Keyring's does: runs once per sign in, runs the signals on `Assessment::of_step()`, which brings the attempt and the device, carries out the answer with `risk::enforce()`, and sets `risk` and `step_up` on the attempt for the policy, before `DetermineRequirement`:

```rust
use laravel_keyring::KeyringConfig;
use laravel_keyring::events::Purpose;
use laravel_keyring::pipeline::{self, Context, Flow, Handling, Step};
use laravel_keyring::risk::{self, Assessment, Checkpoint};

#[derive(Debug)]
struct StrictRisk;

impl Step for StrictRisk {
    fn handle<'a>(&'a self, context: &'a mut Context<'_>) -> Handling<'a> {
        Box::pin(async move {
            if context.attempt.purpose != Purpose::Login || context.attempt.risk.is_some() {
                return Ok(Flow::Next);
            }

            let config = laravel::config().section::<KeyringConfig>().clone();
            let found = risk::assess(&Assessment::of_step(context, &config)).await?;
            let user = context.user::<User>().expect("the application's user").clone();
            let action = risk::enforce::<Users>(&user, &found, Checkpoint::Login).await?;

            context.attempt.step_up = action.step_up || !found.findings.is_empty();
            context.attempt.risk = Some(found);

            Ok(if action.deny { Flow::Fail } else { Flow::Next })
        })
    }
}

KeyringServiceProvider::<Users>::new()
    .pipeline(|steps| steps.replace(pipeline::ASSESS_RISK, StrictRisk));
```

`enforce::<P>()` takes your user provider's type, which signing out everywhere needs, and has no session to note a password hold in. `step_up` set after `DetermineRequirement` only counts from the next answer on. Outside a sign in, `Assessment::for_user()` builds an assessment. `risk::decide()` only asks the response, and `risk::signals_for(&config, checkpoint)` lists the signals that run there.

## Using Risk in Your Policy

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

```rust
KeyringServiceProvider::<Users>::new().policy(|_user: &User, attempt: &Attempt| {
    if attempt.risk.as_ref().is_some_and(|risk| risk.has("new_country")) {
        Requirement::aal2()
    } else {
        Requirement::aal2().if_enrolled()
    }
});
```

## Events and Logging

When an action does anything, Keyring dispatches `laravel_keyring::events::RiskAssessed`, with the `Risk`, the `Action` and the `Checkpoint`, and logs it under the strongest thing the action did, as in the PHP package: `risk_denied`, `risk_reauthenticate`, `risk_locked`, `risk_password_change`, `risk_step_up`, `risk_revoked_sessions` or `risk_notified`, with `checkpoint`, `score` and `reasons`. `notify()` sends the `suspicious_activity` email with the reasons.

## How It Works

Each built-in signal works as the PHP package's, for the reasons its [How It Works](https://keyringauth.com/docs/0.x/risk#how-it-works) gives. A request-time step-up notes the record it moved to in the default cache store, where the PHP package uses `cache.limiter`.
