# Security

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

## Introduction

The crate makes the PHP package's guarantees, held to the same routes, answers and status codes by the [contract suite](https://github.com/keyringauth/keyring/blob/main/contract/README.md), which runs the same HTTP tests against both. This page goes through the [PHP security page](https://keyringauth.com/docs/0.x/security) section by section, and says where the crate's guarantee differs, and why. Where a section says nothing more, the PHP page holds as written.

## Guarantees

### Signing In

As in the PHP package. A refused sign in takes at least `timebox` (500 ms), a wrong password and an unknown account get the same answer, and a password hash still runs for an unknown address. Passwords are put in NFC form before they're checked.

An OpenID Connect provider's token endpoint, key set and userinfo endpoint have to be on public addresses, as in the PHP package, and here the request connects only to the addresses that were checked, so DNS rebinding can't point it at the server's own network in between. Behind a proxy (`HTTPS_PROXY`), the proxy resolves the name again. See [Security Notes](https://keyringauth.com/docs/0.x/rust/sso#security-notes).

### Rate Limiting

The limits are the PHP package's `Throttle`, counted under the same keys: attempts a minute per address (shared, so a success only gives back its own attempt), per username as typed and per account; locks that double each time up to `longest_lock` (`longest_ip_lock` for an address), counted for a day; failures in a row up to `consecutive` (100), kept in `keyring_failure_counts`; and `lock_after`. Browsers the account has signed in from count apart, so someone guessing elsewhere can only make `consecutive_elsewhere` (80) of them, under keys a typed name can't spell: `{factor}|consecutive-known|typed:{name}` for their failures in a row under a name, and `{factor}|account-known|{account}` for their per-minute counts and locks, where everyone else's are `{factor}|consecutive|typed:{name}` and `{factor}|account|{account}`. A second factor's limits are counted under its own keys.

laravel-rust's limiter is a token bucket, so the throttle keeps its own counts in the default cache store, as Laravel's `RateLimiter` would count them. The limiters on Keyring's other routes (`keyring`, `keyring-pages`, `keyring-login-options` and `keyring-session-changes`) are settings in `limits`, not limiters you redefine.

#### At the Cap

As in the PHP package: an authenticator that has failed `limits.consecutive` times in a row is refused until it's set up again, or for the password and the factors that start a sign in, until a reset or `laravel_keyring::clear_account(&user)`. `lock_after` never holds a factor that only comes second.

```rust
laravel_keyring::clear_account(&user).await?;
```

`clear_account()` starts the account's minute counts and locks over too, and the failures in a row on every factor that starts a sign in. It leaves the limits on addresses, on the names typed and on second factors. Call it from a support tool once the owner has proved who they are. `unlock(&user)` also lifts a risk lock, and `unlock_factor(&user, factor)` starts one factor's limits over.

#### Locking Until a Reset

`limits.lock_after` works as in the PHP package: the account's password is refused after that many failures until a reset or `clear_account()`.

#### Octane's Cache Store

