# Protected Changes

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

```go
k := keyring.New[models.User](func(cfg *keyring.Config) {
	cfg.Features.ResetPasswords = true
	cfg.Features.UpdatePasswords = true
	cfg.Features.EmailChanges = true
	cfg.Features.EmailVerification = true
}).
	ResetPasswordsWith(actions.ResetUserPassword{}).
	UpdatePasswordsWith(actions.UpdateUserPassword{}).
	ValidateEmailChangesWith(actions.ValidateEmailChange{})
```

A feature that's on without its action stops `Register`. With `UpdatePasswords` or `EmailChanges` on, that attribute is [protected](https://keyringauth.com/docs/0.x/go/protected-changes#protected-attributes).

## Protected Attributes

`Features.UpdatePasswords` protects `password`, and `Features.EmailChanges` protects the address (the `Email` column). List others in `Protected`:

```go
cfg.Protected = []string{"phone"}
```

The PHP package checks every save of the user model, on Eloquent's `updating` event. Laravel Go's models have an `Updating` hook instead, so your user model calls `GuardChanges` from it, with the columns the save writes:

```go
func (u *User) Updating(ctx context.Context, values db.Values) error {
	return keyring.From[User](ctx).GuardChanges(ctx, u, values)
}
```

Outside a Keyring flow, that refuses a protected attribute the save changes with a `*keyring.ProtectedAttributeError` naming them. In any flow, `WithoutProtection` included, it refuses an address held for someone else with a `*keyring.ReservedAddressError` (see [The Old Address Is Reserved](https://keyringauth.com/docs/0.x/go/protected-changes#the-old-address-is-reserved)), as the PHP package does. A save that doesn't go through the model, such as `db.Table("users").Update(...)`, calls it the same way first.

What counts as changed is decided against the user's stored row, read inside the save's transaction, as Eloquent's `isDirty()` decides it: `model.Save` hands the hook every column, so a `Save` that only changes the name goes through, and one that changes the address doesn't. A change of address that goes through also forgets the reset link the old address was sent, as the PHP package does on any save that changes the address.

`Register` refuses a user type without an `Updating` hook while anything is protected, the closest Laravel Go has to the PHP package's trait guarding every save on its own. If your users aren't Laravel Go models, set `Config.GuardChangesManually` and call `GuardChanges` yourself before every write of a user.

Keyring runs your password actions and its own address change with a context that lets their writes through, so write with the `ctx` they're given. `k.ProtectedAttributes()` lists what's protected, as `Keyring::protectedAttributes()`.

## Bypassing Protection

For trusted admin tooling, such as a support agent fixing an address, wrap the change in `WithoutProtection`, with a reason:

```go
err := keyring.From[models.User](r).WithoutProtection(r, "Support ticket 42", func(ctx context.Context) error {
	return model.Update(ctx, user, db.Values{"email": "new@example.com"})
})
```

The change gets a context `GuardChanges` lets through. Each use dispatches `ProtectionBypassed` with the reason, about whoever is signed in on the request (or a context made from it), and logs a `protection_bypassed` entry before the change runs. A bypass that can't be logged doesn't happen, and its error is returned.

## 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 `ValidatesEmailChanges` action checks the request and returns the new address. The contract app's is the PHP package's stub:

```go
type ValidateEmailChange struct{}

type emailChange struct {
	Email string `json:"email"`
}

func (f *emailChange) Rules(*web.Request) (validation.Rules, error) {
	return validation.For(f, rule.Field(&f.Email, rule.Required, rule.Email, rule.Max(255))), nil
}

func (ValidateEmailChange) Validate(r *web.Request, _ *models.User) (string, error) {
	form, err := r.Validate[emailChange]()
	if err != nil {
		return "", err
	}

	return strings.ToLower(strings.TrimSpace(form.Email)), nil
}
```

Don't check whether the address is taken: Keyring does, without telling anyone. It looks in the user model's table, in the `Email` column, whoever you keep from signing in, as the PHP package looks without global scopes. An action that's also a `keyring.TakenAddresses` answers that itself, with `Taken(ctx, email) (bool, error)`, for users that aren't Laravel Go models.

Keyring saves the new address itself with `model.Update`, writing the `Email` column and, for a new address that has just confirmed and a user type with an `EmailVerifiedAt` field, `email_verified_at` in the same write, as the PHP package saves the model. An action that's also a `keyring.SavesEmails` saves it instead:

```go
func (ValidateEmailChange) SaveEmail(ctx context.Context, user *models.User, email string, verified bool) error {
	values := db.Values{"email": email}
	if verified {
		values["email_verified_at"] = date.Now(ctx).UTC().Truncate(time.Second)
	}

	_, err := db.Table("users").Where("id", "=", user.ID).Update(ctx, values)

	return err
}
```

`verified` is true when a new address has just confirmed, and false when an undo puts the old address back, which leaves verification as it is. Write with `ctx`: see [Confirming](https://keyringauth.com/docs/0.x/go/protected-changes#confirming).

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 `ChangesMiddleware` and `Limits.Forms`, answers `email-change-requested` whether or not the address is taken. With `Features.EmailVerification` on, a user with an unverified address gets a `422` on `email`, and an account is mailed for `Limits.Notices` changes every `Limits.NoticesPer` (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. The emails go off the request's goroutine, so how long they take doesn't give away which case it was.

### 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 `EmailChanges.EstablishedAfter` (7 days) 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 as verified, stops trusting the user's devices, signs out every other session (`email_changed`) unless `EmailChanges.SignOutOthers` is off, and moves a browser signed in as the account to a new ID and record.

Set the `EmailChanges` fields one at a time: assigning the whole struct leaves `SignOutOthers` off.

A confirmation runs in one database transaction, which locks the change's row and then the user's, under Keyring's lock on the user. A `SaveEmail` that writes with its `ctx` joins that transaction, so a confirmation that fails after it takes the address back.

Don't call `CancelEmailChanges` from `SaveEmail` 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 `LinkRoot` (`APP_URL` unless you set it). The confirm link lasts `EmailChanges.ConfirmableFor` (a day). Their `GET` answers the `email-change` page (`{ "action", "url", "token" }`) and changes nothing, under `Limits.Pages`. Their `POST` `{ "token" }`, signed in or not, under `Limits.Forms`, confirms, from either address in either order (`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, `confirm_email_change`, `email_change_notice` and `email_address_in_use`, replaceable with `Notifications.AccountMail` (see [Emails a Flow Needs](https://keyringauth.com/docs/0.x/go/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 `EmailChanges.EstablishedAfter` 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.

What it changes in the tables is one transaction, so a failure part way leaves the link working. Once everyone is signed out, later changes are closed and new methods removed once more, for a request that was saving one while the undo ran. What was removed is announced once all of that is done, so a listener that fails can't take the undo back, as it would in PHP. With no account left, there's nothing to undo, and the link isn't spent.

### The Old Address Is Reserved

While an applied change can be undone (`EmailChanges.RevertableFor`, 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. Check it yourself where you create users or change addresses, such as an admin screen or an import, as the PHP package's `UnreservedAddress` rule:

```go
reserved, err := keyring.From[models.User](r).AddressReserved(r, address, user) // nil for anyone
```

A save through a model whose `Updating` hook calls [`GuardChanges`](https://keyringauth.com/docs/0.x/go/protected-changes#protected-attributes) is checked already. Creating a user isn't a change, so check a new user's address with `AddressReserved`.

> [!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](https://keyringauth.com/docs/0.x/go/impersonation#whats-refused-while-impersonating).

From your own code, `k.PendingEmailChange(ctx, user)` returns the waiting `*keyring.EmailChange` or `nil`, and `k.CancelEmailChanges(ctx, user)` cancels it, as the PHP package's `EmailChanges` methods.

## Changing the Password

`PUT /user/password` `{ "current_password", "password", "password_confirmation", "sign_out_others" }`, with `Features.UpdatePasswords`, behind `ChangesMiddleware`, the session lock and the `keyring-session-changes` limit. Your `UpdatesUserPasswords` action checks the rules and saves the new hash. The contract app's:

```go
type UpdateUserPassword struct{}

func (UpdateUserPassword) Update(ctx context.Context, user *models.User, input map[string]any) error {
	rules, err := keyring.From[models.User](ctx).PasswordRules(ctx, user)
	if err != nil {
		return err
	}
	password, err := rules.Check(ctx, input)
	if err != nil {
		return err
	}

	hashed, err := hash.Make(ctx, password)
	if err != nil {
		return err
	}

	now := date.Now(ctx).UTC().Truncate(time.Second)
	_, err = db.Table("users").Where("id", "=", user.ID).Update(ctx, db.Values{"password": hashed, "updated_at": now})

	return err
}
```

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 holding the user's row, with a deadline a little before its lock lapses, 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, signed in again with `auth.Login` so the guard knows the new password. It answers `password-updated`. The action must save a new password or fail.

On PostgreSQL and MySQL, a change whose action fails rolls back with the user's row lock. On SQLite the action's write stands, and what follows it is done before the failure is returned.

> [!WARNING]
> A new password signs out every other session, whatever `sign_out_others` says. Laravel Go's `auth.Session` keeps a fingerprint of the password hash in each session and signs out every session made before it changed, so Keyring ends their records as `password_changed` straight away. `sign_out_others` only decides the rest of signing out everywhere, such as a new remember token. The browser that changed it carries on, but isn't brought back by "remember me" afterwards. See [Differences From PHP](https://keyringauth.com/docs/0.x/go/differences#passwords).

A first password, chosen by a user who had none, isn't established for `EstablishedAfter`, 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/go/risk#requiring-a-new-password) signal finds a breached password. For anything else, place it from your own code:

```go
k := keyring.From[models.User](r)

held, err := k.RequirePasswordChange(r, user, "Reported phished on 12 November.")

k.RequiresPasswordChange(r, user) // true until the password changes
k.PasswordChangeReason(r, user)
k.CancelPasswordChange(r, user) // the evidence was wrong
```

`RequirePasswordChange` reports `false` and does nothing for a user without a password. The reason is `""` for none. Then set `PasswordChangeURL`, such as `/settings/password`. While a user is held, `RequirePasswordChange[U]`, at the end of the `web` group, answers their every JSON request with the `403` `{ "status": "change-password", "message", "redirect" }`, and sends a page visit to `PasswordChangeURL`, but for changing the password (`user-password.update`), the confirm routes (`keyring.confirm.*`), signing out (`logout`), email verification (`verification.*`), the `PasswordChangeURL` page and the routes `PasswordChangeExcept` names, by route name with `*` as a wildcard. An application route with one of those names is let through too. 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. Given the request as its context, `RequirePasswordChange` makes that session find it at once. Keyring dispatches `PasswordChangeRequired` when a hold is placed, and doesn't email the user.

A held user is let through to `PasswordChangeURL`'s page past [`RequireEnrollment`](https://keyringauth.com/docs/0.x/go/policies#requiring-a-second-factor) too: the hold comes first. In the PHP package a held user with no second factor can be sent back and forth between the two.

### 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

`keyring.PasswordRules` is the PHP package's `PasswordRules::for()`, with the same rules, order and messages, all on `password`: confirmed, `Passwords.MinWithMFA` or `MinWithoutMFA` characters (8 once the user has a second factor, 15 otherwise and at registration) up to `Passwords.Max` (128), 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.RefuseUnchecked`), 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.

Get them from `k.PasswordRules(ctx, user)`, with `nil` for a user registering. They're a Laravel Go `validation.Rule` for a form, and `Check` reads a map, for an action:

```go
k := keyring.From[models.User](r)

// Registration: no user yet, so the name and address given count as theirs.
passwords, err := k.PasswordRules(r, nil)
rule.Field(&f.Password, passwords.Context(f.Name, f.Email))

// A change or a reset: the user's second factor and words.
rules, err := k.PasswordRules(ctx, user)
password, err := rules.Check(ctx, input)

// Administrators need 20 characters, second factor or not.
password, err = rules.AtLeast(20).Check(ctx, input)
```

As a rule, it reads the field's `_confirmation` beside it, and refuses with every rule the password breaks, one message each. `Check` returns the password, or a validation error on `password`. `AtLeast` only ever raises the minimum, and `AtMost` sets the maximum instead, none for zero. `MinLength()` is the fewest characters they ask for.

Keyring converts each password to Unicode's NFC form before your action sees it, and before it measures, hashes or checks one. If your own code sets a password, such as a seeder, normalise it first, with `golang.org/x/text/unicode/norm`'s `norm.NFC.String`.

Laravel Go checks bcrypt hashes only, so a PHP application's Argon2 passwords can't be checked here. See [Differences From PHP](https://keyringauth.com/docs/0.x/go/differences#passwords).

### 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, and the organisation it's at, unless anyone can have an address there.

```go
cfg.Passwords.Context = []string{"Acme", "Acme Rockets", "Roadrunner"}
```

## Resetting the Password

`POST /forgot-password` `{ "email" }` answers `reset-link-sent` for every address, and sends the link off the request's goroutine: nothing for an address nobody has or one sent a link in the last `Passwords.ResetThrottle` (a minute), 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. Keyring's migrations create that table where it's missing, in Laravel's schema, since a Laravel Go application doesn't have it. The link is `/reset-password/{token}?email=...` from `LinkRoot` (`APP_URL` unless you set it), never the request's host, in Keyring's own email with the wording of Laravel's `ResetPassword` and the subject "Reset your password". `Notifications.AccountMail` replaces it (see [Emails a Flow Needs](https://keyringauth.com/docs/0.x/go/security-log-and-emails#emails-a-flow-needs)), and the email's `Token` lets you link to a page of your own.

`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:

```go
type ResetUserPassword struct{}

func (ResetUserPassword) Reset(ctx context.Context, user *models.User, input map[string]any) error {
	return savePassword(ctx, user, input) // as Update above
}
```

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.

A reset runs under the owner's lock, so of two resets with one link only one goes through, and it's refused once the account's address has changed since it was looked up. `Passwords.ResetLinkFor` (an hour) and `Passwords.ResetThrottle` stand in for Laravel's broker settings in `config/auth.php`. Laravel Go has no `PasswordReset` event of its own; Keyring dispatches its own `PasswordReset[U]`.

## Email Verification

With `Features.EmailVerification` on, 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 Go has no `MustVerifyEmail` a user type opts into, so `Features.EmailVerification` stands in for it. With it on, the user type needs an `EmailVerifiedAt` field (a `*time.Time`, `time.Time` or `sql.NullTime`) or an `EmailVerified` bool, and the users Keyring finds them with must be an `auth.EmailVerifier`, as `auth.ModelUsers` is. `Register` checks both. With it off, no user is held back for an address they haven't verified. A Go application sharing users with a PHP application that verifies should turn it on.

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 `VerificationLinkFor` (an 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` and the subject "Verify your email address"; `Notifications.AccountMail` replaces it. Keyring dispatches its own `Verified[U]`.

## 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 Keyring's own, each generic over the user type, as in the PHP package: `EmailChangeRequested`, `EmailChanged` and `EmailChangeReverted` (with a `keyring.EmailChange`, the PHP package's `PendingChange` without its tokens), `PasswordChanged`, `PasswordReset`, `PasswordChangeRequired`, `ProtectionBypassed`, `Registered`, `Verified` and `LinkRefused`. Laravel Go dispatches no auth events of its own. See [Events](https://keyringauth.com/docs/0.x/go/events).
