# Protected Changes

Source: https://keyringauth.com/docs/0.x/rust/protected-changes

## Introduction

Whoever controls the email address and password controls the account, so Keyring's flows for changing them check who's asking, tell the owner, and can be undone, as in the PHP package. Each runs code of yours, so each starts off. Turn it on and give the provider its action:

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

laravel::Application::configure()
    .with_providers(|providers| {
        providers.add(
            KeyringServiceProvider::<Users>::new()
                .reset_user_passwords_using(ResetUserPassword)
                .update_user_passwords_using(UpdateUserPassword)
                .change_emails_using(ChangeEmail)
                .verify_emails(),
        );
    })
    .with_auth(|auth, _| {
        auth.session::<Users>();
        laravel_keyring::http::verification_page::<User>(auth);
    })
    .with_config(|config, _| {
        let features = &mut config.section_mut::<KeyringConfig>().features;
        features.reset_passwords = true;
        features.update_passwords = true;
        features.email_changes = true;
        features.email_verification = true;
    });
```

A feature that's on without its action stops the application booting. With `update_passwords` or `email_changes` on, that attribute is [protected](https://keyringauth.com/docs/0.x/rust/protected-changes#protected-attributes).

## Protected Attributes

`features.update_passwords` protects `password`, and `features.email_changes` protects the address. List others in `protected`:

```rust
config.section_mut::<KeyringConfig>().protected = vec!["phone".into()];
```

laravel-rust has no model events, so nothing checks every save of a user, as the PHP package's `HasKeyring` does on Eloquent's `updating` event. Call `laravel_keyring::protection::guard(&[...])` with the attributes a save changes wherever you save users. It fails with `ProtectedAttribute` for a protected one outside a Keyring flow:

```rust
async fn update_profile(user: &User, name: &str, email: Option<&str>) -> laravel::Result<()> {
    if email.is_some() {
        laravel_keyring::protection::guard(&["email"])?; // fails outside Keyring's email change flow
    }

    // ...save
    Ok(())
}
```

Keyring runs your password actions inside `protection::changing(Some(&["password"]), ...)` and the email change action inside `changing(None, ...)`, so a guard in them passes, as in your provider's `update_password()`. `protection::attributes()` lists what's protected, as `Keyring::protectedAttributes()`.

## Bypassing Protection

For trusted admin tooling, wrap the change in `protection::without_protection()`, with the admin who made it and a reason:

```rust
use laravel_keyring::protection;

protection::without_protection(Some(&admin), Some("Support ticket 42"), async {
    save_email(&user, "new@example.com").await
})
.await??;
```

Each use dispatches `ProtectionBypassed` with the actor and reason, and logs a `protection_bypassed` entry against the actor before the change runs, and doesn't run the change at all if it can't be logged.

## Changing the Email Address

Whoever controls an address can reset the password, so the new address always has to confirm, as in the PHP package. The old address can revert the change while it's pending, and for a while after, and it stays reserved meanwhile.

Your `ChangesEmails` action validates the new address, as `ValidatesEmailChanges` does, and reads and saves the user's address, which the PHP package does on the model itself:

```rust
use laravel::db;
use laravel::validation::InvalidInput;
use laravel_keyring::{ChangesEmails, Input};

struct ChangeEmail;

impl ChangesEmails<User> for ChangeEmail {
    async fn validate(&self, _user: &User, input: Input) -> laravel::Result<String> {
        // Check the address and return it, lowercased. Don't check whether
        // it's taken: Keyring does, without telling anyone.
        let email = input.get("email").and_then(|email| email.as_str()).unwrap_or_default();
        let email = email.trim().to_lowercase();
        let looks_right = email.split_once('@').is_some_and(|(name, domain)| {
            !name.is_empty() && domain.contains('.') && !email.contains(char::is_whitespace)
        });

        if !looks_right || email.chars().count() > 255 {
            return Err(InvalidInput::new()
                .with("email", "The email field must be a valid email address.")
                .into());
        }

        Ok(email)
    }

    fn email(&self, user: &User) -> String {
        user.email.clone()
    }

