# Impersonation

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

## Introduction

Impersonation lets support staff or an administrator sign in as another user, see the app as they do, then go back to their own account, as in the PHP package:

- Nobody may impersonate anyone until you say who may.
- The impersonated session starts with nothing the impersonator proved. It ends after an hour, or sooner if the user ends it.
- While it lasts, Keyring refuses every change to how the user signs in.

## Turning It On

Turn on `features.impersonation`, and give the provider `allow_impersonation_when()`:

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

laravel::Application::configure()
    .with_providers(|providers| {
        providers.add(
            KeyringServiceProvider::<Users>::new()
                .allow_impersonation_when(|impersonator: &User, user: &User| impersonator.is_admin && !user.is_admin),
        );
    })
    .with_config(|config, _| {
        config.section_mut::<KeyringConfig>().features.impersonation = true;
    });
```

The migration that adds the impersonation columns always runs with the provider's others, so there's no `MissingMigration`.

Starting needs AAL2 and two factors proved in the last 15 minutes, as the PHP package's default `impersonation.middleware`. laravel-rust has no middleware names for a setting to list, so it's two settings instead: `impersonation.requires_aal2` (what `RequireAssurance::aal2()` asks) and `impersonation.fresh_for`. For an application that only signs in with a password:

```rust
let impersonation = &mut config.section_mut::<KeyringConfig>().impersonation;
impersonation.requires_aal2 = false;
impersonation.fresh_for = Some(std::time::Duration::from_secs(15 * 60)); // or None for nothing more
```

The confirm for AAL2 asks for both factors afresh, where the PHP package's builds on what still counts toward it.

> [!WARNING]
> Every server must share the default cache store. An impersonation's end is claimed there, so servers with separate caches can each log it.

## Who May Impersonate Whom

Until you give the provider `allow_impersonation_when()`, nobody may (`no_callback`, with a warning in the application's log). It's given the impersonator and then the user, as the PHP closure is. Whatever it says, Keyring refuses yourself, a user who may not sign in, an ID nobody has, a second impersonation, and a session with no record.

The closure runs on every request of a running impersonation, so decide from its two arguments alone. When it needs to look something up, implement `laravel_keyring::AuthorizesImpersonation` instead: an error then counts as a no while it runs, and is a server error before it starts.

`laravel_keyring::impersonation::allows(&impersonator, &user)` says whether to show a button, and `impersonation::refusal(&impersonator, &user)` says why not, an `ImpersonationRefusal` (`Myself` is the PHP package's `Self`, a name Rust keeps for itself), or `None` when they may.

An admin without a second factor can still impersonate someone if your closure lets them, since `RequireEnrollment` doesn't stand in front of Keyring's `POST /impersonate/{user}`. If you require a second factor of admins, check it in `allow_impersonation_when()`.

## Routes

| Method | URI | Does |
|---|---|---|
| `POST` | `/impersonate/{user}` | Signs in as the user with that ID. |
| `POST`, `DELETE` | `/impersonate` | Stops, and goes back. |

They're there while `features.impersonation` is on, in the `web` group with its CSRF check, and take the session lock.

### Starting

The browser package's `impersonate(user.id)` works with the crate unchanged. One who hasn't proved what `requires_aal2` and `fresh_for` ask is sent to confirm, with a `423` for JSON. One with no second factor gets `enroll-first`. A refusal is a `403` `impersonation-refused`, the same for every reason. Success goes to `impersonation.redirect_url`, `home` when `None`. Keyring's start and stop send `Clear-Site-Data`, and an Inertia visit loads the next page in full.

### Stopping

A successful stop answers `impersonation-ended` and goes to `impersonation.return_url`, `home` when `None`. A second stop is a `409` with `not-impersonating`, as in the PHP package.

## From Your Own Code

Routes of your own start and stop one with `impersonation::impersonate()` and `stop_impersonating()`, as `Keyring::impersonate()` and `stopImpersonating()`:

```rust
use laravel::auth::Auth;
use laravel::http::{IntoResponse, Redirect, Request, Response};
use laravel::session::Session;
use laravel_keyring::impersonation::{self, ImpersonationStart};

