Testing
On this page
Introduction
The crate's test helpers, in laravel_keyring::testing, are the PHP package's Keyring\Testing, shaped for laravel-rust's own test tooling: #[laravel::test], its TestRequest and TestResponse, and its HTTP client's fake. They let your tests exercise your application's rules, such as who needs which factors and which routes need step-up, without real codes, signatures or waiting.
Setting Up
Add the crate's testing feature to your dev-dependencies only:
[dev-dependencies]laravel-keyring = { git = "https://github.com/keyringauth/keyring", rev = "<commit>", features = ["testing"] }Refused checks take at least timebox (500 ms). testing::instant_timebox(&app) has them answer at once, where the PHP package's InteractsWithKeyring does it by itself:
use laravel::Application;use laravel_keyring::testing; fn app() -> Application { let app = my_app::configure(Application::configure().for_testing(env!("CARGO_MANIFEST_DIR"))) .refresh_database() .create(); testing::instant_timebox(&app); app}laravel-rust's test client doesn't carry cookies or the session between a test's requests, so a test that signs in through Keyring's routes and then makes another request carries the session cookie itself. The helpers below act as a signed-in user on one request instead.
Acting at an Assurance Level
InteractsWithKeyring adds with_assurance, verified_with and with_proofs to each TestRequest, after acting_as:
use laravel::testing::prelude::*;use laravel_keyring::Assurance;use laravel_keyring::testing::InteractsWithKeyring; #[laravel::test(app = app)]async fn billing_needs_aal2(app: Application) -> laravel::Result<()> { let user = create_user().await?; app.get("/billing").acting_as(&user).with_assurance(Assurance::Aal2).await.assert_ok(); // A plain acting_as proves nothing, so a JSON request is asked to step up. app.get("/billing") .acting_as(&user) .header("accept", "application/json") .await .assert_status(423); Ok(())}A plain acting_as(&user) proves nothing, so routes behind RequireFreshVerification, including Keyring's own routes for managing sign-in methods, ask for step-up. Each helper sets the session's proofs afresh, so to set a level or authenticators with a time, use with_proofs():
use laravel_keyring::testing::Proofs; let an_hour_ago = laravel::time::Timestamp::from_second(laravel::now().timestamp().as_second() - 60 * 60).unwrap(); app.get("/settings/security") .acting_as(&user) .with_proofs(Proofs::level(Assurance::Aal2).fresh_at(an_hour_ago)) .await .assert_redirect_contains("/confirm");That's the PHP package's freshAt().
Acting With Real Authenticators
verified_with(&[&authenticator]) pretends the session verified the password and those authenticators, just now, with what each really proves:
use laravel_keyring::testing::{AuthenticatorFactory, InteractsWithKeyring}; let passkey = AuthenticatorFactory::passkey(false).established().create_for(user.id).await?; app.get("/admin") .acting_as(&user) .verified_with(&[&passkey]) .await .assert_ok();Impersonating
There's no helper to act as an impersonated session. Start one through POST /impersonate/{user} with a session that has proved what impersonation.requires_aal2 and fresh_for ask, and carry the session cookie to the next request.
Faking Factors
testing::fake(&app) decides factor checks, as Keyring::fake(), and returns a KeyringFake that asserts which were made:
use laravel_keyring::testing; #[laravel::test(app = app)]async fn signs_in_with_any_totp_code(app: Application) -> laravel::Result<()> { let fake = testing::fake(&app); fake.pass(["password", "totp"]); // ...sign in, answer the challenge with any code... fake.assert_verified("totp"); fake.assert_verified_times("password", 1); fake.assert_not_checked("recovery"); Ok(())}pass() and fail() take factor keys. A factor you don't name is checked for real. assert_verified(), assert_failed(), assert_not_checked() and assert_nothing_checked() check what happened, and the assertions with a count are the _times methods. testing::fake() replaces an earlier fake rather than returning it, and refuses to run in production, as the PHP package's does.
Factories
AuthenticatorFactory adds authenticator rows for a user, as the PHP package's factory states do. Each is a builder ending in create_for(user_id):
use laravel_keyring::testing::{AuthenticatorFactory, RECOVERY_CODES, totp_code}; let totp = AuthenticatorFactory::totp().named("Work phone").default().create_for(user.id).await?;let codes = AuthenticatorFactory::recovery_codes().create_for(user.id).await?; // RECOVERY_CODESlet key = AuthenticatorFactory::security_key(true).established().create_for(user.id).await?;let google = AuthenticatorFactory::sso("google", "google-42", "https://accounts.google.com", None).create_for(user.id).await?; let code = totp_code(&totp, 0); // the code the app would show nowThere are totp(), totp_with_secret(), recovery_codes(), recovery_codes_with(), email_code(), passkey(synced), security_key(user_verified), sso() and sso_default(), with algorithm(), attested(), named(), default(), established() and unconfirmed(). create_for() returns a TestAuthenticator, with the row's id and secret. totp_code(&authenticator, step) gives an authenticator app's code, step moving the time on by 30 seconds a step, as each code works once. SessionErrors::of(&response) reads the validation errors a response flashed.
Virtual Authenticators
VirtualAuthenticator answers Keyring's WebAuthn options with real signed responses, as the PHP package's does:
use laravel_keyring::testing::VirtualAuthenticator; let mut key = VirtualAuthenticator::new(); // From the options POST /user/authenticators/passkey answered with:let credential = key.register(&options);// From the options GET /login/passkey/options answered with:let answer = key.assert(&options);origin(), user_verification(), aaguid(), synced(), backed_up() and counts() change what it says, rsa(bits) makes an RS256 key, and rewind_counter() makes it look cloned. VirtualAuthenticator::eddsa() makes Ed25519 keys, which the crate refuses, for testing that refusal.
Keys That Attest
VirtualManufacturer makes keys that attest, with a root certificate to trust:
use laravel_keyring::testing::{AttestationFormat, VirtualAuthenticator, VirtualManufacturer}; let maker = VirtualManufacturer::new();// Trust maker.root (PEM) in webauthn.attestation_roots.let mut key = VirtualAuthenticator::new().attested_by(&maker, AttestationFormat::Packed);VirtualManufacturer::with(intermediate, days) signs through an intermediate certificate, or for a number of days. AttestationFormat::FidoU2f is the older format.
Identity Providers
FakeIdentityProvider stands in for a provider, with really signed ID tokens. See Single Sign-On.
The Conformance Suite
KeyringConformance checks that your setup keeps Keyring's guarantees, as the PHP package's trait does. It's a builder that returns a report rather than a trait of test methods:
use laravel_keyring::testing::{self, KeyringConformance}; #[laravel::test(app = app)]async fn keeps_keyrings_guarantees(app: Application) -> laravel::Result<()> { testing::instant_timebox(&app); KeyringConformance::<Users>::new( || async { create_user_with_password("correct horse battery staple").await }, |user: &User| user.email.clone(), ) .password("correct horse battery staple") .run(&app) .await .assert_passed(); Ok(())}The first closure makes a new user for each check, and the second gives the username they sign in with. registration(form) gives a registration form for a new address, and production_hash_rounds() says how many bcrypt rounds production uses, for the timing check. run() runs every check, each a testing::Check, and check(&app, check) runs one. The report's failures() and skipped() say what didn't pass, and assert_passed() fails the test with them.
A check that doesn't apply, such as one for a feature that's off, is skipped. acknowledge_dangerous_steps(&[...]) acknowledges a pipeline step you dangerously replaced or removed, as keyringAcknowledgedDangerousSteps(), and acknowledge_unchecked_routes(&[...]) a route that uses the session without AuthenticateSession. It doesn't check that a registry returns what it revokes, or bcrypt's half of the 64-character password check, as laravel-rust only hashes with bcrypt.