    async fn update(&self, user: &User, email: &str, verified: bool) -> laravel::Result<()> {
        // Keyring calls this inside its flow, so the guard lets it through.
        laravel_keyring::protection::guard(&["email"])?;
        let id = user.id;

        if verified {
            let now = laravel::now().strftime("%Y-%m-%d %H:%M:%S").to_string();
            db::query!("UPDATE users SET email = {email}, email_verified_at = {now} WHERE id = {id}")
                .update()
                .await?;
        } else {
            db::query!("UPDATE users SET email = {email} WHERE id = {id}").update().await?;
        }

        Ok(())
    }
}
```

`update()` is called with `verified` true when a new address has just confirmed, so mark it verified, and false when an undo puts the old address back. The [starter kit's `actions.rs`](https://github.com/keyringauth/keyring/blob/main/rust/starter-kit/src/actions.rs) validates the address with laravel-rust's `email` rule instead.

`taken()` answers whether another account has an address: `Some(true)`, `Some(false)`, or `None` for Keyring's own check, which asks your provider's `find_for_login()`. That finds users by what they sign in with, so if that's a username rather than the address, answer `taken()` yourself, or every address looks free. Answer it too for an account `find_for_login()` doesn't find, such as a soft-deleted one.

Changes are kept in the PHP package's `keyring_pending_changes` rows, so a change either side asked for confirms and undoes on the other.

### Requesting a Change

`POST /user/email` `{ "email" }`, behind the fresh check and the `keyring` limiter, answers `email-change-requested` whether or not the address is taken. A `MustVerifyEmail` user with an unverified address gets a `422` on `email`, and an account is mailed for `limits.notices` changes every `limits.notices_per` (a `429` on `email` after). The change is saved under the lock on the user, only while the session is still signed in, over the address the user has now, after cancelling any other that's waiting.

### Confirming

As in the PHP package: the new address is mailed a link to confirm, and the current one a notice with a link to undo, and one to confirm from there too unless the session proved something the user has (not a recovery code) that the account has had for `email_changes.established_after` and since before the session signed in. A change applies only while the address is still the one it was asked from and the new one is free. Applying it saves the address through your action as verified, stops trusting the user's devices, signs out every other session (`email_changed`) unless `email_changes.sign_out_others` is off, and moves a browser signed in as the account to a new ID and record.

A confirmation runs in one database transaction, which starts by locking the change's row, under Keyring's lock on the user. Write the address in `update()` through the default connection, from the same task (`db::query!` does): that write joins the transaction, so a confirmation that fails after it takes the address back. A write made elsewhere can land while the claim beside it rolls back, so a confirmation that finds the account already has the new address finishes the change, where the PHP package would cancel it.

Don't call `cancel_email_changes()` from `update()` or from a password action: it takes the lock on the user those run under.

### The Emailed Links

The links are `/email-changes/{change}/confirm/{token}` and `/email-changes/{change}/revert/{token}`, from `APP_URL` (or `link_root_using()`). Their `GET` answers the `email-change` page (`{ "action", "url", "token" }`) and changes nothing, under `keyring-pages`. Their `POST` `{ "token" }`, signed in or not, under `keyring`, confirms (`email-change-confirmed` while the other address has to, then `email-changed`) or undoes (`email-change-reverted`, on to `forgot-password` while resets are on). A wrong or spent token is `email-change-invalid` with `LinkRefused`, and a change that doesn't exist a `404`.

When another account has the new address, or it's reserved, the new address is sent "Someone tried to use your email address" with no link, so the change can never apply. The three emails are Keyring's own, replaceable with `notifications.confirm_email_change()`, `email_change_notice()` and `email_address_in_use()` (see [Emails a Flow Needs](https://keyringauth.com/docs/0.x/rust/security-log-and-emails#emails-a-flow-needs)).

### Reverting

Undoing puts the old address back (even when a later change moved it), closes every later change, removes each authenticator added since the session that asked signed in or within `established_after` before the change (the recovery codes too once nothing they recover is left), each with `AuthenticatorRemoved` and no freeze, and signs out every session (`email_change_undone`), as in the PHP package.

Two differences:

- An undo announces what it removed once its transaction has committed and everyone is signed out, so a listener that fails can't take the undo back, as it would in PHP. Its error still answers the request. laravel-rust holds an event's listeners until the transaction commits; register a listener with `listen_at_dispatch` for one that runs inside the transaction.
- An undo loads the account with your provider's `find()`. A deactivated account that `find()` doesn't load gets no address back, and the link answers `email-change-invalid`, where the PHP package puts the address back for when the account is restored.

### The Old Address Is Reserved

While an applied change can be undone (`email_changes.revertable_for`, 7 days), the address it replaced stays with its owner, as the PHP package's `ReservedAddresses`. It's found by the PHP package's keyed hash of the address lowercased and folded, so a lookalike a database collation would take for it is held too. Registration and email changes count it as taken, and `laravel_keyring::address_reserved::<User>(address, except)` checks one for your own code, as the `UnreservedAddress` rule. Call it where you create users or change addresses yourself.

> [!WARNING]
> The fold covers Latin, Greek and Cyrillic letters, general punctuation and format characters. A character of another script, such as Chinese, Japanese or Korean, is kept as it is, where the PHP package transliterates it, so such an address only matches itself, and a reservation either side makes for it isn't found by the other. If your users have such addresses and both sides take registrations, check reservations on one side only.

### Checking and Cancelling

`GET /user/email` answers `{ "pending": { "email", "confirmed", "needsCurrentConfirmation", "expiresAt" } }` or `null`. `DELETE /user/email` cancels it (`email-change-cancelled`), as a password reset, a password change and signing out everywhere else do, the undo link working on until the change would have expired. Both `POST` and `DELETE /user/email` are refused while impersonating.

From your own code, `laravel_keyring::pending_email_change(&user)`, `cancel_email_changes(&user)` and `email_last_changed_at(&user)` are the PHP package's `EmailChanges` methods.

## Changing the Password

`PUT /user/password` `{ "current_password", "password", "password_confirmation", "sign_out_others" }`, with `features.update_passwords`, behind the fresh check, the session lock and the `keyring-session-changes` limiter. Your `UpdatesUserPasswords` action checks the rules and saves the new hash:

```rust
use laravel::auth::UserProvider;
use laravel_keyring::{Input, PasswordRules, UpdatesUserPasswords};

