Building Your ApplicationTesting

Testing

On this page

Introduction

Keyring for Go's test helpers, in the keyringtest package, are the PHP package's Keyring\Testing, shaped for Laravel Go's own test tooling: laraveltest's client, its RefreshDatabase, and its fakes for events and the HTTP client. 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.

None of it works in production: keyringtest.New fails the test where APP_ENV is production, and Keyring never asks a fake installed in an application that runs there.

Setting Up

Test with laraveltest, on your application's options, with RefreshDatabase so Keyring's tables are migrated:

Go
import (    "testing"     "go.laravel.com/laraveltest"     "app/bootstrap") func TestBillingNeedsASecondFactor(t *testing.T) {    client := laraveltest.New(t, bootstrap.Options(), laraveltest.RefreshDatabase)     // ...}

Refused checks take at least Config.Timebox (500 ms). keyringtest.New gives you the helpers for the application the client tests, and has its refusals answer at once from then on, as the PHP package's InteractsWithKeyring swaps in its InstantTimebox:

Go
import "keyringauth.com/go/keyringtest" client := laraveltest.New(t, bootstrap.Options(), laraveltest.RefreshDatabase)kt := keyringtest.New[models.User](t, client)

That's every route that checks a sign in: the password, passkeys, single sign-on, first factors of your own, Keyring.AttemptSSO, challenges and confirms, registration and password resets. Timebox itself stays as it is, so the conformance suite's timing check still reads it. In production it's never instant, whoever asked.

The helpers stack: a subtest that calls keyringtest.New or kt.Fake() for the same application leaves its parent's instant timebox and fake in place, and when the subtest ends the parent's fake decides again.

laraveltest's client keeps cookies between a test's requests once it's a browser (client.NewBrowser()), so a test can sign in through Keyring's routes and carry on as that user. client.ActingAs(&user) signs a request in without Keyring, so its session has proved nothing: routes behind RequireFreshVerification, including Keyring's own routes for managing sign-in methods, and behind RequireAssurance ask for step-up.

Go
client.ActingAs(&user).    WithHeader("Accept", "application/json").    Get("/billing").    AssertStatus(423)

Acting at an Assurance Level

kt.ActingAs(&user, proofs) is client.ActingAs(&user) with a session that proved what proofs says, as the PHP package's withAssurance(). keyringtest.Assurance(level) is enough to reach the level: a password for AAL1, a password and an authenticator app's code for AAL2, and an attested security key that verified the user for AAL3. Level 0 proves nothing, and the zero keyringtest.Proofs{} is a password, just now.

Go
kt.ActingAs(&user, keyringtest.Assurance(keyring.AAL2)).    WithHeader("Accept", "application/json").    GetJSON("/billing").    AssertOK()

FreshAt(at) has it proved at that time, as the PHP package's freshAt():

Go
anHourAgo := client.Now().Add(-time.Hour) kt.ActingAs(&user, keyringtest.Assurance(keyring.AAL2).FreshAt(anHourAgo)).    WithHeader("Accept", "application/json").    DeleteJSON("/account").    AssertStatus(423)

The session is a new one, written as laraveltest's WithSession writes it, so every client laraveltest.New made shares it. For a browser of its own, kt.WithProofs(client.NewBrowser(), proofs) starts one there, and kt.Session(proofs) gives the session values for WithSession.

Acting With Real Authenticators

keyringtest.VerifiedWith(authenticators...) is the password and each of those authenticators, as the PHP package's verifiedWith(), with what each really proves, so a password and an authenticator app give AAL2, and an established passkey that can't leave its device is device bound:

Go
passkey := kt.Add(&user, keyringtest.Passkey(false).Established()) kt.ActingAs(&user, keyringtest.VerifiedWith(passkey)).Get("/admin").AssertOK()

It takes FreshAt(at) too. An authenticator that isn't confirmed proves nothing, and fails the test.

Impersonating

There's no helper to act as an impersonated session. Starting an impersonation takes two factors proved in the last 15 minutes by default, and the impersonation carries on in the browser that started it, so sign the admin in through Keyring's routes in a browser of its own, with an authenticator app kt.Add gave them, and start through Keyring's route:

Go
app := kt.Add(&admin, keyringtest.TOTP()) browser := client.NewBrowser().WithHeader("Accept", "application/json")browser.PostJSON("/login", map[string]any{"email": admin.Email, "password": "password"}).AssertStatus(202)browser.PostJSON("/login/challenge/totp", map[string]any{"code": kt.TOTPCode(app, 0)}).AssertOK() browser.PostJSON("/impersonate/"+strconv.FormatInt(user.ID, 10), map[string]any{}).    AssertOK().    AssertJSONPath("status", "impersonation-started")

admin and user are users your test created, with your own AllowImpersonationWhen letting one impersonate the other. Later requests from the same browser carry on as the user, and browser.DeleteJSON("/impersonate") goes back to the admin. kt.ActingAs(&admin, keyringtest.Assurance(keyring.AAL2)) can start one too, but every request it makes runs as the admin, so it can't carry on as the user: once it's started, the session's record is the user's, so Keyring signs the next ActingAs(&admin) request out with a 401 (signed-out). Step-up can't be met while impersonating, so a route behind RequireAssurance or RequireFreshVerification answers 403 until the impersonation stops. After stopping, the admin is at AAL1 with nothing fresh.

Faking Factors

kt.Fake() decides factor checks, as Keyring::fake(), and returns a *keyringtest.Fake that asserts which were made, reporting to the test New was given:

Go
func TestSignsInWithAnyTOTPCode(t *testing.T) {    client := laraveltest.New(t, bootstrap.Options(), laraveltest.RefreshDatabase)    kt := keyringtest.New[models.User](t, client)    fake := kt.Fake().Pass("password", "totp")     // ...sign in, answer the challenge with any code...     fake.AssertVerified("totp").        AssertVerifiedTimes("password", 1).        AssertNotChecked("recovery")}

Pass and Fail take factor keys, those of first factors you added with Keyring.AddPrimaryFactor too. A factor you don't name is checked for real. A factor it passes needs nothing posted, as its rules (and a first factor's Validate) are skipped, and its authenticator is marked as used, as a real check marks it. Identifying the user still happens for real: an address nobody has fails even when password passes, a passkey sign in needs an answer naming one of the user's passkeys, and an identity provider's sign in needs the account it vouches for linked. Passing sso skips the provider's part, so ProviderIdentityAccepted isn't dispatched at sign in. A factor checked inside a request that does something else, such as the password that adds a first second factor, is checked for real and not noted, as in the PHP package.

AssertVerified, AssertFailed, AssertNotChecked and AssertNothingChecked check what happened, the assertions with a count are the Times methods, and Checks() lists every check in order. Calling kt.Fake() again starts a new fake, with nothing decided or noted, that decides in place of the earlier one until its test ends.

Factories

kt.Add(&user, authenticators) adds an authenticator row for a user, as the PHP package's factory states do, and returns a keyringtest.Authenticator with the row's ID, and an app's Secret or a set's Codes:

Go
app := kt.Add(&user, keyringtest.TOTP().Named("Work phone").Default())codes := kt.Add(&user, keyringtest.RecoveryCodes()) // codes.Codeskey := kt.Add(&user, keyringtest.Passkey(false).Established())google := kt.Add(&user, keyringtest.SSO("google", "google-42", "https://accounts.google.com", "")) code := kt.TOTPCode(app, 0) // the code the app would show now

There are TOTP(), TOTPWithSecret(), RecoveryCodes(), EmailCode(), Passkey(synced), SSO() and SSODefault(), with Algorithm(), Named(), Default(), Established() and Unconfirmed(). A set of recovery codes is a new set Keyring made, so it has no fixed codes as the PHP factory's: use the ones it returns. A passkey made here has no real public key, so it only verifies through kt.Fake(): for real answers, add a virtual authenticator. kt.Authenticator(id) finds a row however it was added.

kt.TOTPCode(app, step) gives an authenticator app's code on the application's clock, with the digest it was set up with, step moving the time on by 30 seconds a step, as each code works once. keyringtest.TOTPCodeFor(secret, algorithm, now, step) gives one for a secret. keyringtest.ErrorsOf(response) reads the validation errors a response gave, from a 422's JSON or flashed on a browser's redirect, as the PHP package's sessionErrors().

Virtual Authenticators

keyringtest.VirtualAuthenticator answers Keyring's WebAuthn options with real signed responses, as the PHP package's does:

Go
key := keyringtest.NewVirtualAuthenticator() // From the options POST /user/authenticators/passkey answered with:credential := key.Register(t, options)// From the options GET /login/passkey/options answered with:answer := key.Assert(t, options)

key.AddTo(kt, &user) adds it for a user without the ceremony. Its fields change what it says:

Field Default What It Does
Origin The application's first WebAuthn origin once AddTo adds it (APP_URL's, unless WebAuthn.Origins lists others), as the PHP package's, and http://localhost before then Where its answers say they come from.
UserVerification true Whether it says it verified the user.
Synced, NotBackedUp false A passkey that syncs between devices: backup eligible, and backed up unless NotBackedUp.
Counts true Whether it counts its signatures. Synced passkeys mostly don't.
CorruptSignature false Signs its next answers wrongly, so a real check refuses them, for a test where kt.Fake() decides the passkey.
Transports ["usb"] The ways it says a browser can reach it, as it registers and as AddTo stores them.

