Differences From PHP
On this page
- Introduction
- Not Available Yet
- What Behaves Differently
- Signing In and Out
- Remember Me
- Ending Another Session
- Policies and the Pipeline
- Requiring a Second Factor
- Managing Authenticators
- Factors of Your Own
- Code Factors
- Passkeys and Attestation
- Devices
- Sessions and the Registry
- Impersonation
- Single Sign-On
- Signing In From Your Own Routes
- Pages and Responses
- Routes
- Risk
- Events
- The Security Log
- Emails
- Passwords
- Email Changes and Reserved Addresses
- Protected Attributes and Users
- Console Commands
- Services for Your Own Code
- Test Helpers
- What Laravel Go Would Need
Introduction
Keyring for Go covers most of the PHP package and passes the whole contract suite: contract/bin/run-go runs every file in it. This page lists everything that isn't the same: what isn't there yet, what works differently because Go or Laravel Go works differently, where the Go port is stricter on purpose, and the Laravel Go API that would let it match the PHP package exactly. Each Go page links here from the sections it affects.
The Go port follows the PHP package wherever the two can agree, and the Rust crate where PHP doesn't apply. Where it parts from the Rust crate in a way you'd notice coming from Rust, this page says so.
Not Available Yet
These need something Laravel Go doesn't have (see What Laravel Go Would Need):
- Laravel's own auth events.
Login,Logout,FailedandLockoutaren't dispatched. Keyring dispatches its ownRegistered,Verified,PasswordResetandPasswordChangedin place of Laravel's. - Translations. Laravel Go has no translator or locale, so every message is the PHP package's English one.
- Argon2 passwords. Laravel Go's
hashchecks bcrypt alone ($2y$,$2a$and$2b$), so a password a PHP application hashed with Argon2 can't be checked here. - Rehashing a password on sign in. Laravel Go's guard signs a fingerprint of the password hash into every session, so a new hash would sign out the user's other sessions.
- Sharing sessions with a PHP application. Session payloads, Laravel's own
sessionstable and the guard's remember cookie are in different formats, so a browser can't move between a Go and a PHP application. Only Keyring's own tables are shared. Each side needs its ownSESSION_TABLEif both use database sessions.
These have nothing in the way, and aren't done yet:
- Security keys and attestation. Only
noneattestation is checked. There's nopackedorfido-u2f, no attestation roots, no AAGUID lists, norequireAttestation()orallowOnly(), and no second key factor (WebAuthn::securityKeys()->as(...)). So no key is ever attested, and nothing reaches AAL3. - Four security emails.
second_factor_failed,recovery_code_used,account_lockedandclone_suspectedaren't sent yet. Their log entries and events are there, andNotifications.Offtakes their names. - The activity page (
activity()andunlistedActivityTypes()), andrecordIpsUsing(). Keyring::unlock($user, $factor), which clears one second factor's limits.Keyring.Unlocktakes the user alone.- A code factor's own rate limits, categories other than possession or address, and a
credential_idfor its row. - Bases for an identity provider driver of your own (the PHP package's OAuth 2.0 and OpenID Connect classes). A driver of your own does the whole flow itself.
- Second factors of your own other than code factors. See Factors of Your Own.
- The PHP package's
fixIncorrectEdDSAKeyfor registrations. - Reading and ending sessions from your own code:
Sessions::signOutEverywhere(),stillSignedIn()and the rest ofSessionsandSessionRegistry. Runkeyring:sign-out, or answerfalsefromAllowSignInWhen. See Services for Your Own Code. StepUpandSessionAssurance, which decide a step-up in a controller and read what the session proved. PutRequireAssuranceorRequireFreshVerificationon the route instead. See Step-Up.- The email for a sign in on an unrecorded device your own
auth.Loginmade, and marking a session recalled on routesAuthenticateSessiondoesn't cover. - Tidying up after a deleted user, as the
HasKeyringtrait'sdeletedlistener does: signing them out withaccount_deleted, ending their reset links, and deleting their sign-in methods, devices and log entries. See Protected Attributes and Users. - Reserved lookalikes in scripts beyond Latin, Greek and Cyrillic. See Email Changes and Reserved Addresses.
- MySQL. The schema is checked against PHP's on SQLite and PostgreSQL only. On MySQL, Laravel Go's timestamp columns are
datetime, where PHP's aretimestamp.
And these have no counterpart, because there are no Eloquent models:
- Swapping the models (
useAuthenticatorModel()and the rest). The tables are Keyring's own. - The
HasKeyringtrait. Your user model'sUpdatinghook callsKeyring.GuardChanges, and code that creates users checksKeyring.AddressReserved.Keyring.SignInMethodsstands in for$user->keyring.
What Behaves Differently
Signing In and Out
- The user type is a type parameter.
keyring.New[models.User]()andkeyring.From[models.User](ctx). Users need an integerID, stringEmailandPasswordfields and aRememberToken, whichRegisterchecks. The tables'authenticatable_idcolumns are big integers. - Finding users. Keyring finds users with
auth.ModelUsers[U]onConfig.Username, unless you hand it yourauth.Users[U]withKeyring.FindUsersWith, since Laravel Go keeps the registered provider to itself. - Signing out one browser. Laravel Go has no
logoutCurrentDevice(). Keyring empties the session and takes back both remember cookies itself, keeping the user's remember token, so a session that ends signs out that browser alone, as in the PHP package. OnlyPOST /logout, but while impersonating, and a session whose record can't be ended, go throughauth.Logout, which gives the user a new remember token. Unlike the Rust crate, which always usesAuth::logout. - A user with no remember token is given one by
auth.Logout, where Laravel'slogout()only cycles a token that's there. Signing out everywhere doesn't give one, where the PHP package'scycleRememberToken()does. Sousers.remember_tokencan differ between the two sides for such a user. - A new password signs out every other session. Laravel Go's guard signs a fingerprint of the password hash into every session, so
sign_out_others: falsecan't keep the others. Their records end at once anyway, aspassword_changed.sign_out_othersdecides the rest of signing out everywhere, such as a new remember token. The browser that changed the password is signed in again under the new hash before it moves to its new record. - Middleware order. Keyring adds
AuthenticateSession[U]to the web group itself, and runsauth.Session[U]inside it, since a package's middleware runs before the application's. Don't addauth.Sessionyourself. Anauth.Sessionof yours that runs ahead of it is refused with a500on every request. - Your own sign out. Your
auth.Logoutis noticed byAuthenticateSessiononce the handler returns, by the record's ID leaving the session, so only on routes in the web group. The reason islogged_out. - A signed-in browser at a guest page goes where Laravel's
RedirectIfAuthenticatedsends it: the route nameddashboard, elsehome, else the site's root. The Rust crate sends it tohome. Laravel Go has noredirectUsersTo(), and can't look up an unnamed/dashboardroute, so name the route if a PHP application sharing users points there. - The session lock. A request that waits the full 10 seconds for the session lock gets a
500, not a423: Laravel Go answers its own lock timeout with a423, which a Keyring client reads as a step-up. - The user's row lock is
FOR NO KEY UPDATEon PostgreSQL,FOR UPDATEon MySQL and none on SQLite, and is waited for 5 seconds at most, where the PHP package waits as long as the database does. Past that the request answers500. There's no setting to turn it off. - A passkey alone that fails names its account, and its
factor_failedentries are refusals, capped bySecurityLog.Refusals, where the PHP package writes every one.FactorFailed.Identifyingsays so. - When
CloneSuspectedfires. When the failure is counted, beforeFactorFailed, where the PHP package dispatches it from inside the check. The entries and their order are the same. - A right code is spent before the
unavailablerefusal, in the PHP package's order. The Rust crate refuses first. - A failed challenge answer doesn't save the attempt, where the PHP package's
VerifyFactorsaves it. The passkey options it held are spent on the server either way. An answer that leaves a code out of guesses is saved, so the page starts again. - The account's limits are cleared by the owner's right code with devices off, as the PHP package's
FailureCounts::succeeded()clears them. The same holds in all three ports. - Times are UTC.
created_aton log entries and alerts, andpassword_reset_tokens.created_at, are written and compared in UTC. A PHP application on anotherapp.timezonesharing the database would see alert times and reset link ages differently.
Remember Me
- The guard's cookie differs. Laravel Go's guard cookie is JSON named
remember_web, where Laravel's isid|token|hashunderremember_web_<sha1>. Keyring's ownremembered_sessioncookie is the same on both sides, but a browser can't move between a Go and a PHP application. - A cookie sign in is told by the session ID changing, as there's no
viaRemember(). Keyring's own sign ins know they asked for it. - Your own
auth.Login(r, user, true)gets Keyring's cookie, and its record is marked remembered just after. The Rust crate records such a session, but not as remembered. - A browser that changes its password isn't brought back by "remember me" afterwards, as with the PHP package. The Go port signs it in again without "remember me".
Ending Another Session
Laravel Go has no way to destroy another browser's session by its ID, so ending one ends its Keyring record, and AuthenticateSession signs that browser out on its next request. Its session data stays in the store until it expires.
DELETE /user/devices/{device} 404s on a device already marked signed out, as the PHP package's ->active() does. After a sign out that failed part way, the report link or the sessions list finishes it.
A 404 for someone else's device or authenticator says Not Found, not the PHP package's "No query results for model [...]", which names a PHP class.
Policies and the Pipeline
- The policy is a closure with the request's context:
Keyring.Require(func(ctx context.Context, user *U, attempt keyring.Attempt) keyring.Requirement). There's no fixed-requirement setting beside it: a closure returning one does the same. - Requirements hang off
Level:keyring.AAL2.Requirement(), withRequireFactorsandRequireStepsfor the PHP package'sfactors()andsteps(), andNoDowngrade()andNoDowngradeExcept(...)for its default argument. The zeroRequirementis the default policy, not a requirement of nothing. - Steps are values implementing
Step[U], given toKeyring.Pipeline, named by their type or aName()method and theStep*constants. - Steps of your own only run between
VerifyFactorandCompleteAttempt.EnsureNotThrottled,VerifyFactorandCompleteAttemptcan't be changed, even dangerously. A change Keyring refuses stopsRegister. - A step can only fail a verification (
StepContext.Fail), not lock it out. - The unregistered-factor refusal stays with
DetermineRequirement, in the PHP package's order. With that step dangerously removed or replaced, Keyring still refuses such an account, where the PHP package's refusal goes with the step. ResolveDevicedoesn't note "trust this device". The form field is read where it's posted, so removing or replacing the step doesn't lose it.AllowSignInWhenanswers a bool, as the PHP closure.AllowsSignIn(nil, user)is allowed outside a request.- Keeping a user out signs this browser out even when ending the others fails, and answers
500, where the PHP package throws before its own sign out. RequireAssurancetakes no recovery code alone for AAL1, as the Rust crate's audit settled, where the PHP package'skeyring:aal1does.
Requiring a Second Factor
RequireEnrollmentfails closed without the session, a500, where the PHP package's finds no user and lets the request through.- The page saved for
continuecarriesRequireEnrollment's own requirement. Laravel Go doesn't let a middleware see the values of the route's other middleware, so giveRequireEnrollmentthe same options as the route'sRequireAssurance, or a user who enrolls enough for one is sent back by the other. - A held user is let through to
PasswordChangeURL's page pastRequireEnrollment. In the PHP package and the Rust crate, a held user with no second factor goes round in a loop between the two pages. - The hold's exceptions are route names, as in the PHP package, so a route of yours with one of those names is let through too.
- The page saved is the URL as it came. Laravel's
fullUrl()sorts the query string, andr.FullURL()keeps it as sent.
Managing Authenticators
- Changes take the owner's cache lock and the user's row, as the Rust crate's do, where the PHP package takes the row lock alone. On SQLite there's no row lock, so the cache lock is what keeps two changes apart.
- Beginning an enrollment counts against
Limits.Forms, where the PHP package's route has no limit. - Making the default the default again keeps it. The PHP package unsets it.
- A posted credential whose
idisn't the attested one is refused, where webauthn-lib stores the attested ID whatever was posted. - Renaming or choosing as default one removed meanwhile is a
404, where the PHP package saves its stale copy and says it did. - A removal whose devices can't be distrusted isn't made, and nothing is announced.
- The first factor's recovery codes are made under the lock, so a set made meanwhile in another request is kept.
- Factors the Go port can't check (a security key a PHP application added, or passkeys with
Factors.Passkeysoff) aren't listed, renamed or removed, and an account with one is refused at sign in with theunavailable422. They still freeze the account once added, and keep the recovery codes. - Registration with managing sign-in methods and no email verification stops
Register, unlessAllowEnrollmentWhendecides, where the PHP package throws at the first enrollment. SignInMethodsis the Rust crate's, as a Go application can't reach$user->keyring.- The QR code is drawn from
rsc.io/qr, 192 pixels across with no margin, not BaconQrCode's markup.
Factors of Your Own
Code factors and primary factors of your own are there (see Code Factors). Any other second factor of your own isn't yet.
- A primary factor is a struct,
PrimaryFactor[U], given toKeyring.AddPrimaryFactor, finding its user with anIdentifiesUsers[U](IdentifyandVerify), which may also implementValidatesSignIns,DiscoversUsersandStalls. - It says what it proves once, for the factor (
Categories,PhishingResistant,DeviceBound), where a PHP factor'scategories(),phishingResistant()anddeviceBound()can vary with the authenticator. What a session proved with one counts for the categories recorded then, as in the PHP package. - It only starts a sign in. It never answers the challenge or confirm pages, and users don't enroll it: the PHP package's
answersChallenges(),enrollable(),onePerUser(),priority()anderrorKey()aren't ported. A refusal is reported on the first ofIdentifiedBy, or oncode. - There's no
attested(),present(),limits()orauthenticators()(virtual authenticators) to override. It counts under the configured limits: the address's alone, or the typed name's and the account's whenIdentifiedByincludesConfig.Username. Verifyanswers whether the proof holds rather than with aVerification, and gets the row as aPrimaryAuthenticator, its secret decrypted.- Keyring doesn't validate its fields (
identificationRules(),rules()): the factor does, inValidate, refusing with a*web.InputError. Keyring calls it before the limits, so a missing field is answered alike whether or not the account is refused without saying so. - A row that isn't the user's confirmed authenticator of the factor, named by
Identified.AuthenticatorID, is taken as nobody found, afterStall. - A primary factor's key is the process's, as the Rust crate's:
Registerrefuses a code factor of another application in the process with the same key, and the other way round.
Code Factors
- A code factor is a struct,
CodeFactor[U], given toKeyring.AddCodeFactor, its sender aSendsCodes[U], and making a new authenticator an optionalMakesCodeAuthenticators[U]. It proves possession, or the address withSentToAnAddress. Registerrefuses what the PHP package refuses at first use:verification_codeinNotifications.Offwith emailed codes on, andLimits.Codesunder one orLimits.CodesPerunder a second with a code factor on. Codes are capped at 18 digits.- Emailed codes are off until
Factors.EmailCodesis set, as the PHP package has them only once registered. - Codes are sent in the request, never queued, so a code never sits in the jobs table. A sender's error is the request's
500, with the new code already kept. - Each cache keeps its values its own way. PHP serializes and Laravel Go doesn't, so a code one side sent is checked only by the side that sent it. The keys and hashes are the same.
- Sends for adding a factor are limited per account only, as in the PHP package. Whoever is signed in chooses the destination, so a paid SMS sender can be made to text other people's numbers, a few every ten minutes per account. Limit by destination and IP in your
Deliver. - Wrong guesses are read, compared, then counted, in all three ports, so two guesses at once can both be checked against the same count. An enrollment's code can get about twice
MaxGuessesacross a code begun again late in the window.
Passkeys and Attestation
- WebAuthn is Keyring's own package (
go/keyring/webauthn, standard library only), running webauthn-lib's checks in its order, so what passes and what's refused matches the PHP package. Ed25519 keys are checked, which the Rust crate can't do. - Records are written back as webauthn-lib writes them: its keys in its order, nulls left out, unknown fields dropped, IDs as unpadded base64url, the AAGUID lowercased. The Rust crate keeps unknown fields and the stored order.
- Answers are capped: authenticator data or an attestation object over 64 KiB is refused before it's read, and so is a registration with an empty credential ID. webauthn-lib reads any size and only caps a credential ID at 1023 bytes.
- Cross-origin answers are refused:
crossOrigin: truewith notopOrigin, and atopOriginofnull, which webauthn-lib lets through. - Settings are checked at boot: origins, the relying party ID and algorithm names, where the PHP package throws on the first ceremony.
- International hosts follow the URL Standard's bidi and joiner rules, as browsers do. A few hosts PHP takes stop
Registerwith passkeys on. Factors.Passkeysis on by default, where the PHP package has whatever factors the application lists.- A passkey alone loads its user with
Find, notFindForLogin, as in the PHP package and the Rust crate. UseAllowSignInWhento keep users out of every factor. - A user handle's oldest key is found by
created_at, thenid. - An AAGUID is read only in its hex form.
- Security keys and attestation aren't there yet. See Not Available Yet.
Devices
- The describer is a function in
Devices.Describe, and the locator aLocatesIPsvalue inDevices.Locator, not classes the container builds. The locator is asked once per request. - Countries are compared as text, so
"1"and"01"are two countries, where the PHP package compares loosely. An empty location is unknown. - The new-device email goes through the queue, after commit, as in the PHP package. Laravel Go uses the
databasequeue wheneverDATABASE_URLis set, so without a worker (orQUEUE_CONNECTION=sync) nothing is sent. - A failed device-trust mark still ends the trust and answers
500, where the PHP package stops before the update. - The device a sign in comes from is loaded again each time the policy is asked, so trust taken away meanwhile counts at once.
Sessions and the Registry
- One driver. The registry is always
keyring_sessionson the application's database. The PHP package'ssessions.driver,tableandconnectionaren't ported. - Overlapping requests are ported (
Sessions.OverlappingRequests, on), unlike the Rust crate. Keyring wraps the web group'sStartSessionstore, removes a replaced session's cookies by renaming them to nothing, and takesSec-Fetch-Siteoff such a request so the CSRF token decides. AStartSessionyou add yourself isn't covered. - A record is ended only if it's the user's, stricter than the PHP package and the Rust crate.
- An alert is shown to one sign in only, marked seen only if still unseen, where the PHP package can show it to two at once.
- Pages that also serve guests are listed by route name in
Sessions.ContinueAsGuest, as in the PHP package. An empty name stopsRegister. - A risk step-up's new record is noted as used now, so a session stepped up near its idle limit carries on. The PHP package and the Rust crate copy the old record's last activity.
- A sign in whose session can't be saved has its record ended, as the Rust crate's
EndUnsavedSignInsends it, by middleware Keyring places in the web group itself. Only a request whose session wasn't saved ends one, where the crate ends the record on any5xx.
Impersonation
- Who may impersonate whom is given to
Keyring.AllowImpersonationWhen, which also takes the request's context. One that panics fails a start with a500, and counts as a no while an impersonation runs. Impersonation.Middlewareis a list of middleware values,RequireAssurance[U]{Level: keyring.AAL2}andRequireFreshVerification[U]{Within: 15 * time.Minute}by default, standing in for the PHP package's['keyring:aal2', 'keyring.fresh:15m']. Unlike the Rust crate's two settings, the confirm for AAL2 builds on what still counts toward it, as in the PHP package.Keyring.Impersonateasks whatImpersonation.Middlewareasks before it starts anything, and returns the step-up's answer for you to send, where the PHP package leaves that to the route's middleware. A refusal is an*ImpersonationRefusedError, and the reasons are string constants (RefusalSelfand the rest).Keyring.StopImpersonating, signed out instead, leavesauth.Userreturning the impersonated user for the rest of the request, as Laravel Go can't make the guard forget a user withoutauth.Logout. Answer straight away.- 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, so a session left that way isn't refused again. The Rust crate does the same. - Someone's name is their
Namefield, or the field ofConfig.Username's column, standing in for thenameattribute and username. - Going back keeps both remember cookies, even when the user's password changed while impersonated and Laravel Go's guard took its cookie back. The Rust crate loses the guard's cookie there.
- Your own
auth.Logoutwhile impersonating ends the impersonation and the parked session, as in the PHP package, and gives the user a new remember token, asAuth::logout()does. There's nologoutCurrentDevice(), so use Keyring'sPOST /logout. - The claim that only one request ends an impersonation is kept in the default cache store, where the PHP package keeps it in
cache.limiter's. Impersonation.ShowInActivityis read by nothing yet, as there's no activity feed.
Single Sign-On
- All four of the PHP package's drivers are there:
oidc,google,microsoftandgithub, so links any of them made in PHP sign in here. - Providers are a slice of
SSOProviderinSSO.Providers, built withOIDCProvider,GoogleProvider,MicrosoftProviderandGitHubProvider. A name given twice stopsRegister. Anything else wrong with one is found when it's built, reported and left off the login page. - A driver of your own implements
IdentityProviderand is registered withSSO.Extend. Its identity is held to the provider and request Keyring knows, and refused without an issuer or subject, where the PHP package takes what its driver says. - ID tokens are checked by Keyring's own
josepackage, and where a provider's URLs point by its ownhostspackage, each ported from the PHP package. Go'scrypto/rsarefuses an RSA exponent over 2³¹−1, which OpenSSL takes. No provider publishes one. ::ffff:0:0/96is inward, and a URL with no host is never the same host as anything, as the Rust crate's fixes.SSO.ResolveHostsstands in forHostResolver::fake(). Nil asks DNS.- DNS rebinding is refused. A token endpoint or key set let through only for being on the public internet is connected to only at a public address, so a name that resolves somewhere private by the time it's connected to is refused. The PHP package resolves the name again and connects.
PrivateEndpoints, the issuer's own host and port, and an issuer on this machine skip it, as they skip the address check. - Linking refuses an account any row already has, before inserting, where the PHP package inserts and turns the unique violation away the same.
Factors.SingleSignOnstarts off, as it needs a provider.- An
amrgiven as an object is read in key order. It counts toward nothing. - Discovery documents are cached as their checked body and read from the cache each time.
- Only a
2xxanswer from a provider counts, as the Rust crate's, where the PHP package takes a3xxtoo. Keyring reads at most 1 MiB of one. - Your application's HTTP client settings don't reach a provider: the headers, tokens, query, retries and transport given in
laravel.Options.HTTPstay behind, where the PHP package's requests go through Laravel'sHttpfacade with whatever it was given.
Signing In From Your Own Routes
Keyring.Attempttakes a factor's key, andKeyring.AttemptSSOthe identity and "remember me", where the PHP package'sKeyring::attempt()reads them from the request. WithFactors.SingleSignOnoff,AttemptSSOis a404. A refusal is the error, forweb.Fail, where the PHP package throws aValidationException.- A browser someone is signed in on is sent on by
AttemptandAttemptSSO, asGuestsends it, where the PHP package signs the new user in over them. SignInAstakesProvedPassword()orProvedAuthenticator(id), one of the user's own sign-in methods of a factor the application has, whereSignIn::as()takes anyVerification.LinkedSSOandLinkNewAccountare the Rust crate's:SingleSignOn::linked(), and the PHP example's creating the row.LinkNewAccountrefuses an account with any sign-in method, a password included, and dispatches nothing, as the PHP example, where the Rust crate's dispatchesAuthenticatorAdded.- Keyring's limiters aren't yours to put on a route, so there's no
keyring-login-optionsfor your own callback. Put a rate limit of your own on it.
Pages and Responses
- Pages are Inertia pages,
auth/{name}, or the page's name and props for a JSON request. There are no views, and norenderUsing(). WithConfig.Pagesoff, anything but JSON is a404. - A lockout's
429is a validation error with its own status. A browser gets the422, which goes back to the form. - Answer bodies. Keyring's own JSON keeps the PHP package's key order. Page props and Laravel Go's own error bodies are maps, so their key order varies.
- A guest's redirect to log in from a signed-in route carries Keyring's security headers, which the PHP package's lacks.
- The
Sec-Purposeheader is read as Laravel reads it, so a Chrome prerender counts as a prefetch.
Routes
- Keyring adds its routes to the web group, under
Config.Prefix. WithConfig.Routesoff, callKeyring.Routeswhere you want them. There's nodomainsetting. - Route names are the PHP package's, so
Sessions.ContinueAsGuest,Config.EnrollmentExceptandConfig.PasswordChangeExcepttake names, as in the PHP package. The Rust crate takes paths. - Middleware are typed values:
RequireAssurance[U]{Level: keyring.AAL2, DeviceBound: true}forkeyring:aal2,device-bound, andRequireFreshVerification[U]{Within: 5 * time.Minute}forkeyring.fresh:5m.Config.ChangesMiddlewareis a list of them. BlockSessionmarks a route for the session lock, standing in for->block(), and works on routes in the web group alone.- Signed links are signed relative to the site with Laravel Go's URL signer, so a link either side signs opens on the other.
Risk
- Signals are values, given with
Keyring.RiskSignals, which adds to them. There's no replacing the list. Each built-in signal is a struct whose zero fields are the PHP package's defaults, so a score of 0 can't be asked for: leave the signal out. - An answer is a struct,
keyring.Action{StepUp: true, Notify: true}, not a builder.LockForis a duration, and zero locks nothing. RespondToRisktakes the context:func(ctx context.Context, risk *keyring.Risk, at keyring.Checkpoint) keyring.Action.Risk.Levelsmust be in order, with a medium of at least 1. The PHP package takes anything.- A sign in's attempt always carries a risk once assessed, empty when nothing was found.
ImpossibleTravel's distance can differ from PHP's in the last bit, as Go's sine and cosine aren't the C library's.- Risk locks aren't shared with PHP, even on one cache store: each side writes the lock in its own format. A lock placed on one side holds on that side only.
Events
- Events are generic structs, such as
keyring.FactorFailed[models.User], carrying the user as*Uand plain values where the PHP payload is a model. SessionEnded[U]is new, dispatched where the PHP package's middleware ends a session.FactorFailedcarriesIdentifyingfor a passkey alone.- Package listeners run first. Keyring's own listeners, which write the security log and send emails, run before your application's, so a listener of yours that fails can't keep an entry off the log.
ProviderIdentityAccepted[U]carries the identity without the request's secrets or the token's nonce.
The Security Log
- Writing never fails a sign in. Each entry is written in its own savepoint. A failed write is reported and goes to
slog.Default(), under akeyringgroup, withnoticeat info andcriticalat error. Laravel Go has no named log channels, so there's nosecurity_log.channel. WithFeatures.SecurityLogoff, every entry goes there. - Request IDs come from your log context under
SecurityLog.ContextKey(trace_id), or a UUID. - The
oncerefusal (a lockout'slocked_out) is taken with one atomic cache add, where the PHP package checks then counts. - Setting a struct whole turns things off.
cfg.Features = keyring.Features{Devices: true}turns the security log off, andcfg.SecurityLog = keyring.SecurityLog{...}turns alerts off. Set fields one at a time.
Emails
- Keyring's own emails have the PHP package's lines without Laravel's notification layout, which Laravel Go hasn't got.
- Replacing one is a function in
Notifications.MailorNotifications.AccountMailreturning amail.Mailable. - Security emails are queued after commit. Account emails (the reset link, the verification link and
already_registered) are sent with the mailer in the background, never queued, as the PHP package sends them in the request: a reset token never sits in the jobs table. - Subjects are those of the Laravel the PHP package runs on: "Reset your password" and "Verify your email address". The Rust crate uses Laravel's older wording.
- A taken address at registration is mailed at the address its account has, and only when that's the address typed once both are normalised. The PHP package and the Rust crate mail the typed address, which on a collation that ignores accents tells another mailbox that an address is registered.
registeredandregistration-receivedname the login page by its route, wherever you placed Keyring's routes.- The 429 for another verification link counts down as the sign-in lockout does.
- See Not Available Yet for the four security emails not sent yet.
Passwords
- The features start off. Registration, email verification, password resets, password changes and email changes are off until you turn them on and give Keyring your actions, as the Rust crate starts them, where the PHP package's config turns them on. One that's on without its action stops
Register. - Actions take and give maps:
CreatesNewUsers[U](Validate, thenCreate),ResetsUserPasswords[U]andUpdatesUserPasswords[U], their passwords already in NFC. They save the password themselves. Config.Emailis new, the PHP package'skeyring.email, apart fromConfig.Username.- Email verification is
Features.EmailVerification, standing in forMustVerifyEmail. With it on, the user type needs anEmailVerifiedAtorEmailVerifiedfield and the users anauth.EmailVerifier. A Go application sharing users with a PHP application that verifies addresses should turn it on. - Who may sign in follows the PHP package's
hidesRegisteredAddresses(): registration on andRegistration.RevealTakenoff. The Rust crate has a switch of its own. - Taken addresses are looked for in the user model's table under
Config.Email, or through an optionalTakenmethod on the action (TakenAddresses). A unique violation fromCreateis looked at again, as in the PHP package, rather than taken as "taken". - The checks the Rust audit moved ahead of the action stay ahead of it: the current password again, the held one, and one bcrypt can't take are refused before your action runs.
- A reset runs under the owner's lock, so two resets with one link go through once, and is refused once the account's address has changed since the link was found. Laravel's broker takes no lock.
- A change's write rolls back with the user's row lock on PostgreSQL and MySQL when the action fails. On SQLite it stands.
- The password actions run with a deadline, 2 seconds before the owner's 10 second lock lapses, and the breach checks fit within it. A check that runs out counts as unchecked.
RequirePasswordChangetakes the reason as a string,""for none.- Laravel's messages for
email|max:255both show, as Laravel doesn't stop at the first rule a field breaks. password_reset_tokensis created by Keyring where it's missing, in Laravel's schema, from a migration with a name no PHP application has. An application migration of yours that makes it and sorts before Keyring's keeps its own.- Resets and an email change at once.
auth.EmailVerifiercan't compare and set, so nullemail_verified_atin the same write as an address change of your own. - TOTP secrets decode as the Rust crate's (any case, spaces, padding, at least 10 bytes), looser than Google2FA: a hand-imported 20 or 52 character secret works here and fails in PHP.
Email Changes and Reserved Addresses
- Saving the address. Keyring saves it with
model.Update, writingConfig.Emailand, for a newly confirmed address,email_verified_atin the same write. AValidatesEmailChanges[U]that's also aSavesEmails[U]saves it itself. - A confirmation that finds the account already has the new address finishes the change rather than cancelling it, as the Rust crate does.
- Changes are found by
authenticatable_typeand attribute, so a change another user type or another attribute made isn't this application's to confirm. - Reserved lookalikes. The PHP package folds an address with Laravel's
Str::transliterate(). It's ported as the Rust crate ports it: a table of what that does to Latin, Greek and Cyrillic letters, general punctuation and characters that don't show. A character from another script is kept, lowercased, where the PHP package transliterates or drops it, so an address with one only matches itself, and a reservation made on one side isn't found by the other.
Protected Attributes and Users
- Laravel Go's models have an
Updatinghook, not Eloquent'supdatingevent. CallKeyring.GuardChanges(ctx, user, values)from it, or before a write that doesn't go through the model, with the columns it writes. It compares them with the stored row, asisDirty()does, and forgets the old address's reset link when the address changes, as the trait'supdatedlistener does.Registerrefuses a user type without the hook while anything is protected, unlessConfig.GuardChangesManuallyis set. See Protected Attributes. - Creating a user isn't a change. Check its address with
Keyring.AddressReserved. - Deleting a user isn't seen by Keyring. Their sessions carry on until
AuthenticateSessionfinds the user gone and signs the browser out, aslogged_out, and their rows stay in Keyring's tables. Delete them yourself where you delete users. Keyring.WithoutProtectiontakes a context and a function, and logsprotection_bypassedbefore the function runs: a bypass that can't be logged doesn't happen.
Console Commands
- They run as your application's commands (
go run . keyring:prune), and exit with the PHP commands' codes: 0 when they worked, 1 when they didn't, and 2 for arguments that don't go together.keyring:prune,keyring:sweep,keyring:sign-outandkeyring:importread from the database's writer, not a read replica, as the PHP package'suseWritePdo()has them. keyring:prunenames each table rather than each model (Pruned 3 [keyring_devices] records.). A zeroSecurityLog.KeepFor,Devices.KeepRevokedFor,Devices.KeepUnseenFororEmailChanges.KeepEndedForis its default, since Go can't tell zero from unset, so a struct set whole doesn't delete the whole table.Registerrefuses a negative one.PruneAtset to""leaves scheduling it to you, as the PHP package'snullprune_at.keyring:sign-outnames a user by theirConfig.Usernamecolumn and ID, and only takes an ID made of digits. It warns when the default cache store is Laravel Go'smemoryordiscardstore.keyring:importreads Fortify's columns from the tableSessionUserTypenames, or the one--tablenames, warning that it files every row underAuthenticatableTypewhen that's another table. It decrypts them with the application key, where the PHP package asks Fortify for its encrypter. It can't read Fortify's config, so a secret that was never confirmed needs--fortify-confirm(or--unconfirmed). A passkey it imports that can't sign in here is listed with the PHP package's warnings, namingWebAuthn.AlgorithmsandWebAuthn.MinimumRSABitswhere they sayconfig/keyring.php. In place of "Register … first", it asks forFactors.Passkeyson. See Importing Two-Factor Data.keyring:installwrites nothing, as the migrations come with the package and the config, the package and the actions are your Go code. It prints thekeyring.Newfor what was picked and what's left to do, asks nothing, and has no--force. Since Keyring for Go has passkeys and the security log on unless they're turned off, it printscfg.Factors.Passkeys = falseandcfg.Features.SecurityLog = falsewhen they aren't picked. There's nosecurity-keysfactor. With an authenticator app or passkeys picked, it requires a second factor unless--optional-second-factor: it printsEnrollmentURLset to/settings/security, and aMiddlewarefunction that appendsRequireEnrollmentto thewebgroup. Where the PHP command asks for theHasKeyringtrait, it asks for the user model'sUpdatinghook that callsGuardChanges(orConfig.GuardChangesManually) wheneverupdate-passwordsoremail-changesis on, sinceRegisterrefuses those without it.- There's no
canSweep()orMissingMigration, as Keyring for Go has the database registry alone and the migrations come with the package.Sessions.SweepEveryis atime.Duration, and zero is off, as the PHP package'snull, since Go can't tell zero from unset. Over 12 hours is 12 hours, whichkeyring:sweepsays as it runs and logs once a day. A zeroSessions.SweepLimitis 1000.
Services for Your Own Code
Keyring.ClearAccountandKeyring.Unlockstart a user's sign-in limits over, the second also lifting a risk lock.Keyring.RequirePasswordChange,RequiresPasswordChange,PasswordChangeReasonandCancelPasswordChangemanage password holds.Keyring.PendingEmailChangeandCancelEmailChangesread and cancel email changes.Keyring.SignInMethodslists a user's sign-in methods as a settings page shows them.Keyring.Record,RecordOrFail,RecordRefusal,CountEntries,AccountsFromandPullAlertsreach the security log.Keyring.Assess,Enforce,NewAssessment,AssessmentOf,IsRiskLockedandSignalsAtreach risk, for a step of your own.- There's no service to sign a user out everywhere from your code. Run
keyring:sign-out, or answerfalsefromAllowSignInWhen, and Keyring signs every session out on its next request.
Test Helpers
keyringtest.New[U](t, client)gives the helpers for one test's application, and has its refusals answer at once, asInteractsWithKeyringdoes for a test case.kt.Fake()starts a new fake that decides in place of an earlier one rather than returning it, its assertions with a count areTimesmethods, and it's undone when the test ends, so a subtest's fake gives way to its parent's again.- Acting as a session that proved something is
kt.ActingAs(&user, proofs), withkeyringtest.Assurance(level)orVerifiedWith(...)andFreshAt(at)for a time, not methods on the test case. - Factory states are values given to
kt.Add(&user, ...).RecoveryCodes()is a new set Keyring made, returned with its codes, rather than the PHP factory's fixed ones, and there's nosecurityKey()orattested(), as Keyring for Go has no security keys or attestation. VirtualAuthenticatorregisters with anoneattestation only, and there's noVirtualManufacturer.FakeIdentityProvidergoes in Keyring's settings withRegister(name)and isServed in the test, throughhttpclienttest.Conformanceis a struct whoseRun(t)runs each check as a subtest on an application of its own, rather than a trait of test methods. It acknowledges dangerous steps and unchecked routes withAcknowledgedDangerousStepsandAcknowledgedUncheckedRoutes, checks the email and password are protected throughmodel.Update(or itsUpdate, for an application withGuardChangesManually), and doesn't check that a registry returns what it revokes or keeps a session's handle when it moves (Keyring for Go has one registry), nor bcrypt's half of the 64-character password check (Laravel Go only hashes with bcrypt).
What Laravel Go Would Need
What the Go port works around, and the Laravel Go API that would let it match the PHP package. "As laravel-rust" means the Rust crate lacked it too.
| Missing in Laravel Go | What It Would Give | What the Go Port Does Instead |
|---|---|---|
Signing out one browser (logoutCurrentDevice()), as laravel-rust |
Signing out without a new remember token. | Empties the session and takes both remember cookies back itself, keeping the token. auth.Logout only for POST /logout, but while impersonating, and where a record can't be ended. |
| Destroying another session by its ID, or the session store from a request, as laravel-rust | Removing an ended session's data at once. | The record's check signs that browser out on its next request. |
viaRemember(), and knowing the guard queued its remember cookie, as laravel-rust |
Telling a remember cookie's sign in. | Tells it by the session ID changing. Keyring's own sign ins know they asked for it. |
Laravel's auth events (Login, Logout, Failed, Lockout, PasswordReset, Registered, Verified), or a hook before auth.Login writes the session, as laravel-rust |
Writing a sign in's record alongside it, and seeing your own sign out as it happens. | Dispatches its own events, and notices your sign out once the handler returns. |
| A per-request clock, or a public way to move the application's | A test clock for one request. | The contract app moves the application's clock with reflect and unsafe, under a lock. |
A route-level session lock (->block()), as laravel-rust |
Taking the session lock for a route. | BlockSession, on a cache lock. |
A fixed-window rate limiter with decay, lock keys and availableIn(), as laravel-rust |
Counting attempts as Laravel's RateLimiter. |
Keeps its own counts in the cache, outside any transaction. |
A public way to reach the application's auth.Users[U] |
Finding users exactly as the guard does. | auth.ModelUsers[U] on Config.Username, or the users given to Keyring.FindUsersWith. |
| A package placing middleware after the application's own | Appending AuthenticateSession after your auth.Session. |
Runs auth.Session[U] inside AuthenticateSession[U]. |
| A validation error with a status other than 422 | A lockout's 429 with its message on the field. |
Wraps the error with a 429 status. A browser gets the 422. |
| A translator and locale, as laravel-rust | Translating Keyring's messages. | English only. |
Reset tokens in password_reset_tokens, as laravel-rust |
Reset links either side sends working on the other. | Keeps the tokens in that table itself, as Laravel's DatabaseTokenRepository. |
| Keeping other sessions when the password changes, as laravel-rust | sign_out_others: false honoured. |
Ends the other records as password_changed either way, and signs this session in again with auth.Login. |
| A generic OpenID Connect driver that checks the ID token | Single sign-on through the framework. | Keyring's own OpenID Connect client, with the jose and hosts packages. |
| A DNS resolver the HTTP client is pinned to, as PHP | Checking an endpoint's addresses and connecting to the same ones. | Resolves a name itself, then the client resolves it again. |
| TOTP and WebAuthn, as laravel-rust | Keyring's own totp and webauthn packages. |
|
| A QR code renderer, as laravel-rust | An authenticator app's QR code. | rsc.io/qr, drawn as an SVG of Keyring's own. |
session.CreateTable's last_activity as PHP's integer |
One sessions table for both sides. |
Each side keeps its own session table. Keyring's tables are shared. |
| Timestamps at PHP's precision by default | Y-m-d H:i:s without thinking about it. |
Keyring's columns are whole seconds and every time it writes is cut to the second. Set DB_TIME_PRECISION=0 for what Laravel Go writes itself, such as email_verified_at. |
A MustVerifyEmail a user type opts into |
Telling a type that verifies its address from one that just has the column. | Features.EmailVerification. |
A timestamp column of PHP's timestamp type on MySQL |
Identical MySQL schemas. | Not checked yet. |
| Argon2 hashes | Checking Argon2 passwords a PHP application made. | bcrypt only. |
A request of its own per test request on laraveltest.RefreshDatabase's transaction |
Requests a test makes at once each waiting for the other. | Runs each request on a db.Concurrent branch. A request a test makes while its own code holds a savepoint on the client's context hangs until the test times out. |
| Named log channels a package can write to | The security log's fallback in a channel of its own. | slog.Default(), under a keyring group. |
A hook around StartSession's load and save |
Overlapping requests without workarounds. | A wrapped store on the web group's StartSession. Others aren't covered. |
Removing a cookie from a web.Response |
Taking a session's cookies off an overlapping request's answer. | Renames each to nothing, which net/http never writes. |
A CSRF check that doesn't pass on Sec-Fetch-Site alone |
The PHP package's 419 for a request on a destroyed session. |
Takes the header off such a request. |
FOR NO KEY UPDATE in the query builder |
The user's row lock without raw SQL. | Raw SQL on PostgreSQL. |
| A middleware seeing the route's other middleware with their values | RequireEnrollment saving a page with what a RequireAssurance on the route asks. |
RequireEnrollment takes the same options. Give it the route's. |
Sec-Purpose: prefetch;prerender read as a prefetch |
StartSession not noting a prerender as the last page seen. |
Keyring reads it as Laravel does for its own pages. |
redirectUsersTo(), and an unnamed /dashboard or /home route |
Choosing where a signed-in browser at a guest page goes. | Asks the dashboard and home route names, then the site's root. |
| Session payloads and the remember cookie in PHP's format, as laravel-rust | One session store for both sides. | Not shared. |
| A request's attribute bag | Keeping a request's location once looked up. | A memo in the request's context. |
| Telling whether a named cache store exists without using it | Register refusing a Risk.Store that isn't configured. |
The first lock panics, a 500. |
| A pipeline of types the container resolves, as laravel-rust | Steps an application names, Keyring's own among them in any order. | Steps[U] of Step[U] values between VerifyFactor and CompleteAttempt, Keyring's checks around them fixed. |
| Cache values in PHP's serialized format | Sharing codes, risk locks and discovery documents with PHP on one store. | Each side reads only what it wrote. |