async fn start(auth: Auth<User>, session: Session, request: Request) -> laravel::Result<Response> {
    let user = find_user(&request).await?;

    // Fails with ImpersonationRefused, a 403, whose reason() says why.
    match impersonation::impersonate(&auth, &session, &request, &user).await? {
        ImpersonationStart::Started => Ok(Redirect::to("/dashboard").into_response()),
        // The step-up first: the confirm page, or enroll-first.
        ImpersonationStart::StepUp(answer) => Ok(answer),
    }
}

async fn stop(auth: Auth<User>, session: Session, request: Request) -> laravel::Result<Redirect> {
    if !impersonation::active(&session) {
        return Ok(Redirect::to("/admin/users")); // back already: a second stop, from a stale tab say
    }

    // None when it signed out instead.
    let impersonator = impersonation::stop_impersonating(&auth, &session, &request).await?;

    Ok(Redirect::to(if impersonator.is_none() { "/login" } else { "/admin/users" }))
}
```

`find_user()` is yours. Put the start on a `POST` in the `web` group, behind `RefuseWhileImpersonating`, as Keyring's route refuses a second impersonation. laravel-rust has no `->block()`, so list the start route in `sessions.block`, so two starts sent at once take turns:

```rust
use laravel::http::Method;

config.section_mut::<KeyringConfig>().sessions.block.push((Method::POST, "/admin/users/{user}/impersonate".to_owned()));
```

`impersonate()` asks what Keyring's route asks first, and returns `ImpersonationStart::StepUp` with the answer to send (the `423` naming the confirm page, or `enroll-first`) without starting anything, where the PHP package leaves that to the route's middleware. Send `Clear-Site-Data: "cache", "storage"` yourself, as Keyring's routes do.

## What Happens to the Sessions

As in the PHP package: starting gives the browser a new session ID and a record for the user that names the impersonator and their parked record, at no level, never remembered, on no device, with no address or browser, lasting `impersonation.lifetime` at most. The impersonator's session is parked, not ended, and kept from idling out while they're busy. `Authenticated` doesn't fire for the user.

Someone's name, for the banner and the sessions list, is their `mail_address()`'s display name, or the address itself without one, standing in for the PHP package's `name` attribute and username.

> [!WARNING]
> Your app's other session data carries over both ways, as in the PHP package. Keyring only forgets its own keys, `auth.password_confirmed_at` and the intended URL as the browser changes hands. Look up roles and "is admin" flags from the signed-in user rather than keeping them in the session.

### Going Back

Going back, on a stop, when `lifetime` runs out, or when the user ends the session, takes the impersonator's record still being good, the impersonator still allowed to sign in, not held for a new password, on the password they had when it started, and under `sessions.end_on_lapse` a level that hasn't lapsed. They come back on a new session ID and record, at AAL1 at most with nothing counting as fresh. Otherwise the browser is signed out. The rules are the [PHP package's](https://keyringauth.com/docs/0.x/impersonation#going-back).

A user's password changing while they're impersonated sends the admin back, but laravel-rust's guard takes back the browser's `remember_web` cookie as it lets the user go: the admin keeps `remembered_session`, and loses the cookie that would sign them in once their session runs out.

### Signing Out While Impersonating

Keyring's `POST /logout` signs the browser out of both sessions, and leaves every remember token as it is. Keyring empties the session and takes back laravel-rust's remember cookie itself, since `Auth::logout` would change the impersonated user's token for something the impersonator did. In your own code, use `Sessions::sign_out()`, which does the same while impersonating, rather than `auth.logout()`.

## What's Refused While Impersonating

As in the PHP package, these get the `403` `{"status": "impersonating", "message": "..."}`: the confirm routes, every changes route (whatever `changes_fresh_for` says), `/confirm/sso/redirect` and an identity provider's callback for a link or a confirm, posting a verification link and sending another, cancelling or requesting an email change, and starting another impersonation. A fresh verification or AAL2 asked anywhere else, your own `RequireFreshVerification` and `RequireAssurance` included, answers the same rather than sending the browser to confirm, and so does `StepUp::unless_met()`. `RequireEnrollment` and a password hold let the impersonator through.

Every start, Keyring's route's too, also refuses, as `impersonating`, a start from a session record an impersonation that hasn't ended already parked: a copy of the session from before a start. The PHP package doesn't check this. That impersonation ends as it's refused.

### Your Own Routes

Put `laravel_keyring::http::RefuseWhileImpersonating` on routes only the user should use, as `keyring.not-impersonating`:

```rust
use laravel_keyring::http::{RefuseWhileImpersonating, RequireFreshVerification};