CredentialID() is its credential ID, base64url as Keyring keeps it in credential_id, and PublicKey() its public key as COSE, as it registers it. RewindCounter() makes it look cloned. NewEdDSAVirtualAuthenticator() makes Ed25519 keys and NewRSAVirtualAuthenticator(bits) RS256 ones, which Keyring takes only where WebAuthn.Algorithms lists RS256.

Keys That Attest

Not available: Keyring for Go only checks none attestation so far, so there's no VirtualManufacturer, and a virtual authenticator registers with a none attestation. See Differences From PHP.

Identity Providers

keyringtest.FakeIdentityProvider stands in for Google, Microsoft, GitHub or any OpenID Connect provider, through httpclienttest, with really signed ID tokens. Register(name) adds it to SSO.Providers, Serve(t, client) answers the application's requests to it, SignIn says who signs in, and Approve turns the URL Keyring sent the browser to into the callback the provider would send. Single Sign-On has a whole test.

Go
google := keyringtest.GoogleIdentityProvider("")// keyring.New[models.User](bootstrap.Keyring, google.Register("google")) in the app's packagesgoogle.Serve(t, client) b := client.NewBrowser().WithHeader("Accept", "application/json")authorize := b.GetJSON("/auth/google/redirect").JSON[map[string]any]()["url"].(string)b.Get(google.SignIn(map[string]any{"sub": "42"}).Approve(authorize))

