# Installation

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

## Introduction

This page covers adding the `laravel-keyring` crate to a Laravel for Rust application. The [Quick Start](https://keyringauth.com/docs/0.x/rust/quick-start) has the short version, which starts from the starter kit.

The crate is version 0.1.0 and early. It isn't on crates.io yet, so an application depends on this repository, pinned to a commit, and its API will change before 1.0.

## Requirements

- Rust 1.99 or later.
- `laravel-rust` `=0.1.4` exactly, since laravel-rust makes no promises between 0.x releases.
- A database driver for laravel-rust: `database-postgres`, `database-mysql` or `database-sqlite`. Keyring needs laravel-rust's `database` feature, and laravel-rust refuses that without a driver.
- A cache store with locks. For more than one server, a store every server shares (see [Running on More Than One Server](https://keyringauth.com/docs/0.x/rust/security#a-shared-lock-store)).
- Inertia, optional, through the crate's `inertia` feature. Without it, Keyring renders views. See [Pages](https://keyringauth.com/docs/0.x/rust/sign-in-flow#pages).

There's no `sodium` requirement: the crate can't verify Ed25519 keys, so it only offers ES256, and RS256 when you list it. See [Signature Algorithms](https://keyringauth.com/docs/0.x/rust/passkeys#signature-algorithms).

## Installing Keyring

Depend on this repository, pinned to a commit, along with laravel-rust and a database driver:

```toml
[dependencies]
laravel-rust = { version = "=0.1.4", features = ["database-postgres"] }
laravel-keyring = { git = "https://github.com/keyringauth/keyring", rev = "<commit>", features = ["inertia"] }
```

Leave out `features = ["inertia"]` if your pages aren't Inertia components.

Then add `KeyringServiceProvider` for your user provider, register that provider as a service, and register the session guard for it:

```rust
use laravel_keyring::{KeyringConfig, KeyringServiceProvider};

laravel::Application::configure()
    .with_providers(|providers| {
        providers.add(KeyringServiceProvider::<Users>::new());
    })
    .with_services(|app| {
        app.singleton(|_| async { Ok(Users) });
    })
    .with_auth(|auth, _| {
        auth.session::<Users>();
    })
    .with_config(|config, _| {
        let keyring = config.section_mut::<KeyringConfig>();
        keyring.authenticatable_type = "App\\Models\\User".into();
        keyring.session_user_type = "pgsql:users".into();
    });
```

`Users` is your user provider (see [Preparing Your User Model](https://keyringauth.com/docs/0.x/rust/installation#preparing-your-user-model)). The `with_config` lines only need changing when the defaults don't match what a PHP application sharing the database writes. See [The Two User Types](https://keyringauth.com/docs/0.x/rust/installation#the-two-user-types).

There's no installer to run first, and no question to answer. `keyring:install` exists, but it only prints the `with_config` for the factors and features you name, since your config is Rust code:

```bash
cargo run -- keyring:install --factor=totp --factor=passkeys --feature=registration --feature=manage-authenticators
```

It takes the PHP command's `--factor` and `--feature` values. With an authenticator app, passkeys or security keys, it also prints `enrollment_url` and the `with_middleware` that requires a second factor of everyone, unless you pass `--optional-second-factor`. It writes nothing, asks nothing, and has no `--force`.

Run your application's `migrate` command to create Keyring's tables:

```bash
cargo run -- migrate
```

If you're moving from Fortify, read [Upgrading From Fortify](https://keyringauth.com/docs/0.x/rust/upgrading-from-fortify) before you migrate.

## What Gets Published

Nothing is published. The provider brings everything with it:

| What | Where It Comes From |
|---|---|
| Migrations | The provider registers them. They create the PHP package's tables, with the same columns: `keyring_authenticators`, `keyring_devices`, `keyring_sessions`, `keyring_pending_changes`, `keyring_events`, `keyring_failure_counts`, `keyring_password_holds` and `keyring_sign_in_changes`. |
| Settings | The `KeyringConfig` section, set in `with_config`. There's no `config/keyring.php`. See [Configuration](https://keyringauth.com/docs/0.x/rust/configuration). |
| Routes, middleware and console commands | The provider registers them, and schedules `keyring:prune`. |
| Listeners | The provider listens to its own events, to write the security log and queue the security emails, ahead of your listeners. |
| Actions | Yours to write, as traits the provider takes: `CreatesNewUsers`, `ResetsUserPasswords`, `UpdatesUserPasswords` and `ChangesEmails`. See [Configuration](https://keyringauth.com/docs/0.x/rust/configuration#registration). |
| Emails | Keyring's own plain-text and HTML emails. Replace one with a closure on `notifications`. See [Security Emails](https://keyringauth.com/docs/0.x/rust/security-log-and-emails#security-emails). |

Keyring's migrations need the `password_reset_tokens` table a new Laravel app has, for password resets. Your migrations create it: `email` (primary), `token` and `created_at`.

The tables' `authenticatable_id` columns are big integers, so user IDs must be integers.

## Preparing Your User Model

There's no model and no `HasKeyring` trait. Your application needs a user type and a user provider for its session guard. The provider finds users by ID and by the username on the login form, and Keyring uses the same provider to find the user a typed username names, so an account's rate limits are its user's. The user implements laravel-rust's `ReceivesMail`, the address Keyring's security emails go to:

```rust
use laravel::auth::{Authenticatable, MustVerifyEmail, UserProvider};
use laravel::db;
use laravel::hash::PasswordHash;

#[derive(Clone, db::FromRow, MustVerifyEmail)]
pub struct User {
    pub id: i64,
    pub name: String,
    pub email: String,
    #[auth(email_verified_at)]
    pub verified: bool,
    pub password: Option<PasswordHash>,
    pub remember_token: Option<String>,
}

impl laravel::notification::ReceivesMail for User {
    fn mail_address(&self) -> Option<laravel::mail::Address> {
        Some(laravel::mail::Address::new(&self.email).with_name(&self.name))
    }
}

impl Authenticatable for User {
    type Id = i64;

    fn auth_id(&self) -> i64 {
        self.id
    }

    fn auth_password(&self) -> Option<&PasswordHash> {
        self.password.as_ref()
    }

    fn remember_token(&self) -> Option<&str> {
        self.remember_token.as_deref()
    }
}

pub struct Users;

impl UserProvider for Users {
    type User = User;

    async fn find(&self, id: &i64) -> laravel::Result<Option<User>> {
        db::query!(
            "SELECT id, name, email, email_verified_at IS NOT NULL AS verified, password, remember_token
            FROM users WHERE id = {id}"
        )
        .select_one_as()
        .await
    }

    async fn find_for_login(&self, email: &str) -> laravel::Result<Option<User>> {
        db::query!(
            "SELECT id, name, email, email_verified_at IS NOT NULL AS verified, password, remember_token
            FROM users WHERE email = {email}"
        )
        .select_one_as()
        .await
    }

    async fn update_password(&self, user: &User, password: &PasswordHash) -> laravel::Result<()> {
        // Only Keyring's password flows may change it. See Protected Changes.
        laravel_keyring::protection::guard(&["password"])?;
        let (id, password) = (user.id, password.as_str());
        db::query!("UPDATE users SET password = {password} WHERE id = {id}").update().await?;

        Ok(())
    }

    async fn update_remember_token(&self, user: &User, token: &str) -> laravel::Result<()> {
        let id = user.id;
        db::query!("UPDATE users SET remember_token = {token} WHERE id = {id}").update().await?;

        Ok(())
    }

    async fn mark_email_as_verified(&self, user: &User) -> laravel::Result<()> {
        let (id, now) = (user.id, laravel::now().strftime("%Y-%m-%d %H:%M:%S").to_string());
        db::query!("UPDATE users SET email_verified_at = {now} WHERE id = {id}").update().await?;

        Ok(())
    }
}
```

The [starter kit's `users.rs`](https://github.com/keyringauth/keyring/blob/main/rust/starter-kit/src/users.rs) is this file. What the PHP trait does, your application does where it saves and deletes users:

- **`$user->keyring`** is `UserKeyring::of(&user)`, and `laravel_keyring::sign_in_methods(&user)` gives a settings page what it shows. See [From PHP](https://keyringauth.com/docs/0.x/rust/authenticators#from-php).
- **Protected attributes.** laravel-rust has no model events, so call `laravel_keyring::protection::guard(&[...])` with the attributes a save changes wherever you save users, as `update_password()` does above. It fails outside Keyring's flows for a protected attribute. See [Protected Attributes](https://keyringauth.com/docs/0.x/rust/protected-changes#protected-attributes).
- **Deleting a user.** Call `laravel_keyring::user_soft_deleted(&user)` or `laravel_keyring::user_deleted(&user)` where you delete users. The first forgets their reset links and signs them out everywhere. The second also deletes their authenticators, devices, pending changes, failure counts, log entries, password holds and sign-in changes.

A user type that derives `MustVerifyEmail` gets no security emails until its address is verified, as in the PHP package. If your application tracks verification some other way, return `None` from `mail_address()` for an address nobody has verified yet, since it may be anyone's. A user with no address gets `None` too, and is sent nothing.

`MustVerifyEmail` and `features.email_verification` go together, as in the PHP package:

- With registration on and hiding taken addresses, the application won't boot unless email verification is on, with `verify_emails()` on the provider. [`registration.reveal_taken`](https://keyringauth.com/docs/0.x/rust/configuration#registration) turns that rule off.
- laravel-rust asks an application whose user type derives `MustVerifyEmail` to mark its verification page, which a provider can't do, so call `laravel_keyring::http::verification_page::<User>(auth)` in `with_auth`. See [Email Verification](https://keyringauth.com/docs/0.x/rust/protected-changes#email-verification).
- With registration on, adding a sign-in method is a server error, naming what to change, for a user who can't prove their address. See [Managing Authenticators](https://keyringauth.com/docs/0.x/rust/authenticators#email-verification).

Keyring looks users up with the provider's `find_for_login()`, by `email` by default (`username` changes the field the form sends). Lookups trim and lowercase the input, so store addresses the same way. `laravel_keyring::normalize_username()` does that, and `normalize_usernames_using()` on the provider changes it. See [Finding the User](https://keyringauth.com/docs/0.x/rust/sign-in-flow#finding-the-user).

### The Two User Types

The PHP package writes a user's type in two places, and the crate has a setting for each:

| Setting | Column | What the PHP Package Writes | Default |
|---|---|---|---|
| `authenticatable_type` | `keyring_authenticators.authenticatable_type`, `keyring_failure_counts.authenticatable_type`, `keyring_devices.authenticatable_type` | The user model's morph class, such as `App\Models\User`, or its morph map alias | `App\Models\User` |
| `session_user_type` (`KEYRING_SESSION_USER_TYPE`) | `keyring_sessions.user_type` | The connection and table the user's ID is unique in, as `connection:table`, such as `pgsql:users` | `DB_CONNECTION:users`, or `postgres:users` when `DB_CONNECTION` is unset |

When the two share a database, set both to what the PHP side writes. Laravel names a PostgreSQL connection `pgsql` where laravel-rust's default is `postgres`, so the default `session_user_type` is often not what the PHP side writes: `keyring:install` prints the value in use. Each setting fails closed in its own way:

- A sign in with authenticators stored under any other `authenticatable_type` fails with a server error that names both types, rather than signing in on the password alone. So an application supports one user type.
- A sign in for a user with open sessions under another `session_user_type` for the same table (`pgsql:users` against `postgres:users`, say) fails with a server error that names both, rather than splitting their sessions in two, where each side's sessions list would hide the other's. Only sessions that have expired, or were ended, don't count: one unused for longer than `sessions.idle` still does, since the PHP side's idle setting may differ. A mismatch is only found once both sides have a session for the same user, so check the setting before going live.

`session_user_type` has to be `connection:table`, both parts there: anything else, such as the user's morph class, stops the application booting, since without the table Keyring couldn't lock the user's row or find their sessions under another type.

Signing out everywhere, a password change or reset, deleting the account and signing out a device end the user's sessions under any other `connection:table` for the same table too, so the PHP side's are never left open. A type for another table, such as `pgsql:admins`, is another user who happens to share the ID, and is left alone. So two different sets of users in tables with the same name on different connections (`pgsql:users` and `mysql:users`) aren't supported: they'd be taken for one user.

When `session_user_type` was wrong and you've set it to what the PHP side writes, the sessions this application wrote under the old value block their users' sign ins until they expire. Move them over instead, with the two values from the error:

```sql
UPDATE keyring_sessions SET user_type = 'pgsql:users' WHERE user_type = 'postgres:users';
```

## Frontend

If you offer passkeys or security keys, install the browser package, `@keyringjs/keyring`. It also has helpers for the challenge page, and works with the crate unchanged, since the crate answers the same requests:

```bash
npm install @keyringjs/keyring
```

For an Inertia frontend, turn on the crate's `inertia` feature, which turns on laravel-rust's, and add laravel-rust's Inertia middleware to the `web` group. Keyring's pages are then the components `auth/login` and the rest. See [Frontend](https://keyringauth.com/docs/0.x/rust/frontend).

## Routes Keyring Registers

Keyring registers its routes in the `web` middleware group, so they get the session, cookies and CSRF check. laravel-rust's routes have no names, so there are no `login` or `password.reset` names to clash with, but don't register your own routes at Keyring's paths.

The full list is in [The Sign In Flow](https://keyringauth.com/docs/0.x/rust/sign-in-flow#routes), [Step-Up](https://keyringauth.com/docs/0.x/rust/step-up), [Managing Authenticators](https://keyringauth.com/docs/0.x/rust/authenticators#routes), [Devices & Sessions](https://keyringauth.com/docs/0.x/rust/devices-and-sessions#routes) and [Protected Changes](https://keyringauth.com/docs/0.x/rust/protected-changes#routes). To change the prefix or domain, or turn the routes off, see [Configuration](https://keyringauth.com/docs/0.x/rust/configuration#routes).

The provider also adds middleware to the `web` group: `BlockSession` and `EndUnsavedSignIns` just ahead of `StartSession`, and `AuthenticateSession` and `RequirePasswordChange` at the end. See [The Session Middleware](https://keyringauth.com/docs/0.x/rust/devices-and-sessions#the-session-middleware).

## After Installing

- Set `APP_URL` to the address users visit. Keyring builds emailed links and the single sign-on callback from it, and passkeys and security keys only work on that origin unless you configure others. See [Passkeys & Security Keys](https://keyringauth.com/docs/0.x/rust/passkeys#relying-party-and-origins).
- Use the PHP side's `APP_KEY` when the two share a database. Keyring encrypts pending logins and authenticators' secrets with it, and keys recovery codes, sent codes and session handles with it.
- Build your [pages](https://keyringauth.com/docs/0.x/rust/quick-start#your-pages). If you require a second factor, build the page at `enrollment_url` too.
- Run a queue worker, or use the `sync` queue connection. [Security emails](https://keyringauth.com/docs/0.x/rust/security-log-and-emails#security-emails) are queued. Sign-in codes are sent straight away.
- Run your application's scheduler every minute (`schedule:run`). Keyring schedules `keyring:prune` daily at `prune_at`, which deletes old devices, finished email changes, old security log entries, ended sessions, old sign-in changes, and password holds lifted a year ago. See [Pruning](https://keyringauth.com/docs/0.x/rust/devices-and-sessions#pruning).
- Sessions end after two hours without activity unless the browser ticked "remember me". To change that, set `sessions.idle`. See [Timeouts](https://keyringauth.com/docs/0.x/rust/devices-and-sessions#timeouts).
- Keep signed-in routes in the `web` group, where `AuthenticateSession` runs. Otherwise, a revoked or timed-out session keeps working on them. See [The Session Middleware](https://keyringauth.com/docs/0.x/rust/devices-and-sessions#the-session-middleware).
- To hear about every session that ends, set `sessions.sweep_every`. Keyring then schedules `keyring:sweep`. See [Sweeping Ended Sessions](https://keyringauth.com/docs/0.x/rust/devices-and-sessions#sweeping-ended-sessions).
- `keyring:sign-out` signs one user out everywhere, and `--all` signs everyone out. See [For Administrators](https://keyringauth.com/docs/0.x/rust/devices-and-sessions#for-administrators).
- Behind a load balancer or proxy, list it with laravel-rust's `trust_proxies`. See [Trusted Proxies](https://keyringauth.com/docs/0.x/rust/security#trusted-proxies).
