# Risk

Source: https://keyringauth.com/docs/0.x/go/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

Add signals with `RiskSignals`, which starts with none, as an application without the PHP package's published provider has none. Each is a struct whose fields are its options, and a zero field takes the PHP package's default:

```go
k := keyring.New[models.User](configure).
	RiskSignals(
		keyring.SessionFingerprintChanged{},
		// These two read the security log: Features.SecurityLog.
		keyring.RepeatedFactorFailures{},
		keyring.SuccessAfterFailures{},
		// These two go by an account's devices: Features.Devices.
		keyring.NewDevice{},
		keyring.InactiveAccount{},
	)
```

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/go/devices-and-sessions#locations).

`RiskSignals` adds to what's there, as the PHP package's `push()`, and the signals run in the order added. Call it before the application starts: it panics after `Register`, since requests already being served read the signals.

## 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. `keyring.DefaultRiskResponse(risk)` is it, to build on.

`RespondToRisk` replaces it with a function of the request's context, the `Risk` and the `Checkpoint`:

```go
k.RespondToRisk(func(ctx context.Context, risk *keyring.Risk, at keyring.Checkpoint) keyring.Action {
	switch {
	case risk.Level == keyring.RiskLow:
		return keyring.Action{}
	case at == keyring.CheckpointRequest:
		return keyring.Action{Reauthenticate: true, Notify: true}
	case risk.Level == keyring.RiskCritical:
		return keyring.Action{Deny: true, LockFor: time.Hour, Notify: true}
	default:
		return keyring.Action{StepUp: true, Notify: true}
	}
})
```

The levels are `RiskLow`, `RiskMedium`, `RiskHigh` and `RiskCritical`, in that order, so `risk.Level >= keyring.RiskHigh` works. Whatever the function answers at sign in, no session is signed out: `RevokeSessions` is dropped there. Like `RiskSignals`, it panics after `Register`.

### 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. Their names are constants:

```go
k.RespondToRisk(func(ctx context.Context, risk *keyring.Risk, at keyring.Checkpoint) keyring.Action {
	action := keyring.DefaultRiskResponse(risk)

	if risk.Has(keyring.FindingInactiveAccount) || risk.Has(keyring.FindingSuccessAfterFailures) || risk.Has(keyring.FindingCredentialStuffing) {
		action.Notify = true
	}

	return action
})
```

## Actions