Each option changes what it answers from then on, and returns the provider, so they chain:

Option What It Does
SignIn(claims) Who signs in next: the ID token's claims, or for GitHub the user its API answers with.
WithEmails(emails...) GitHub's list of the user's addresses (email, primary, verified, visibility), which its API answers /user/emails with.
SignedInAt(at) The user signed in there at at, so their ID tokens' auth_time says so, and they're let through on that session until a request asks for a new sign in (prompt=login, or a max_age they're past). Without it, the first Approve signs them in. AuthenticatedAt() says when they last did.
IgnoringReauthentication() Keeps them on that session even when a request asks for a new sign in, as a provider that ignores prompt=login and max_age would.
WithAuthTimeClaim() Has the fake Microsoft send auth_time, as an app registration with that optional claim has the real one do. The fake Google sends it only when the request's claims parameter asks, and every other fake always does.
WithClaims(claims) Adds claims to the next ID tokens, or replaces them. A nil value leaves one out.
WithHeader(header) Adds JOSE header parameters to the next ID tokens, or replaces them. A nil value leaves one out.
WithDiscovery(entries) Adds entries to the discovery document, or replaces them. A nil value leaves one out.
Expired(), Unsigned(), SignedWithPublicKeyAsSecret(), SignedWithUnpublishedKey() Next ID tokens that ran out an hour ago, say "alg": "none", are "signed" with HS256 and the public key as the secret, or are signed with a key the key set doesn't list.
RotateKeys(retireOld) Signs with a new key from now on, which the key set lists too, and lists the old ones no longer with retireOld.
WithKeyIssuer(issuer) The issuer its keys name, as Microsoft's say which tenant's tokens each signs: https://login.microsoftonline.com/{tenantid}/v2.0 for the fake Microsoft, nothing for the others. nil names none.
SendsIssuer() Sends RFC 9207's iss with every callback, and says so in discovery.
AuthMethods(methods...) The client authentication methods the token endpoint takes, and discovery lists: client_secret_basic and client_secret_post to start with.
FailExchange(status, error) Refuses every code at the token endpoint with this status and error.
Down() Answers discovery, the key set and GitHub's API with a 503.

Deny(url, error) is the callback for a user who said no (access_denied when error is empty). IDToken(claims) is an ID token for those claims, signed as the next one would be, JWKS() the keys its key set lists, and TokenIssuer() the issuer its tokens come from. DiscoveryFetches() and KeyFetches() count how often Keyring read its discovery document and keys. The client it knows is keyringtest.ClientID with keyringtest.ClientSecret.

kt.Client() is the laraveltest client the helpers were made for, and kt.Keyring() the application's *keyring.Keyring.

SSO.ResolveHosts stands in for the PHP package's HostResolver::fake(): give it a function that answers each host's addresses, so a test can point a provider at a server of its own without DNS. Nil asks DNS.

Go
cfg.SSO.ResolveHosts = func(ctx context.Context, host string) []string {    return []string{"127.0.0.1"}}

The Conformance Suite

keyringtest.Conformance checks that your setup keeps Keyring's guarantees, as the PHP package's trait does. Each check is a subtest, on an application of its own:

Go
func TestKeyring(t *testing.T) {    keyringtest.Conformance[models.User]{        App: func(t testing.TB) *laraveltest.Client {            return laraveltest.New(t, bootstrap.Options(), laraveltest.RefreshDatabase)        },        User: func(t testing.TB, client *laraveltest.Client) *models.User {            user := client.Create(factories.User) // whose password is "password"            return &user        },    }.Run(t)}

User makes a new user each time, whose password is Password (password when it's empty), whose address is verified, and who has no sign-in methods but the password. Username gives what they sign in with, their Email unless you say. Registration gives a registration form for a new address, and ProductionHashRounds how many bcrypt rounds production uses, for the timing check. Run(t, names...) runs only the checks named, as keyringtest.Checks names them, and so does go test -run 'TestKeyring/revokes'. Check(t, name) runs one and returns how it went.

A check that doesn't apply, such as one for a feature that's off, is skipped. AcknowledgedDangerousSteps acknowledges a pipeline step you dangerously replaced or removed, as keyringAcknowledgedDangerousSteps(), and AcknowledgedUncheckedRoutes a route that starts a session without AuthenticateSession. The check that the user model protects the email and password updates a user with model.Update, so your model's Updating hook has to call Keyring.GuardChanges (see Protected Attributes). With GuardChangesManually, where your own code calls it instead, give Update the function that saves a user the way your code does:

Go
keyringtest.Conformance[models.User]{    // App, User, ...    Update: func(ctx context.Context, user *models.User, values db.Values) error {        return users.Save(ctx, user, values) // calls Keyring.GuardChanges first    },}.Run(t)

A correct password has to answer 202 for the challenge, or 200 with the browser signed in. The route check fails when a route starts a session or runs auth.Session without AuthenticateSession, and when no route runs AuthenticateSession at all. The check that every factor begins enrolling begins each for a user of its own, so it stays under Limits.Forms. It doesn't check that a registry returns what it revokes or keeps a session's handle when it moves, as Keyring for Go has one registry, nor bcrypt's half of the 64-character password check, as Laravel Go only hashes with bcrypt.

The Contract Suite

The contract suite holds Keyring for Go to the same routes, JSON, status codes and cookies as the PHP package. contract/bin/run-go builds the contract app in go/contract-app, migrates a new SQLite file in a temporary directory, serves the app on a free port of 127.0.0.1 reached as localhost, and runs bun test against it:

Terminal
(cd contract && bun install)contract/bin/run-go

Unless the arguments name files, it runs the files the Go port passes, listed in the script, which is every file in contract/tests now. The script can also leave out single tests the port doesn't pass yet, printing each as skipped, and lists none. Naming a file runs every test in it:

Terminal
contract/bin/run-go tests/email-changes.test.tscontract/bin/run-go --randomize

It needs Go, python3 (to find a free port) and curl (to wait for the app). Off CI it builds at the lowest priority on four cores. The server's log is printed when a test fails.

Keyring's Own Tests

The package's own tests run on SQLite in memory:

Terminal
cd go/keyringgo test ./...

Set KEYRING_TEST_DATABASE_URL to run them on PostgreSQL instead, on a database of their own:

Terminal
KEYRING_TEST_DATABASE_URL=postgres://postgres@127.0.0.1:5432/keyring_go_test go test ./...

bin/ci go go-databases runs both, as CI does.