route
    .middleware(RefuseWhileImpersonating)
    .middleware(RequireFreshVerification::<Users>::new())
    .group(|route| {
        route.delete("/account", delete_account);
    });
```

## Showing a Banner

`impersonation::banner(&session)` is what a banner needs, as `Keyring::impersonation()`: `None` when nobody is impersonating, otherwise `impersonator` (`id` and `name`), `startedAt`, `expiresAt` and `stopUrl`, serializing as the PHP package's. It's read from the session, so it costs no query. Share it with your pages in your Inertia middleware's `share()`:

```rust
let session = request.session()?.clone();

Ok(props! {
    impersonation => laravel_keyring::impersonation::banner(&session),
})
```

The browser package's `Impersonation` type describes it. `impersonation::active(&session)` says whether a session is impersonating, and `impersonation::impersonator::<User>(&session)` loads who is, as `Keyring::impersonator()`.

## The Time Limit

`impersonation.lifetime`, an hour by default, can't be zero. `sessions.absolute` caps it. It ends by itself `lifetime` after it started, and the next request goes back, as in the PHP package.

## The Sessions List

The impersonated session shows in the user's sessions list with `"impersonated": true` and `"impersonator": { "name" }`, with no name, address or device of its own, as in the PHP package. `impersonation.show_in_sessions` off leaves it out unless it's the one asking.

## Security Log and Events

As in the PHP package: the start and end are logged on both accounts as `impersonation_started` and `impersonation_ended`, with `impersonator`, `user` and `role`, and the end's `reason` and `returned`. A refused start is logged as `impersonation_refused` on the impersonator's account. The end reasons are `stopped`, `expired`, `revoked`, `impersonator_session_ended`, `lost` and `signed_out`. `ImpersonationStarted` and `ImpersonationEnded` are in `laravel_keyring::events`. `impersonation.show_in_activity` off leaves both types out of `security_log::activity()`.

## How It Works

As in the [PHP docs](https://keyringauth.com/docs/0.x/impersonation#how-it-works), with these differences:

- **One ending.** Only one request ends an impersonation, by a claim on its handle in the default cache store, where the PHP package uses `cache.limiter`'s.
- **Session IDs.** Overlapping requests aren't covered, as [`sessions.overlapping_requests`](https://keyringauth.com/docs/0.x/rust/devices-and-sessions#requests-that-overlap-a-sign-in) isn't there. The check against a parked record stands in for it.
- **Failed starts.** A start whose session can't be saved has its record ended (`EndUnsavedSignIns`) rather than left for the sweep.

## Migrating From Another Package

The PHP packages this section covers have no Rust counterparts. Their concepts map as the [PHP docs](https://keyringauth.com/docs/0.x/impersonation#migrating-from-another-package) show, with `allow_impersonation_when()`, `impersonation::impersonate()`, `stop_impersonating()`, `impersonation::active()` and `RefuseWhileImpersonating` in place of the facade methods and middleware.