struct UpdateUserPassword;

impl UpdatesUserPasswords<User> for UpdateUserPassword {
    async fn update(&self, user: &User, input: Input) -> laravel::Result<()> {
        let password = PasswordRules::for_user(user).await?.check(&input).await?;

        Users.update_password(user, &laravel::hash::make(&password).await?).await
    }
}
```

Keyring checks `current_password` itself, and refuses the current password again, one bcrypt can't take, and one a hold was placed over, before your action runs. It runs your action under the lock on the user, and does everything around the save as the PHP package does: forgets the reset links, cancels an email change, lifts a hold, stops trusting the user's devices, clears the account's sign-in limits, ends every other session (`password_changed`), and moves this one to a new ID and record. It answers `password-updated`.

> [!WARNING]
> A new password signs out every other session, whatever `sign_out_others` says. laravel-rust's guard keeps a fingerprint of the password hash in each session and signs out every session made before it changed. `sign_out_others` only decides the rest of signing out everywhere, such as a new remember token. The browser that changed it carries on.

A first password, chosen by a user who had none, isn't established for `authenticator_changes.established_after`, as in the PHP package.

## Requiring a Password Change

Keyring never expires passwords. When there's evidence that a password is known to someone else, it can hold the user until they choose another, as in the PHP package. It places the hold itself when the [`BreachedPassword`](https://keyringauth.com/docs/0.x/rust/risk#requiring-a-new-password) signal finds a breached password. For anything else, place it from your own code:

```rust
laravel_keyring::require_password_change(&user, Some("Reported phished on 12 November.")).await?;