An `Action` is a struct: the zero `Action` allows, and each field adds to what's done. What each does is the PHP package's, as its [table](https://keyringauth.com/docs/0.x/risk#actions) shows:

| Go | PHP |
|---|---|
| `keyring.Action{}` | `Action::allow()` |
| `Action{StepUp: true}` | `Action::stepUp()` |
| `Action{Reauthenticate: true}` | `Action::reauthenticate()` |
| `Action{Deny: true}` | `Action::deny()` |
| `RevokeSessions: true` | `->revokeAllSessions()` |
| `LockFor: time.Hour` | `->lockFor('1h')` |
| `Notify: true` | `->notify()` |
| `ChangePassword: true` | `->requirePasswordChange()` |

`LockFor` of zero locks nothing, where the PHP package's `lockFor(0)` still names the action `locked`. `DoesSomething()` says whether an action does anything, and `Name()` is the name it's logged under.

Locks are kept in the cache store `Risk.Store` names, or the default store when it's empty, as the PHP package's `risk.store`. A store the application hasn't configured fails the first request that looks for a lock, since `Register` can't tell. 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 `k.Unlock(ctx, user)`, which also clears the limits on the factors that can start a sign in. `Unlock` checks nothing about who's asking, so check that first.

A lock placed by Keyring for Go isn't seen by the PHP package on the same store, or the other way round: the two write cache values differently. Apps sharing users should name separate stores. See [Differences From PHP](https://keyringauth.com/docs/0.x/go/differences#risk).

### Requiring a New Password

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

```go
k := keyring.New[models.User](func(cfg *keyring.Config) {
	cfg.PasswordChangeURL = "/settings/password"
}).RiskSignals(keyring.BreachedPassword{})
```

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

## Checkpoints

Signals run at one or both checkpoints, `keyring.Checkpoint`:

- **`CheckpointLogin`** runs once per sign in, once the first factor (a password, a passkey or an identity provider) is right, in the pipeline's `StepEnsureNotRiskLocked` and `StepAssessRisk` steps.
- **`CheckpointRequest`** 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 the policy 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 now. The PHP package copies the old record's last activity, so a session stepped up near its idle limit idles out minutes later there. See [Differences From PHP](https://keyringauth.com/docs/0.x/go/differences#risk).

A browser [impersonating](https://keyringauth.com/docs/0.x/go/impersonation) someone isn't assessed on a request, as in the PHP package: the request is the impersonator's. `InactiveAccount` doesn't count an impersonated session's use as the owner's.

## Configuring Signals

An option is a field. Leave the rest at zero for the PHP package's defaults:

```go
k.RiskSignals(
	keyring.NewDevice{Score: 20},
	keyring.RepeatedFactorFailures{Threshold: 3},
	keyring.InactiveAccount{After: 180 * 24 * time.Hour},
)
```

Durations are `time.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`), as the PHP package's config writes them. Since a zero field is the default, a score of 0 can't be asked for: leave the signal out instead. There's no replacing the list, only adding to it.

`Risk.Levels` sets the scores at which risk is medium, high and critical (30, 60, 90). Set the fields one at a time: assigning a whole `RiskSettings` leaves the levels at zero, which `Register` refuses, as it refuses a medium under 1 and levels out of order:

```go
cfg.Risk.Levels.Medium = 25
cfg.Risk.Store = "redis"
```

`Risk.RecentChange` is how long an address that changed counts as recent for `RecentlyChangedRecovery`, seven days.

## Built-in Signals

The built-in signals are types in the `keyring` package, 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.

`ImpossibleTravel`'s distance can differ from the PHP package's in the last bit, since Go's sine and cosine aren't the C library's. Only a distance a hair from a whole kilometre could print differently. Countries are compared as text, where the PHP package compares loosely.

## Writing a Signal

A signal of your own implements `keyring.Signal`: an `Assess` method that gets the `*keyring.Assessment` and returns a `*keyring.Finding`, or nil when nothing's wrong. The assessment has the `Checkpoint`, the `Request`, the `User` (a pointer to your user type, as `any`), the `Attempt` at sign in, the `Session`'s record on a request, `IsNewDevice()` and `Location()`. A finding's `Score` is an `int` from 0 to 100:

```go
type CountryRules struct {
	Blocked []string
}

func (s CountryRules) Assess(a *keyring.Assessment) (*keyring.Finding, error) {
	country, ok := a.Location().Get("country")
	if !ok || !slices.Contains(s.Blocked, country.(string)) {
		return nil, nil
	}

	return &keyring.Finding{
		Signal: "country_not_allowed",
		Score:  90,
		Reason: fmt.Sprintf("Signing in from a country that isn't allowed (%s).", country),
	}, nil
}
```

Add it with the others, as `k.RiskSignals(CountryRules{Blocked: []string{"XX"}})`. Signals aren't generic, so reach your user with a type assertion, `a.User.(*models.User)`. A signal runs at sign in unless it has a `Checkpoints() []keyring.Checkpoint` method, which can return `[]keyring.Checkpoint{keyring.CheckpointRequest}` to run it on every signed-in request instead. 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 Go, keep the client on the signal itself, and cache its answers as the PHP example does:

```go
// IPReputation is your client for an abuse list.
type IPReputation interface {
	// IsListed reports whether the address is listed, and false for ok when
	// the list can't be reached.
	IsListed(ctx context.Context, ip string) (listed, ok bool)
}

type ListedIP struct {
	Reputation IPReputation
	Score      int
}

func (s ListedIP) Assess(a *keyring.Assessment) (*keyring.Finding, error) {
	ip := a.Request.IP()
	key := "ip-reputation:" + ip

	listed, found, err := cache.Get[bool](a.Request, key)
	if err != nil {
		return nil, err
	}
	if !found {
		var ok bool
		listed, ok = s.Reputation.IsListed(a.Request, ip)

		// Only a real answer is kept, so an outage isn't remembered.
		if ok {
			if err := cache.Put(a.Request, key, listed, time.Hour); err != nil {
				return nil, err
			}
		}
	}

	if !listed {
		return nil, nil
	}

	return &keyring.Finding{Signal: "listed_ip", Score: s.Score, Reason: "Signing in from an address on an abuse list."}, nil
}
```

Add it as `k.RiskSignals(ListedIP{Reputation: torExitList, Score: 40})`, where `torExitList` is your client. An error fails the sign in, so give your client a short timeout and answer not ok when the list is unreachable. See the [PHP docs](https://keyringauth.com/docs/0.x/risk#ip-reputation) for the rest.

## Running Risk Yourself

`Assess` and `Enforce` are public, for a pipeline step that replaces `StepAssessRisk`, as the PHP package's `RiskEngine`. One that replaces it does what Keyring's does: runs once per sign in, runs the signals on `AssessmentOf`, which brings the attempt and the device, carries out the answer with `Enforce`, and sets `Risk` and `StepUp` on the attempt for the policy, before `StepDetermineRequirement`:

```go
type StrictRisk struct {
	Keyring *keyring.Keyring[models.User]
}

func (s StrictRisk) Handle(r *web.Request, c *keyring.StepContext[models.User]) error {
	if c.Attempt.Purpose != keyring.PurposeLogin || c.Attempt.Risk != nil {
		return nil
	}

	found, err := s.Keyring.Assess(s.Keyring.AssessmentOf(r, c))
	if err != nil {
		return err
	}
	action, err := s.Keyring.Enforce(r, c.User, found, keyring.CheckpointLogin)
	if err != nil {
		return err
	}

	c.Attempt.StepUp = action.StepUp || len(found.Findings) > 0
	c.Attempt.Risk = found
	if action.Deny {
		c.Fail()
	}

	return nil
}

k := keyring.New[models.User](configure)
k.Pipeline(func(steps keyring.Steps[models.User]) keyring.Steps[models.User] {
	return steps.Replace(keyring.StepAssessRisk, StrictRisk{Keyring: k})
})
```

Without the purpose and `Risk` check, the signals run, and their answer is carried out, again for every answer at the challenge page and for every confirm. `Enforce` announces the risk, signs out everywhere (never at sign in), locks and holds for a new password. Denying, stepping up and signing the session out are the caller's. A `StepUp` set after `StepDetermineRequirement` only counts from the next answer on.

Outside a sign in, `k.NewAssessment(r, user, checkpoint)` builds an assessment; set its `Attempt` or `Session` as need be. `k.SignalsAt(checkpoint)` lists the signals that run there, and `k.IsRiskLocked(ctx, user)` says whether a user is locked, for a step that dangerously replaces `StepEnsureNotRiskLocked`.

## Using Risk in Your Policy

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

```go
k.Require(func(ctx context.Context, user *models.User, attempt keyring.Attempt) keyring.Requirement {
	if attempt.Risk.Has("new_country") {
		return keyring.AAL2.Requirement()
	}

	return keyring.AAL2.Requirement().IfEnrolled()
})
```

A sign in's attempt always carries a risk once assessed, empty when no signal found anything, as in the PHP package. `attempt.Risk` is nil only outside a sign in: a confirm, a removal, a fresh verification.

## Events and Logging

When an action does anything, Keyring dispatches `keyring.RiskAssessed[U]`, with the `User`, 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. The locator is asked once per request, and a failing one is reported and leaves the location unknown. A request-time step-up notes the record it moved to in the default cache store for five minutes, so requests stepping up alongside join it, where the PHP package uses `cache.limiter`.
