# Passkeys & Security Keys

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

## Introduction

Keyring supports WebAuthn, the standard behind passkeys and security keys, with the PHP package's two profiles. Passkeys are on by default. Turn on security keys with `webauthn.security_keys`:

```rust
use laravel_keyring::KeyringConfig;
use laravel_keyring::config::KeyProfile;

laravel::Application::configure().with_config(|config, _| {
    let keyring = config.section_mut::<KeyringConfig>();
    keyring.factors.passkeys = true;
    keyring.webauthn.security_keys = Some(KeyProfile::security_keys());
});
```

The crate checks the ceremonies with webauthn-rs-core, where the PHP package uses `web-auth/webauthn-lib`. A key's stored record is the PHP package's, so a key added on either side works on the other, apart from Ed25519 keys (see [Signature Algorithms](https://keyringauth.com/docs/0.x/rust/passkeys#signature-algorithms)).

## The Two Profiles

The profiles are the PHP package's, as its [docs](https://keyringauth.com/docs/0.x/passkeys#the-two-profiles) describe:

| | Passkeys (`factors.passkeys`) | Security keys (`webauthn.security_keys`) |
|---|---|---|
| Key | `passkey` | `security-key` |
| User verification | required | preferred, unless `require_user_verification` |
| Can start a sign in | yes, without a username | no, only as a further factor |
| Priority | 100 | 90 |

Users add either through the [authenticator routes](https://keyringauth.com/docs/0.x/rust/authenticators). Keyring excludes credentials the user already has, and refuses any credential registered to any account.

## What a Key Proves

As in the PHP package: every WebAuthn verification proves possession, and also inherence when the key reports that it verified the user. A key that verified the user is two factors, enough alone for [AAL2](https://keyringauth.com/docs/0.x/rust/policies#assurance-levels). Whether a key can sync comes from its backup-eligible flag, read on every sign in, and a key that can't is device bound. AAL3 needs a [verified attestation](https://keyringauth.com/docs/0.x/rust/passkeys#requiring-attestation) too.

With `webauthn.require_user_verification` off, a passkey on the challenge page that didn't verify the user is one factor, though signing in with one alone always asks for it.

## Relying Party and Origins

| Setting | Default | Notes |
|---|---|---|
| `webauthn.relying_party_id` (`KEYRING_WEBAUTHN_RP_ID`) | `APP_URL`'s host | The domain keys are bound to. Changing it later stops existing keys working. |
| `webauthn.origins` | `APP_URL`'s origin | The exact origins allowed to complete a ceremony. |
| `webauthn.timeout` | 60 seconds | How long the browser waits. |
| `webauthn.login_options_for` | 5 minutes | How long an answer to a usernameless challenge is accepted, never less than `timeout`. |
| `webauthn.attestation_roots` | Empty | PEM certificates a key's attestation must chain to. |

An origin that isn't a full URL, or a relying party ID that isn't each origin's host or a parent domain of it, stops the application booting, where the PHP package refuses every response. WebAuthn only works on `https` and `localhost`, so in development `APP_URL` must match the address in your browser, such as `http://localhost:8000`. Origins don't follow Keyring's `domain` setting.

## Signature Algorithms

`webauthn.algorithms` lists the signature algorithms keys may use. It's `ES256` alone by default, where the PHP package's is ES256 and EdDSA:

| Name | Algorithm | |
|---|---|---|
| `ES256` | ECDSA with P-256 and SHA-256 | Nearly every authenticator supports it. |
| `EdDSA` | Ed25519 | Never offered or accepted here. |
| `RS256` | RSASSA-PKCS1-v1_5 with SHA-256 | Off by default. See below. |

webauthn-rs-core 0.6.2, which checks the signatures, reads an Ed25519 key but can't verify with it. Checking one another way would mean redoing the whole of webauthn-rs-core's checks, which isn't a small or safe addition. So `EdDSA` in the list is never offered to a browser, an Ed25519 key is never added, and one added on the PHP side is refused here like a wrong answer. If both sides serve the same users, leave `EdDSA` out on the PHP side too. A list with no algorithm the crate can check stops the application booting.

### RS256 and Windows Hello

RS256 is off for the reasons the [PHP docs](https://keyringauth.com/docs/0.x/passkeys#rs256-and-windows-hello) give: OWASP ASVS 5.0.0 doesn't approve it, but some Windows Hello passkeys only sign with it. To offer it, add it last:

```rust
keyring.webauthn.algorithms = vec!["ES256".into(), "RS256".into()];
```

With RS256 on, Keyring refuses RSA keys under `webauthn.minimum_rsa_bits` (2048) when a key is added and at every sign in, and never accepts under 2048 bits.

## Attestation and AAGUIDs

By default, Keyring asks for `none` attestation and accepts any authenticator, including synced passkeys. Each key's AAGUID is stored, but without attestation that's only what the key claims.

### Requiring Attestation

To accept only certain hardware keys, require each new key to prove who made it, and list the makers' root certificates as PEM text. Keyring never downloads anything:

```rust
use laravel_keyring::config::KeyProfile;

keyring.webauthn.security_keys = Some(KeyProfile {
    require_attestation: true,
    ..KeyProfile::security_keys()
});
keyring.webauthn.attestation_roots = vec![include_str!("../attestation/yubico-fido-root-ca.pem").to_owned()];
```

`webauthn.require_attestation` does the same for passkeys, which would turn away nearly every synced passkey. A key is added only when its `packed` or `fido-u2f` statement chains to one of the roots, signed over something stronger than SHA-1, as in the PHP package. A root that can't be read stops the application booting.

Two differences from the PHP package's validator:

- The root is found by a name exactly equal to the last certificate's issuer. A root whose name only matches loosely never signs for a chain here, and any root by that exact name with a short key refuses the key.
- A `fido-u2f` statement signs neither the flags nor the AAGUID beside it, so one with a flag set or an AAGUID that isn't all zeros is refused. The PHP package takes the AAGUID.

See [Passkeys and Attestation](https://keyringauth.com/docs/0.x/rust/differences#passkeys-and-attestation) for the rest.

### Attestation and AAL3

As in the PHP package: a key reaches AAL3 only when its factor requires attestation and the key was added with an attestation Keyring verified, recorded in the `attestation` column, and its second factor is its own user verification or a password. To stop an existing model counting, clear its `attestation` column:

```rust
laravel::db::query!("UPDATE keyring_authenticators SET attestation = NULL WHERE aaguid = {aaguid}").update().await?;
```

### Allowing Only Certain Models

List the AAGUIDs of the models you accept in the profile's `aaguids`, or `webauthn.aaguids` for passkeys:

```rust
keyring.webauthn.security_keys = Some(KeyProfile {
    require_attestation: true,
    aaguids: Some(vec!["2fc0579f-8113-47ea-b116-bb5a8db9202a".into()]),
    ..KeyProfile::security_keys()
});
```

An AAGUID that isn't a UUID, or a list without `require_attestation`, stops the application booting. Every root in `attestation_roots` is trusted for every model. To prevent one maker certifying another's AAGUID, [trust each model separately](https://keyringauth.com/docs/0.x/rust/passkeys#trusting-each-model-separately).

### Trusting Each Model Separately

Give `webauthn.trusts` your own `TrustsAuthenticators`, as binding the PHP package's contract. It returns the roots a model's attestation may chain to, by AAGUID:

```rust
use std::sync::Arc;
use laravel_keyring::config::TrustsAuthenticators;

#[derive(Debug)]
struct ModelRoots {
    yubico: String,
}

impl TrustsAuthenticators for ModelRoots {
    fn roots(&self, aaguid: &str) -> Vec<String> {
        match aaguid {
            "2fc0579f-8113-47ea-b116-bb5a8db9202a" => vec![self.yubico.clone()],
            _ => Vec::new(),
        }
    }
}

keyring.webauthn.trusts = Some(Arc::new(ModelRoots {
    yubico: include_str!("../attestation/yubico-fido-root-ca.pem").to_owned(),
}));
```

Return PEM certificates, or the bare base64 a metadata statement lists. A model with no roots is refused, and a root that's neither PEM nor base64 DER is reported and refuses the key.

### What Is Kept

A key that passes has its `attestation` column set to `basic`, the only type the crate keeps, with the certificates it sent as the record's `trustPath`.

## Counters and Cloned Keys

As in the PHP package: a counter that didn't go up suggests a clone, so Keyring refuses that sign in, dispatches `CloneSuspected`, and can send the `clone_suspected` [security email](https://keyringauth.com/docs/0.x/rust/security-log-and-emails#security-emails), which starts off. Synced passkeys usually report zero, so this check doesn't apply to them.

## Signing In Without a Username

The routes and steps are the PHP package's: `GET /login/passkey/options`, then `POST /login/passkey` with `credential`. See [Signing In With a Passkey](https://keyringauth.com/docs/0.x/rust/sign-in-flow#signing-in-with-a-passkey). Options are used once, right or wrong, in the session and in the cache, so an answer sent again, or one to options another browser was given, is refused. So is one from another origin or from inside another page's frame, one that isn't a `public-key` credential whose `id` is its `rawId`, an empty ID, a key nobody added, or a user handle that isn't the key's.

These requests name no account, so only the per-address rate limit applies. Fetching options has its own limit of 60 a minute per address (`limits.login_options`).

The routes that take an answer (`POST /login/passkey`, `POST /login/challenge/{factor}`, `POST /confirm/{factor}` and `POST /user/authenticators/{factor}/confirm`) take a body of up to 64 KB, where laravel-rust's default is 2 MB, and answer a larger one with a `413` before reading it. A real answer is a few kilobytes, and decoding a crafted one near 2 MB would take many times its size in memory. An answer whose decoded fields come to more than 64 KB is refused as a wrong one, wherever it comes from, `sign_in::attempt()` included.

Adding a key refuses one whose authenticator data names an empty credential ID, or one longer than 512 bytes, as invalid.

## Laravel's Passkeys Client

`@laravel/passkeys`' sign-in calls work against the crate's login routes, as they do against the PHP package's, since the routes answer the same JSON. Its add-a-passkey calls don't match Keyring's enrollment routes.

### Signing In With It

Pass Keyring's login routes to the client, as the [PHP docs](https://keyringauth.com/docs/0.x/passkeys#signing-in-with-it) show. If you set a `prefix`, add it to both paths.

### Adding a Passkey and Step-Up

Use `@keyringjs/keyring`'s [`enroll`](https://keyringauth.com/docs/0.x/rust/frontend#managing-authenticators) and [`useChallenge`](https://keyringauth.com/docs/0.x/rust/frontend#the-challenge-page). Passkeys made with `laravel/passkeys` keep working once you [import them](https://keyringauth.com/docs/0.x/rust/upgrading-from-fortify#importing-two-factor-data).

## Customising a Profile

`webauthn.keys` adds more security key factors under keys of their own, as `WebAuthn::securityKeys()->as()`:

```rust
use laravel_keyring::config::{KeyFactor, KeyProfile};

keyring.webauthn.keys.push(KeyFactor::new(
    "staff-key",
    KeyProfile { require_attestation: true, ..KeyProfile::security_keys() },
));
```

They only ever come second: a second passkey factor that signs in alone (`WebAuthn::passkeys()->as()`) isn't there. A key name other than `passkey` or `security-key` also needs a line in the frontend's [factor map](https://keyringauth.com/docs/0.x/rust/frontend#the-challenge-page). There's no profile class to subclass.

## Stored Data

Each key is a row in `keyring_authenticators`, in the PHP package's form: web-auth/webauthn-lib's `CredentialRecord` JSON in `public_key`, its count in `sign_count`, its backup flags in `meta`, and the PHP package's columns for the rest, as its [docs](https://keyringauth.com/docs/0.x/passkeys#stored-data) list. Updates take a row lock. The user handle is the PHP package's keyed hash.

`PasskeyRecord`, behind the crate's `testing` feature, writes a record without an enrollment, for tests. To test passkeys without a browser, see [Virtual Authenticators](https://keyringauth.com/docs/0.x/rust/testing#virtual-authenticators).

## How It Works

Spending a challenge removes it from the session, and Keyring records in the default cache store that the answer was used, until the challenge would have expired, as the PHP package's `SpentChallenges` does. An answer arriving more than `webauthn.login_options_for` after its challenge is refused. A second factor's or step-up's challenge ends with the pending login, and a new key's with the enrollment.
