From b1648080e49b4a24867e78bfdad27b892c3e21e4 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Tue, 17 Nov 2026 20:22:34 +0000 Subject: [PATCH 1/9] fix(step-up): count a recovery code only beside another factor, and remove codes an undone email change leaves nothing to recover --- CHANGELOG.md | 2 +- docs/protected-changes.md | 4 +- docs/security.md | 6 +- docs/step-up.md | 2 +- src/Changes/EmailChanges.php | 20 +++- .../Middleware/RequireFreshVerification.php | 24 +++- tests/Feature/CustomFactorTest.php | 18 +++ tests/Feature/EmailChangeHardeningTest.php | 107 ++++++++++++++++++ tests/Feature/StepUpTest.php | 48 ++++++++ 9 files changed, 216 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d2132a1a..6e369a69 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,7 +22,7 @@ The first release. Nothing is tagged yet. - 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()` and `noDowngrade()` say how a policy treats users who can't meet it yet, or who have a passkey. - `keyring.enrolled` to make everyone set up a second factor, which the installer adds when you pick one. -- Step-up middleware: `keyring:aal2` and `keyring.fresh:15m`, with a shared confirm flow. Changing how an account signs in takes the strongest proof the account can give. +- Step-up middleware: `keyring:aal2` and `keyring.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 diff --git a/docs/protected-changes.md b/docs/protected-changes.md index 297c9f63..b7e9b7a8 100644 --- a/docs/protected-changes.md +++ b/docs/protected-changes.md @@ -112,7 +112,7 @@ A `MustVerifyEmail` user whose address isn't verified yet is refused with `keyri ### Confirming -The new address must always confirm. The current address must confirm too, unless this session proved a possession factor the account has had for `email_changes.established_after` (7 days by default), and since before this session signed in. A newer factor doesn't count, so whoever got in can't add one, use it and skip the check, in the same session or by signing in again with it. Neither does another account's factor, so an impersonated or switched session can't skip it with the admin's. +The new address must always confirm. The current address must confirm too, unless this session proved a possession factor other than a recovery code that the account has had for `email_changes.established_after` (7 days by default), and since before this session signed in. A newer factor doesn't count, so whoever got in can't add one, use it and skip the check, in the same session or by signing in again with it. Neither does another account's factor, so an impersonated or switched session can't skip it with the admin's. The change applies once every required confirmation is in. When it applies, Keyring checks the address is still the one the change was requested from, and that no one else has taken the new one in the meantime. If either has changed, the pending change is cancelled. Applying also sets `email_verified_at`, when the model has that attribute loaded, and stops trusting the user's devices. @@ -147,7 +147,7 @@ The current address can revert the change while it's pending, and for `email_cha - puts the old address back, even when it was a later change that moved it, - cancels any later email changes, so links from them can't move the address away again, -- deletes every authenticator that wasn't established when the change was asked for (added within `email_changes.established_after` before it, or since the session that asked signed in), one at a time, dispatching `AuthenticatorRemoved` for each. That can include one the owner added that week, which they can add again, +- deletes every authenticator that wasn't established when the change was asked for (added within `email_changes.established_after` before it, or since the session that asked signed in), one at a time, dispatching `AuthenticatorRemoved` for each. That can include one the owner added that week, which they can add again. When none of what's left is a factor for recovery codes to recover, the codes go too, as they do when the user removes their last second factor, with an `AuthenticatorRemoved` of their own, - signs out every session, and changes the "remember me" token. The user is then redirected to the forgot password page (or the login page, when password resets are off) with `status` set to `email-change-reverted`, since whoever made the change may also know the password. Reverting doesn't change the password itself. diff --git a/docs/security.md b/docs/security.md index 9bc1d868..5d4d4c3f 100644 --- a/docs/security.md +++ b/docs/security.md @@ -159,7 +159,7 @@ The failures in a row and the locks held until a reset are in your database eith - The first recovery codes are shown to a session that has proved two factors: confirming a new sign-in method takes proving it, and the session counts that proof from the same response (NIST SP 800-63B-4, Sec. 3.1.2.1). Later sets need a fresh verification of both. - With `noDowngrade()`, users with a passkey or security key can't be offered a weaker way in. Recovery codes stay on offer as the way back in, unless you pass `except: []`. - With `ifEnrolled()`, a policy the user can't fully meet still asks for the strongest version they can give, so a user with a second factor never signs in with one factor. -- Adding, removing or changing sign-in methods, revoking devices, changing the password and starting an email change need a fresh verification with the strongest combination the account can give, and at least what signing in would ask (NIST SP 800-63B-4's rule for binding authenticators, Sec. 4.1.2.1). Users with a possession factor always use one, and users with a key that can't leave its device use that, so a stolen session plus a phished password and code isn't enough. A recovery code with the password stands in for a lost key, as NIST's account recovery allows. +- Adding, removing or changing sign-in methods, revoking devices, changing the password and starting an email change need a fresh verification with the strongest combination the account can give, and at least what signing in would ask (NIST SP 800-63B-4's rule for binding authenticators, Sec. 4.1.2.1). Users with a possession factor always use one, and users with a key that can't leave its device use that, so a stolen session plus a phished password and code isn't enough. A recovery code with the password stands in for a lost key, as NIST's account recovery allows. At a step-up a recovery code never counts on its own, so an account with nothing but a set of codes beside its password confirms with the password. - The fresh window is fixed from the moment of verification and doesn't slide with activity. - Users can't add a sign-in method until their email is verified (with `MustVerifyEmail`), so someone who registers an address first can't plant a factor that survives the real owner's password reset. With registration on, a user model that can't verify its email can't add sign-in methods at all. - Users can't remove authenticators below what they need to sign in, even with several removals at once. @@ -191,12 +191,12 @@ The failures in a row and the locks held until a reset are in your database eith ### Account Changes - With `Features::updatePasswords()` and `Features::emailChanges()` on, `password` and `email` can only change through Keyring's flows. Bypassing that needs `Keyring::withoutProtection()`, which is announced and logged. Without them, your app changes those attributes itself. -- An email change needs a fresh verification, confirmation from the new address, and confirmation from the current address unless the session proved a second factor the account has had for a week (`email_changes.established_after`) and since before it signed in. +- An email change needs a fresh verification, confirmation from the new address, and confirmation from the current address unless the session proved a second factor the account has had for a week (`email_changes.established_after`) and since before it signed in. A recovery code isn't one. - An email change never reveals whether the new address has an account, in its answer, its timing or the pending change it shows: its emails, like the reset email, are sent after the response. - An email change only applies if the address is still the one it was requested from. - Emailed links (email verification, email change confirm and revert, and "this wasn't me") only act on a button press (a POST), so mail scanners that open links change nothing. No `GET` route of Keyring's changes state. The page posts the link's token or signature in the body to a URL without it, as the password reset does, so the request that acts doesn't leave it in access logs a second time. - A password reset with a bad token gets the same answer for every address. Password rules, which are shorter for accounts with MFA, only run once the token checks out. -- Reverting an email change signs out every session, ends any sign in still waiting for its second factor, closes later changes and removes sign-in methods that weren't established when it was asked for. Cancelling a change doesn't stop its revert link working. +- Reverting an email change signs out every session, ends any sign in still waiting for its second factor, closes later changes and removes sign-in methods that weren't established when it was asked for, with the recovery codes when none of what's left is a factor for them to recover. Cancelling a change doesn't stop its revert link working. - While an email change can be reverted, nobody else can take the address it replaced, so the revert always has somewhere to put it back. - Password resets give the same answer for every address, sign out every session, cancel pending email changes, and lift risk locks and sign-in lockouts. - A password change takes the current password as well as a fresh verification, checked by Keyring itself rather than by your action. A user with no password yet sets one with the fresh verification alone. diff --git a/docs/step-up.md b/docs/step-up.md index a4b9b3e8..de00c492 100644 --- a/docs/step-up.md +++ b/docs/step-up.md @@ -67,7 +67,7 @@ NIST SP 800-63B-4 (Sec. 4.1.2.1) has a new authenticator bound at the highest le - Users with only a password confirm with their password, so an account can always add its first sign-in method. - Users with two factors prove both again, even where the policy would sign them in with one. A stolen session plus one phished factor can't add, remove or change anything. - Users with a key that can't leave its device use it, with its own user verification or their password beside it. A password and an authenticator app's code isn't enough for them, whatever the policy says. That goes for an attested key, which could reach AAL3, and for one nothing vouches for. -- A recovery code stands in for a lost key, with the password, as it does at sign in. A policy that takes none there (`noDowngrade(except: [])`, or an explicit `phishingResistant()`) takes none here. +- A recovery code stands in for a lost key, with the password, as it does at sign in. A policy that takes none there (`noDowngrade(except: [])`, or an explicit `phishingResistant()`) takes none here. A code is never the whole of a confirmation: a user whose only other sign-in method is a set of recovery codes confirms with the password, and isn't offered the codes. - Users who have any possession factor (an authenticator app, a passkey or a security key) always use one. An [email code](factors.md#email-codes) isn't one, so it can't stand in. A user whose only other sign-in method it is proves the password and an emailed code, which is what lets them add a real second factor. - A policy the user can't fully meet yet (one that asks for a passkey they haven't added) counts as far as they can, so they can still add it. - A policy that asks for more than that is heard. A [policy closure](policies.md#deciding-per-user-and-attempt) is asked about the browser the request comes from, and about one nothing is known of, and the stricter answer stands. A policy that asks more of a new device is honoured, and a trusted device gets no discount. Risk isn't assessed again, so a policy that reads `$attempt->risk` is asked with none. diff --git a/src/Changes/EmailChanges.php b/src/Changes/EmailChanges.php index 691af524..630be32f 100644 --- a/src/Changes/EmailChanges.php +++ b/src/Changes/EmailChanges.php @@ -21,6 +21,7 @@ use Keyring\Events\EmailChangeReverted; use Keyring\Events\LinkRefused; use Keyring\Exceptions\MissingNotification; +use Keyring\Factors\RecoveryCodes; use Keyring\KeyringManager; use Keyring\Login\Verification; use Keyring\Models\Authenticator; @@ -350,6 +351,7 @@ protected function sessionProvedEstablishedSecondFactor(Authenticatable&Model $u $ids = collect($this->assurance->all()) ->filter(fn (Verification $verification) => $verification->authenticator !== null + && $verification->factor !== RecoveryCodes::KEY && in_array(Category::Possession, $verification->categories, true)) ->map(fn (Verification $verification) => $verification->authenticator); @@ -482,11 +484,14 @@ protected function unestablishedSince(PendingChange $change): CarbonInterface } /** - * One by one, so each removal is logged and announced. + * One by one, so each removal is logged and announced. Recovery codes + * go too when what's removed was the last factor they recover, as they + * do when the user removes it: left behind, a code would stand where + * that factor stood. */ protected function removeAuthenticatorsAddedSince(Authenticatable&Model $user, CarbonInterface $since): void { - $this->keyring->authenticatorModel()::query() + $removed = $this->keyring->authenticatorModel()::query() ->ownedBy($user) ->where('created_at', '>=', $since) ->get() @@ -494,6 +499,17 @@ protected function removeAuthenticatorsAddedSince(Authenticatable&Model $user, C $authenticator->delete(); AuthenticatorRemoved::dispatch($user, $authenticator); }); + + $keyring = $this->keyring->for($user)->refresh(); + + if ($removed->isEmpty() || $keyring->hasFactorToRecover()) { + return; + } + + $keyring->of(RecoveryCodes::KEY)->each(function (Authenticator $codes) use ($user) { + $codes->delete(); + AuthenticatorRemoved::dispatch($user, $codes); + }); } protected function taken(Authenticatable&Model $user, string $email): bool diff --git a/src/Http/Middleware/RequireFreshVerification.php b/src/Http/Middleware/RequireFreshVerification.php index 1325691b..7c783549 100644 --- a/src/Http/Middleware/RequireFreshVerification.php +++ b/src/Http/Middleware/RequireFreshVerification.php @@ -14,6 +14,7 @@ use Keyring\Login\Attempt; use Keyring\Login\Requirement; use Keyring\Login\StepUp; +use Keyring\Login\Verification; use Keyring\Sessions\SessionAssurance; use Keyring\Support\Duration; use Keyring\UserKeyring; @@ -25,8 +26,9 @@ * signing in would ask of them: both factors for a user with two, and the * key for a user with one that can't leave its device. Adding a sign-in * method takes proving the best the account already has. - * Users with a possession factor always use one. The window is fixed from the - * moment of verification and doesn't slide with activity. + * Users with a possession factor always use one, and a recovery code only + * counts beside another factor. The window is fixed from the moment of + * verification and doesn't slide with activity. */ class RequireFreshVerification { @@ -41,8 +43,13 @@ public function handle(Request $request, Closure $next, string $window = '15m'): { $since = now()->getTimestamp() - Duration::seconds($window); $requirement = $this->requirement($request); + $proved = $this->assurance->since($since); - if ($requirement->isMetBy($this->assurance->since($since))) { + if (! $requirement->acceptsRecoveryCodes) { + $proved = array_values(array_filter($proved, fn (Verification $verification) => $verification->factor !== RecoveryCodes::KEY)); + } + + if ($requirement->isMetBy($proved)) { return $next($request); } @@ -75,9 +82,14 @@ protected function requirement(Request $request): Requirement // it could never add anything again. $requirement = $keyring->reachable($policy->atLeast($this->strongest($keyring, $policy))); - return $keyring->has(Category::Possession) - ? $requirement->atLeast(Requirement::aal1()->including(Category::Possession)) - : $requirement; + if ($keyring->has(Category::Possession)) { + $requirement = $requirement->atLeast(Requirement::aal1()->including(Category::Possession)); + } + + // A recovery code stands in for a lost factor beside another one. It + // is never the whole of a verification: with one factor to prove, + // that factor is what's asked for. + return $requirement->factors < 2 ? $requirement->withoutRecoveryCodes() : $requirement; } /** diff --git a/tests/Feature/CustomFactorTest.php b/tests/Feature/CustomFactorTest.php index 8cb6c2df..d008a63d 100644 --- a/tests/Feature/CustomFactorTest.php +++ b/tests/Feature/CustomFactorTest.php @@ -12,6 +12,7 @@ use Keyring\Factors\EmailCode; use Keyring\Factors\Factor; use Keyring\Factors\Password; +use Keyring\Factors\RecoveryCodes; use Keyring\Factors\Totp; use Keyring\Login\Attempt; use Keyring\Login\Requirement; @@ -205,6 +206,23 @@ public function verify(Attempt $attempt, Authenticator $authenticator, Request $ $this->get('/billing')->assertOk(); $this->get('/app')->assertOk(); }); + + it('takes a recovery code in its place at a step-up, beside the password', function () { + Keyring::factors([Password::class, VoicePrint::class, RecoveryCodes::class]); + Authenticator::factory()->recoveryCodes(['aaaa-aaaa-aaaa-aaaa-aaaa-aaaa-aa'])->for($this->user, 'authenticatable')->create(); + Route::middleware(['web', 'auth', 'keyring.fresh:15m'])->get('/account', fn () => 'danger zone'); + + $this->post('/login', ['email' => 'taylor@example.com', 'password' => 'password']); + $this->post(route('keyring.login.verify', 'voice'), ['code' => 'my voice is my passport']); + $this->travel(16)->minutes(); + + $this->get('/account')->assertRedirect(route('keyring.confirm.challenge')); + $this->post(route('keyring.confirm.verify', 'recovery'), ['code' => 'aaaa-aaaa-aaaa-aaaa-aaaa-aaaa-aa']); + $this->get('/account')->assertRedirect(route('keyring.confirm.challenge')); + + $this->post(route('keyring.confirm.verify', 'password'), ['password' => 'password']); + $this->get('/account')->assertOk(); + }); }); // What holds for email codes holds for any code factor: its codes' state is diff --git a/tests/Feature/EmailChangeHardeningTest.php b/tests/Feature/EmailChangeHardeningTest.php index bc59cf1c..66227d06 100644 --- a/tests/Feature/EmailChangeHardeningTest.php +++ b/tests/Feature/EmailChangeHardeningTest.php @@ -299,6 +299,113 @@ function confirmBoth(PendingChange $change, array $tokens): EmailConfirmation ->and(Authenticator::find($before->id))->not->toBeNull(); }); +it('removes recovery codes with the last factor an undo removes', function () { + Event::fake([AuthenticatorRemoved::class]); + $codes = Authenticator::factory()->recoveryCodes()->for($this->user, 'authenticatable')->create(['created_at' => now()->subMonths(2)]); + $this->travel(1)->month(); + $totp = Authenticator::factory()->totp()->for($this->user, 'authenticatable')->create(['created_at' => now()->subDays(3)]); + $change = requestChange($this->user, 'new@example.com', Assurance::AAL2); + $tokens = tokensFor('new@example.com', 'taylor@example.com'); + + confirmBoth($change, $tokens); + app(EmailChanges::class)->revert($change->fresh(), $tokens['revert']); + + expect(Authenticator::find($totp->id))->toBeNull() + ->and(Authenticator::find($codes->id))->toBeNull(); + Event::assertDispatched(AuthenticatorRemoved::class, fn (AuthenticatorRemoved $event) => $event->authenticator->is($codes)); +}); + +it('leaves nothing but the password to confirm with once an undo removes a replaced authenticator app', function () { + Route::middleware(['web', 'auth', 'keyring.fresh:15m'])->get('/account', fn () => 'danger zone'); + $signIn = function (?string $code = null) { + $this->post('/login', ['email' => 'taylor@example.com', 'password' => 'password']); + + if ($code !== null) { + $this->post(route('keyring.login.verify', 'totp'), ['code' => $code]); + } + }; + $enroll = function () { + $secret = $this->postJson(route('keyring.authenticators.store', 'totp'))->json('enrollment.secret'); + + return [$secret, $this->postJson(route('keyring.authenticators.confirm', 'totp'), ['code' => totpCode($secret)])->assertOk()->json('recoveryCodes')]; + }; + $signOut = function () { + $this->post(route('logout')); + $this->flushSession(); + Auth::forgetGuards(); + }; + + // The codes come with a first app, which is replaced a month later. + $signIn(); + [$first, $codes] = $enroll(); + $firstId = Authenticator::query()->where('factor', 'totp')->sole()->id; + $signOut(); + + $this->travel(30)->days(); + $signIn(totpCode($first)); + [$second] = $enroll(); + $this->deleteJson(route('keyring.authenticators.destroy', $firstId))->assertOk(); + $signOut(); + + // An email change days later, confirmed from both addresses and undone. + $this->travel(3)->days(); + $signIn(totpCode($second)); + $this->postJson(route('keyring.email.store'), ['email' => 'new@example.com'])->assertOk(); + $change = PendingChange::sole(); + $tokens = tokensFor('new@example.com', 'taylor@example.com'); + confirmBoth($change, $tokens); + $signOut(); + + $this->travel(1)->day(); + app(EmailChanges::class)->revert($change->fresh(), $tokens['revert']); + + expect(Authenticator::query()->ownedBy($this->user)->pluck('factor')->all())->toBe([]); + + $this->travel(1)->day(); + $signIn(); + $this->travel(20)->minutes(); + + $this->get('/account')->assertRedirect(route('keyring.confirm.challenge')); + $this->inertia()->get(route('keyring.confirm.challenge')) + ->assertJsonPath('props.factor', 'password') + ->assertJsonPath('props.alternatives', []); + $this->flushHeaders(); + + $this->post(route('keyring.confirm.verify', 'recovery'), ['code' => $codes[0]]); + $this->get('/account')->assertRedirect(route('keyring.confirm.challenge')); + $this->postJson(route('keyring.email.store'), ['email' => 'other@example.com'])->assertStatus(423); +}); + +it('keeps recovery codes when an undo leaves a factor for them to recover', function () { + $codes = Authenticator::factory()->recoveryCodes()->for($this->user, 'authenticatable')->create(['created_at' => now()->subMonth()]); + $kept = Authenticator::factory()->totp()->for($this->user, 'authenticatable')->create(['created_at' => now()->subMonth()]); + $change = requestChange($this->user, 'new@example.com', Assurance::AAL2); + $tokens = tokensFor('new@example.com', 'taylor@example.com'); + + $this->travel(1)->minutes(); + $planted = Authenticator::factory()->passkey()->for($this->user, 'authenticatable')->create(); + + confirmBoth($change, $tokens); + app(EmailChanges::class)->revert($change->fresh(), $tokens['revert']); + + expect(Authenticator::find($planted->id))->toBeNull() + ->and(Authenticator::find($kept->id))->not->toBeNull() + ->and(Authenticator::find($codes->id))->not->toBeNull(); +}); + +it('still asks the current address when the session proved a recovery code rather than its second factor', function () { + Authenticator::factory()->totp()->for($this->user, 'authenticatable')->create(['created_at' => now()->subMonth()]); + Authenticator::factory()->recoveryCodes(['aaaa-aaaa-aaaa-aaaa-aaaa-aaaa-aa'])->for($this->user, 'authenticatable')->create(['created_at' => now()->subMonth()]); + + $this->post('/login', ['email' => 'taylor@example.com', 'password' => 'password']); + $this->post(route('keyring.login.verify', 'recovery'), ['code' => 'aaaa-aaaa-aaaa-aaaa-aaaa-aaaa-aa']); + $this->assertAuthenticatedAs($this->user); + + $this->postJson(route('keyring.email.store'), ['email' => 'new@example.com'])->assertOk(); + + expect(PendingChange::query()->latest('id')->first()->current_token)->not->toBeNull(); +}); + it('cancels pending email changes when the password is reset', function () { $change = requestChange($this->user, 'attacker@example.com'); $tokens = tokensFor('attacker@example.com', 'taylor@example.com'); diff --git a/tests/Feature/StepUpTest.php b/tests/Feature/StepUpTest.php index be92c904..781dc485 100644 --- a/tests/Feature/StepUpTest.php +++ b/tests/Feature/StepUpTest.php @@ -17,6 +17,7 @@ use Keyring\Login\Attempt; use Keyring\Login\AttemptStore; use Keyring\Login\Requirement; +use Keyring\Login\Verification; use Keyring\Models\Authenticator; use Keyring\Sessions\SessionAssurance; use Keyring\Sessions\Sessions; @@ -264,6 +265,53 @@ function signIn(): void expect(Keyring::factor('recovery')->present($recovery->fresh())['remaining'])->toBe(0); }); +it('asks for the password when recovery codes are all an account has beside it', function () { + Authenticator::factory()->recoveryCodes(['aaaa-aaaa-aaaa-aaaa-aaaa-aaaa-aa'])->for($this->user, 'authenticatable')->create(['created_at' => now()->subMonth()]); + signIn(); + $this->travel(16)->minutes(); + + $this->get('/account')->assertRedirect(route('keyring.confirm.challenge')); + $this->inertia()->get(route('keyring.confirm.challenge')) + ->assertJsonPath('props.factor', 'password') + ->assertJsonPath('props.alternatives', []); + $this->flushHeaders(); + + $this->post(route('keyring.confirm.verify', 'recovery'), ['code' => 'aaaa-aaaa-aaaa-aaaa-aaaa-aaaa-aa']); + $this->get('/account')->assertRedirect(route('keyring.confirm.challenge')); + $this->postJson(route('keyring.email.store'), ['email' => 'new@example.com'])->assertStatus(423); + expect(app(SessionAssurance::class)->all())->each(fn ($verification) => $verification->factor->not->toBe(RecoveryCodes::KEY)); + + $this->post(route('keyring.confirm.verify', 'password'), ['password' => 'password'])->assertRedirect('/account'); + $this->get('/account')->assertOk(); +}); + +it('does not count a recovery code the session proved toward a step-up that refuses them', function () { + $codes = Authenticator::factory()->recoveryCodes(['aaaa-aaaa-aaaa-aaaa-aaaa-aaaa-aa'])->for($this->user, 'authenticatable')->create(); + + // However the session came to hold a recent proof of the codes alone. + Route::middleware(['web', 'auth'])->post('/proved-codes', function () use ($codes) { + app(SessionAssurance::class)->record([Verification::of($codes)]); + + return 'ok'; + }); + + signIn(); + $this->travel(16)->minutes(); + $this->post('/proved-codes')->assertOk(); + + $this->get('/account')->assertRedirect(route('keyring.confirm.challenge')); +}); + +it('counts a sign in with the password and a recovery code as fresh beside an authenticator app', function () { + $totp = Authenticator::factory()->totp()->for($this->user, 'authenticatable')->create(); + Authenticator::factory()->recoveryCodes(['aaaa-aaaa-aaaa-aaaa-aaaa-aaaa-aa'])->for($this->user, 'authenticatable')->create(); + + signIn(); + $this->post(route('keyring.login.verify', 'recovery'), ['code' => 'aaaa-aaaa-aaaa-aaaa-aaaa-aaaa-aa'])->assertRedirect(); + + $this->get('/account')->assertOk(); +}); + it('does not spend a recovery code on a step-up it could never finish', function () { Keyring::factors([Password::class, WebAuthn::passkeys(), RecoveryCodes::class]); $this->user->forceFill(['password' => null])->saveQuietly(); From be1cd78482cdd753c6718946b9df066eee2d8fd4 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Tue, 17 Nov 2026 20:25:15 +0000 Subject: [PATCH 2/9] fix(registration): answer the same for every address however creating the user fails, and refuse a password bcrypt can't hash, replacing the test that pinned the throw --- CHANGELOG.md | 4 +- docs/protected-changes.md | 2 +- docs/security.md | 4 +- docs/sign-in-flow.md | 5 +- lang/en/keyring.php | 1 + src/Login/Registration.php | 39 +++++++- src/Support/PasswordRules.php | 16 +++- tests/Feature/PasswordResetTest.php | 15 ++++ tests/Feature/PasswordRulesTest.php | 11 +++ tests/Feature/RegistrationTest.php | 134 +++++++++++++++++++++++++--- 10 files changed, 208 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6e369a69..765ce8a2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ The first release. Nothing is tagged yet. ### 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, with new users signing in once they've verified theirs. `registration.reveal_taken` says when an address is taken instead. +- 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. `registration.reveal_taken` says 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/passkeys` client. 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, and `allowOnly()` to limit them to certain models by AAGUID. @@ -38,7 +38,7 @@ The first release. Nothing is tagged yet. - Protected `email` and `password` attributes, 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 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, and Unicode normalised to NFC. +- 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_URL` and opened on pages that send no referrer. diff --git a/docs/protected-changes.md b/docs/protected-changes.md index b7e9b7a8..95889190 100644 --- a/docs/protected-changes.md +++ b/docs/protected-changes.md @@ -251,7 +251,7 @@ The check runs in `Keyring\Http\Middleware\RequirePasswordChange`, which Keyring - breached passwords rejected, in production by default. Laravel's check lets a password through when Have I Been Pwned can't be reached; set [`passwords.refuse_unchecked`](configuration.md#passwords) to refuse it instead, - the most common passwords rejected always, whatever their case and with or without spaces around them, from a list bundled with Keyring: the 10,000 most common of 8 characters or more and the 3,000 most common of 15 or more, 13,052 in all, taken from SecLists (MIT licensed). `resources/passwords/README.md` in the package records the exact source, - no passwords made up of [context-specific words](#context-specific-words): the site's name, the words you list, and the user's name, email username and email domain, -- with bcrypt, Laravel's default, passwords over 72 bytes are rejected, because bcrypt silently ignores the rest. That's 72 plain characters but as few as 18 emoji, so 64 characters don't always fit. Set `HASH_DRIVER=argon2id` to accept every password up to `max`, which is what OWASP ASVS 5.0.0 (6.2.9) needs (see [Passwords](configuration.md#passwords)), +- with bcrypt, Laravel's default, passwords over 72 bytes are rejected, because bcrypt silently ignores the rest, and so are passwords with a NUL byte, which bcrypt can't hash at all. That's 72 plain characters but as few as 18 emoji, so 64 characters don't always fit. Set `HASH_DRIVER=argon2id` to accept every password up to `max`, which is what OWASP ASVS 5.0.0 (6.2.9) needs (see [Passwords](configuration.md#passwords)), - and `confirmed`, so the request needs `password_confirmation`. Passwords may hold any Unicode characters, and Keyring puts each one in Unicode's NFC form before it's measured, hashed or checked, as NIST SP 800-63B-4 recommends (Sec. 3.1.1.2). The same "é" is one code point from some keyboards and two from others, and without this a password set on one device could fail on another. The rules above count what will be hashed: a character is one code point of the NFC form. Keyring's routes do this for the input they hand your actions (`password`, `password_confirmation` and `current_password`) and for every password they check. If your own code sets a password some other way, such as a seeder, an admin tool or a route of your own, pass it through `PasswordRules::normalize()` first: diff --git a/docs/security.md b/docs/security.md index 5d4d4c3f..12b62651 100644 --- a/docs/security.md +++ b/docs/security.md @@ -52,7 +52,7 @@ Guarantees about a [feature](quick-start.md#adding-features), such as devices or - Pending logins are encrypted JSON in the session, never `serialize()`d, and expire after `pending_logins.keep_for`, as soon as the user's password or email address changes, as soon as a sign-in method they've already proved is removed from the account (by its owner, or by an undone email change), or when `keyring.guard` is no longer the guard they started under. An emailed code could have gone to the address the account no longer has, so an email change and its undo both end a sign in that was waiting for one. - The session ID is regenerated and the old one destroyed when a user proves a factor (signing in or stepping up), changes their password or signs out everywhere else, so a copied session cookie stops working, and someone who planted a session ID before the password step doesn't share the pending login. On Laravel's `cookie` session driver, where there is nothing on the server to destroy, the old copy is signed out through its registry record instead. - A password reset never signs anyone in, so the policy still applies at the next login. -- Registration doesn't reveal whether an address has an account, unless you set `registration.reveal_taken`. A free address, a taken one, one reserved for its previous owner and one whose account you keep out get the same response, status, cookies and session, after the same validation, in at least `timebox`, with one password hash each and every email sent after the response. Nobody is signed in by registering. Whether an address is taken is decided by Keyring, not by your action, so the guarantee doesn't depend on how the action is written, as long as it doesn't check for itself. See [Registration](sign-in-flow.md#without-revealing-who-has-an-account). +- Registration doesn't reveal whether an address has an account, unless you set `registration.reveal_taken`. A free address, a taken one, one reserved for its previous owner and one whose account you keep out get the same response, status, cookies and session, after the same validation, in at least `timebox`, with one password hash each and every email sent after the response. Nobody is signed in by registering. Whether an address is taken is decided by Keyring, not by your action, so the guarantee doesn't depend on how the action is written, as long as it doesn't check for itself. A password the hasher can't take is refused for every address whatever the action's rules, and anything else `create()` throws is reported and answered like the rest. See [Registration](sign-in-flow.md#without-revealing-who-has-an-account). - With that registration, an account can't be signed in until its address is verified, and a correct password is answered like a wrong one until then. Verifying takes the emailed link and the password together, so neither someone who registered an address they can't read mail for, nor its owner who never chose that password, ends up with a verified account. A finished password reset also verifies the address. - Checking a password can rehash it under the app's current settings. The new hash is only saved over the one that was checked, under a row lock, so a sign in that overlaps a reset can't write the old password back, and whatever device trust it was given is withdrawn when it's ended. - A login attempt can't sign the owner out. Risk responses at login never revoke sessions, change the "remember me" token or stop trusting devices, even from a custom responder. @@ -205,7 +205,7 @@ The failures in a row and the locks held until a reset are in your database eith - New passwords need at least 8 characters with a second factor and 15 without, and neither minimum can be configured below 8. Any characters are accepted, with no composition rules. - New passwords are checked against the 10,000 most common of 8 characters or more and the 3,000 most common of 15 or more, in every environment, and against your app's name, the words you list in `passwords.context` and the user's own name and email address, with look-alike characters read as letters. The whole password is compared, as NIST SP 800-63B-4 Sec. 3.1.1.2 requires: one made up of those words is refused, and a passphrase that only has one in it is not. - In production, new passwords are also checked against breach lists (Have I Been Pwned). That check lets a password through when the service can't be reached, unless you set `passwords.refuse_unchecked`. -- New passwords are refused rather than silently cut short by bcrypt. With bcrypt that limit is 72 bytes, so hash with argon2id to accept every password up to `passwords.max`. +- New passwords are refused rather than silently cut short by bcrypt. With bcrypt that limit is 72 bytes, so hash with argon2id to accept every password up to `passwords.max`. A new password bcrypt can't hash at all, one with a NUL byte, is refused with the other rules too, so registration, a change and a reset answer it with a validation error. - Passwords never expire. A user is held until they choose a new one when there's evidence theirs is compromised (NIST SP 800-63B-4, Sec. 3.1.1.2): by your app, by a risk response of yours, or by Keyring's own response when the `BreachedPassword` signal, which is off until you turn it on, finds the password they just signed in with in a breach. The hold outlasts signing out and clearing the cache, ends with a password change or reset, and is never placed on an account without a password. ### Links and Headers diff --git a/docs/sign-in-flow.md b/docs/sign-in-flow.md index 99cb355c..534c2be8 100644 --- a/docs/sign-in-flow.md +++ b/docs/sign-in-flow.md @@ -276,6 +276,8 @@ By default (`registration.reveal_taken` is `false`), nobody can use the form to - The answer is always the same: a redirect to the login page with the `registration-received` status ("Thanks for registering. We've emailed that address with what to do next."), or that status as JSON. Nobody is signed in. - Validation errors from your action are shown as usual. They're the same for every address, because your action never looks at whether it's taken. +- After your action's `validate()`, Keyring refuses a password the hasher can't take, whatever your rules say: with bcrypt, one over 72 bytes or with a NUL byte. Only a free address hashes the password it was sent, so otherwise that address alone would fail. +- **If `create()` throws**, which only happens for a free address, the exception is passed to `report()` and the answer is the usual one. Nothing is created or sent, so the visitor is told to check an inbox that gets nothing, and a `create()` that keeps failing shows in your error tracker rather than as failed requests. A `ValidationException` thrown there is shown like any other validation error, since it's your action refusing the form on purpose. - **A free address** gets its account, and Laravel's `Registered` event is dispatched once the response has been sent, which emails the verification link. - **A taken address** gets nothing created or changed. Once the response has been sent, Keyring emails it your `already_registered` [notification](security-log-and-emails.md#emails-a-flow-needs), which says someone tried to register and links to the login page and, with `Features::resetPasswords()`, the forgot password page. If the account there was never verified, it's sent another verification link instead, since the first may be lost or expired. - An address is mailed five times an hour at most by registration (`limits.notices` every `limits.notices_per`), verification links included, so the form can't be used to fill someone's inbox. Past that the answer stays the same and nothing is sent. @@ -298,7 +300,7 @@ This needs email verification, and Keyring says so rather than leaking quietly: It also means an account that isn't verified can't be signed in at all, however it got that way: a session whose user loses `email_verified_at` is signed out on its next request. Mark accounts you create yourself (an import, a seeder, a social login) as verified. -Three things are still yours to keep quiet. A username of your own that has to be unique (a handle, say) will say when it's taken, because your action checks it. Your `Registered` listeners run after the response, so they can't slow down one answer and not the other, but anything your action's `create()` does that takes noticeably longer than the timebox will show. And your mail provider's bounce or delivery reports are outside the request altogether. +Three things are still yours to keep quiet. A username of your own that has to be unique (a handle, say) will say when it's taken, because your action checks it, and so will a `ValidationException` your `create()` throws for a free address only. Your `Registered` listeners run after the response, so they can't slow down one answer and not the other, but anything your action's `create()` does that takes noticeably longer than the timebox will show. And your mail provider's bounce or delivery reports are outside the request altogether. ### Saying When an Address Is Taken @@ -314,6 +316,7 @@ Many apps would rather tell someone straight away that they already have an acco - A taken address gets Laravel's "has already been taken" error on the email field, next to any other validation errors. Nothing is emailed. - A new user is signed in straight away, counting the password they just chose as proved, and `Registered` is dispatched during the request. The policy isn't consulted, since they have no other factors yet. The answer comes from `RegisterResponse`, which by default behaves like `AuthenticatedResponse`. Swap it to send new users somewhere else, like onboarding. See [Responses](#responses). - Users can sign in before verifying their address, and email verification is optional. +- An exception your action's `create()` throws isn't caught: there's nothing left to hide, so it fails like any other request. This tells anyone who asks whether an address has an account: the error says so, and so does being signed in. It's the trade most consumer apps make, and it doesn't meet ASVS 6.3.8. diff --git a/lang/en/keyring.php b/lang/en/keyring.php index 09d2efbc..1558c4e0 100644 --- a/lang/en/keyring.php +++ b/lang/en/keyring.php @@ -25,6 +25,7 @@ 'device_name' => ':browser on :platform', 'unknown_device' => 'Unknown device', 'near' => 'near :place', + 'password_null_byte' => 'The :attribute can\'t contain a null character.', 'password_too_long' => 'The :attribute is too long. It can take up 72 bytes: that\'s 72 plain letters, digits and symbols, and fewer with accented letters, other alphabets or emoji.', 'unavailable' => 'Your account needs a sign-in method that isn\'t set up. Please contact support.', ]; diff --git a/src/Login/Registration.php b/src/Login/Registration.php index feb07cac..e7b4f80e 100644 --- a/src/Login/Registration.php +++ b/src/Login/Registration.php @@ -32,6 +32,7 @@ use Keyring\Support\Throttle; use Keyring\Support\Url; use LogicException; +use Throwable; use function Illuminate\Support\defer; @@ -87,15 +88,28 @@ public function ensureReady(): void * after the response. Each path makes one password hash, the slowest * thing either does. * + * Only a free address runs the action's create(), so anything it throws + * would say the address was free. It's reported and answered like the + * rest, with nothing sent. A ValidationException is the action refusing + * the form on purpose, and is passed on. + * * @throws ValidationException */ public function quietly(Request $request, CreatesNewUsers $creator): void { $this->container->make(Timebox::class)->call(function () use ($request, $creator) { - $input = $creator->validate($this->input($request)); + $input = $this->validate($request, $creator); $email = $this->address($request, $input); - $user = $this->taken($email) ? null : $this->create($creator, $input, $email); + try { + $user = $this->taken($email) ? null : $this->create($creator, $input, $email); + } catch (ValidationException $e) { + throw $e; + } catch (Throwable $e) { + report($e); + + return; + } if ($user !== null) { // Laravel's listener mails the verification link, which would @@ -128,7 +142,7 @@ public function quietly(Request $request, CreatesNewUsers $creator): void public function openly(Request $request, CreatesNewUsers $creator): Authenticatable&Model { try { - $input = $creator->validate($this->input($request)); + $input = $this->validate($request, $creator); } catch (ValidationException $e) { if ($this->taken($email = $this->address($request))) { $e->validator->errors()->merge($this->alreadyTaken($email)->errors()); @@ -144,6 +158,25 @@ public function openly(Request $request, CreatesNewUsers $creator): Authenticata return $user ?? throw $this->alreadyTaken($email); } + /** + * The action's validation, then Keyring's own check that the password + * can be hashed: whatever rules the action has, a password the hasher + * would refuse is refused here, the same for every address, rather than + * failing only where an account is created. + * + * @return array + * + * @throws ValidationException + */ + protected function validate(Request $request, CreatesNewUsers $creator): array + { + $input = $creator->validate($this->input($request)); + + Validator::make($input, ['password' => [PasswordRules::hashable()]])->validate(); + + return $input; + } + /** * The form, with its password as it will be hashed and checked from now * on, so the action's rules measure that. diff --git a/src/Support/PasswordRules.php b/src/Support/PasswordRules.php index 6fce0d72..3dd870aa 100644 --- a/src/Support/PasswordRules.php +++ b/src/Support/PasswordRules.php @@ -89,7 +89,7 @@ public static function for((Authenticatable&Model)|null $user = null, ?Closure $ return [ 'required', 'string', 'confirmed', $rule, - self::notCommon(), self::withoutContext($site, $personal), self::bcryptLimit(), + self::notCommon(), self::withoutContext($site, $personal), self::hashable(), ...$strict ? [self::notBreached($min)] : [], ]; } @@ -343,12 +343,20 @@ public static function forVerifying(#[\SensitiveParameter] string $password, ?st * Bcrypt only uses the first 72 bytes. Refuse longer passwords instead of * silently ignoring the end of them. That's bytes, not characters, so * under bcrypt passwords.max is never reached and 64 characters of - * accented or non-Latin text are too many. Argon2 has no such limit. + * accented or non-Latin text are too many. It can't hash a NUL byte at + * all, so one is refused here rather than failing when it's hashed. + * Argon2 has neither limit. */ - private static function bcryptLimit(): Closure + public static function hashable(): Closure { return function (string $attribute, mixed $value, Closure $fail) { - if (Hash::getDefaultDriver() === 'bcrypt' && is_string($value) && strlen($value) > 72) { + if (Hash::getDefaultDriver() !== 'bcrypt' || ! is_string($value)) { + return; + } + + if (str_contains($value, "\0")) { + $fail(__('keyring::keyring.password_null_byte')); + } elseif (strlen($value) > 72) { $fail(__('keyring::keyring.password_too_long')); } }; diff --git a/tests/Feature/PasswordResetTest.php b/tests/Feature/PasswordResetTest.php index 8846b0f1..4ad17010 100644 --- a/tests/Feature/PasswordResetTest.php +++ b/tests/Feature/PasswordResetTest.php @@ -102,6 +102,21 @@ public function call(callable $callback, int $microseconds) ->assertJsonPath('props.email', ''); }); +it('refuses a new password bcrypt can\'t hash, on a change and a reset', function () { + $password = "correct horse\0battery staple"; + + $this->actingAs($this->plain)->freshAt(now())->putJson(route('user-password.update'), [ + 'current_password' => 'password', + 'password' => $password, + 'password_confirmation' => $password, + ])->assertUnprocessable()->assertJsonValidationErrors('password'); + auth()->logout(); + + $this->postJson(route('password.update'), ['token' => Password::broker()->createToken($this->plain), 'email' => 'plain@example.com', 'password' => $password, 'password_confirmation' => $password]) + ->assertUnprocessable()->assertJsonValidationErrors('password'); + expect(Hash::check('password', $this->plain->fresh()->password))->toBeTrue(); +}); + it('ends outstanding reset links when the password is changed', function (bool $signOutOthers) { $token = Password::broker()->createToken($this->plain); diff --git a/tests/Feature/PasswordRulesTest.php b/tests/Feature/PasswordRulesTest.php index d41d4311..3748bf1d 100644 --- a/tests/Feature/PasswordRulesTest.php +++ b/tests/Feature/PasswordRulesTest.php @@ -399,6 +399,17 @@ function passes(string $password, mixed ...$arguments): bool : expect($errors->all())->toBe([__('keyring::keyring.password_too_long', ['attribute' => 'password'])]) ->and($errors->first())->toContain('72 bytes')->toContain('fewer with accented letters, other alphabets or emoji'); })->with('64 characters'); + + it('refuses a NUL byte with bcrypt, which can\'t hash one, and takes it with argon2id', function () { + $password = "correct horse\0battery staple"; + $errors = fn () => Validator::make(['password' => $password, 'password_confirmation' => $password], ['password' => PasswordRules::for()])->errors()->all(); + + expect($errors())->toBe([__('keyring::keyring.password_null_byte', ['attribute' => 'password'])]); + + config(['hashing.driver' => 'argon2id']); + + expect($errors())->toBe([]); + }); }); /** diff --git a/tests/Feature/RegistrationTest.php b/tests/Feature/RegistrationTest.php index 2e8ec255..df6ff620 100644 --- a/tests/Feature/RegistrationTest.php +++ b/tests/Feature/RegistrationTest.php @@ -14,12 +14,15 @@ use Illuminate\Notifications\AnonymousNotifiable; use Illuminate\Support\Arr; use Illuminate\Support\Facades\Event; +use Illuminate\Support\Facades\Exceptions; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Notification; use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\URL; +use Illuminate\Support\Facades\Validator; use Illuminate\Support\Timebox; use Illuminate\Testing\TestResponse; +use Illuminate\Validation\ValidationException; use Keyring\Contracts\SessionRegistry; use Keyring\Enums\Assurance; use Keyring\Exceptions\EmailVerificationRequired; @@ -43,6 +46,34 @@ afterEach(fn () => Model::clearBootedModels()); +/** + * The published action, failing where it creates the user. + */ +class FailingCreateNewUser extends CreateNewUser +{ + public static ?Throwable $failure = null; + + public function create(array $input): User + { + throw self::$failure ?? new LogicException('No failure set.'); + } +} + +/** + * An action with password rules of its own that leave out Keyring's. + */ +class LooseCreateNewUser extends CreateNewUser +{ + public function validate(array $input): array + { + return Validator::make($input, [ + 'name' => ['required', 'string'], + 'email' => ['required', 'string', 'email'], + 'password' => ['required', 'string', 'confirmed'], + ])->validate(); + } +} + /** * The registration form, filled in well unless a field says otherwise. * @@ -177,6 +208,32 @@ function verificationLinkSentTo(User $user): string } })->with(['a form post' => false, 'json' => true]); + // Bcrypt can't hash a NUL byte, and only a free address hashes the + // visitor's password, so it's refused before either path is taken. + it('refuses a password bcrypt can\'t hash the same for every address', function (bool $json) { + $answers = []; + + foreach (addressesToRegister() as $case => $address) { + $this->flushSession(); + $this->travel(2)->minutes(); + + $form = registrationForm(['email' => $address(), 'password' => "correct horse\0battery staple", 'password_confirmation' => "correct horse\0battery staple"]); + + $answers[$case] = visibleAnswer($json ? $this->postJson('/register', $form) : $this->post('/register', $form)); + } + + expect($answers['free']['status'])->toBe($json ? 422 : 302) + ->and(User::query()->where('email', 'free@example.com')->exists())->toBeFalse(); + + $json + ? expect(json_decode($answers['free']['body'], true)['errors'])->toHaveKey('password') + : expect($answers['free']['errors'])->toHaveKey('password'); + + foreach ($answers as $case => $answer) { + expect($answer)->toEqual($answers['free'], "A {$case} address was answered differently."); + } + })->with(['a form post' => false, 'json' => true]); + it('says to check the inbox, whatever happened', function () { $this->post('/register', registrationForm()) ->assertRedirect(route('login')) @@ -406,21 +463,69 @@ protected function usleep(int $microseconds): void expect(User::sole()->is($owner))->toBeTrue(); }); - it('still fails when the users table refuses a new user for another reason', function () { + // Only a free address gets as far as creating a user, so however that + // fails, it's answered like the rest. The app still hears of it. + it('answers the same when the action can\'t create the user, and reports why', function (Throwable $failure) { + Exceptions::fake(); + FailingCreateNewUser::$failure = $failure; + Keyring::createUsersUsing(FailingCreateNewUser::class); + $answers = []; + + foreach (addressesToRegister() as $case => $address) { + $this->flushSession(); + $this->travel(2)->minutes(); + + $answers[$case] = visibleAnswer($this->post('/register', registrationForm(['email' => $address()]))); + } + + foreach ($answers as $case => $answer) { + expect($answer)->toEqual($answers['free'], "A {$case} address was answered differently."); + } + + expect($answers['free']['session']['status'] ?? null)->toBe('registration-received') + ->and(User::query()->where('email', 'free@example.com')->exists())->toBeFalse(); + Exceptions::assertReported($failure::class); + Exceptions::assertReportedCount(1); + + // Nothing goes to the free address: it has no account to speak of. + Notification::assertNotSentTo(new AnonymousNotifiable, AlreadyRegistered::class, fn ($n, $c, $to) => $to->routes['mail'] === 'free@example.com'); + })->with([ // A unique index on something else, which the action let through. - Keyring::createUsersUsing((new class extends CreateNewUser - { - public function create(array $input): User - { - throw new UniqueConstraintViolationException('testing', 'insert into users', [], new Exception('users_handle_unique')); - } - })::class); + 'a unique index' => fn () => new UniqueConstraintViolationException('testing', 'insert into users', [], new Exception('users_handle_unique')), + 'anything else' => fn () => new RuntimeException('The users table is unavailable.'), + ]); - $this->withoutExceptionHandling(); + it('passes on a validation error the action throws while creating the user', function () { + FailingCreateNewUser::$failure = ValidationException::withMessages(['email' => 'Not from that domain.']); + Keyring::createUsersUsing(FailingCreateNewUser::class); - expect(fn () => $this->post('/register', registrationForm()))->toThrow(UniqueConstraintViolationException::class); + $this->post('/register', registrationForm(['email' => 'free@example.com']))->assertSessionHasErrors(['email' => 'Not from that domain.']); }); + // Keyring's own check, whatever rules the action has: bcrypt can't hash + // these, and only a free address would try. + it('refuses a password the hasher can\'t take the same for every address, whatever the action\'s rules', function (string $password) { + Keyring::createUsersUsing(LooseCreateNewUser::class); + $answers = []; + + foreach (addressesToRegister() as $case => $address) { + $this->flushSession(); + $this->travel(2)->minutes(); + + $answers[$case] = visibleAnswer($this->post('/register', registrationForm(['email' => $address(), 'password' => $password, 'password_confirmation' => $password]))); + } + + expect($answers['free']['errors'])->toHaveKey('password') + ->and(User::query()->where('email', 'free@example.com')->exists())->toBeFalse(); + + foreach ($answers as $case => $answer) { + expect($answer)->toEqual($answers['free'], "A {$case} address was answered differently."); + } + })->with([ + 'a NUL byte' => ["correct horse\0battery staple"], + 'over 72 bytes' => [str_repeat('correct horse battery staple ', 3)], + ]); + it('refuses the password alone until the address is verified, like an account that isn\'t there', function () { $this->post('/register', registrationForm()); @@ -635,6 +740,15 @@ public function create(array $input): User revealTakenAddresses(); }); + it('still fails when the action can\'t create the user, since it says the address was free anyway', function () { + FailingCreateNewUser::$failure = new RuntimeException('The users table is unavailable.'); + Keyring::createUsersUsing(FailingCreateNewUser::class); + + $this->withoutExceptionHandling(); + + expect(fn () => $this->post('/register', registrationForm()))->toThrow(RuntimeException::class, 'The users table is unavailable.'); + }); + it('registers and signs in like any other login', function () { $this->post('/register', registrationForm(['email' => 'Taylor@Example.com']))->assertRedirect('/dashboard'); From b236fbd6cca4b2967a02c58110c8a1c2bb50ea53 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Tue, 17 Nov 2026 20:59:28 +0000 Subject: [PATCH 3/9] fix(responses): flash a page's result encrypted and read it with keyring::result(), moving the test that read the plain flash --- CHANGELOG.md | 1 + UPGRADE.md | 1 + docs/authenticators.md | 2 +- docs/frontend.md | 4 +- docs/security.md | 4 +- docs/sign-in-flow.md | 2 +- src/Concerns/RendersPages.php | 17 ++++++++ src/Facades/Keyring.php | 1 + src/Http/Responses/StatusResponse.php | 19 +++++++-- src/Support/EncryptedSession.php | 13 ++++++- tests/Feature/AuthenticatorManagementTest.php | 39 ++++++++++++++++++- tests/Fixtures/public-api.json | 1 + 12 files changed, 92 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 765ce8a2..996c6aff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -60,6 +60,7 @@ The first release. Nothing is tagged yet. - `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. Also `keyring:import fortify`, and `keyring: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-popups` and 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. - `@entity/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. diff --git a/UPGRADE.md b/UPGRADE.md index 8b9faead..977cb37f 100644 --- a/UPGRADE.md +++ b/UPGRADE.md @@ -12,6 +12,7 @@ Changes made since the first installs from `dev-main`, for anyone already runnin - **`timebox` defaults to `500ms`, up from `250ms`.** It has to be longer than one password hash takes, and bcrypt at 12 rounds is close to 250ms on ordinary hardware. Set it in `config/keyring.php` to keep the old value. - **An address a change replaced is looked up differently while it's reserved**, so that "ß" is found under either spelling a database takes it for. Reservations made before this, for an address with a doubled "s", aren't found until they lapse (a week at most). - **Rate limits, locks and risk locks are kept under new keys.** Ones in place when this is deployed are left behind: an account locked then is unlocked early, once. +- **What a form or Inertia response flashes for the page is encrypted.** Read it with `Keyring::result()` (or `Keyring::result('recoveryCodes')` for one key) instead of `session('keyring.result')`, which now holds ciphertext. In an Inertia middleware, share `'keyringResult' => fn () => Keyring::result()`. JSON responses are unchanged. - **Saving the current password as the new one is refused** on `PUT /user/password`, with a validation error on `password`. - **A mid-session risk step-up signs the session out when `sessions.end_on_lapse` is on**, where it used to carry on with nothing proved. - **`webauthn.relying_party.name` is gone.** WebAuthn deprecates the relying party name and most browsers don't show it, so the options now carry the relying party ID in its place, as Laravel's passkeys package does. Remove the key and `KEYRING_WEBAUTHN_RP_NAME` from your config, and any call to or override of `Ceremonies::relyingPartyName()`, which is gone too. Keys registered before keep working. diff --git a/docs/authenticators.md b/docs/authenticators.md index eaf69951..c514dd95 100644 --- a/docs/authenticators.md +++ b/docs/authenticators.md @@ -191,7 +191,7 @@ Every route answers with a [status response](sign-in-flow.md#status-responses). | Update | `authenticator-updated` | `authenticator` | | Remove | `authenticator-removed` | | -Other requests are redirected back with the `status` flashed, and the extra data flashed under `keyring.result` (for example `session('keyring.result.enrollment')`). The [browser package](frontend.md#managing-authenticators) uses the JSON form. +Other requests are redirected back with the `status` flashed, and the extra data flashed, encrypted, for the next request. Read it with `Keyring::result()`, or one key with `Keyring::result('enrollment')`. The [browser package](frontend.md#managing-authenticators) uses the JSON form. ## From JavaScript diff --git a/docs/frontend.md b/docs/frontend.md index 0cb603b1..29517894 100644 --- a/docs/frontend.md +++ b/docs/frontend.md @@ -406,7 +406,7 @@ Update any paths your own pages link to directly, such as `/login` or `/register ## Flash Messages and Alerts -Keyring's non-JSON responses flash a `status` slug to the session (JSON responses include it as `status`, with a readable `message`), such as `code-sent`, `password-updated`, `device-revoked` or `email-change-requested`. Extra data, such as new recovery codes, is flashed as `keyring.result`. See [Status Responses](sign-in-flow.md#status-responses). +Keyring's non-JSON responses flash a `status` slug to the session (JSON responses include it as `status`, with a readable `message`), such as `code-sent`, `password-updated`, `device-revoked` or `email-change-requested`. Extra data, such as new recovery codes, is flashed encrypted: read it with `Keyring::result()`, not from the session. See [Status Responses](sign-in-flow.md#status-responses). Share them through your Inertia middleware alongside the ["was this you?" alerts](security-log-and-emails.md#was-this-you-alerts). `Keyring::statusMessage()` translates a slug from `keyring::status.*`, and gives `null` for anything else: @@ -419,7 +419,7 @@ public function share(Request $request): array ...parent::share($request), 'status' => fn () => $request->session()->get('status'), 'statusMessage' => fn () => Keyring::statusMessage($request->session()->get('status')), - 'keyringResult' => fn () => $request->session()->get('keyring.result'), + 'keyringResult' => fn () => Keyring::result(), 'keyringAlerts' => fn () => $request->session()->get('keyring.alerts', []), ]; } diff --git a/docs/security.md b/docs/security.md index 12b62651..448c3f4b 100644 --- a/docs/security.md +++ b/docs/security.md @@ -289,7 +289,7 @@ Everything Keyring stores about a person, how it's protected, how long it stays | `keyring_failure_counts` | None beyond whose it is: the user's ID, the factor, the authenticator's ID and two counts of failures in a row. | Plain. | Until a success, a password reset or `Keyring::unlock()` clears it, or its authenticator is removed. Never pruned, since a row is what keeps an authenticator refused [at the cap](#at-the-cap). Deleted with a force deleted user. | | `keyring_password_holds` | That the user has to choose a new password, and the reason your app or a risk response gave: write nothing personal there. | Plain. | Until the password changes or the hold is called off. Deleted with a force deleted user. | | Your app's log (without `Features::securityLog()`) | The same as `keyring_events`, one line per event. | Whatever protects that log channel. | Whatever that channel keeps (`days` on a `daily` channel). | -| The session | A sign in waiting for its second factor, an enrollment in progress (including the secret being set up), and what the session has verified. | Encrypted with `APP_KEY` inside the session, whichever session driver holds it. | 10 minutes for a pending login (`pending_logins.keep_for`), 15 for an enrollment (`enrollments.keep_for`), otherwise the session's life. | +| The session | A sign in waiting for its second factor, an enrollment in progress (including the secret being set up), what a form or Inertia response hands the next page (such as that secret, or new recovery codes), and what the session has verified. | Encrypted with `APP_KEY` inside the session, whichever session driver holds it. | 10 minutes for a pending login (`pending_logins.keep_for`), 15 for an enrollment (`enrollments.keep_for`), otherwise the session's life. | | The rate limiter's cache store | Counts of attempts, keyed by a SHA-1 of the factor with the account, the typed username or the IP address. Also hashes of sent codes, marks for answered WebAuthn challenges and enrollments under way, and risk locks (in `risk.store`), which are kept under the user's ID. | Hashed keys, so the store holds no names or addresses to read back. A risk lock's key holds the user's ID as it is. | A minute for counts, up to 24 hours for locks, 30 days for the failures in a row counted under a typed username (`limits.remember_names_for`). | | Laravel's own tables | The reset token and address in `password_reset_tokens`, and `remember_token` on your users table. | Laravel hashes the reset token. | Laravel's `auth.passwords.*.expire`. Keyring deletes a user's reset tokens when they're deleted or their address changes. | @@ -438,7 +438,7 @@ Rotating `APP_KEY` with the old key in `APP_PREVIOUS_KEYS` keeps encrypted value | Algorithm | Where | What it protects | |---|---|---| -| Laravel's encrypter, with your `app.cipher`: AES-256-CBC with an HMAC-SHA-256 tag by default, or AES-256-GCM | The `secret` of an authenticator (TOTP secrets, the set of recovery code hashes, whatever a code factor of yours keeps there); `value` and `previous_value` of a pending change (both addresses); pending logins and enrollments in the session, whatever the session driver | Secrets and addresses at rest. | +| Laravel's encrypter, with your `app.cipher`: AES-256-CBC with an HMAC-SHA-256 tag by default, or AES-256-GCM | The `secret` of an authenticator (TOTP secrets, the set of recovery code hashes, whatever a code factor of yours keeps there); `value` and `previous_value` of a pending change (both addresses); pending logins, enrollments and the results flashed for a page in the session, whatever the session driver | Secrets and addresses at rest. | | Laravel's cookie encryption, the same cipher | The device cookie and the "remember me" pairing cookie, when your `web` group encrypts cookies, as it does by default | Tokens in the browser. | | HMAC-SHA-256 under a purpose key | Recovery codes; emailed codes, and those of your own code factors, while they wait in the cache to be typed; the lookup hash of an address an email change holds; the WebAuthn user handle; the handle a page knows a session by | Values that are only ever compared or looked up, never read back. | | SHA-256, unkeyed | Device tokens and email change tokens (confirm, current address, revert) | Long random tokens, so a copy of the table can't be used as one. Each has well over 128 bits, which is why a plain hash is enough. | diff --git a/docs/sign-in-flow.md b/docs/sign-in-flow.md index 534c2be8..fab0716c 100644 --- a/docs/sign-in-flow.md +++ b/docs/sign-in-flow.md @@ -515,7 +515,7 @@ JSON clients get the slug, its translated message, the redirect (when there is o } ``` -Other requests are redirected (back, or to `redirect`) with the slug flashed as `status`, and any data flashed as `keyring.result`, for example `session('keyring.result.recoveryCodes')`. +Other requests are redirected (back, or to `redirect`) with the slug flashed as `status`, and any data flashed for the next request, encrypted with `APP_KEY` since it can hold a secret being set up or new recovery codes. Read it with `Keyring::result()`, or one key of it in dot notation, for example `Keyring::result('recoveryCodes')`. It's null when nothing was flashed. `session('keyring.result')` holds only the ciphertext. The messages live in `lang/en/status.php`, as `keyring::status.{slug}`. The pages Keyring renders that show a status (`login`, `forgot-password` and `verify-email`) receive the translated message as their `status` prop, not the slug. The slugs are: diff --git a/src/Concerns/RendersPages.php b/src/Concerns/RendersPages.php index ad2d588f..d7b469af 100644 --- a/src/Concerns/RendersPages.php +++ b/src/Concerns/RendersPages.php @@ -9,6 +9,8 @@ use Inertia\ComponentNotFoundException; use Inertia\ResponseFactory; use Keyring\Exceptions\MissingPage; +use Keyring\Http\Responses\StatusResponse; +use Keyring\Support\EncryptedSession; /** * Keyring's pages, rendered by the app: Inertia components or Blade views. @@ -86,4 +88,19 @@ public function statusMessage(mixed $status): ?string return is_string($message) ? $message : null; } + + /** + * What the last status response flashed for the page beside its status, + * such as new recovery codes, or one key of it in dot notation, like + * "enrollment.secret". It's kept encrypted in the session, so read it + * here rather than from session('keyring.result'). Null, or $default, + * when nothing was flashed. + */ + public function result(?string $key = null, mixed $default = null): mixed + { + $request = request(); + $result = $request->hasSession() ? app(EncryptedSession::class)->get(StatusResponse::RESULT) : null; + + return $key === null ? ($result ?? $default) : data_get($result, $key, $default); + } } diff --git a/src/Facades/Keyring.php b/src/Facades/Keyring.php index 4add773c..f84ed3ef 100644 --- a/src/Facades/Keyring.php +++ b/src/Facades/Keyring.php @@ -34,6 +34,7 @@ * @method static \Keyring\KeyringManager validateEmailChangesUsing(string $action) * @method static \Illuminate\Support\Collection activity(\Illuminate\Contracts\Auth\Authenticatable&\Illuminate\Database\Eloquent\Model $user, int $limit = 25) * @method static string|null statusMessage(mixed $status) + * @method static mixed result(string|null $key = null, mixed $default = null) * @method static \Keyring\KeyringManager respondWith(string $contract, \Closure|string $implementation) * @method static \Illuminate\Contracts\Support\Responsable response(string $contract, mixed ...$with) * @method static \Illuminate\Contracts\Auth\StatefulGuard guard() diff --git a/src/Http/Responses/StatusResponse.php b/src/Http/Responses/StatusResponse.php index b992ad0e..d515c016 100644 --- a/src/Http/Responses/StatusResponse.php +++ b/src/Http/Responses/StatusResponse.php @@ -8,11 +8,17 @@ use Illuminate\Support\Arr; use Keyring\Contracts\Responses\StatusResponse as StatusResponseContract; use Keyring\Facades\Keyring; +use Keyring\Support\EncryptedSession; class StatusResponse implements StatusResponseContract { use ChoosesFormat; + /** + * Where a non-JSON response flashes its data, encrypted. + */ + public const string RESULT = 'keyring.result'; + /** * @param string $status a slug such as "device-revoked", with its message in keyring::status * @param array $data @@ -36,9 +42,14 @@ public function toResponse($request) } // Extra data goes under keyring.result: flashing "keyring" itself would - // replace the session's verifications and registry ID. - return ($this->redirect === null ? back() : redirect($this->redirect)) - ->with('status', $this->status) - ->with($this->data === [] ? [] : ['keyring.result' => $this->data]); + // replace the session's verifications and registry ID. It can hold a + // secret being set up or new recovery codes, so it's encrypted like + // the enrollment it came from, whatever the session driver. Pages + // read it back with Keyring::result(). + if ($this->data !== []) { + app(EncryptedSession::class)->flash(self::RESULT, $this->data); + } + + return ($this->redirect === null ? back() : redirect($this->redirect))->with('status', $this->status); } } diff --git a/src/Support/EncryptedSession.php b/src/Support/EncryptedSession.php index 4255ad58..8c0c03c8 100644 --- a/src/Support/EncryptedSession.php +++ b/src/Support/EncryptedSession.php @@ -12,7 +12,8 @@ /** * Keeps half-finished work (a login waiting for its second factor, an - * authenticator being set up) in the session as encrypted JSON, never + * authenticator being set up) and the results flashed for a page (a secret + * being set up, new recovery codes) in the session as encrypted JSON, never * serialize(). Encrypted even where the session already is, so a session * store that leaks doesn't give away a pending secret. * @@ -33,6 +34,16 @@ public function put(string $key, array $data): void $this->session->put($key, Crypt::encryptString(json_encode($data, JSON_THROW_ON_ERROR))); } + /** + * Put it for the next request only, as Laravel's flash data is. + * + * @param array $data + */ + public function flash(string $key, array $data): void + { + $this->session->flash($key, Crypt::encryptString(json_encode($data, JSON_THROW_ON_ERROR | JSON_INVALID_UTF8_SUBSTITUTE))); + } + /** * What was put under the key, or null when there's nothing there or it * can't be read back (APP_KEY changed, or it isn't Keyring's). diff --git a/tests/Feature/AuthenticatorManagementTest.php b/tests/Feature/AuthenticatorManagementTest.php index a40cfab8..0b9b8799 100644 --- a/tests/Feature/AuthenticatorManagementTest.php +++ b/tests/Feature/AuthenticatorManagementTest.php @@ -6,9 +6,11 @@ use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Http\Request; use Illuminate\Support\Facades\Event; +use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Notification; use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Validator; +use Illuminate\Support\Str; use Illuminate\Testing\TestResponse; use Keyring\Changes\AuthenticatorChanges; use Keyring\Concerns\HasKeyring; @@ -341,10 +343,45 @@ // The enrollment details are flashed for the page, without wiping // Keyring's other session data (verifications, the session registry). - expect(session('keyring.result.enrollment.secret'))->not->toBeNull(); + expect(Keyring::result('enrollment.secret'))->not->toBeNull(); $this->postJson(route('keyring.authenticators.store', 'totp'))->assertOk(); }); +// What a form or Inertia page is handed goes through the session store, and +// a store can be read without APP_KEY: a database, files, a backup. +it('keeps a secret being set up and new recovery codes out of the stored session', function () { + $directory = sys_get_temp_dir().'/keyring-sessions-'.Str::random(8); + mkdir($directory); + config(['session.driver' => 'file', 'session.files' => $directory]); + app('session')->forgetDrivers(); + app()->forgetInstance('session.store'); + $this->actingAs($this->user)->withAssurance(Assurance::AAL2); + $stored = fn () => implode('', array_map(file_get_contents(...), glob($directory.'/*') ?: [])); + + $this->inertia()->post(route('keyring.authenticators.store', 'totp'))->assertRedirect(); + $this->flushHeaders(); + $secret = Keyring::result('enrollment.secret'); + + expect($secret)->toBeString()->not->toBe('') + ->and($stored())->not->toBe('')->not->toContain($secret); + + $this->from('/settings')->post(route('keyring.authenticators.confirm', 'totp'), ['code' => totpCode($secret)])->assertRedirect('/settings'); + $codes = Keyring::result('recoveryCodes'); + + expect($codes)->toBeArray()->not->toBeEmpty(); + + foreach ($codes as $code) { + expect($stored())->not->toContain($code); + } + + // Read once, by the next request, like any flash. + $this->get('/settings'); + $this->get('/settings'); + + expect(Keyring::result())->toBeNull(); + File::deleteDirectory($directory); +}); + it('only allows the shorter password with a real second factor, not recovery codes alone', function () { $codes = Authenticator::factory()->recoveryCodes()->for($this->user, 'authenticatable')->create(); diff --git a/tests/Fixtures/public-api.json b/tests/Fixtures/public-api.json index 7ed80bce..74238d1f 100644 --- a/tests/Fixtures/public-api.json +++ b/tests/Fixtures/public-api.json @@ -271,6 +271,7 @@ "resetUserPasswordsUsing", "respondWith", "response", + "result", "risk", "routes", "securityEventModel", From f338ff3de9ef3753fb193dc0a6ae2cdae9ce4a6d Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Tue, 17 Nov 2026 20:28:59 +0000 Subject: [PATCH 4/9] fix(passwords): save a password change only over the password it checked, while its session is still signed in --- CHANGELOG.md | 2 +- docs/protected-changes.md | 2 +- docs/security.md | 2 +- src/Changes/PasswordChanges.php | 38 +++++++++-- src/Http/Controllers/PasswordController.php | 1 + tests/Concurrency/RaceTest.php | 24 +++++++ tests/Concurrency/worker.php | 14 ++++ tests/Feature/PasswordResetTest.php | 76 +++++++++++++++++++++ 8 files changed, 152 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 996c6aff..3cf2322b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,7 +37,7 @@ The first release. Nothing is tagged yet. - Protected `email` and `password` attributes, 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 resets that sign nobody in, end every session and leave second factors alone. +- 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_URL` and opened on pages that send no referrer. diff --git a/docs/protected-changes.md b/docs/protected-changes.md index 95889190..ae4228b6 100644 --- a/docs/protected-changes.md +++ b/docs/protected-changes.md @@ -207,7 +207,7 @@ Your action doesn't need to check `current_password` again. One that still does, A user without a password (for example, one who only uses passkeys) can set one with just the fresh verification. -Keyring runs your action as one of its own flows, so it may change the protected `password` attribute, and only that: changing `email` there still throws. The action must save a new password or throw a `ValidationException`; returning without saving throws a `LogicException`, since everything that follows assumes the password changed. Afterwards Keyring regenerates the session ID, destroying the old one, cancels any pending email change, ends any reset links still outstanding, stops trusting the user's devices, including this one, and starts the account's sign-in limits over as a reset does, so a password that too many wrong guesses had got refused works again. With `sign_out_others` on, it also revokes every other session and changes the "remember me" token. The response is the `password-updated` [status response](sign-in-flow.md#status-responses). +Keyring runs your action as one of its own flows, so it may change the protected `password` attribute, and only that: changing `email` there still throws. The action must save a new password or throw a `ValidationException`; returning without saving throws a `LogicException`, since everything that follows assumes the password changed. It runs holding the user's row, and the save only goes ahead while the session is still signed in and the stored password is still the one `current_password` was checked against: a change that a reset, or a change from another session, overtook is refused, with the reset's password left in place. Your action's validation and hashing run in that transaction, while the row is held, so anything else it does (an event, a queued email) happens before the save commits, and on PostgreSQL a query error it catches leaves the save undone. A sign in that rehashes the same password at that moment makes the change fail as a wrong current password, and sending it again works. If your own code calls `PasswordChanges::change()`, don't call it inside a transaction of yours: the lock would then be held through what comes after the save, which takes other rows. Afterwards Keyring regenerates the session ID, destroying the old one, cancels any pending email change, ends any reset links still outstanding, stops trusting the user's devices, including this one, and starts the account's sign-in limits over as a reset does, so a password that too many wrong guesses had got refused works again. With `sign_out_others` on, it also revokes every other session and changes the "remember me" token. The response is the `password-updated` [status response](sign-in-flow.md#status-responses). ## Requiring a Password Change diff --git a/docs/security.md b/docs/security.md index 448c3f4b..97029a09 100644 --- a/docs/security.md +++ b/docs/security.md @@ -199,7 +199,7 @@ The failures in a row and the locks held until a reset are in your database eith - Reverting an email change signs out every session, ends any sign in still waiting for its second factor, closes later changes and removes sign-in methods that weren't established when it was asked for, with the recovery codes when none of what's left is a factor for them to recover. Cancelling a change doesn't stop its revert link working. - While an email change can be reverted, nobody else can take the address it replaced, so the revert always has somewhere to put it back. - Password resets give the same answer for every address, sign out every session, cancel pending email changes, and lift risk locks and sign-in lockouts. -- A password change takes the current password as well as a fresh verification, checked by Keyring itself rather than by your action. A user with no password yet sets one with the fresh verification alone. +- A password change takes the current password as well as a fresh verification, checked by Keyring itself rather than by your action. A user with no password yet sets one with the fresh verification alone. The new password is only saved over the one that was checked, under a row lock, and only while the session is still signed in, so a change that overlaps a reset can't replace the password the reset set. - Password changes cancel pending email changes, so someone who knew the old password can't finish one. - Every change to how someone signs in can end their other sessions. A password reset and a reverted email change end every session. A password change and an applied email change end the others unless told not to (`sign_out_others` on the request, `email_changes.sign_out_others` in the config). Adding or removing an authenticator, or making new recovery codes, ends them when the request asks (`sign_out_others`). And "sign out everywhere else" (`DELETE /user/sessions`) is always registered, whatever features are on. - New passwords need at least 8 characters with a second factor and 15 without, and neither minimum can be configured below 8. Any characters are accepted, with no composition rules. diff --git a/src/Changes/PasswordChanges.php b/src/Changes/PasswordChanges.php index 420b1eb9..47ce8d34 100644 --- a/src/Changes/PasswordChanges.php +++ b/src/Changes/PasswordChanges.php @@ -5,8 +5,10 @@ namespace Keyring\Changes; use Closure; +use Illuminate\Auth\AuthenticationException; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Database\Eloquent\Model; +use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use Illuminate\Validation\ValidationException; use Keyring\Events\PasswordChanged; @@ -14,6 +16,7 @@ use Keyring\Risk\RiskLocks; use Keyring\Sessions\Sessions; use Keyring\Support\PasswordRules; +use Keyring\Support\RowLock; use Keyring\Support\Throttle; use LogicException; use RuntimeException; @@ -47,13 +50,35 @@ public function __construct( * Saving it again as the new one is refused: nothing would have changed, * and a user held until they change it would be let go. * + * The save holds the user's row, and only goes ahead over the password + * $user was loaded with, the one $current was checked against: a reset + * or another change that finished since has stored a different one, and + * this is refused rather than saved over it. Given the request, it's + * also refused once the request's session has been signed out, as a + * reset does. + * * @param Closure(): void $save * * @throws ValidationException + * @throws AuthenticationException */ - public function change(Authenticatable&Model $user, Closure $save, ?string $currentSession, bool $signOutOthers = true, #[\SensitiveParameter] ?string $current = null): void + public function change(Authenticatable&Model $user, Closure $save, ?string $currentSession, bool $signOutOthers = true, #[\SensitiveParameter] ?string $current = null, ?Request $request = null): void { - if (! $this->save($user, $save, old: $current)) { + $checked = (string) $user->getAuthPassword(); + + $overChecked = function (Authenticatable&Model $stored, Closure $write) use ($checked): void { + if (! hash_equals($checked, (string) $stored->getAuthPassword())) { + throw ValidationException::withMessages(['current_password' => __('validation.current_password')]); + } + + $write(); + }; + + $hold = fn (Closure $write) => $request === null + ? RowLock::hold($user, fn (?Model $stored) => $stored instanceof Authenticatable ? $overChecked($stored, $write) : throw new AuthenticationException) + : $this->sessions->whileSignedIn($request, $user, fn (Authenticatable&Model $stored) => $overChecked($stored, $write)); + + if (! $this->save($user, $save, old: $current, hold: $hold)) { throw ValidationException::withMessages(['password' => __('keyring::keyring.password_unchanged')]); } @@ -103,13 +128,18 @@ public function reset(Authenticatable&Model $user, Closure $save, #[\SensitivePa * password has nothing to be the same as. With $keepHold the rest still * happens for a password that didn't change, and only the hold is kept. * + * $hold, when given, runs the write: it holds the row while it does. + * What follows the write takes other rows, and runs once it has let go. + * * @param Closure(): void $save + * @param (Closure(Closure(): void): void)|null $hold */ - protected function save(Authenticatable&Model $user, Closure $save, #[\SensitiveParameter] ?string $old = null, #[\SensitiveParameter] ?string $new = null, bool $keepHold = false): bool + protected function save(Authenticatable&Model $user, Closure $save, #[\SensitiveParameter] ?string $old = null, #[\SensitiveParameter] ?string $new = null, bool $keepHold = false, ?Closure $hold = null): bool { $before = $user->getAuthPassword(); + $write = fn () => $this->protection->changing($save, only: [$user->getAuthPasswordName()]); - $this->protection->changing($save, only: [$user->getAuthPasswordName()]); + $hold === null ? $write() : $hold($write); $after = $user->newQuery()->whereKey($user->getKey())->first()?->getAuthPassword(); diff --git a/src/Http/Controllers/PasswordController.php b/src/Http/Controllers/PasswordController.php index 1897c9b2..d142d12e 100644 --- a/src/Http/Controllers/PasswordController.php +++ b/src/Http/Controllers/PasswordController.php @@ -48,6 +48,7 @@ public function update(Request $request, UpdatesUserPasswords $updater, Password signOutOthers: $request->boolean('sign_out_others', true), // Only one that was checked: an account with no password has none. current: filled($user->getAuthPassword()) && is_string($current = $request->input('current_password')) ? $current : null, + request: $request, ); $sessions->rotate($request); diff --git a/tests/Concurrency/RaceTest.php b/tests/Concurrency/RaceTest.php index d5813924..d5c90d89 100644 --- a/tests/Concurrency/RaceTest.php +++ b/tests/Concurrency/RaceTest.php @@ -3,6 +3,8 @@ declare(strict_types=1); use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Hash; +use Keyring\Changes\PasswordChanges; use Keyring\Contracts\SessionRegistry; use Keyring\Enums\Assurance; use Keyring\Facades\Keyring; @@ -220,6 +222,28 @@ 'still signed in' => [false, 'added'], ]); +// A password saved while the change waits for the user's row: a reset's +// UPDATE, or another session's change. The change then finds a password it +// didn't check, and is refused. +it('refuses a password change whose current password is replaced while its request waits', function (string $meanwhile, string $expected, string $stored) { + $user = taylor(); + $now = now()->getTimestamp(); + app(SessionRegistry::class)->save(new RegisteredSession('asking', (string) $user->id, RegisteredSession::typeOf($user), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600)); + + [$changed] = contend($user, [['change-password', $user->id, 'asking']], fn () => match ($meanwhile) { + 'reset' => app(PasswordChanges::class)->reset($owner = $user->fresh(), fn () => $owner->forceFill(['password' => 'the reset password'])->save()), + 'change' => app(PasswordChanges::class)->change($other = $user->fresh(), fn () => $other->forceFill(['password' => 'the reset password'])->save(), currentSession: 'asking', signOutOthers: false), + default => null, + }); + + expect($changed)->toBe($expected) + ->and(Hash::check($stored, $user->fresh()->password))->toBeTrue(); +})->with([ + 'reset meanwhile' => ['reset', 'signed out', 'the reset password'], + 'changed elsewhere meanwhile' => ['change', 'refused', 'the reset password'], + 'nothing meanwhile' => ['', 'changed', 'a passphrase sent a moment later'], +]); + it('lets one of two requests use a "remember me" cookie, and starts one session between them', function () { $user = taylor(); $now = now()->getTimestamp(); diff --git a/tests/Concurrency/worker.php b/tests/Concurrency/worker.php index 6189434c..07a7282e 100644 --- a/tests/Concurrency/worker.php +++ b/tests/Concurrency/worker.php @@ -13,6 +13,7 @@ use Illuminate\Validation\ValidationException; use Keyring\Changes\AuthenticatorChanges; use Keyring\Changes\EmailChanges; +use Keyring\Changes\PasswordChanges; use Keyring\Contracts\SessionRegistry; use Keyring\Enums\Assurance; use Keyring\Enums\Purpose; @@ -112,6 +113,19 @@ 'sign-out-everyone' => app(SessionRegistry::class)->revokeEveryone(), 'confirm-email-change' => app(EmailChanges::class)->confirm(PendingChange::findOrFail($id), $value)->name, 'revert-email-change' => app(EmailChanges::class)->revert(PendingChange::findOrFail($id), $value), + 'change-password' => (function () use ($id, $value) { + // A request its middleware let through as this session, with its + // current password checked against the user it loaded. + $request = Request::create('/user/password', 'PUT'); + $request->setLaravelSession(app('session.store')); + $request->session()->put(Sessions::KEY, $value); + + $user = User::findOrFail($id); + + app(PasswordChanges::class)->change($user, fn () => $user->forceFill(['password' => 'a passphrase sent a moment later'])->save(), currentSession: $value, request: $request); + + return 'changed'; + })(), 'request-email-change' => (function () use ($id, $value) { // A request its middleware let through as this session. $request = Request::create('/user/email', 'POST'); diff --git a/tests/Feature/PasswordResetTest.php b/tests/Feature/PasswordResetTest.php index 4ad17010..de6014b5 100644 --- a/tests/Feature/PasswordResetTest.php +++ b/tests/Feature/PasswordResetTest.php @@ -10,12 +10,14 @@ use Illuminate\Support\Timebox; use Keyring\Changes\PasswordChanges; use Keyring\Contracts\SessionRegistry; +use Keyring\Enums\Assurance; use Keyring\Events\FactorVerified; use Keyring\Events\PasswordChanged as PasswordChangedEvent; use Keyring\Facades\Keyring; use Keyring\Features; use Keyring\Models\Authenticator; use Keyring\Notifications\PasswordChanged; +use Keyring\Sessions\RegisteredSession; use Keyring\Tests\Fixtures\User; beforeEach(function () { @@ -233,6 +235,80 @@ public function check(#[SensitiveParameter] $value, $hashedValue, array $options ->and(app(SessionRegistry::class)->forUser($user))->toBeEmpty(); }); +/** + * A hasher that plays the given work just before its next check: after a + * request has loaded the user, while it checks their current password, and + * before it holds their row. + */ +function beforeNextHashCheck(Closure $work): void +{ + Hash::extend('racing', fn () => new class(['rounds' => 4]) extends BcryptHasher + { + public static ?Closure $before = null; + + public function check(#[SensitiveParameter] $value, $hashedValue, array $options = []) + { + [$before, self::$before] = [self::$before, null]; + $before?->__invoke(); + + return parent::check($value, $hashedValue, $options); + } + }); + config(['hashing.driver' => 'racing']); + + Hash::driver()::$before = $work; +} + +// The change checked the password the reset replaced. Saved anyway, it +// would put a password the owner never chose over the one they just did. +it('does not save a password change over a reset that finished while its current password was being checked', function () { + $user = taylor(); + $this->post('/login', ['email' => 'taylor@example.com', 'password' => 'password']); + + beforeNextHashCheck(function () use ($user) { + app(PasswordChanges::class)->reset( + $owner = $user->fresh(), + fn () => $owner->forceFill(['password' => 'a-brand-new-long-password-1'])->save(), + ); + + // The owner signs in again with the password they just chose. + $now = now()->getTimestamp(); + app(SessionRegistry::class)->save(new RegisteredSession('owner', (string) $user->id, RegisteredSession::typeOf($user), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600)); + }); + + $this->putJson(route('user-password.update'), [ + 'current_password' => 'password', + 'password' => 'a passphrase the owner never chose', + 'password_confirmation' => 'a passphrase the owner never chose', + ])->assertUnauthorized(); + + expect(Hash::check('a-brand-new-long-password-1', $user->fresh()->password))->toBeTrue() + ->and(app(SessionRegistry::class)->find('owner')?->isActive(now()->getTimestamp()))->toBeTrue(); +}); + +// Another of the account's sessions changed the password and kept this one +// signed in. What this request checked is no longer the password. +it('does not save a password change over another that finished while its current password was being checked', function () { + $user = taylor(); + $this->post('/login', ['email' => 'taylor@example.com', 'password' => 'password']); + + beforeNextHashCheck(fn () => app(PasswordChanges::class)->change( + $other = $user->fresh(), + fn () => $other->forceFill(['password' => 'a-brand-new-long-password-1'])->save(), + currentSession: null, + signOutOthers: false, + )); + + $this->putJson(route('user-password.update'), [ + 'current_password' => 'password', + 'password' => 'a passphrase sent a moment later', + 'password_confirmation' => 'a passphrase sent a moment later', + ])->assertUnprocessable()->assertJsonValidationErrors('current_password'); + + expect(Hash::check('a-brand-new-long-password-1', $user->fresh()->password))->toBeTrue(); + $this->assertAuthenticated(); +}); + it('does not leave a browser trusted by a sign in that a reset ended', function () { withFeatures([Features::resetPasswords(), Features::devices()]); config(['keyring.devices.trust_for' => '30d']); From 4b0a559cc6904f82d49e58f5ef51345a3b92e9f9 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Tue, 17 Nov 2026 20:31:05 +0000 Subject: [PATCH 5/9] fix(registration): keep a followed verification link under a new session id --- CHANGELOG.md | 2 +- docs/security.md | 2 +- docs/sign-in-flow.md | 2 +- src/Login/VerificationLink.php | 5 ++++- tests/Feature/RegistrationTest.php | 33 ++++++++++++++++++++++++++++++ 5 files changed, 40 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3cf2322b..985bc214 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ The first release. Nothing is tagged yet. ### 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. `registration.reveal_taken` says when an address is taken instead. +- 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_taken` says 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/passkeys` client. 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, and `allowOnly()` to limit them to certain models by AAGUID. diff --git a/docs/security.md b/docs/security.md index 97029a09..3a3848c4 100644 --- a/docs/security.md +++ b/docs/security.md @@ -53,7 +53,7 @@ Guarantees about a [feature](quick-start.md#adding-features), such as devices or - The session ID is regenerated and the old one destroyed when a user proves a factor (signing in or stepping up), changes their password or signs out everywhere else, so a copied session cookie stops working, and someone who planted a session ID before the password step doesn't share the pending login. On Laravel's `cookie` session driver, where there is nothing on the server to destroy, the old copy is signed out through its registry record instead. - A password reset never signs anyone in, so the policy still applies at the next login. - Registration doesn't reveal whether an address has an account, unless you set `registration.reveal_taken`. A free address, a taken one, one reserved for its previous owner and one whose account you keep out get the same response, status, cookies and session, after the same validation, in at least `timebox`, with one password hash each and every email sent after the response. Nobody is signed in by registering. Whether an address is taken is decided by Keyring, not by your action, so the guarantee doesn't depend on how the action is written, as long as it doesn't check for itself. A password the hasher can't take is refused for every address whatever the action's rules, and anything else `create()` throws is reported and answered like the rest. See [Registration](sign-in-flow.md#without-revealing-who-has-an-account). -- With that registration, an account can't be signed in until its address is verified, and a correct password is answered like a wrong one until then. Verifying takes the emailed link and the password together, so neither someone who registered an address they can't read mail for, nor its owner who never chose that password, ends up with a verified account. A finished password reset also verifies the address. +- With that registration, an account can't be signed in until its address is verified, and a correct password is answered like a wrong one until then. Verifying takes the emailed link and the password together, so neither someone who registered an address they can't read mail for, nor its owner who never chose that password, ends up with a verified account. A followed link is kept under a new session ID, so it only lets in the browser that followed it, even one whose session ID someone else also held. A finished password reset also verifies the address. - Checking a password can rehash it under the app's current settings. The new hash is only saved over the one that was checked, under a row lock, so a sign in that overlaps a reset can't write the old password back, and whatever device trust it was given is withdrawn when it's ended. - A login attempt can't sign the owner out. Risk responses at login never revoke sessions, change the "remember me" token or stop trusting devices, even from a custom responder. diff --git a/docs/sign-in-flow.md b/docs/sign-in-flow.md index fab0716c..8227902a 100644 --- a/docs/sign-in-flow.md +++ b/docs/sign-in-flow.md @@ -288,7 +288,7 @@ A new user can't sign in until their address is verified. If they could, anyone Verifying takes the emailed link and the password together: -1. The user follows the link. Their browser isn't signed in, so Keyring remembers the link in the session and sends them to the login page with the `sign-in-to-verify` status. Opening the link changes nothing by itself, so a mail scanner that fetches it verifies nothing. +1. The user follows the link. Their browser isn't signed in, so Keyring remembers the link in the session, under a new session ID, and sends them to the login page with the `sign-in-to-verify` status. The new ID means only the browser that followed the link holds it, whoever else had the one it came with. It comes with a new CSRF token, so a login page already open in another tab of that browser needs reloading before it can post. Opening the link changes nothing by itself, so a mail scanner that fetches it verifies nothing. 2. They sign in. From the browser that followed the link, their account may sign in, and doing so verifies the address (Laravel's `Verified` event fires). They're sent back to the link, which has nothing left to do and sends them on to `home`. From then on they sign in anywhere, like anyone else. A link works until it expires (`auth.verification.expire`, 60 minutes), and registering again with the same address sends a new one. A finished [password reset](protected-changes.md#resetting-the-password) verifies the address too, since its link went to the same inbox. That's the way in for the owner of an address someone else registered first: they can't verify an account whose password they don't know, and whoever registered it never sees the link. diff --git a/src/Login/VerificationLink.php b/src/Login/VerificationLink.php index daa04fb6..1e5fc9cf 100644 --- a/src/Login/VerificationLink.php +++ b/src/Login/VerificationLink.php @@ -34,10 +34,13 @@ public function __construct( ) {} /** - * Keep a link whose signature has been checked, for as long as it's good. + * Keep a link whose signature has been checked, for as long as it's good, + * under a new session ID: one only the browser that followed it holds, + * whoever else had the ID it came with. */ public function remember(Request $request, string $id, string $hash): void { + $request->session()->regenerate(true); $request->session()->put(self::KEY, ['id' => $id, 'hash' => $hash, 'expires' => $request->integer('expires')]); } diff --git a/tests/Feature/RegistrationTest.php b/tests/Feature/RegistrationTest.php index df6ff620..b4116847 100644 --- a/tests/Feature/RegistrationTest.php +++ b/tests/Feature/RegistrationTest.php @@ -13,6 +13,7 @@ use Illuminate\Foundation\Http\Events\RequestHandled; use Illuminate\Notifications\AnonymousNotifiable; use Illuminate\Support\Arr; +use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Exceptions; use Illuminate\Support\Facades\Hash; @@ -614,6 +615,38 @@ protected function usleep(int $microseconds): void $this->assertGuest(); }); + // The link is kept under a session ID only the browser that followed it + // holds, whatever ID that browser came with. + it('keeps a followed link under a new session id, so a browser holding the old one can\'t sign in with it', function () { + $this->post('/register', registrationForm()); + $user = User::sole(); + $cookie = config('session.cookie'); + + // A browser that sends only this session ID, and nothing else of this one. + $as = function (string $id) use ($cookie) { + session()->flush(); + Auth::forgetGuards(); + + return $this->withCredentials()->withOnlyCookies([$cookie => $id]); + }; + + $this->flushSession(); + $shared = $this->get('/login')->getCookie($cookie)->getValue(); + $followed = $as($shared)->get(verificationLinkSentTo($user))->assertRedirect(route('login'))->getCookie($cookie)->getValue(); + + expect($followed)->not->toBe($shared); + + $as($shared)->post('/login', ['email' => 'taylor@example.com', 'password' => 'correct horse battery staple']) + ->assertSessionHasErrors(['email' => __('auth.failed')]); + $this->assertGuest(); + expect($user->fresh()->hasVerifiedEmail())->toBeFalse(); + + $as($followed)->post('/login', ['email' => 'taylor@example.com', 'password' => 'correct horse battery staple']) + ->assertSessionHasNoErrors(); + $this->assertAuthenticatedAs($user); + expect($user->fresh()->hasVerifiedEmail())->toBeTrue(); + }); + it('stops accepting a followed link once it has expired, or the address has changed', function (Closure $change) { $this->post('/register', registrationForm()); $user = User::sole(); From efdc8d5267ce29e7f82caaec7627bc9114f52cbf Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Tue, 17 Nov 2026 20:35:10 +0000 Subject: [PATCH 6/9] fix(log): write an entry whatever text it holds, and keep authenticator names valid utf-8 --- CHANGELOG.md | 2 +- docs/authenticators.md | 4 +- docs/security.md | 2 +- lang/en/keyring.php | 1 + src/Activity/SecurityLog.php | 38 +++++++++++++++++-- src/Factors/Factor.php | 27 ++++++++++++- .../Controllers/AuthenticatorController.php | 7 +++- src/Models/Authenticator.php | 14 +++++++ tests/Feature/AuthenticatorManagementTest.php | 30 +++++++++++++++ tests/Feature/CommandsTest.php | 14 +++++++ tests/Feature/SecurityLogTest.php | 36 ++++++++++++++++++ 11 files changed, 166 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 985bc214..342d135f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,7 +50,7 @@ The first release. Nothing is tagged yet. ### 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. Without the table it goes to your app's log. +- 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. diff --git a/docs/authenticators.md b/docs/authenticators.md index c514dd95..513304d5 100644 --- a/docs/authenticators.md +++ b/docs/authenticators.md @@ -87,7 +87,7 @@ Adding is always two steps. Nothing is saved until the second one succeeds. } ``` -Authenticator apps and email codes take an optional `name` when beginning or confirming (the one sent when confirming wins); passkeys and security keys take it when confirming. Names default to "Authenticator app", "Email", "Passkey" or "Security key", and are cut to 64 characters. +Authenticator apps and email codes take an optional `name` when beginning or confirming (the one sent when confirming wins); passkeys and security keys take it when confirming. Names default to "Authenticator app", "Email", "Passkey" or "Security key", and are cut to 64 characters. A name that isn't valid UTF-8, or holds a NUL character, is refused with an error on `name`. ### Confirming @@ -148,7 +148,7 @@ It loads the user's authenticators, so keep it lazy as above. A session that jus | Field | | |---|---| -| `name` | Optional, up to 64 characters. | +| `name` | Optional, up to 64 characters of valid UTF-8. | | `default` | Optional boolean. `true` makes this the default and clears the flag on the user's others. Not allowed for recovery codes. | The default authenticator is offered first when a second factor is needed. Recovery codes are a fallback, so they can't be made the default. diff --git a/docs/security.md b/docs/security.md index 3a3848c4..2e4f54ec 100644 --- a/docs/security.md +++ b/docs/security.md @@ -267,7 +267,7 @@ A URL ends up in places a request's body doesn't: access logs, proxies, the brow ### Logging -- Sign ins, failed factors, lockouts, session starts and ends, sessions "remember me" carried on, and every change to how an account signs in are recorded as shipped. A session your own code starts with `Auth::login()` isn't. They go in the [security log](security-log-and-emails.md) table, which is on by default, or in your app's log when you turn the table off. There is no setting that records nothing. +- Sign ins, failed factors, lockouts, session starts and ends, sessions "remember me" carried on, and every change to how an account signs in are recorded as shipped. A session your own code starts with `Auth::login()` isn't. They go in the [security log](security-log-and-emails.md) table, which is on by default, or in your app's log when you turn the table off. There is no setting that records nothing. Text in an entry's details that isn't valid UTF-8, such as an authenticator's name stored before Keyring refused it, is cleaned up so the entry is still written. One whose details can't be kept at all is written without them and the reason reported. Authenticator names are kept as valid UTF-8 however they're saved. - What was refused is recorded too: a request for someone else's authenticator, device or verification link, a sign-in method that wasn't added, a removal that would have left the account unable to sign in, an emailed link with a wrong, ended or expired token or signature, a request the form rate limiter turned away, and a verification the pipeline's final gate turned away. None of it changes the answer the requester gets. - No entry holds a password, code, token, signature, session ID or request body, in the table or in the app's log. Form validation errors aren't logged. - Every entry carries a severity, the ID of the request that wrote it and the time. In the table the time is in your `app.timezone`, which is UTC unless you changed it; in your app's log it's written with its offset. See [Times](security-log-and-emails.md#times). diff --git a/lang/en/keyring.php b/lang/en/keyring.php index 1558c4e0..f9d1f76c 100644 --- a/lang/en/keyring.php +++ b/lang/en/keyring.php @@ -25,6 +25,7 @@ 'device_name' => ':browser on :platform', 'unknown_device' => 'Unknown device', 'near' => 'near :place', + 'invalid_name' => 'The :attribute has characters that aren\'t valid text.', 'password_null_byte' => 'The :attribute can\'t contain a null character.', 'password_too_long' => 'The :attribute is too long. It can take up 72 bytes: that\'s 72 plain letters, digits and symbols, and fewer with accented letters, other alphabets or emoji.', 'unavailable' => 'Your account needs a sign-in method that isn\'t set up. Please contact support.', diff --git a/src/Activity/SecurityLog.php b/src/Activity/SecurityLog.php index e7e0c452..c4425863 100644 --- a/src/Activity/SecurityLog.php +++ b/src/Activity/SecurityLog.php @@ -41,13 +41,25 @@ public function __construct( /** * Log an event: in keyring_events with Features::securityLog(), and in * the app's log without it, so it's always recorded somewhere. An entry - * the table won't take is reported and goes to the app's log instead. + * the table won't take is reported and goes to the app's log instead, + * and one whose details can't be kept is reported and logged without + * them. * * @param array $meta */ public function record(string $type, ?Authenticatable $user = null, ?string $factor = null, ?string $device = null, array $meta = [], ?Severity $severity = null): ?SecurityEvent { - return rescue(fn () => $this->keep($this->entry($type, $user, $factor, $device, $meta, $severity), orWrite: true)); + return rescue(function () use ($type, $user, $factor, $device, $meta, $severity) { + try { + $event = $this->entry($type, $user, $factor, $device, $meta, $severity); + } catch (Throwable $e) { + report($e); + + $event = $this->entry($type, $user, $factor, $device, [], $severity); + } + + return $this->keep($event, orWrite: true); + }); } /** @@ -173,7 +185,7 @@ protected function entry(string $type, ?Authenticatable $user, ?string $factor, 'ip' => $this->keyring->recordedIp(request()), 'user_agent' => UserAgent::from(request()), 'request_id' => $this->requestId(), - 'meta' => $meta === [] ? null : $meta, + 'meta' => $meta === [] ? null : $this->scrubbed($meta), 'created_at' => now(), ]); @@ -184,6 +196,26 @@ protected function entry(string $type, ?Authenticatable $user, ?string $factor, return $event; } + /** + * The details with any text in them made valid UTF-8, as the table's JSON + * and the log's need it to be. Some of it is chosen by whoever the entry + * is about, an authenticator's name say, and must not keep it from + * being written. + * + * @param array $meta + * @return array + */ + protected function scrubbed(array $meta): array + { + array_walk_recursive($meta, function (mixed &$value) { + if (is_string($value)) { + $value = mb_scrub($value, 'UTF-8'); + } + }); + + return $meta; + } + /** * Keep the entry in the table, or in the app's log when the table is * off. With $orWrite, one the table won't take goes there as well. diff --git a/src/Factors/Factor.php b/src/Factors/Factor.php index eebb3d14..cce98d1a 100644 --- a/src/Factors/Factor.php +++ b/src/Factors/Factor.php @@ -147,7 +147,32 @@ protected function makeAuthenticator(array $attributes): Authenticator */ public function enrollmentRules(): array { - return [...$this->rules(), 'name' => ['nullable', 'string', 'max:64']]; + return [...$this->rules(), 'name' => ['nullable', ...self::nameRules()]]; + } + + /** + * What an authenticator's name must be, wherever the user gives one: + * text of up to 64 characters, and valid UTF-8, which the log, the + * pages and the databases that store it all need. + * + * @return list + */ + public static function nameRules(): array + { + return ['string', 'max:64', self::validText()]; + } + + /** + * Refuses text that isn't valid UTF-8, or that holds a NUL character no + * database keeps, and leaves anything else to the other rules. + */ + public static function validText(): Closure + { + return function (string $attribute, mixed $value, Closure $fail) { + if (is_string($value) && (! mb_check_encoding($value, 'UTF-8') || str_contains($value, "\0"))) { + $fail(__('keyring::keyring.invalid_name')); + } + }; } /** diff --git a/src/Http/Controllers/AuthenticatorController.php b/src/Http/Controllers/AuthenticatorController.php index ae1671bc..bd1e40dd 100644 --- a/src/Http/Controllers/AuthenticatorController.php +++ b/src/Http/Controllers/AuthenticatorController.php @@ -15,6 +15,7 @@ use Keyring\Enrollment\Enrollment; use Keyring\Enrollment\EnrollmentStore; use Keyring\Events\EnrollmentRefused; +use Keyring\Factors\Factor; use Keyring\Factors\RecoveryCodes; use Keyring\Http\Controllers\Concerns\RespondsWithStatus; use Keyring\KeyringManager; @@ -54,6 +55,10 @@ public function store(Request $request, string $factor): StatusResponse { $factor = $this->enrollable($request, $factor); + // A name given now is kept for the confirm, which may not send one. + // Anything that isn't text is left out of it, as before. + Input::validate($request, ['name' => [Factor::validText()]]); + // Enrolling a code factor sends a code, wherever the user asks for it to go. if ($factor instanceof SendsCodes) { $this->throttle->sending($factor->key(), $this->keyring->user()); @@ -108,7 +113,7 @@ public function update(Request $request, string $authenticator): StatusResponse $authenticator = $this->changes->find($this->keyring->user(), $authenticator); $changes = $request->validate([ - 'name' => ['sometimes', 'string', 'max:64'], + 'name' => ['sometimes', ...Factor::nameRules()], // Recovery codes are a fallback, never the way to sign in first. 'default' => ['sometimes', 'boolean', Rule::prohibitedIf($authenticator->factor === RecoveryCodes::KEY)], ]); diff --git a/src/Models/Authenticator.php b/src/Models/Authenticator.php index 8938495c..4cf4e29f 100644 --- a/src/Models/Authenticator.php +++ b/src/Models/Authenticator.php @@ -12,6 +12,7 @@ use Illuminate\Database\Eloquent\Attributes\Unguarded; use Illuminate\Database\Eloquent\Attributes\UseFactory; use Illuminate\Database\Eloquent\Builder; +use Illuminate\Database\Eloquent\Casts\Attribute; use Illuminate\Database\Eloquent\Concerns\HasUlids; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; @@ -110,6 +111,19 @@ public function isVirtual(): bool return ! $this->exists && $this->id === $this->factor; } + /** + * A name is stored as valid UTF-8, without NUL characters, however it got here: an import, your + * own code, a factor of your own. Keyring's forms refuse one that isn't, + * and what's left of one is kept rather than breaking the pages and the + * log entries that show it. + * + * @return Attribute + */ + protected function name(): Attribute + { + return Attribute::make(set: fn (mixed $value) => is_string($value) ? str_replace("\0", '', mb_scrub($value, 'UTF-8')) : $value); + } + public function markAsUsed(): void { if (! $this->isVirtual()) { diff --git a/tests/Feature/AuthenticatorManagementTest.php b/tests/Feature/AuthenticatorManagementTest.php index 0b9b8799..3af0872e 100644 --- a/tests/Feature/AuthenticatorManagementTest.php +++ b/tests/Feature/AuthenticatorManagementTest.php @@ -303,6 +303,36 @@ ->assertJsonValidationErrors('name'); }); +// Sent as a form: JSON can't carry text that isn't valid UTF-8. +it('refuses a name that isn\'t valid text, on a rename and when adding one', function () { + $totp = Authenticator::factory()->totp()->for($this->user, 'authenticatable')->create(['name' => 'Phone']); + $json = ['Accept' => 'application/json']; + + $this->patch(route('keyring.authenticators.update', $totp->id), ['name' => "\xff"], $json)->assertJsonValidationErrors('name'); + $this->patchJson(route('keyring.authenticators.update', $totp->id), ['name' => "Work\0phone"])->assertJsonValidationErrors('name'); + expect($totp->fresh()->name)->toBe('Phone'); + + $this->post(route('keyring.authenticators.store', 'totp'), ['name' => "\xff"], $json)->assertJsonValidationErrors('name'); + + $secret = $this->postJson(route('keyring.authenticators.store', 'totp'))->assertOk()->json('enrollment.secret'); + $this->post(route('keyring.authenticators.confirm', 'totp'), ['code' => totpCode($secret), 'name' => "Phone \xff"], $json) + ->assertJsonValidationErrors('name'); + + expect(Authenticator::query()->where('factor', 'totp')->count())->toBe(1); +}); + +it('keeps a name that isn\'t valid text as what can be read of it, however it is saved', function () { + $totp = Authenticator::factory()->totp()->for($this->user, 'authenticatable')->create(['name' => "Phone \xff"]); + app(AuthenticatorChanges::class)->update($totp, ['name' => "Work \xfe"]); + + expect(mb_check_encoding($totp->fresh()->name, 'UTF-8'))->toBeTrue() + ->and($totp->fresh()->name)->toStartWith('Work '); + + app(AuthenticatorChanges::class)->update($totp, ['name' => "Work\0phone"]); + + expect($totp->fresh()->name)->toBe('Workphone'); +}); + it('limits password guesses when removing the last second factor', function () { $totp = Authenticator::factory()->totp()->for($this->user, 'authenticatable')->create(); diff --git a/tests/Feature/CommandsTest.php b/tests/Feature/CommandsTest.php index 74c17832..4624d672 100644 --- a/tests/Feature/CommandsTest.php +++ b/tests/Feature/CommandsTest.php @@ -800,6 +800,20 @@ function passkeysTable(): void expect($this->user->keyring->refresh()->of('passkey')->first()->name)->toBe('MacBook'); }); + it('imports a passkey whose name isn\'t valid text as what can be read of it', function () { + if (DB::getDriverName() !== 'sqlite') { + $this->markTestSkipped('PostgreSQL and strict MySQL refuse to store text that isn\'t valid UTF-8.'); + } + + passkeysTable(); + DB::table('passkeys')->insert(['user_id' => $this->user->id, 'name' => "MacBook \xff", ...passkeyRow($this->user)]); + + $this->artisan('keyring:import', ['source' => 'fortify'])->assertSuccessful(); + + $name = Authenticator::query()->where('factor', 'passkey')->sole()->name; + expect(mb_check_encoding($name, 'UTF-8'))->toBeTrue()->and($name)->toStartWith('MacBook '); + }); + it('imports a passkey whose algorithm the app does not take, and says it will be refused', function (bool $dryRun) { $key = VirtualAuthenticator::rsa(); $other = User::create(['name' => 'Abigail', 'email' => 'abigail@example.com', 'password' => 'password']); diff --git a/tests/Feature/SecurityLogTest.php b/tests/Feature/SecurityLogTest.php index 8da03109..c130a76f 100644 --- a/tests/Feature/SecurityLogTest.php +++ b/tests/Feature/SecurityLogTest.php @@ -6,10 +6,14 @@ use Illuminate\Database\Eloquent\Attributes\Table; use Illuminate\Http\Request; use Illuminate\Support\Facades\Context; +use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Exceptions; use Illuminate\Support\Str; use Keyring\Activity\SecurityLog; +use Keyring\Enums\Assurance; use Keyring\Enums\Severity; +use Keyring\Events\AuthenticatorAdded; +use Keyring\Events\CloneSuspected; use Keyring\Facades\Keyring; use Keyring\Features; use Keyring\Models\Authenticator; @@ -111,6 +115,38 @@ function nextRequest(): void Exceptions::assertReportedCount(1); }); +// A name stored before Keyring refused ones like it, or straight into the +// table, is still in the entries about its authenticator. +it('logs what happens to an authenticator whose stored name isn\'t valid text', function () { + if (DB::getDriverName() !== 'sqlite') { + $this->markTestSkipped('PostgreSQL and strict MySQL refuse to store text that isn\'t valid UTF-8.'); + } + + Exceptions::fake(); + $this->actingAs($this->user)->withAssurance(Assurance::AAL2); + $odd = Authenticator::factory()->totp()->for($this->user, 'authenticatable')->create(); + Authenticator::factory()->totp()->for($this->user, 'authenticatable')->create(); + DB::table('keyring_authenticators')->where('id', $odd->id)->update(['name' => "\xff"]); + + AuthenticatorAdded::dispatch($this->user, $odd->fresh()); + CloneSuspected::dispatch($odd->fresh()); + $this->deleteJson(route('keyring.authenticators.destroy', $odd->id))->assertOk(); + + expect(loggedTypes())->toBe(['authenticator_added', 'clone_suspected', 'authenticator_removed']) + ->and(mb_check_encoding((string) json_encode(logEntry('authenticator_removed')->meta), 'UTF-8'))->toBeTrue(); + Exceptions::assertNothingReported(); +}); + +it('logs an entry whose details can\'t be kept without them, and reports why', function () { + Exceptions::fake(); + + app(SecurityLog::class)->record('authenticator_removed', $this->user, meta: ['name' => NAN]); + + expect(loggedTypes())->toBe(['authenticator_removed']) + ->and(logEntry('authenticator_removed')->meta)->toBeNull(); + Exceptions::assertReportedCount(1); +}); + it('logs a bypass to the app\'s log with the table off, and refuses it when that fails too', function () { config(['logging.default' => 'memory']); $log = logTo(); From fb0736d93a6ba4e74271d3a819ed99718d8d3d69 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Wed, 18 Nov 2026 10:15:57 +0000 Subject: [PATCH 7/9] fix(log): cut a factor key taken from the url to fit the log --- src/Activity/SecurityLog.php | 4 +++- tests/Feature/RefusedAccessTest.php | 11 +++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/Activity/SecurityLog.php b/src/Activity/SecurityLog.php index c4425863..cf4457e8 100644 --- a/src/Activity/SecurityLog.php +++ b/src/Activity/SecurityLog.php @@ -180,7 +180,9 @@ protected function entry(string $type, ?Authenticatable $user, ?string $factor, $event = new ($this->keyring->securityEventModel())([ 'type' => $type, 'severity' => $severity ?? Severity::of($type), - 'factor' => $factor, + // Taken from the URL for a refused enrollment, so cut to fit the + // column, and the entry is still kept. + 'factor' => $factor === null ? null : mb_substr($factor, 0, 64), 'device_id' => $device, 'ip' => $this->keyring->recordedIp(request()), 'user_agent' => UserAgent::from(request()), diff --git a/tests/Feature/RefusedAccessTest.php b/tests/Feature/RefusedAccessTest.php index 47501753..e4a458ab 100644 --- a/tests/Feature/RefusedAccessTest.php +++ b/tests/Feature/RefusedAccessTest.php @@ -145,6 +145,17 @@ ->and(logEntry('enrollment_refused')->user()->is($unverified))->toBeTrue(); }); +it('records a refusal for a factor key too long for the log, cut to fit', function () { + revealTakenAddresses(); + $unverified = User::create(['name' => 'New', 'email' => 'new@example.com', 'password' => 'password']); + + $this->actingAs($unverified)->withAssurance(Assurance::AAL1) + ->postJson(route('keyring.authenticators.store', str_repeat('a', 80))) + ->assertForbidden(); + + expect(logEntry('enrollment_refused')->factor)->toBe(str_repeat('a', 64)); +}); + it('records a refused attempt to remove the last sign-in method the account needs', function () { Event::fake([AuthenticatorRemovalRefused::class]); Keyring::require(Requirement::aal2()); From 4eea3f4bb1f6e8e99f8ee0a591fb06b610568b77 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Wed, 18 Nov 2026 10:15:57 +0000 Subject: [PATCH 8/9] docs(registration): describe the password and create() handling by what they enforce --- docs/sign-in-flow.md | 4 ++-- src/Login/Registration.php | 7 +++---- tests/Feature/RegistrationTest.php | 4 ++-- 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/docs/sign-in-flow.md b/docs/sign-in-flow.md index 8227902a..7fe047e2 100644 --- a/docs/sign-in-flow.md +++ b/docs/sign-in-flow.md @@ -276,8 +276,8 @@ By default (`registration.reveal_taken` is `false`), nobody can use the form to - The answer is always the same: a redirect to the login page with the `registration-received` status ("Thanks for registering. We've emailed that address with what to do next."), or that status as JSON. Nobody is signed in. - Validation errors from your action are shown as usual. They're the same for every address, because your action never looks at whether it's taken. -- After your action's `validate()`, Keyring refuses a password the hasher can't take, whatever your rules say: with bcrypt, one over 72 bytes or with a NUL byte. Only a free address hashes the password it was sent, so otherwise that address alone would fail. -- **If `create()` throws**, which only happens for a free address, the exception is passed to `report()` and the answer is the usual one. Nothing is created or sent, so the visitor is told to check an inbox that gets nothing, and a `create()` that keeps failing shows in your error tracker rather than as failed requests. A `ValidationException` thrown there is shown like any other validation error, since it's your action refusing the form on purpose. +- After your action's `validate()`, Keyring refuses a password the hasher can't take, whatever your rules say: with bcrypt, one over 72 bytes or with a NUL byte. It's refused the same for every address, before Keyring looks at whether the address is taken. +- **If `create()` throws**, the exception is passed to `report()` and the answer is the usual one. Nothing is created or sent, so the visitor is told to check an inbox that gets nothing, and a `create()` that keeps failing shows in your error tracker rather than as failed requests. A `ValidationException` thrown there is shown like any other validation error, since it's your action refusing the form on purpose. - **A free address** gets its account, and Laravel's `Registered` event is dispatched once the response has been sent, which emails the verification link. - **A taken address** gets nothing created or changed. Once the response has been sent, Keyring emails it your `already_registered` [notification](security-log-and-emails.md#emails-a-flow-needs), which says someone tried to register and links to the login page and, with `Features::resetPasswords()`, the forgot password page. If the account there was never verified, it's sent another verification link instead, since the first may be lost or expired. - An address is mailed five times an hour at most by registration (`limits.notices` every `limits.notices_per`), verification links included, so the form can't be used to fill someone's inbox. Past that the answer stays the same and nothing is sent. diff --git a/src/Login/Registration.php b/src/Login/Registration.php index e7b4f80e..76850cd5 100644 --- a/src/Login/Registration.php +++ b/src/Login/Registration.php @@ -88,10 +88,9 @@ public function ensureReady(): void * after the response. Each path makes one password hash, the slowest * thing either does. * - * Only a free address runs the action's create(), so anything it throws - * would say the address was free. It's reported and answered like the - * rest, with nothing sent. A ValidationException is the action refusing - * the form on purpose, and is passed on. + * Anything the action's create() throws is reported and answered like + * the rest, with nothing sent. A ValidationException is the action + * refusing the form on purpose, and is passed on. * * @throws ValidationException */ diff --git a/tests/Feature/RegistrationTest.php b/tests/Feature/RegistrationTest.php index b4116847..4a2d6699 100644 --- a/tests/Feature/RegistrationTest.php +++ b/tests/Feature/RegistrationTest.php @@ -209,8 +209,8 @@ function verificationLinkSentTo(User $user): string } })->with(['a form post' => false, 'json' => true]); - // Bcrypt can't hash a NUL byte, and only a free address hashes the - // visitor's password, so it's refused before either path is taken. + // Bcrypt can't hash a NUL byte: refused before Keyring looks at the + // address, so the same for every one. it('refuses a password bcrypt can\'t hash the same for every address', function (bool $json) { $answers = []; From 52fc91442c23145c4386d582bafa92aa93c1165d Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Wed, 18 Nov 2026 10:15:57 +0000 Subject: [PATCH 9/9] docs(log): say authenticator names are kept valid when saved through the model --- docs/security.md | 2 +- src/Models/Authenticator.php | 9 +++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/security.md b/docs/security.md index 2e4f54ec..f91b5053 100644 --- a/docs/security.md +++ b/docs/security.md @@ -267,7 +267,7 @@ A URL ends up in places a request's body doesn't: access logs, proxies, the brow ### Logging -- Sign ins, failed factors, lockouts, session starts and ends, sessions "remember me" carried on, and every change to how an account signs in are recorded as shipped. A session your own code starts with `Auth::login()` isn't. They go in the [security log](security-log-and-emails.md) table, which is on by default, or in your app's log when you turn the table off. There is no setting that records nothing. Text in an entry's details that isn't valid UTF-8, such as an authenticator's name stored before Keyring refused it, is cleaned up so the entry is still written. One whose details can't be kept at all is written without them and the reason reported. Authenticator names are kept as valid UTF-8 however they're saved. +- Sign ins, failed factors, lockouts, session starts and ends, sessions "remember me" carried on, and every change to how an account signs in are recorded as shipped. A session your own code starts with `Auth::login()` isn't. They go in the [security log](security-log-and-emails.md) table, which is on by default, or in your app's log when you turn the table off. There is no setting that records nothing. Text in an entry's details that isn't valid UTF-8, such as an authenticator's name stored before Keyring refused it, is cleaned up so the entry is still written. One whose details can't be kept at all is written without them and the reason reported. Authenticator names are kept as valid UTF-8 whenever they're saved through the model. - What was refused is recorded too: a request for someone else's authenticator, device or verification link, a sign-in method that wasn't added, a removal that would have left the account unable to sign in, an emailed link with a wrong, ended or expired token or signature, a request the form rate limiter turned away, and a verification the pipeline's final gate turned away. None of it changes the answer the requester gets. - No entry holds a password, code, token, signature, session ID or request body, in the table or in the app's log. Form validation errors aren't logged. - Every entry carries a severity, the ID of the request that wrote it and the time. In the table the time is in your `app.timezone`, which is UTC unless you changed it; in your app's log it's written with its offset. See [Times](security-log-and-emails.md#times). diff --git a/src/Models/Authenticator.php b/src/Models/Authenticator.php index 4cf4e29f..30feca2f 100644 --- a/src/Models/Authenticator.php +++ b/src/Models/Authenticator.php @@ -112,10 +112,11 @@ public function isVirtual(): bool } /** - * A name is stored as valid UTF-8, without NUL characters, however it got here: an import, your - * own code, a factor of your own. Keyring's forms refuse one that isn't, - * and what's left of one is kept rather than breaking the pages and the - * log entries that show it. + * A name is stored as valid UTF-8, without NUL characters, whatever + * saves it through the model: an import, your own code, a factor of + * your own. Keyring's forms refuse one that isn't, and what's left of + * one is kept rather than breaking the pages and the log entries that + * show it. * * @return Attribute */