There's no Octane here, but the same holds for laravel-rust's `memory` store: it's one process's alone, so with more than one process or server each keeps counts, locks and spent challenges of its own. Use a store every process shares. See [A Shared Lock Store](https://keyringauth.com/docs/0.x/rust/security#a-shared-lock-store).

### Single-Use Codes

As in the PHP package: a TOTP code can't be reused (each authenticator keeps the last step it accepted, under a row lock), a recovery code works once, an emailed code works once and only for the authenticator it was sent to (its [sign-in link](https://keyringauth.com/docs/0.x/rust/factors#signing-in-from-the-email) posts the code, so the two are used up together, and finishes only the sign in it was sent for, in the browser that holds it), and a passkey challenge is answered once, in the session and in the cache. Codes and challenges are in the default cache store.

### Second Factors and Step-Up

As in the PHP package, with one tightening: `RequireAssurance::aal1()` takes no recovery code alone, where the PHP package's `keyring:aal1` does. `RequireAssurance`'s confirm asks for the whole level afresh, where the PHP package builds on what still counts toward it.

The gates (`RequireFreshVerification`, `RequireAssurance`, `StepUp::unless_met()` and `meets()`, and the step-up before impersonating) count what the browser session proved only for the user its Keyring record belongs to, and only that user's own authenticators. The PHP package gets this by working with session guards only. Here a route can take its user from a request guard, with laravel-rust's `Authenticate::via()`, while the browser session is someone else's: that session counts as having proved nothing, so the gate asks for a confirm (or enrollment) and never lets the request through on another account's proofs. Put the gate after `Authenticate::via()` on such a route. A gate ahead of it checks the session's own user, and the request guard changes who the handler acts as afterwards. When an application can't order the two, such as a gate added to a whole group whose routes pick their own guards, one middleware of its own that runs the guard and then the gate does the same.

`SessionAssurance` reads the session alone, and says what the session's own user proved. Don't report it for a user a request guard gave.

### Sessions and Devices

As in the PHP package, with these differences, each from laravel-rust:

- Ending another session ends its record, and `AuthenticateSession` signs that browser out on its next request. Its session data stays in the store until it expires, and a request it has in flight still finishes.
- Every sign-out gives the user a new remember token, so it also stops "remember me" in their other browsers.
- A new password signs out every other session, whatever `sign_out_others` says.
- Requests that overlap a sign in, step-up or sign-out aren't kept from saving the old session again, as `sessions.overlapping_requests` isn't there. Keyring's own routes that spend session state take the session lock, and a copy of a session that moved on is signed out by its record.

### Account Changes

As in the PHP package, except that laravel-rust has no model events: `password` and the address only stay inside Keyring's flows where you call `protection::guard()` as you save users. See [Protected Attributes](https://keyringauth.com/docs/0.x/rust/protected-changes#protected-attributes).

### Links and Headers

As in the PHP package: every Keyring response gets `Cache-Control: no-store, private`, `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY` and `Cross-Origin-Opener-Policy: same-origin-allow-popups`, with `Referrer-Policy: same-origin`, or `no-referrer` on pages that emailed links open, from `http::SecurityHeaders`. Signing out sends `Clear-Site-Data`. An Inertia form on a page an emailed link opened that goes anywhere but back loads the next page in full.

#### Emailed Links

Links start at `APP_URL`, never the request's host. An app on several domains starts them elsewhere with the provider's `link_root_using()`:

```rust
KeyringServiceProvider::<Users>::new().link_root_using(|| tenant_url());
```

`laravel_keyring::link_root()` says where they start. `tenant_url()` is yours.

#### Tokens in Emailed Links

As in the PHP package: the links' tokens and signatures are in the URL of the page they open, which changes nothing, and the page posts them in the body. An emailed code's sign-in link carries its code there, encrypted, works once, and lasts as long as its code and no longer than its sign in.

### Request Input

As in the PHP package: Keyring reads its fields from the body, as a form or as JSON, and ignores the query string.

The routes that take a passkey or security key's answer read a body of up to 64 KB rather than laravel-rust's 2 MB, and answer a larger one with a `413`, as decoding a crafted answer takes many times its size in memory. See [Signing In Without a Username](https://keyringauth.com/docs/0.x/rust/passkeys#signing-in-without-a-username).

### Storage

As in the PHP package: secrets are encrypted with the application key, recovery codes, sent codes and session handles are keyed hashes, device tokens are kept as their SHA-256, and reset tokens as their bcrypt hash.

### Logging

As in the PHP package. The security log never holds a password, code, token, signature or session ID. Without the table, entries go to `tracing`.

## What Keyring Keeps

The tables are the PHP package's, so what Keyring keeps is what its [list](https://keyringauth.com/docs/0.x/security#what-keyring-keeps) says. `record_ips_using` stores less of an address.

## What Your App Must Provide

### HTTPS and HSTS

As in the PHP package: serve the whole app over HTTPS, redirect HTTP to it, and send `Strict-Transport-Security`.

### Trusted Proxies

Per-address limits go by `Request::ip()`. Behind a load balancer or proxy, list it with laravel-rust's `trust_proxies`, or every request comes from the proxy's address and shares one count:

```rust
laravel::Application::configure().with_middleware(|middleware, _| {
    middleware.trust_proxies(["10.0.0.10"]);
});
```

`trust_proxies` panics on a value that isn't an IP address or network. For a list read from the environment, use `try_trust_proxies`.

### Secure Cookies

Set `SESSION_SECURE_COOKIE=true` and an `https://` `APP_URL` in production. Keyring's cookies are `Secure` and `__Host-` or `__Secure-` prefixed over HTTPS, as in the PHP package. See [Keyring's Cookies](https://keyringauth.com/docs/0.x/rust/devices-and-sessions#keyrings-cookies).

### A Content Security Policy

As in the PHP package: Keyring sends no `Content-Security-Policy`, so yours must include `frame-ancestors`.

### Headers on Your Other Responses

`SecurityHeaders` runs only on Keyring's routes. Send `X-Content-Type-Options: nosniff` on your whole app, and decide your own `Referrer-Policy` and `Cache-Control` for pages that show account details.

### Bot Checks

As in the PHP package: Keyring has no CAPTCHA. Add one of your own where you need it.

### A Shared Lock Store

The default cache store has to support locks and be shared by every server, as it holds what Keyring has to see the same everywhere: the session lock, the locks on each user's sessions and sign-in methods, the sign-in rate limits and their marks (`known-since`, `cleared`), the `keyring-session-changes`, `keyring-login-options` and `keyring` limiters, the passkey challenges already answered, the single sign-on states and links already used and identity providers' discovery documents and keys (in `sso.store`), the codes a code factor sent with their guesses and the codes already used, the enrollments and freeze proofs already used, risk locks and the records a risk step-up moved sessions to, the counts that keep the security log's refusals and the security emails to a few an hour, the claim on each impersonation's end, and the scheduler's lock that keeps `keyring:sweep` to one runner.

The `memory` store is one process's alone, so with it each server keeps counts, locks and spent challenges of its own. The contract app uses the `database` store (`CACHE_STORE=database`). Where the PHP package splits these between `cache.limiter`, `risk.store` and `session.block_store`, the crate keeps them all in the default store, apart from `sso.store`.

Every change to a user's sessions, password and sign-in methods runs under one cache lock keyed on the user, where the PHP package uses a row lock on the user's model. The cache lock doesn't keep the PHP side out, so some changes also lock the user's row as the PHP package does: `SELECT ... FOR UPDATE` on their `id` in the table `session_user_type` names, in a transaction on the default connection. Changing sign-in methods always takes it. On the `database` session driver, so does moving a session to a new record (a step-up, "remember me" or a rotation), and a sign in when `sessions.max` is set, as the PHP package's `register()` does. A PHP sign out everywhere then can't miss a session moving on this side at the same moment, and a sign in on each side can't each count the sessions without the other's. The row is waited for 5 seconds at most; past that the change fails rather than going ahead without the lock. On SQLite, and when that table isn't there, no row is locked: a missing table is logged as a warning once, and looked for again each time, so one made after the application started is locked from then on.

## Cryptography

The crate adds no cipher or hash of its own. Everything belongs to laravel-rust or a Rust crate, chosen to make the PHP package's values, so the two read each other's.

### Keys

| Key | Used For |
|---|---|
| `APP_KEY` (and `APP_PREVIOUS_KEYS`) | Encrypting pending logins, authenticators' secrets, flashed results and Keyring's cookies, as Laravel encrypts them. Keys derived from it (HKDF) for recovery codes, sent codes, session handles, reserved addresses and passkey user handles. Signing verification and "this wasn't me" links, as Laravel signs them. |

Use the PHP side's `APP_KEY` when the two share a database.

### Algorithms

| Algorithm | Where |
|---|---|
| Laravel's encryption, through laravel-rust | Secrets, pending logins, flashed results, cookies. |
| HMAC-SHA256 | Recovery codes, sent codes, session handles, reserved addresses, signed links. |
| SHA-256 | Device tokens, `sso` credential IDs. |
| bcrypt, through laravel-rust | Passwords, reset tokens. |
| ES256, RS256 (webauthn-rs-core) | Passkeys and security keys. |
| RS256, PS256, ES256, EdDSA (`rsa`, `p256`, `ed25519-dalek`) | Identity providers' ID tokens. |
| HMAC-SHA1, SHA-256, SHA-512 | Authenticator app codes, as each was set up. |

### Random Values

Every random value comes from the operating system's generator, through the `getrandom` crate or laravel-rust's `str::random()`.

### Changing an Algorithm

Not available: there's no hasher to swap, as laravel-rust only hashes passwords with bcrypt. Ed25519 passkeys can't be added. See [Signature Algorithms](https://keyringauth.com/docs/0.x/rust/passkeys#signature-algorithms).

### Peppering Passwords

Not available, as in the PHP package, for the reasons its [docs](https://keyringauth.com/docs/0.x/security#peppering-passwords) give.

## What a Request Costs

As in the PHP package's [table](https://keyringauth.com/docs/0.x/security#what-a-request-costs): bcrypt on a sign in, a reset and a password change, Have I Been Pwned on a new password in production and with `BreachedPassword`, and an identity provider's endpoints on single sign-on, each behind a rate limit. The account-locked email is sent in the background, off the refused sign in's answer.

## Standards

The crate keeps the PHP package's standards, as its [page](https://keyringauth.com/docs/0.x/security#standards) lists them, and [OWASP ASVS and NIST SP 800-63B](https://keyringauth.com/docs/0.x/rust/owasp-asvs) goes through where the crate stands.

## Known Limitations

### Where Keyring Departs From a Standard

As in the PHP package, plus:

- **`RequireAssurance::aal1()`** is stricter than the PHP package's, not looser: no recovery code alone.
- **`sign_out_others: false`** can't be honoured on a password change, so every other session ends. This is stricter, not looser.

### Other Limits

The PHP package's [other limits](https://keyringauth.com/docs/0.x/security#other-limits) hold. These are the crate's own:

- **Overlapping requests.** A request that overlapped a sign in, step-up or sign-out can save the old session again, as `sessions.overlapping_requests` isn't there.
- **Ended sessions' data.** An ended session's data stays in the store until it expires, as laravel-rust can't destroy another browser's session.
- **Reserved lookalikes** in scripts beyond Latin, Greek and Cyrillic only match themselves, and a reservation for such an address isn't found by the other side.
- **Ed25519 passkeys** can't be verified, so a user with only one can't sign in here.
- **Lock timeouts.** A request that waits the full 10 seconds for the session lock gets a `500`, not a `423`.

See [Differences From PHP](https://keyringauth.com/docs/0.x/rust/differences) for everything else.
