Repository navigation
Releases
Releases · keyringphp/keyring
v0.4.0
Single Sign-On
- A
SingleSignOnfactor signs users in with identity providers, with no other package: Google, Microsoft (any tenant, organisations, personal accounts, or one tenant), GitHub, and any OpenID Connect provider through discovery. Configure them under the newssoconfig section, and register drivers of your own withKeyring::sso()->extend(). See Single Sign-On, and More Identity Providers for the config of eight more OpenID Connect providers and drivers for Discord, Bitbucket, Facebook, and LinkedIn. GET /auth/{provider}/redirect(keyring.sso.redirect) sends a guest to the provider, andGET /auth/{provider}/callback(keyring.sso.callback) is the one URL each provider sends users back to, for signing in, for linking and for confirming. They're only registered whensso.providerslists a provider, and answer404until the factor is registered. The callback only finishes Keyring's own sign ins, links and confirms, and a guest's draws on thekeyring-login-optionsrate limiter. Theloginpage gets aprovidersprop with each provider'sname,labelandurl. A provider that can't be built, such as one missing itsclient_id, one whose name holds more than letters, digits,-and_, or one whosescopes,parametersortoken_endpoint_auth_methodisn't something it can take, is reported and left off the page rather than failing it. A callback whose request has expired, while someone is signed in, fails straight away rather than as a link, without asking for a fresh verification or logging a refused link: a confirm goes back to the confirm page withexpired, even once the confirm itself has run out, and a link back to the page it was started from withenrollment_expired. One whose request this browser doesn't have at all goes back to the confirm page withexpiredwhile a confirm is in progress, andhomeotherwise.- A sign in with a provider goes through the same pipeline as the login form, so rate limits, the policy and risk apply, and a user with a second factor is still asked for it. It counts as a knowledge factor, like the password, and is never offered on the challenge page.
- A sign in, or a new link, with a provider whose
freshnessisreauthenticatecounts towardkeyring.freshfrom itsauth_time, which Keyring asks for where the provider takes theclaimsparameter, so one the provider let straight through on an old session isn't a fresh verification, and one withoutauth_timenever is. Withneverit never counts. Its session and assurance level still start when the user came back either way. Only a provider opted intoround_tripcounts from when the user came back, whateverauth_timeit sends.Verificationhas a newauthenticatedAt, withVerification::UNKNOWNfor a provider that didn't say when,provedAt()gives the earlier of the two, andSessionAssurance::provedSince()is what freshness reads.SignIn::enrolled()takes theVerificationadding a method proved. - A link confirms a step-up: the confirm page offers it, with the new
GET /confirm/sso/redirect(keyring.sso.confirm) in itschallengeasurl, which sends the user back to the provider with the link's address aslogin_hint. A provider whosefreshnessisreauthenticateis sentmax_age=0, withprompt=loginwhere it takes it (not at Google, and in place ofmax_ageat Microsoft), and the confirm needs anauth_timeno earlier than when the user was sent there, give or take a minute. One opted intoround_tripgets a plain round trip, which counts as much as signing in with it again does. One that'snevergets a plain round trip too, which counts toward the session's level, as signing in again would, and never towardkeyring.fresh, so it's only offered toward a level, such as after AAL2 lapses.keyring.freshonly asks for what can be proved recently, so a user with aneverlink and a second factor, and no password, confirms with the second factor alone, and one who can't confirm at all getsenroll-firststraight away. The round trip never sets Laravel'sauth.password_confirmed_at, and a visit to/confirmof the user's own, wherepassword.confirmsends them, only offers what can be proved recently, so a user still signed in to GitHub doesn't passpassword.confirmwithout typing anything.StepUp::unlessMet()andmeets()with both a level and a moment ask for them in turn, the level first, when the account can't freshly prove the level, so a user with aneverlink and an authenticator app, and no password, isn't sent to enroll. A recovery code isn't offered on a fresh verification that only the link could finish beside it. The callback only confirms the same account, for the user and the confirm that started it, and goes through the confirm page's pipeline, so rate limits and events apply as they do there.IdentityProviderhas a newsupportsReauthentication(), saying whether the provider can be asked, andfreshness(),Keyring::sso()->start()takes amaxAgeand aloginHint,AuthorizationRequestkeeps when it was made (createdAt), andcomplete()refuses an identity without a recent enoughauthTimewith the newSsoFailure::StaleAuthentication. - A user held for a new password can confirm with a link too: the hold lets through
keyring.sso.confirm, and the provider's callback for a confirm, though not its callback for a new link. A confirm's callback that comes back late, or is used up while the confirm is still in progress, fails as it would without a hold. - A provider's
freshnessoption, aKeyring\Enums\SsoFreshness, says how much its sign ins and confirms count towardkeyring.fresh:reauthenticate,round_trip, ornever(orfalse). The defaults are the most secure each driver can give:reauthenticateforoidc, which asks forauth_timewith theclaimsparameter where discovery says it's taken, and formicrosoft, which needs theauth_timeoptional claim added to the app registration (without it no sign in is fresh, and a confirm fails with a reportedStaleAuthenticationthat says what to add), andneverforgoogle,github, and drivers built onOAuth2Provider.round_tripis only ever an opt-in.reauthenticatethrows anInvalidArgumentExceptionfor a provider that can't be asked, such as GitHub. When a link's provider and the one a sign in came through differ, the stricter counts, so renaming or removing a provider never makes a sign in count for more. A link only takes the name of the provider a sign in or a new link of the same account came through once its own is no longer configured, so the stricter keeps counting however many sign ins come through the other. The config'sfreshnesswins over a driver's ownfreshness(), for drivers of your own too, andKeyring::sso()->freshness()gives the value that counts. A user whose only way in is aneverlink can't make protected changes, and gets out with a password reset. See Freshness. - Accounts at providers are matched on their issuer and subject, never on the email address. Nobody is signed up or linked by their address, and an account nobody linked gets the same error as a wrong password. Users link accounts from your settings page with
POST /user/authenticators/sso, which needs a fresh verification and a verified address, and unlink them like any other authenticator. A link comes with no recovery codes and is never the default. - Every request carries PKCE (S256), a
statekept in the browser's session and used once, and for OpenID Connect anonce. ID tokens are checked for their signature against the provider's published keys, issuer, audience, times and nonce, and a callback naming another issuer (RFC 9207) is refused. Microsoft addresses count as unverified unless the tenant vouches for the domain withxms_edov, and a GitHub address only counts as verified when it's the primary one GitHub has verified. - A completed password reset unlinks every provider linked to the account, before it signs every session out and again after, and an undone email change unlinks the ones linked since. The
ssofactor key is reserved for the factor. - A user who says no at the provider is sent back with the new
sso-cancelledstatus. Failed sign ins are logged asfactor_failed, and refused links asenrollment_refused. EverySsoFailedKeyring catches is reported to the exception handler, apart from a user saying no and a spent or unknown state (SsoFailed::expected()). - Discovery documents and key sets are only cached once they've been checked, and a provider's RSA keys have a 2048-bit floor of their own (
SignedToken::SHORTEST_RSA_KEY), apart from passkeys'minimum_rsa_bits. An issuer elsewhere can't name plain HTTP endpoints, nor a token endpoint or key set on a private or local address other than on its own host and port, unless the newprivate_endpointsoption says it may. Microsoft'sorganizationstenant refuses personal accounts. token_endpoint_auth_methodtakesnonefor a public client, and a driver built onOAuth2Provideradds values of its own withallowedAuthMethods().scopesleaves out anullor empty string, so anenv()can turn one off.FactorFailedhasfirstFactor()andafterFirstFactor(), andafterPassword()is now onlytrueafter the password. A second factor failing after a sign in with a provider is still logged assecond_factor_failed, and its email names the link that was used instead of saying the password was entered.- Laravel's
Failedevent only takes the username from the request for a factor that asks for one, so an identity provider's callback can't put one there with its query string. Keyring\Testing\FakeIdentityProviderstands in for a provider in tests, with really signed ID tokens carrying anauth_time(leave it ...
v0.3.0
Sessions and Devices
- A session keeps its handle when it moves to a new record: when "remember me" carries it on, when a risk response asks it to verify again, and with
rotateon thecookiesession driver. Each record names the one the session started on (origin), and the handle comes from that. Sessions that started before the upgrade keep the handles they had. Needs a new migration, see the upgrade guide. Sessions::stillSignedIn($user, $handle), for code that knows a session by its handle to ask whether the user is still signed in on it. It appliesKeyring::allowSignInWhen()and the session's timeouts, and it changes nothing.- A conformance check that the session registry keeps
originwhen a session moves, so a missing migration or a custom driver that drops it is caught in your tests. - The session registry says which records it revoked.
revoke()returns the record it revoked, ornullwhen it revoked nothing, andrevokeAll()andrevokeDevice()return the records they revoked instead of a count. Custom registry drivers need to return them too: see the upgrade guide.Sessions::signOutEverywhere(),Sessions::revokeDevice()and theSessionsRevokedevent still give a count. - The conformance suite checks that the configured registry returns the records it revoked.
- A
RegisteredSessionEndedevent for every registered session that ends, whoever ends it and wherever: signing out, the app's ownAuth::logout()orAuth::logoutCurrentDevice()(announced aslogged_outunless the app gives a reason of its own withSessions::because()), signing out everywhere, ending a session or a device, the device and session limits, a deleted user, a risk response, a password change or reset, an email change or its undo, and the session middleware finding a session idle, expired, used twice or kept out. It names the session by its handle, with the handle under each previous app key too, and says why it ended (Keyring\Enums\SessionEndReason). It never carries the registry ID. On thedatabasedriver it goes out once the transaction it was revoked in commits, and not at all if that's rolled back. A listener that throws is reported and doesn't stop the sign-out. See Hearing About Ended Sessions. - An
EveryoneSignedOutevent whenkeyring:sign-out --allor the registry'srevokeEveryone()ends every user's sessions at once. - Every registry driver, a custom one included, is wrapped in
AnnouncingSessionRegistry, which dispatches those events from what the driver returns.app(SessionRegistry::class)returns the wrapper, and itsinner()the driver. See the upgrade guide. - A conformance check that signing out announces the session that ended, which fails when a
SessionRegistryis bound in the container without the wrapper. - A driver that fails after revoking some of a user's records throws a
PartialRevocationwith the ones it revoked, so they're still announced. Thecachedriver does this when the store fails part way through signing out everywhere, and keeps a revocation whose copy into the record fails. On thecachedriver only, what a synchronous listener wrote on the user's connection is kept too, when Keyring's row lock is the outermost transaction: inside one of the app's own, the failure still rolls it back unless the app catches it. A database failure, deadlocks and lost connections included, always rolls it back. On thedatabasedriver with the registry on the user's connection, the failure rolls back the whole change, a sign in's new record included. With the registry on asessions.connectionof its own, it behaves as thecachedriver does. On either driver, signing out everywhere still cycles the remember token, stops trusting devices and cancels a pending email change before the failure is thrown, signing a device out still cycles the remember token, and signing out everywhere else still gives this session a new ID. - Registry IDs are marked
#[\SensitiveParameter]on the contract, both drivers andSessions, so they stay out of reported stack traces. keyring:sweep, which ends sessions that timed out with no request to end them and announces them asidleorexpired, and announces again any ended session whose event was lost, so every ended session is announced at least once on thedatabasedriver. Turn it on withsessions.sweep_every, and Keyring schedules it before the prune, on one server and never overlapping. One run announces again, and ends, at mostsessions.sweep_limit(1000) sessions each. A listener that throws is tried again five minutes later, then at doubling intervals for a day. Needs a new migration, see the upgrade guide.- Once the new migration has run,
keyring:prunekeeps sessions a sweep still has to end or announce, whether or not one is scheduled. An expired session nobody ended stays up to a day longer before the prune removes it, and so does one the sweep ended for timing out, so its browser is still told why. keyring:sign-out --allmarks the sessions it ends for itsEveryoneSignedOut, so the sweep never announces them one by one, and counts them announced once the event has gone out. If it didn't, the sweep dispatchesEveryoneSignedOutagain, up to a day later, the latest of any lost ones, which settles the rest. Itsatis a cut-off on sign-in time, never "end everything now".- With the migration run, a record "remember me" moved a session to stays until it expires, so a used cookie still raises
RememberMeReusedafter the sweep ended its session and the prune ran. RememberMeReusednow also fires when the session a used cookie was carried on to has timed out since, so a sweep ending that session doesn't hide the reuse. The used record is revoked then, so the same cookie is reported once.- A browser that comes back after its session was revoked once it had timed out, by the sweep or by signing out everywhere, is signed out as
idleorexpired, inSessionEndedand the security log, as it would be had nothing revoked it first. It used to sayrevoked. One the sweep ended keeps saying so until a day after its expiry. One signed out everywhere says so until the prune removes its record, a day at most. - The database registry driver rethrows a failed query without its bindings, so record IDs, which are what "remember me" cookies hold, stay out of exception messages, logs and error trackers.
PartialRevocationno longer repeats the failure's message. - On the
cachedriver, revoking a record and moving it with "remember me" take turns under the owner's lock (on a store with locks), so a sign-out that lands mid-move is never lost without an event. A revocation that can't have the lock within five seconds goes ahead without it. On adatabasecache store, a failed cache query is rethrown without the cache keys it named, which hold record IDs. - Signing out signs the browser out even when the session registry fails to revoke its record. The failure is still thrown, but the next request is a guest, where it used to be registered as a new session.
sessions.continue_as_guestlists routes that also serve guests. A page visit to one whose session has ended is signed out and asked for again as a guest, rather than sent to log in, whatever the reason it ended. Thesigned-outstatus is flashed and no intended URL is saved. JSON requests still get a401.- A sign-out your app does itself with
Auth::logout()orAuth::logoutCurrentDevice(), on Keyring's guard in a request with a session, now ends the registered session too, with its "remember me" cookie and what the session proved. Before, the record stayed good until it timed out. On thecookiesession driver, a copy of the session stayed signed in, and afterlogoutCurrentDevice(), so did a copy of its "remember me" cookies.
Policies and Step-Up
StepUp::unlessMet()to ask for step-up from a controller, for an integration that reads what to ask for from the request, such as an OpenID Connect provider withacr_valuesandmax_age. It takes anAssurancelevel, a moment the user must have verified since, or both, and gives the same answer as thekeyringandkeyring.freshmiddleware. Asking for nothing, or for a moment more than a few seconds in the future, throws.StepUp::meets()to ask the same thing without starting a step-up, for a request that mustn't show the user anything, such as one withprompt=none. It takesunlessMet()'s arguments and returnstruewhereunlessMet()returnsnull, and leaves no confirm attempt or page to come back to in the session.keyring:{level}gives a guest Laravel's usualAuthenticationExceptioneven when the session still holds what the last user proved, askeyring.freshalready did. A session keeps that when the guard can no longer load its user, say because the account was deleted, and on a route withoutauth, the guest used to get through on it.- The docs explain how to read what a session proved, for claims like
amr,acr, andauth_time. SessionAssurance::level()andcountingToward()take a timestamp, to count only what was proved since then with each level still on its own clock, so claims built formax_agedon't report a level that lapsed.- Users sent to enroll by
keyring.enrolled, by step-up, or by the confirm page with nothing to confirm with now get the page they were going to back ascontinueon theauthenticator-addedstatus. Users held for a new password are redirected there bypassword-updated. Only top-level navigations and Inertia visits are remembered, and only on the app's own origin, for the same user, within an hour. Bind your ownKeyring\Login\Detoursand overrideput()to keep other pages out, such asprompt=noneauthorize requests.
...
v0.2.0
Rate Limits and Risk
- A
CredentialStuffingrisk signal, off until you turn it on: a sign in from an IP address where five or more other accounts failed a factor in the last hour. It reads the security log, and the published provider lists it commented out. Keyring's own response emails the user whenever it fires, as it does for a sign in after several failures.
v0.1.0
The first release.
Signing In
- Sign in, sign out, registration, password resets and email verification, with your own actions and pages.
- Registration that doesn't reveal who has an account: the same answer for a free and a taken address, even when your action fails to create the user, with new users signing in once they've verified theirs, from the browser that followed the link, which gets a new session ID for it.
registration.reveal_takensays when an address is taken instead. - Factors behind one contract: password, authenticator apps, passkeys, security keys, email codes and recovery codes, plus your own. Many authenticators per user, with a default and "try another way".
- Passkeys and security keys from one WebAuthn driver: ES256 and EdDSA by default, RS256 when you ask for it, a challenge that is answered once and runs out on the server, and sign in with Laravel's
@laravel/passkeysclient. Like Laravel's passkeys package, the options name the relying party by its ID, so there's no name to set. WebAuthn::securityKeys()->requireAttestation()to only add hardware keys whose attestation chains to root certificates you list, andallowOnly()to limit them to certain models by AAGUID.- Authenticator app codes that work once, with SHA-1, SHA-256 or SHA-512, and a window of one time step or none.
- Email codes as an extra step at sign in. They are opt-in and never count as a second factor.
- Recovery codes of 128 random bits, stored as keyed hashes, with a flag that says when a used set should be replaced.
Keyring::attempt()to start a sign in from your own route, for social logins and the like.Keyring::allowSignInWhen()to keep banned or unapproved accounts out, however they try to sign in. The first request it refuses ends every session the account has.- A verification pipeline you can add steps to, with the steps that enforce Keyring's guarantees protected from being removed by accident.
Policies and Step-Up
- Policies built from assurance levels that follow NIST SP 800-63B-4: AAL2 needs a factor the user has, and AAL3 an attested key that can't leave its device.
ifEnrolled()andnoDowngrade()say how a policy treats users who can't meet it yet, or who have a passkey. keyring.enrolledto make everyone set up a second factor, which the installer adds when you pick one.- Step-up middleware:
keyring:aal2andkeyring.fresh:15m, with a shared confirm flow. Changing how an account signs in takes the strongest proof the account can give, and a recovery code only counts there beside another factor.
Sessions and Devices
- A registry of signed-in sessions that works on any session driver: a list of the user's sessions to end one by one, signing out everywhere else, a limit on sessions per account, and idle and absolute timeouts kept on the server.
- Assurance levels that lapse on NIST's clock, with
sessions.end_on_lapseto end the session with its level. - "Remember me" tied to the session it was ticked for: it carries that session on and can't outlast its timeouts, a revocation or a risk response. Its cookie works once and is replaced each time. A used one sent again ends the session for everyone holding it, with a
RememberMeReusedevent and aremember_me_reusedlog entry. - Devices: trusted devices, new-device emails with a "this wasn't me" link, and a limit on devices per account.
Secure,__Host-prefixed cookies named for what they do (known_device,remembered_session).keyring:sign-outto end one user's sessions or everyone's.
Account Changes
- Protected
emailandpasswordattributes, which only change through Keyring's flows once it handles them. - Email changes confirmed from both addresses and revertable from the old one, with the old address reserved while they can be undone.
- Password changes that take the current password and are only saved over the one that was checked, and resets that sign nobody in, end every session and leave second factors alone.
- Password rules that follow OWASP ASVS 5.0.0 and NIST SP 800-63B-4: 15 characters alone or 8 with a second factor, no composition rules, a bundled list of the most common passwords, your own context words, a breach check that can refuse what it couldn't check, Unicode normalised to NFC, and, with bcrypt, a password it would cut short or can't hash refused.
Keyring::requirePasswordChange(), and a risk action of the same name, to hold a user until they choose a new password when theirs is known to someone else.- Emailed links that only act on a button press, with the token or signature posted in the body, built from
APP_URLand opened on pages that send no referrer.
Rate Limits and Risk
- Rate limits per account, per typed username and per IP address, with locks that double, a count of their own for browsers the account has signed in from, a cap on failures in a row kept in the database, and
limits.lock_afterto keep an account locked until its password is reset. - A timebox around every verification, registration and refused password reset, so a refusal takes the same time whatever the reason.
- Risk signals with an action for each level: a new device, a new country, impossible travel, a session turning up in another browser, repeated failed second factors, a sign in after several failures or after a long quiet period, a recently changed email address and a password found in a breach. A new app starts with the ones its features can feed, and a password found in a breach holds its user until they choose another.
Logging and Emails
- A security log with a severity and a request ID on every entry, of sign ins, sessions "remember me" carried on, failures, lockouts, changes and what was refused, capped so a refused request can't fill it, and written whatever text an entry is about. Without the table it goes to your app's log.
- "Was this you?" alerts at the next sign in.
- Security emails about changes to how an account signs in and about suspicious attempts, sent from the start as far as your features go. Each is a notification you can swap for your own or turn off, and
SecurityNotice::toMailUsing()writes them all from your own template. support_contact, so every notice can say who to contact.Keyring\Events\*for everything above, with Laravel's own auth events raised beside them.
Tooling
keyring:install, which asks which sign-in methods and features you want and publishes a config, a provider and your actions. Its defaults give the password alone, and every other sign-in method is in the provider, commented out, to turn on later. Alsokeyring:import fortify, andkeyring:prune, scheduled daily.- Security headers on Keyring's responses:
Cache-Control: no-store,X-Content-Type-Options: nosniff,X-Frame-Options: DENY,Cross-Origin-Opener-Policy: same-origin-allow-popupsand a referrer policy. Keyring::result(), for a page to read what a form or Inertia response flashed for it, such as new recovery codes, which is kept encrypted in the session.- Test helpers, a fake, factories, a virtual WebAuthn authenticator and a conformance suite that checks your setup still keeps Keyring's guarantees.
@keyringjs/keyring, a browser package for WebAuthn, enrollment, sessions and the challenge page, with Vue and React bindings.- Documentation of where Keyring stands on every requirement of OWASP ASVS 5.0.0 and NIST SP 800-63B-4 that bears on it, and of each place it deliberately does something else.