laravel_keyring::requires_password_change(&user).await?; // true until the password changes
laravel_keyring::password_change_reason(&user).await?;
laravel_keyring::cancel_password_change(&user).await?; // the evidence was wrong
```

`require_password_change()` returns `false` and does nothing for a user without a password. Then set `password_change_url`, such as `/settings/password`. While a user is held, `RequirePasswordChange`, at the end of the `web` group, answers their every request with the `403` `{ "status": "change-password", "message", "redirect" }`, and sends a page visit to `password_change_url`, but for changing the password, the confirm routes, an identity provider's callback for a confirm, signing out, email verification, the `password_change_url` page and `password_change_except`, which lists paths rather than route names. `password_change_url` also gets past [`RequireEnrollment`](https://keyringauth.com/docs/0.x/rust/policies#requiring-a-second-factor) while they're held, so a user without a second factor isn't sent back and forth between it and the enrollment page. Once the hold ends, the page asks for a second factor again. Serve only the change-password page at that path. Paths in `password_change_except` don't get past `RequireEnrollment`. The rest of the rules are the [PHP package's](https://keyringauth.com/docs/0.x/protected-changes#requiring-a-password-change), and holds are kept in `keyring_password_holds`, so either side's holds apply on the other.

"No hold" is kept in the session for a minute, as in the PHP package, so other sessions find a new hold within a minute. Keyring dispatches `PasswordChangeRequired` when a hold is placed, and doesn't email the user.

### Carrying On Afterwards

Keyring remembers the page a held user was heading for, and after they change their password, `password-updated` redirects there, as in the PHP package. The page is kept only for a page the browser navigated to.

## Password Rules

`laravel_keyring::PasswordRules` is the PHP package's `PasswordRules::for()`, with the same rules, order and messages, all on `password`: confirmed, `passwords.min_with_mfa` or `min_without_mfa` characters (8 once the user has a second factor, 15 otherwise and at registration) up to `passwords.max`, not breached when `passwords.uncompromised` asks (in production by default, letting a password through when Have I Been Pwned can't be asked, unless `passwords.refuse_unchecked`), not one of the most common passwords, not made up of `app.name`, `passwords.context` or the user's own words, and within bcrypt's 72 bytes. See the [PHP docs](https://keyringauth.com/docs/0.x/protected-changes#password-rules) for why.

It's a builder your actions call, not a list of Laravel rules:

```rust
use laravel_keyring::PasswordRules;

// Registration: no user yet, so the name and address given count as theirs.
PasswordRules::new().context(["Taylor Otwell", "taylor@example.com"]).check(&input).await?;

// A change or a reset: the user's second factor and words.
let password = PasswordRules::for_user(&user).await?.check(&input).await?;

// Administrators need 20 characters, second factor or not.
PasswordRules::for_user(&user).await?.min(20).check(&input).await?;
```

`check(&input)` returns the password or an `InvalidInput`, and `validate(&input, &mut errors)` adds to errors of your own, returning the password when it passed. `.min()` only ever raises the minimum, and never under eight, and `.max()` sets the maximum instead. A password that isn't a string gets `must be a string` alone, where Laravel's validator also measures it.

Keyring converts each password to Unicode's NFC form before your action sees it, and before it measures, hashes or checks one. There's no public `normalize()`: if your own code sets a password, such as a seeder, normalise it first, with the `unicode-normalization` crate's `.nfc()`.

### Context-Specific Words

As in the PHP package: a password is refused when, with its digits, spaces and punctuation removed, it's one of the context words, or several run together, with lookalike characters read as letters. The words are `app.name`, `passwords.context`, and the user's name and address, which are their `mail_address()`'s display name and address, standing in for the `name`, username and email attributes, and the organisation it's at, unless anyone can have an address there.

```rust
config.section_mut::<KeyringConfig>().passwords.context = vec!["Acme".into(), "Acme Rockets".into(), "Roadrunner".into()];
```

## Resetting the Password

`POST /forgot-password` `{ "email" }` answers `reset-link-sent` for every address, and sends the link after the answer: nothing for an address nobody has or one sent a link in the last `passwords.throttle`, otherwise a 64-character token kept as its bcrypt hash in Laravel's `password_reset_tokens` table, by address, so a link either side made works on the other. The link is `/reset-password/{token}?email=...` from `APP_URL` (or `link_root_using()`), never the request's host, in Keyring's own email with the wording of Laravel's `ResetPassword`. `notifications.reset_link()` replaces it (see [Emails a Flow Needs](https://keyringauth.com/docs/0.x/rust/security-log-and-emails#emails-a-flow-needs)).

`POST /reset-password` takes `token`, `email`, `password` and `password_confirmation`. Your `ResetsUserPasswords` action checks the rules and saves the password, as the change action does:

```rust
use laravel::auth::UserProvider;
use laravel_keyring::{Input, PasswordRules, ResetsUserPasswords};

