# Testing

Source: https://keyringauth.com/docs/0.x/testing

## Introduction

Keyring ships helpers in the `Keyring\Testing` namespace. They let your tests exercise your app's rules, such as who needs which factors and which routes need step-up, without real codes, signatures or waiting.

## Setting Up

Add the `InteractsWithKeyring` trait to your base `TestCase`:

```php
use Keyring\Testing\InteractsWithKeyring;

abstract class TestCase extends BaseTestCase
{
    use InteractsWithKeyring;
}
```

The trait also swaps in an instant timebox, so failed factor checks don't wait the usual 500ms. Without the trait, every failed verification waits the full `timebox`. New passwords are only checked against Have I Been Pwned in production, so your tests make no network calls. See [Passwords](https://keyringauth.com/docs/0.x/configuration#passwords).

## Acting at an Assurance Level

The trait adds methods for tests where a user is signed in:

```php
use Keyring\Enums\Assurance;

$this->actingAs($user)->withAssurance(Assurance::AAL2)->get('/billing')->assertOk();

$this->actingAs($user)->freshAt(now()->subHour())->deleteJson('/account')->assertStatus(423);
```

Here, `/billing` and `/account` stand for your routes behind `keyring:aal2` and `keyring.fresh`.

- `withAssurance` pretends the session proved enough to reach the level you pass. A password reaches AAL1. A password and a TOTP code reach AAL2. An attested security key that verified the user reaches AAL3. `Assurance::None` proves nothing.
- `freshAt` pretends those verifications happened at the time you pass, which matters for [`keyring.fresh`](https://keyringauth.com/docs/0.x/step-up#fresh-verification). Without it, they happen now.

You may chain both, in either order. The level defaults to AAL1, so `freshAt` on its own gives the user a password verification at that time.

A plain `actingAs($user)` proves nothing. Routes behind `keyring.fresh`, including Keyring's routes for managing sign-in methods, then ask for step-up: a JSON request gets a `423`, and any other request is redirected to the confirm page. A user with only a password also needs the password to add their first second factor (see [The Password for a First Second Factor](https://keyringauth.com/docs/0.x/authenticators#the-password-for-a-first-second-factor)):

```php
$this->actingAs($user)->withAssurance(Assurance::AAL1)
    ->postJson(route('keyring.authenticators.store', 'totp'), ['password' => 'password'])
    ->assertOk();
```

Use `sessionErrors()` to read the validation errors the last request flashed, as a `MessageBag`. Prefer it over `session('errors')`, which is a plain array right after a request when the session is serialized as JSON:

```php
$this->post('/login', ['email' => $user->email, 'password' => 'wrong']);

expect($this->sessionErrors()->first('email'))->toBe(__('auth.failed'));
```

## Acting With Real Authenticators

`withAssurance` only pretends, so its verifications aren't tied to any authenticator. Code that looks up the authenticator behind a verification, such as the [email change](https://keyringauth.com/docs/0.x/protected-changes#confirming) check for an established second factor, finds none. Tell the test which authenticator the session verified:

```php
use Keyring\Models\Authenticator;

$totp = Authenticator::factory()->totp()->established()->for($user, 'authenticatable')->create();

$this->actingAs($user)->verifiedWith($totp)->post('/user/email', ['email' => 'new@example.com']);
```

`verifiedWith` accepts any number of authenticators, and pretends the session verified the password and each one you pass. The level is whatever those reach, so a password and an app give AAL2. Use it in place of `withAssurance`, and chain `freshAt` with it as before. Reach for it when the user has a passkey or security key and calls a route behind `keyring.fresh`, since `withAssurance(Assurance::AAL2)` doesn't pretend to have proved a key.

An authenticator made without the factory's `established` state was added just now, so it isn't [established](https://keyringauth.com/docs/0.x/authenticators#established-authenticators). A passkey made that way doesn't make `noDowngrade()` ask for a passkey, and the account's other sign-in methods stay [frozen](https://keyringauth.com/docs/0.x/authenticators#frozen-sign-in-methods) while it's there. Use `established` for one the user has had a while:

```php
Authenticator::factory()->passkey()->established()->for($user, 'authenticatable')->create();
```

## Impersonating

[Starting an impersonation](https://keyringauth.com/docs/0.x/impersonation#starting) takes two factors proved in the last 15 minutes by default. So act at AAL2 to start one, once your callback says who may:

```php
use Keyring\Enums\Assurance;
use Keyring\Facades\Keyring;

$this->actingAs($admin)->withAssurance(Assurance::AAL2)
    ->post(route('keyring.impersonation.store', $user))
    ->assertRedirect('/dashboard');

$this->assertAuthenticatedAs($user);
expect(Keyring::impersonating())->toBeTrue()
    ->and(Keyring::impersonator()->is($admin))->toBeTrue();
```

`/dashboard` is your `impersonation.redirect_url`, or `home`. Later requests in the same test carry on as the user, and `delete(route('keyring.impersonation.destroy'))` goes back to the admin. Step-up can't be met while impersonating, so a route behind `keyring:aal2` or `keyring.fresh` answers `403` until the impersonation stops. After stopping, the admin is at AAL1 with nothing fresh, so call `withAssurance()` again before visiting such a route.

## Faking Factors

`Keyring::fake()` decides factor checks without real proofs. To pass `passkey` and `totp` and fail `email-code`:

```php
use Keyring\Facades\Keyring;

Keyring::fake()->pass('passkey', 'totp')->fail('email-code');
```

- Passed factors verify with whatever is posted, even nothing. Their validation rules are skipped.
- Failed factors always fail.
- Any factor you don't name is checked for real.
- Passing `sso` skips the provider, so no `ProviderIdentityAccepted` is dispatched, and the verification has no `providerAmr` or `providerAcr`. Use `FakeIdentityProvider` to test those.

Identifying the user still happens for real. Posting an unknown email to `/login` fails even when `password` passes. Rate limiting, devices, risk and your policy all run as normal:

```php
Keyring::fake()->pass('totp');

$this->post('/login', ['email' => $user->email, 'password' => 'password'])
    ->assertRedirect(route('keyring.login.challenge'));

$this->post(route('keyring.login.verify', 'totp'))->assertRedirect('/dashboard');
```

The fake also records every factor check made once the account is known, faked or real. A test can assert what a request asked for:

```php
$fake = Keyring::fake()->pass('totp');

// ...

$fake->assertVerified('totp');
$fake->assertFailed('password', times: 2);
$fake->assertNotChecked('recovery');
```

| Method | Asserts |
|---|---|
| `assertVerified($factor, $times = null)` | The factor was checked and verified, that many times if given. |
| `assertFailed($factor, $times = null)` | The factor was checked and failed, that many times if given. |
| `assertNotChecked($factor)` | The factor was never checked. |
| `assertNothingChecked()` | No factor was checked. |

`Keyring::fake()` throws a `LogicException` in the `production` environment, where nothing you bind by hand can fake a check. Other environments may use it, so a browser suite against `local` or `staging` works.

## Factories

`Keyring\Models\Authenticator` has a factory. Attach authenticators to a user with the `authenticatable` relationship:

```php
use Keyring\Models\Authenticator;

Authenticator::factory()->totp()->for($user, 'authenticatable')->create();
Authenticator::factory()->securityKey()->default()->for($user, 'authenticatable')->create();
```

| State | Creates |
|---|---|
| `totp($secret = null)` | An authenticator app with a random secret, or the one you give. This is the default state. |
| `recoveryCodes($codes = [...])` | A set of recovery codes that accepts the codes you give. Each must be in Keyring's form, 26 base32 characters (`a`-`z` and `2`-`7`), with or without dashes, or in Fortify's form, 20 letters and digits. Anything else throws an `InvalidArgumentException`. |
| `emailCode()` | Email codes. |
| `passkey($synced = true)` | A user-verified passkey, synced unless you pass `false`. One that isn't synced is device bound, and reaches AAL3 when it's `attested()` and its factor requires attestation. |
| `securityKey($userVerified = false)` | A security key. |
| `attested($aaguid, $type = 'basic')` | Chain it onto a key, for a key whose model was checked by attestation. |
| `sso($provider = 'fake', $subject = '248289761001', $issuer = 'https://idp.test', $email = 'taylor@example.com')` | An account at an identity provider, linked for [single sign-on](https://keyringauth.com/docs/0.x/sso). The defaults are the account a plain `FakeIdentityProvider` signs in. |
| `default()` | Marks it as the default. |
| `established()` | Makes it a month old, so it counts as [established](https://keyringauth.com/docs/0.x/authenticators#established-authenticators). |
| `unconfirmed()` | Not yet confirmed, so it doesn't count. |

The `totpCode` method, from `InteractsWithKeyring`, gives the code an authenticator app would show now. It accepts a TOTP authenticator or a secret:

```php
$totp = Authenticator::factory()->totp()->for($user, 'authenticatable')->create();

$this->post(route('keyring.login.verify', 'totp'), ['code' => $this->totpCode($totp)]);
```

Each code works once, as in real life. So enrolling an app and signing in with it within the same 30 seconds fails. Keyring keeps TOTP time on Laravel's clock. For the next code, call `$this->travel(30)->seconds()`, or pass a later step, such as `$this->totpCode($totp, step: 1)`. An authenticator's code uses the digest it was set up with. For a bare secret, that's SHA-1 unless you pass `algorithm: 'sha256'`.

The `passkey` and `securityKey` states have no real public key, so they only verify with `Keyring::fake`. For real WebAuthn responses, use a virtual authenticator.

## Virtual Authenticators

`Keyring\Testing\VirtualAuthenticator` is a software WebAuthn key. It answers the options Keyring gives the browser with real, signed responses, so the whole ceremony runs without a browser or a hardware key:

```php
use Keyring\Enums\Assurance;
use Keyring\Testing\VirtualAuthenticator;

$key = new VirtualAuthenticator;

// Register it, with the password, as the user's first second factor.
$this->actingAs($user)->withAssurance(Assurance::AAL1);
$options = $this->postJson(route('keyring.authenticators.store', 'passkey'), ['password' => 'password'])->json('enrollment.options');
$this->postJson(route('keyring.authenticators.confirm', 'passkey'), ['credential' => $key->register($options)])->assertOk();
$this->post('/logout');

// Sign in with it, without a username.
$options = $this->getJson(route('keyring.login.options', 'passkey'))->json('options');
$this->post(route('keyring.login.factor', 'passkey'), ['credential' => $key->assert($options)])
    ->assertRedirect('/dashboard');
```

On the challenge page, read the options from the page props instead. With Inertia, send the `X-Inertia` header to receive the page as JSON:

```php
$options = $this->withHeaders(['X-Inertia' => 'true'])
    ->get(route('keyring.login.challenge'))
    ->json('props.challenge.options');

$this->flushHeaders();

$this->post(route('keyring.login.verify', 'security-key'), ['credential' => $key->assert($options)]);
```

The constructor accepts these options:

| Option | Default | |
|---|---|---|
| `origin` | The first origin Keyring accepts | The origin the key claims to be on. Unless you set `webauthn.origins`, that's your `APP_URL`'s origin. |
| `userVerification` | `true` | Whether the key reports that it verified the user. Use `false` for a basic security key. |
| `aaguid` | 16 zero bytes | The AAGUID the key reports, as raw bytes. |
| `algorithm` | `ES256` | `ES256`, `EdDSA` or `RS256`. |
| `bits` | `2048` | How long an `RS256` key is. |
| `backedUp` | `null` | Whether a `synced` key reports that it has been backed up. `null` means it has. |
| `synced` | `false` | Whether the key reports that it is a passkey that syncs between devices. |
| `counts` | `true` | Whether the key counts its signatures. Pass `false` for a synced passkey, whose counter stays at zero. Then only the challenge tells an answer from the same answer sent again. |

`VirtualAuthenticator::eddsa()` makes a key that signs with Ed25519 instead of P-256. It needs PHP's `sodium` extension, as Keyring's Ed25519 support does. `VirtualAuthenticator::rsa()` makes an RS256 key. Keyring only accepts that algorithm once [`webauthn.algorithms`](https://keyringauth.com/docs/0.x/passkeys#signature-algorithms) lists it. `rsa(1024)` makes a key too short to be accepted.

Call `$key->assert($options, $origin)` to answer from another origin, to test that Keyring rejects it. `$key->rewindCounter()` makes the next response reuse an old counter, as a cloned key would.

### Keys That Attest

A factor that [requires attestation](https://keyringauth.com/docs/0.x/passkeys#requiring-attestation) refuses a plain virtual authenticator. `Keyring\Testing\VirtualManufacturer` makes keys with a throwaway root certificate. Trust its root, and its keys attest the way hardware does:

```php
use Keyring\Testing\VirtualManufacturer;

$maker = new VirtualManufacturer;
config(['keyring.webauthn.attestation_roots' => [$maker->root]]);

$key = $maker->key('2fc0579f-8113-47ea-b116-bb5a8db9202a');

$options = $this->postJson(route('keyring.authenticators.store', 'security-key'), ['password' => 'password'])->json('enrollment.options');
$this->postJson(route('keyring.authenticators.confirm', 'security-key'), ['credential' => $key->register($options)])->assertOk();
```

`key()` takes the model's AAGUID, the format (`packed` by default, or `fido-u2f`, which has no AAGUID), and whether the key verifies the user. `new VirtualManufacturer(intermediate: true)` signs the keys' certificates with an intermediate certificate instead of the root. The `days:` argument sets how long the certificates last.

To check that your app turns keys away, use a key from a second `VirtualManufacturer` that you don't trust, or `(new VirtualAuthenticator)->selfAttested()`, which attests with its own key pair.

## Identity Providers

`Keyring\Testing\FakeIdentityProvider` stands in for Google, Microsoft, GitHub or any OpenID Connect provider, through `Http::fake()`, with really signed ID tokens. `register()` adds it to `sso.providers`, `signIn()` says who signs in, and `approve()` turns the URL Keyring sent the browser to into the callback the provider would send:

```php
use Keyring\Models\Authenticator;
use Keyring\Sso\Providers\GoogleProvider;
use Keyring\Testing\FakeIdentityProvider;

$google = FakeIdentityProvider::google()->register('google');
Authenticator::factory()->sso('google', subject: '42', issuer: GoogleProvider::ISSUER)->for($user, 'authenticatable')->create();

$url = $this->get(route('keyring.sso.redirect', 'google'))->headers->get('Location');

$this->get($google->signIn(['sub' => '42'])->approve($url))->assertRedirect('/dashboard');
```

Keyring only registers the `/auth` routes when `sso.providers` lists a provider as the app boots. So keep the provider in `config/keyring.php` too, since `register()` only changes the config afterwards.

The fake's ID tokens carry `auth_time`, except the fake Google's (only when the request asks) and the fake Microsoft's (only after `withAuthTimeClaim()`). See [Testing](https://keyringauth.com/docs/0.x/sso#testing) in Single Sign-On for `signedInAt()` and freshness.

## The Conformance Suite

The `Keyring\Testing\KeyringConformance` trait provides tests that check your setup still keeps Keyring's guarantees. They cover your policy, factors, swapped responses and pipeline changes. A check for a feature you've turned off is skipped, with the reason. A skip isn't a pass, so it means your setup doesn't use that feature. To start, add the trait to a test class and tell it how to make a user:

```php
namespace Tests\Feature;

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Notification;
use Keyring\Testing\KeyringConformance;
use Tests\TestCase;

class KeyringConformanceTest extends TestCase
{
    use KeyringConformance, RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();

        Notification::fake();
    }

    protected function keyringUser(): User
    {
        return User::factory()->create(['password' => 'password', 'email_verified_at' => now()]);
    }
}
```

`keyringUser()` must return a user whose password is `password`. To use another password, override `keyringPassword()`. The user's email must be verified, and the user must have no extra factors. Faking notifications stops the email code factor sending real mail when the suite enrolls it.

The suite checks that:

- a correct password signs the user in or leads to the challenge page;
- a wrong password and an unknown account get the same error;
- registering with a taken address is answered the same as a free one, and signs nobody in (skipped with `registration.reveal_taken`);
- protected attributes can't change outside Keyring's flows;
- changing sign-in methods needs a fresh verification;
- every enrollable factor can begin enrolling, except single sign-on, which needs a provider to send the user to;
- signing out revokes the registered session;
- the registry's `revoke()`, `revokeDevice()` and `revokeAll()` return exactly the records they revoked, and nothing else.;
- signing out announces the ended session once, with a [`RegisteredSessionEnded`](https://keyringauth.com/docs/0.x/devices-and-sessions#hearing-about-ended-sessions).;
- the `database` driver's table has the columns that record which ended sessions were announced, so [`keyring:sweep`](https://keyringauth.com/docs/0.x/devices-and-sessions#sweeping-ended-sessions) can run (skipped on other drivers);
- the registry keeps the `origin` a session started on when the session moves, so its [handle](https://keyringauth.com/docs/0.x/devices-and-sessions#listing-and-ending-sessions) holds;
- every route that uses the `auth` middleware for Keyring's guard also runs [`keyring.session`](https://keyringauth.com/docs/0.x/devices-and-sessions#the-session-middleware);
- passwords of 64 characters are allowed: `passwords.max` is at least 64, and the hasher isn't bcrypt, which stops at 72 bytes;
- the password broker has a `throttle`, so one account can't be sent [a reset link](https://keyringauth.com/docs/0.x/protected-changes#resetting-the-password) as often as anyone asks (skipped without `Features::resetPasswords()`);
- one password hash takes less time than [`timebox`](https://keyringauth.com/docs/0.x/configuration#pending-logins-timebox-and-rate-limits), so a refusal that hashes doesn't take longer than one that doesn't;
- no mandatory pipeline step was removed, or replaced with `dangerouslyRemove` or `dangerouslyReplace`.

The timing check times a hash on the test machine, so it's a guide to your servers, not a measurement of them. Bcrypt is timed at 12 rounds, or at your own setting if that's higher. If production hashes with different options, return those from `keyringProductionHashOptions()`.

If you remove a [mandatory step](https://keyringauth.com/docs/0.x/sign-in-flow#mandatory-steps) on purpose, or your tests need a setting production doesn't, override these methods in your test class:

| Method | Returns |
|---|---|
| `keyringPassword()` | The password `keyringUser()` gives its user, if not `password`. |
| `keyringProductionHashOptions()` | The hash options production uses, if they differ from your tests'. |
| `keyringAcknowledgedDangerousSteps()` | The classes of the [mandatory steps](https://keyringauth.com/docs/0.x/sign-in-flow#mandatory-steps) you removed on purpose. |
| `keyringRegistration(string $email)` | A form your `CreatesNewUsers` action accepts, if it validates more than `name`, `email`, `password` and `password_confirmation`. |
| `keyringAcknowledgedUncheckedRoutes()` | The URIs of routes you leave out of the route check on purpose. |
| `keyringAcknowledgesBcryptLimit()` | `true` to keep bcrypt and its 72-byte limit. |

The route check reads your routes as they're registered. It looks for `auth:{guard}` by name, plain `auth` when Keyring's guard is the default, and `auth:sanctum` on routes with Sanctum's `statefulApi()`. It lists the URIs missing the middleware, so add `keyring.session` to their group.

A new Laravel app hashes with bcrypt, so the password length check fails until you set `HASH_DRIVER=argon2id` (see [Passwords](https://keyringauth.com/docs/0.x/configuration#passwords)). If your tests run on bcrypt for speed but production doesn't, keep bcrypt for the test class with `keyringAcknowledgesBcryptLimit()`.

The `KeyringConformance` trait includes `InteractsWithKeyring`, and its tests are ordinary `test_*` methods.