struct ResetUserPassword;

impl ResetsUserPasswords<User> for ResetUserPassword {
    async fn reset(&self, user: &User, input: Input) -> laravel::Result<()> {
        let password = PasswordRules::for_user(user).await?.check(&input).await?;

        Users.update_password(user, &laravel::hash::make(&password).await?).await
    }
}
```

Everything around it is the PHP package's: a bad token gets the same `422` on `email` as an address with no account, in at least `timebox`, with `LinkRefused`. A right one uses the link up, unlinks identity providers, signs every session out (`password_reset`), cancels an email change, clears the account's sign-in limits, lifts a risk lock, lifts a hold (or puts one back in force over the same password), verifies the address where registration hides who has an account, and answers `password-reset` naming the `login` page. Nobody is signed in.

`passwords.expire` (one hour) and `passwords.throttle` (one minute) stand in for Laravel's broker settings in `config/auth.php`. The `password_reset_tokens` table is yours to create, as a new Laravel app's migrations do: `email` (primary), `token` and `created_at`. There's no Laravel `PasswordReset` event; Keyring dispatches its own.

## Email Verification

With `features.email_verification` on, for a user type that derives laravel-rust's `MustVerifyEmail` and a provider given `verify_emails()`, Keyring answers `GET /email/verify` (`verify-email`, or `email-verified` for a verified user), `POST /email/verification-notification` (`verification-link-sent`), the emailed link's page, `GET /email/verify/{id}/{hash}`, and its button, `POST /email/verify/{id}/{hash}` `{ "expires", "signature" }`, as in the PHP package. Opening the link verifies nothing: only the button does.

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`. Your provider implements `mark_email_as_verified()`.

The link is signed relative to the site, as Laravel's `temporarySignedRoute(..., absolute: false)` signs it, with `APP_KEY` and every key in `APP_PREVIOUS_KEYS`, so a link either side sends opens on the other. It lasts `verification_expire` (one hour). A refused link is a `403` with `LinkRefused`, and one opened by someone else's account a `403` with `AccessRefused`. The email is Keyring's own, with the wording of Laravel's `VerifyEmail`; `notifications.verification_link()` replaces it. There's no Laravel `Verified` event.

## Routes

| Method | URI | Does |
|---|---|---|
| `GET`, `POST`, `DELETE` | `/user/email` | The pending change, requesting one, and cancelling it. |
| `GET` | `/email-changes/{change}/confirm/{token}`, `/email-changes/{change}/revert/{token}` | The emailed links' page. |
| `POST` | `/email-changes/{change}/confirm`, `/email-changes/{change}/revert` | Confirms or undoes. |
| `PUT` | `/user/password` | Changes the password. |
| `GET`, `POST` | `/forgot-password` | The page, and asking for a link. |
| `GET` | `/reset-password/{token}` | The reset page. |
| `POST` | `/reset-password` | Resets the password. |
| `GET` | `/email/verify` | The verify-email page. |
| `GET`, `POST` | `/email/verify/{id}/{hash}` | The verification link's page, and its button. |
| `POST` | `/email/verification-notification` | Sends another link. |

Each is there while its feature is on.

## Events

These are in `laravel_keyring::events`, as in the PHP package: `EmailChangeRequested`, `EmailChanged` and `EmailChangeReverted` (with an `EmailChange`, the PHP package's `PendingChange` without its tokens), `PasswordChanged`, `PasswordReset`, `PasswordChangeRequired`, `ProtectionBypassed` and `LinkRefused`. Laravel's `PasswordReset` and `Verified` aren't dispatched. See [Events](https://keyringauth.com/docs/0.x/rust/events).
