From 9fafcdcaec40b3ff1b1a3bbb5f1716a30ca61902 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Wed, 11 Nov 2026 19:22:51 +0000 Subject: [PATCH 1/9] fix: close what the fourth security audit confirmed --- config/keyring.php | 8 +- ...8_000003_create_keyring_sessions_table.php | 5 +- lang/en/keyring.php | 1 + src/Activity/SecurityLog.php | 8 +- src/Changes/AuthenticatorChanges.php | 16 +- src/Changes/EmailChanges.php | 31 +++- src/Changes/PasswordChanges.php | 55 ++++++- src/Console/InstallCommand.php | 5 + src/Devices/DeviceManager.php | 12 +- src/Factors/WebAuthn.php | 5 + .../Controllers/AuthenticatorController.php | 14 +- src/Http/Controllers/ChallengeController.php | 15 +- .../Controllers/EmailChangeController.php | 7 +- .../EmailVerificationController.php | 13 +- src/Http/Controllers/PasswordController.php | 1 + .../Controllers/PasswordResetController.php | 33 +++- .../Controllers/RegisteredUserController.php | 10 +- src/Http/Middleware/AuthenticateSession.php | 26 ++- src/KeyringManager.php | 21 ++- src/Login/Attempt.php | 14 ++ src/Login/AttemptStore.php | 1 + src/Login/SignIn.php | 52 ++++-- src/Models/PendingChange.php | 8 +- src/Pipeline/AccountLimit.php | 10 ++ src/Pipeline/Steps/EnsureNotThrottled.php | 54 +++++- src/Pipeline/Verifier.php | 13 +- src/Risk/RiskLocks.php | 8 +- src/Sessions/CacheSessionRegistry.php | 79 +++++++-- src/Sessions/DatabaseSessionRegistry.php | 6 +- src/Sessions/RegisteredSession.php | 25 +++ src/Sessions/SessionAssurance.php | 22 ++- src/Sessions/Sessions.php | 80 ++++++++- src/Support/Refusal.php | 61 +++++++ src/Support/Throttle.php | 37 ++++- src/Testing/KeyringConformance.php | 44 +++++ src/Testing/VirtualManufacturer.php | 7 +- src/WebAuthn/Ceremonies.php | 21 +++ tests/Concurrency/Helpers.php | 8 +- tests/Concurrency/RaceTest.php | 86 +++++++++- tests/Concurrency/worker.php | 38 +++++ tests/Feature/AuthenticatorManagementTest.php | 68 ++++++++ tests/Feature/CommandsTest.php | 21 ++- tests/Feature/ConformanceTest.php | 29 ++++ tests/Feature/DeletingUsersTest.php | 2 +- tests/Feature/DevicesAndSessionsTest.php | 147 ++++++++++++++++- tests/Feature/EmailChangeHardeningTest.php | 108 +++++++++++- tests/Feature/ExtendingTest.php | 4 +- tests/Feature/MailLimitsTest.php | 30 ++++ tests/Feature/OctaneTest.php | 51 ++++++ tests/Feature/PasswordHoldTest.php | 49 ++++++ tests/Feature/PasswordResetTest.php | 40 +++++ tests/Feature/RememberMeTest.php | 28 +++- tests/Feature/RiskTest.php | 42 ++++- tests/Feature/SessionHardeningTest.php | 29 ++++ tests/Feature/StepUpTest.php | 4 + tests/Feature/ThrottlingTest.php | 154 +++++++++++++++++- tests/Feature/WebAuthnAttestationTest.php | 29 +++- tests/Feature/WebAuthnTest.php | 28 ++++ tests/Fixtures/public-api.json | 2 +- 59 files changed, 1678 insertions(+), 147 deletions(-) create mode 100644 src/Support/Refusal.php diff --git a/config/keyring.php b/config/keyring.php index 5075f9d1..7cee6d3b 100644 --- a/config/keyring.php +++ b/config/keyring.php @@ -438,12 +438,14 @@ | Timebox |-------------------------------------------------------------------------- | - | Every failed factor verification takes at least this long, so response - | timing doesn't reveal whether an account exists. + | Every refused sign in, registration and password reset takes at least + | this long, so response timing doesn't reveal whether an account exists. + | It only hides what's shorter than it: keep it comfortably longer than + | one password hash takes on your servers. | */ - 'timebox' => '250ms', + 'timebox' => '500ms', /* |-------------------------------------------------------------------------- diff --git a/database/migrations/2026_11_08_000003_create_keyring_sessions_table.php b/database/migrations/2026_11_08_000003_create_keyring_sessions_table.php index 62245ac4..6ba0c761 100644 --- a/database/migrations/2026_11_08_000003_create_keyring_sessions_table.php +++ b/database/migrations/2026_11_08_000003_create_keyring_sessions_table.php @@ -15,7 +15,8 @@ public function up(): void { Schema::create('keyring_sessions', function (Blueprint $table) { $table->string('id', 64)->primary(); - $table->string('user_id')->index(); + $table->string('user_id'); + $table->string('user_type'); $table->string('guard'); $table->string('device_id', 26)->nullable()->index(); $table->unsignedTinyInteger('assurance')->default(0); @@ -28,6 +29,8 @@ public function up(): void $table->string('replaced_by', 64)->nullable(); $table->unsignedInteger('replaced_at')->nullable(); $table->boolean('remembered')->default(false); + + $table->index(['user_type', 'user_id']); }); } diff --git a/lang/en/keyring.php b/lang/en/keyring.php index eca55344..09d2efbc 100644 --- a/lang/en/keyring.php +++ b/lang/en/keyring.php @@ -14,6 +14,7 @@ 'recovery_needs_second_factor' => 'Recovery codes back up another second factor. Add one first, like an authenticator app or a passkey.', 'password_common' => 'That password is too common. Choose another.', 'password_context' => 'Your password can\'t be made up of your name, your email address or the name of this site. Add some words of your own.', + 'password_unchanged' => 'That is your current password. Choose another.', 'password_unchecked' => 'We couldn\'t check that password against known data breaches just now. Please try again in a moment.', 'password_to_remove_last_factor' => 'Enter your password to remove your last second factor.', 'password_too_short_alone' => 'Without a second factor your password needs at least :min characters. Change it first, then remove this.', diff --git a/src/Activity/SecurityLog.php b/src/Activity/SecurityLog.php index f707b6bc..e7e0c452 100644 --- a/src/Activity/SecurityLog.php +++ b/src/Activity/SecurityLog.php @@ -5,6 +5,7 @@ namespace Keyring\Activity; use Closure; +use DateTimeInterface; use Illuminate\Cache\RateLimiter; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Database\Eloquent\Builder; @@ -114,15 +115,18 @@ public function activity(Authenticatable&Model $user, int $limit = 25): Collecti /** * Unseen events worth asking "was this you?" about. Marks them seen. + * With $since, only those logged after that moment: the rest stay unseen + * for whoever may see them. * * @return Collection */ - public function pullAlerts(Authenticatable&Model $user): Collection + public function pullAlerts(Authenticatable&Model $user, ?DateTimeInterface $since = null): Collection { - return $this->safely(function () use ($user) { + return $this->safely(function () use ($user, $since) { $alerts = $this->query($user) ->whereIn('type', config('keyring.security_log.alerts')) ->whereNull('seen_at') + ->when($since, fn (Builder $query) => $query->where('created_at', '>', $since)) ->latest('created_at') ->get(); diff --git a/src/Changes/AuthenticatorChanges.php b/src/Changes/AuthenticatorChanges.php index 6609f50a..36a9fb2a 100644 --- a/src/Changes/AuthenticatorChanges.php +++ b/src/Changes/AuthenticatorChanges.php @@ -4,8 +4,10 @@ namespace Keyring\Changes; +use Illuminate\Auth\AuthenticationException; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Database\Eloquent\Model; +use Illuminate\Http\Request; use Illuminate\Support\Arr; use Illuminate\Validation\ValidationException; use Keyring\Contracts\Enrollable; @@ -42,16 +44,26 @@ public function __construct( * An emailed code isn't a factor, so it comes with none: there would be * nothing for them to recover. * + * With the request it came in, the session that asked has to still be + * signed in when it's saved: one ended while the request ran (an email + * change undone, say) adds nothing. + * * @return list|null + * + * @throws AuthenticationException */ - public function add(Authenticatable&Model $user, Enrollable $factor, Authenticator $authenticator): ?array + public function add(Authenticatable&Model $user, Enrollable $factor, Authenticator $authenticator, ?Request $request = null): ?array { $keyring = $this->keyring->for($user); $isRecovery = $factor->key() === RecoveryCodes::KEY; $recoverable = array_any($factor->categories($authenticator), fn (Category $category) => $category->authenticates()); $recovery = ! $isRecovery && $recoverable && ! $keyring->hasRecoveryCodes() ? $this->recoveryCodes() : null; - $authenticator->getConnection()->transaction(function () use ($factor, $user, $keyring, $authenticator, $isRecovery, $recovery) { + $authenticator->getConnection()->transaction(function () use ($factor, $user, $keyring, $authenticator, $isRecovery, $recovery, $request) { + if ($request !== null) { + $this->sessions->stillSignedIn($request, $user); + } + if (! $factor->multiple()) { $replaced = $keyring->of($factor->key())->each->delete(); diff --git a/src/Changes/EmailChanges.php b/src/Changes/EmailChanges.php index a85a0972..9fb39545 100644 --- a/src/Changes/EmailChanges.php +++ b/src/Changes/EmailChanges.php @@ -88,9 +88,22 @@ public function request(Authenticatable&Model $user, string $email, Request $req $signedInAt = $this->signedInAt($request); $needsCurrent = ! $this->sessionProvedEstablishedSecondFactor($user, $signedInAt); - $change = $this->keyring->pendingChangeModel()::query()->getConnection()->transaction(function () use ($user, $email, $current, $tokens, $needsCurrent, $signedInAt) { + $change = $this->keyring->pendingChangeModel()::query()->getConnection()->transaction(function () use ($user, $email, &$current, $tokens, $needsCurrent, $signedInAt, $request) { $this->cancel($user); + // After the change rows and before the user's, the order a + // confirmation and an undo take them in. An undo ends every + // session once it has closed the changes it found: a request + // that was already under way is refused here, and one that got + // in first has saved its change where the undo's last look + // closes it. The address is the row's, not the one this request + // loaded before an undo moved it. + $current = (string) $this->sessions->stillSignedIn($request, $user)->getAttribute($this->attribute()); + + if ($email === $this->keyring->normalizeUsername($current)) { + return null; + } + $change = new ($this->keyring->pendingChangeModel())([ 'attribute' => $this->attribute(), 'value' => $email, @@ -105,6 +118,10 @@ public function request(Authenticatable&Model $user, string $email, Request $req return tap($change->authenticatable()->associate($user))->save(); }); + if ($change === null) { + return null; + } + // After the response, so timing doesn't give away which case it was. defer(function () use ($change, $email, $current, $tokens, $needsCurrent, $taken) { $link = fn (string $route, string $token) => Url::route($route, ['change' => $change->id, 'token' => $token]); @@ -217,7 +234,9 @@ public function revert(PendingChange $change, #[\SensitiveParameter] string $tok $change->forceFill(['reverted_at' => now()])->save(); - $this->removeAuthenticatorsAddedSince($user, $this->unestablishedSince($change)); + // As the account now is: what's removed is announced to the + // address that was just put back, not the one taken off. + $this->removeAuthenticatorsAddedSince($change->owner() ?? $user, $this->unestablishedSince($change)); return true; }); @@ -227,6 +246,14 @@ public function revert(PendingChange $change, #[\SensitiveParameter] string $tok if ($reverted && ($user = $change?->owner())) { $this->sessions->signOutEverywhere($user); + // Once more, now no session is left to make another. A request + // that was under way while the undo ran either waited for the + // sign-out and was refused, or saved what it was saving before + // it: a later change, or a sign-in method, that the first look + // was too early to find. + $this->closeLaterChanges($user, $change); + $this->removeAuthenticatorsAddedSince($user, $this->unestablishedSince($change)); + EmailChangeReverted::dispatch($user, $change); } diff --git a/src/Changes/PasswordChanges.php b/src/Changes/PasswordChanges.php index 4b9ee914..3f9b75a1 100644 --- a/src/Changes/PasswordChanges.php +++ b/src/Changes/PasswordChanges.php @@ -7,10 +7,13 @@ use Closure; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Database\Eloquent\Model; +use Illuminate\Support\Facades\Hash; +use Illuminate\Validation\ValidationException; use Keyring\Events\PasswordChanged; use Keyring\Events\PasswordReset; use Keyring\Risk\RiskLocks; use Keyring\Sessions\Sessions; +use Keyring\Support\PasswordRules; use Keyring\Support\Throttle; use LogicException; @@ -39,11 +42,20 @@ public function __construct( * account's sign-in limits start over, as after a reset: a password the * cap had got refused elsewhere works again. * + * $current is the password they proved to get here, when they have one. + * 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. + * * @param Closure(): void $save + * + * @throws ValidationException */ - public function change(Authenticatable&Model $user, Closure $save, ?string $currentSession, bool $signOutOthers = true): void + public function change(Authenticatable&Model $user, Closure $save, ?string $currentSession, bool $signOutOthers = true, #[\SensitiveParameter] ?string $current = null): void { - $this->save($user, $save); + if (! $this->save($user, $save, old: $current)) { + throw ValidationException::withMessages(['password' => __('keyring::keyring.password_unchanged')]); + } + $this->sessions->distrustDevices($user); $this->throttle->clearAccount($user); @@ -60,11 +72,16 @@ public function change(Authenticatable&Model $user, Closure $save, ?string $curr * account's throttle locks are lifted so a lock can't keep the owner out * for good. * + * $new is the password they sent. When it's the one the account already + * had, the reset goes through like any other, so the form doesn't tell a + * link's holder that a guess was right, but a hold stays: the password + * it's waiting to see the back of is still the password. + * * @param Closure(): void $save */ - public function reset(Authenticatable&Model $user, Closure $save): void + public function reset(Authenticatable&Model $user, Closure $save, #[\SensitiveParameter] ?string $new = null): void { - $this->save($user, $save); + $this->save($user, $save, new: $new, keepHold: true); $this->sessions->signOutEverywhere($user); $this->locks->unlock($user); $this->throttle->clearAccount($user); @@ -77,22 +94,46 @@ public function reset(Authenticatable&Model $user, Closure $save): void * nothing else, and make sure it did: everything that follows (signing * out, lifting locks, telling the user) assumes the password changed. * + * A new hash isn't a new password: the same one hashes differently every + * time. So the answer is whether the password itself changed, as far as + * can be told: from $old, a password known to have been the account's, + * checked against the new hash, or from $new, the one that was sent, + * checked against the old hash. With $keepHold the rest still happens + * for a password that didn't change, and only the hold is kept. + * * @param Closure(): void $save */ - protected function save(Authenticatable&Model $user, Closure $save): void + protected function save(Authenticatable&Model $user, Closure $save, #[\SensitiveParameter] ?string $old = null, #[\SensitiveParameter] ?string $new = null, bool $keepHold = false): bool { $before = $user->getAuthPassword(); $this->protection->changing($save, only: [$user->getAuthPasswordName()]); - if ($user->newQuery()->whereKey($user->getKey())->first()?->getAuthPassword() === $before) { + $after = $user->newQuery()->whereKey($user->getKey())->first()?->getAuthPassword(); + + if ($after === $before) { throw new LogicException('The password action returned without saving a new password. Throw a ValidationException to refuse it.'); } + $changed = ! $this->matches($old, $after) && ! $this->matches($new, $before); + + if (! $changed && ! $keepHold) { + return false; + } + $this->emailChanges->cancel($user); $this->resetTokens->forget($user); // A user held until they chose a new password just did. - $this->holds->lift($user); + if ($changed) { + $this->holds->lift($user); + } + + return $changed; + } + + protected function matches(#[\SensitiveParameter] ?string $password, ?string $hash): bool + { + return $password !== null && filled($hash) && Hash::check(PasswordRules::forVerifying($password, $hash), $hash); } } diff --git a/src/Console/InstallCommand.php b/src/Console/InstallCommand.php index 1e1c8186..84b48c3f 100644 --- a/src/Console/InstallCommand.php +++ b/src/Console/InstallCommand.php @@ -177,6 +177,11 @@ public function handle(Filesystem $files): int $writesProvider => 'Nothing makes users set up a second factor. To require one, see "Requiring a Second Factor" in the "Policies" docs', default => null, }, + // A config that was kept isn't changed, so it may not have what + // the provider just written needs. + $writesProvider && $factors !== [] && ! in_array(Features::manageAuthenticators(), $features, true) + ? 'Add Features::manageAuthenticators() to the features in config/keyring.php: without it nobody can set up the sign-in methods you picked'.($enrolled ? ', and everyone is sent to set one up' : '') + : null, $writesProvider && in_array('email-codes', $factors, true) ? 'Email codes are an extra step at sign in, not a second factor: a password and an emailed code is still AAL1. See "Email Codes" in the "Factors" docs' : null, 'Add features later by uncommenting them in config/keyring.php', ])); diff --git a/src/Devices/DeviceManager.php b/src/Devices/DeviceManager.php index 3b539281..aa63709d 100644 --- a/src/Devices/DeviceManager.php +++ b/src/Devices/DeviceManager.php @@ -8,6 +8,7 @@ use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Collection as EloquentCollection; use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\UniqueConstraintViolationException; use Illuminate\Http\Request; use Illuminate\Support\Collection; use Illuminate\Support\Str; @@ -91,7 +92,16 @@ public function signIn(Request $request, Authenticatable&Model $user, bool $prov $device->trusted_until = Duration::fromNow($for); } - $device->save(); + try { + // In a transaction of its own, so a refused insert leaves one + // the caller has open usable. + $device->getConnection()->transaction(fn () => $device->save()); + } catch (UniqueConstraintViolationException $e) { + // Two sign ins at once from a browser the account hadn't used, + // carrying the same cookie: the other stored the device first, + // and this one carries on with it. + $device = ($device->exists ? null : $this->query($user)->where('token_hash', $device->token_hash)->first()) ?? throw $e; + } if ($device->wasRecentlyCreated) { $this->forgetOldest($user, $device); diff --git a/src/Factors/WebAuthn.php b/src/Factors/WebAuthn.php index 25f056ee..2ef4530b 100644 --- a/src/Factors/WebAuthn.php +++ b/src/Factors/WebAuthn.php @@ -120,6 +120,11 @@ public function deviceBound(Authenticator $authenticator): bool * certificate chained to a root the app trusts. Without that, "can't * leave its device" is only the key's word for it. A key added before * the factor asked, or one the factor has stopped asking about, isn't. + * + * The model list (allowOnly) says which keys may be added. It isn't + * read again here: narrowing it leaves the keys already added as they + * are, so an app can change what it hands out without locking out + * everyone who holds the old model. */ public function attested(Authenticator $authenticator): bool { diff --git a/src/Http/Controllers/AuthenticatorController.php b/src/Http/Controllers/AuthenticatorController.php index 2d4f695b..ae1671bc 100644 --- a/src/Http/Controllers/AuthenticatorController.php +++ b/src/Http/Controllers/AuthenticatorController.php @@ -32,12 +32,18 @@ class AuthenticatorController { use RespondsWithStatus; + // A route keeps its controller once it has made one, and in a worker + // that serves many requests that can be longer than a request lasts. + // These hold the session they were made for, or reach something that + // does, so they're asked of the app handling the request each time. + protected EnrollmentStore $enrollments { get => app(EnrollmentStore::class); } + + protected SignIn $signIn { get => app(SignIn::class); } + public function __construct( protected KeyringManager $keyring, - protected EnrollmentStore $enrollments, protected AuthenticatorChanges $changes, protected Throttle $throttle, - protected SignIn $signIn, protected Sessions $sessions, ) {} @@ -50,7 +56,7 @@ public function store(Request $request, string $factor): StatusResponse // 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()->getAuthIdentifier()); + $this->throttle->sending($factor->key(), $this->keyring->user()); } $enrollment = $factor->beginEnrollment($this->keyring->user(), $request); @@ -80,7 +86,7 @@ public function confirm(Request $request, string $factor): StatusResponse throw ValidationException::withMessages([$factor->errorKey() => __('keyring::keyring.enrollment_expired')]); } - $recoveryCodes = $this->changes->add($this->keyring->user(), $factor, $authenticator); + $recoveryCodes = $this->changes->add($this->keyring->user(), $factor, $authenticator, $request); $this->enrollments->forget($factor->key()); $this->signOutOthers($request); diff --git a/src/Http/Controllers/ChallengeController.php b/src/Http/Controllers/ChallengeController.php index f35b0e1c..e14f24af 100644 --- a/src/Http/Controllers/ChallengeController.php +++ b/src/Http/Controllers/ChallengeController.php @@ -32,12 +32,19 @@ class ChallengeController { use RespondsWithStatus; + // A route keeps its controller once it has made one, and in a worker + // that serves many requests that can be longer than a request lasts. + // These hold the session they were made for, or reach something that + // does, so they're asked of the app handling the request each time. + protected AttemptStore $attempts { get => app(AttemptStore::class); } + + protected StepUp $stepUp { get => app(StepUp::class); } + + protected Verifier $verifier { get => app(Verifier::class); } + public function __construct( protected KeyringManager $keyring, - protected AttemptStore $attempts, - protected StepUp $stepUp, protected Throttle $throttle, - protected Verifier $verifier, ) {} public function show(Request $request, ?string $factor = null): mixed @@ -140,7 +147,7 @@ public function send(Request $request, string $factor): mixed $authenticator = $this->authenticatorFor($request, $attempt, $factor->key()) ?? abort(404); - $this->throttle->sending($factor->key(), $attempt->userId); + $this->throttle->sending($factor->key(), $attempt->user()); $factor->send($attempt, $authenticator); diff --git a/src/Http/Controllers/EmailChangeController.php b/src/Http/Controllers/EmailChangeController.php index 2ec5a11d..0b42d8bf 100644 --- a/src/Http/Controllers/EmailChangeController.php +++ b/src/Http/Controllers/EmailChangeController.php @@ -22,8 +22,13 @@ class EmailChangeController { use RespondsWithStatus; + // A route keeps its controller once it has made one, and in a worker + // that serves many requests that can be longer than a request lasts. + // These hold the session they were made for, or reach something that + // does, so they're asked of the app handling the request each time. + protected EmailChanges $changes { get => app(EmailChanges::class); } + public function __construct( - protected EmailChanges $changes, protected KeyringManager $keyring, ) {} diff --git a/src/Http/Controllers/EmailVerificationController.php b/src/Http/Controllers/EmailVerificationController.php index 10085123..00cfa7af 100644 --- a/src/Http/Controllers/EmailVerificationController.php +++ b/src/Http/Controllers/EmailVerificationController.php @@ -15,6 +15,7 @@ use Keyring\KeyringManager; use Keyring\Login\VerificationLink; use Keyring\Support\Input; +use Keyring\Support\Throttle; class EmailVerificationController { @@ -83,7 +84,7 @@ public function verify(VerifyEmailRequest $request): mixed return $this->keyring->response(VerifiedResponse::class, justNow: true); } - public function send(Request $request): mixed + public function send(Request $request, Throttle $throttle): mixed { if ($this->verified($request)) { return $this->keyring->response(VerifiedResponse::class); @@ -92,6 +93,16 @@ public function send(Request $request): mixed $user = $this->keyring->user(); if ($user instanceof MustVerifyEmail) { + // The address is whatever was typed at registration, and nobody + // has shown it's theirs. It's mailed no more often from here + // than from the registration form, and out of the same count. + // The account is its own, so it's told when that's used up. + $address = $this->keyring->normalizeUsername($user->getEmailForVerification()); + + if (($wait = $throttle->notifying('registration', 'mail:'.$address)) !== null) { + throw Throttle::exception($this->keyring->email(), $wait); + } + $user->sendEmailVerificationNotification(); } diff --git a/src/Http/Controllers/PasswordController.php b/src/Http/Controllers/PasswordController.php index 4bc2a82e..7b4611a5 100644 --- a/src/Http/Controllers/PasswordController.php +++ b/src/Http/Controllers/PasswordController.php @@ -46,6 +46,7 @@ public function update(Request $request, UpdatesUserPasswords $updater, Password fn () => $updater->update($user, PasswordRules::normalizeInput(Input::all($request))), currentSession: $sessions->current($request)?->id, signOutOthers: $request->boolean('sign_out_others', true), + current: is_string($current = $request->input('current_password')) ? $current : null, ); $sessions->rotate($request); diff --git a/src/Http/Controllers/PasswordResetController.php b/src/Http/Controllers/PasswordResetController.php index 0130dc09..a7982e8d 100644 --- a/src/Http/Controllers/PasswordResetController.php +++ b/src/Http/Controllers/PasswordResetController.php @@ -19,6 +19,7 @@ use Keyring\KeyringManager; use Keyring\Support\Input; use Keyring\Support\PasswordRules; +use Keyring\Support\Refusal; use function Illuminate\Support\defer; @@ -32,9 +33,14 @@ class PasswordResetController { use RespondsWithStatus; + // A route keeps its controller once it has made one, and in a worker + // that serves many requests that can be longer than a request lasts. + // These hold the session they were made for, or reach something that + // does, so they're asked of the app handling the request each time. + protected PasswordChanges $passwords { get => app(PasswordChanges::class); } + public function __construct( protected KeyringManager $keyring, - protected PasswordChanges $passwords, ) {} public function create(Request $request): mixed @@ -73,13 +79,24 @@ public function update(Request $request, ResetsUserPasswords $resetter): StatusR 'password' => ['required', 'string'], ]); - $status = $this->broker()->reset([ - ...$this->credentials($request), - ...Arr::only($input, ['token', 'password']), - ], fn (Authenticatable&Model $user) => $this->passwords->reset( - $user, - fn () => $resetter->reset($user, PasswordRules::normalizeInput(Input::all($request))), - )); + // The broker only checks a token against a hash for an address that + // has a link outstanding, so how long a refusal takes would say + // which addresses do. Its own wait is Laravel's (200ms), and is + // switched off for good on a broker a reset has gone through, which + // a long-lived worker keeps. So every refusal is held for Keyring's + // timebox, like a refused sign in, on a timebox of its own. + $status = Refusal::timed(function () use ($request, $input, $resetter) { + $status = $this->broker()->reset([ + ...$this->credentials($request), + ...Arr::only($input, ['token', 'password']), + ], fn (Authenticatable&Model $user) => $this->passwords->reset( + $user, + fn () => $resetter->reset($user, PasswordRules::normalizeInput(Input::all($request))), + new: $input['password'], + )); + + return [$status, $status === PasswordBroker::PASSWORD_RESET]; + }); // Laravel says "no user with that address" for unknown accounts. Answer // every failure like a bad token instead. diff --git a/src/Http/Controllers/RegisteredUserController.php b/src/Http/Controllers/RegisteredUserController.php index d2abc618..e6ae8463 100644 --- a/src/Http/Controllers/RegisteredUserController.php +++ b/src/Http/Controllers/RegisteredUserController.php @@ -5,6 +5,7 @@ namespace Keyring\Http\Controllers; use Illuminate\Auth\Events\Registered; +use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Http\Request; use Keyring\Contracts\CreatesNewUsers; use Keyring\Contracts\Responses\RegisterResponse; @@ -15,6 +16,7 @@ use Keyring\Login\Registration; use Keyring\Login\SignIn; use Keyring\Login\Verification; +use Keyring\Support\Throttle; class RegisteredUserController { @@ -29,7 +31,7 @@ public function create(): mixed return $this->keyring->render('register'); } - public function store(Request $request, CreatesNewUsers $creator, Registration $registration, SignIn $signIn): mixed + public function store(Request $request, CreatesNewUsers $creator, Registration $registration, SignIn $signIn, Throttle $throttle): mixed { // Before anything is saved, so a broken setup doesn't take the address. $registration->ensureReady(); @@ -44,6 +46,12 @@ public function store(Request $request, CreatesNewUsers $creator, Registration $ $user = $registration->openly($request, $creator); + // Laravel's listener mails the verification link. Counted with what + // the address is sent if a new one is asked for. + if ($user instanceof MustVerifyEmail) { + $throttle->notifying('registration', 'mail:'.$this->keyring->normalizeUsername($user->getEmailForVerification())); + } + event(new Registered($user)); if (! $this->keyring->signsInAfterRegistering($user, $request)) { diff --git a/src/Http/Middleware/AuthenticateSession.php b/src/Http/Middleware/AuthenticateSession.php index 9c28dc9a..6e76272d 100644 --- a/src/Http/Middleware/AuthenticateSession.php +++ b/src/Http/Middleware/AuthenticateSession.php @@ -131,7 +131,7 @@ protected function ended(RegisteredSession $session, Authenticatable $user, int return match (true) { $session->revokedAt !== null => 'revoked', $session->expiresAt <= $now => 'expired', - $session->userId !== (string) $user->getAuthIdentifier() => 'other_user', + ! $session->belongsTo($user) => 'other_user', $session->replacedBy !== null => 'replaced', $this->sessions->idledOut($session, $now) => 'idle', default => null, @@ -285,12 +285,9 @@ protected function resume(Request $request, Authenticatable&Model $user, bool $r */ protected function reused(Request $request, Authenticatable $user, RegisteredSession $session): Response { - $current = $this->sessions->latest($session); - - // Already ended some other way: there's nothing left to end. - if ($current?->isActive(now()->getTimestamp())) { - $this->sessions->registry()->revoke($current->id); - + // Null when it had already ended some other way: there's nothing + // left to end. + if ($current = $this->sessions->endLatest($user, $session)) { RememberMeReused::dispatch($user, $current); } @@ -310,6 +307,13 @@ protected function assessRisk(Request $request, mixed $user, RegisteredSession $ return $this->signOut($request, 'risk'); } + // A step-up forgets what the session proved, which is the level it + // signed in at running out. Where that ends a session, it ends this + // one, as it does one "remember me" brings back with nothing proved. + if ($action->stepUp && $this->assurance->endsOnLapse()) { + return $this->signOut($request, 'risk'); + } + if (! $action->doesSomething()) { return null; } @@ -340,8 +344,12 @@ protected function signOut(Request $request, string $reason): Response // "remember me" would carry on, too. Otherwise the same cookies // would sign it in again the moment it's let back. A cookie that was // used a moment ago stands for the session it was used for. - if (in_array($reason, ['not_allowed', 'risk'], true) && ($remembered = $this->sessions->remembered($request)) !== null) { - $this->sessions->registry()->revoke(($this->sessions->latest($remembered) ?? $remembered)->id); + // Only when it's this account's: the cookie is the browser's to + // send, and it may name someone else's. + $user = $this->keyring->guard()->user(); + + if (in_array($reason, ['not_allowed', 'risk'], true) && $user !== null && ($remembered = $this->sessions->remembered($request))?->belongsTo($user)) { + $this->sessions->endLatest($user, $remembered); } if ($user = $this->signIn->out($request, onlyThisBrowser: true)) { diff --git a/src/KeyringManager.php b/src/KeyringManager.php index ec546907..9ff4e3c5 100644 --- a/src/KeyringManager.php +++ b/src/KeyringManager.php @@ -315,14 +315,25 @@ public function describeDevicesUsing(Closure $callback): static /** * A user agent as a name people recognise, like "Firefox on Windows". * Also a weak risk signal (a session's browser changing), never a factor. + * + * A describer of the app's own is the app's code, run in the middle of + * a sign in. One that throws is reported and gives no name, and a name + * longer than a device's column holds is cut to fit, so neither fails + * the sign in it was only naming a browser for. */ public function describeDevice(?string $userAgent): ?string { - return match (true) { - blank($userAgent) => null, - $this->deviceDescriber !== null => ($this->deviceDescriber)($userAgent), - default => UserAgent::describe($userAgent), - }; + if (blank($userAgent)) { + return null; + } + + if ($this->deviceDescriber === null) { + return UserAgent::describe($userAgent); + } + + $name = rescue(fn () => ($this->deviceDescriber)($userAgent)); + + return is_string($name) ? mb_substr($name, 0, 255) : null; } /** diff --git a/src/Login/Attempt.php b/src/Login/Attempt.php index b74c43e1..fe8b21d6 100644 --- a/src/Login/Attempt.php +++ b/src/Login/Attempt.php @@ -110,6 +110,20 @@ public function user(): Authenticatable&Model return $this->resolvedUser; } + /** + * Whether every authenticator this attempt has proved is still on the + * account. One taken off since (a stolen key, a method an undone email + * change removed) stops counting in a signed-in session, and counts for + * nothing in a sign in that hasn't finished either. + */ + public function keepsItsAuthenticators(): bool + { + $ids = array_values(array_unique(array_filter(array_column($this->verifications, 'authenticator')))); + + return $ids === [] + || Keyring::authenticatorModel()::query()->ownedBy($this->user())->whereKey($ids)->count() === count($ids); + } + public function resolveDevice(?string $deviceId): void { $this->deviceId = $deviceId; diff --git a/src/Login/AttemptStore.php b/src/Login/AttemptStore.php index d3a8d77a..38f590d2 100644 --- a/src/Login/AttemptStore.php +++ b/src/Login/AttemptStore.php @@ -86,6 +86,7 @@ protected function stillStands(Purpose $purpose, Attempt $attempt, mixed $creden && ($purpose === Purpose::Login || $this->isSignedIn($attempt)) && is_string($credentials) && hash_equals($credentials, $this->credentials($attempt->user())) + && $attempt->keepsItsAuthenticators() && Keyring::allowsSignIn($attempt->user()); } catch (AttemptExpired) { return false; diff --git a/src/Login/SignIn.php b/src/Login/SignIn.php index e73636eb..fca62cf3 100644 --- a/src/Login/SignIn.php +++ b/src/Login/SignIn.php @@ -22,6 +22,7 @@ use Keyring\Models\SecurityEvent; use Keyring\Sessions\SessionAssurance; use Keyring\Sessions\Sessions; +use Throwable; /** * The one place a user becomes signed in (after a login or registration) @@ -47,25 +48,40 @@ public function complete(Request $request, Attempt $attempt): void } $this->keyring->guard()->login($user, $attempt->remember); - $request->session()->regenerate(true); - $this->assurance->reset($attempt->verifications); - $device = $this->devices->signIn( - $request, - $user, - provedSecondFactor: Requirement::aal2()->isMetBy($attempt->verifications), - trust: $this->earnedTrust($attempt), - ); + // All of it or none: the guard is signed in from here, and a sign + // in that failed before its session was registered and looked at + // again would otherwise be left signed in, for the session + // middleware to take up as one the app started itself. + try { + $request->session()->regenerate(true); + $this->assurance->reset($attempt->verifications); + + $device = $this->devices->signIn( + $request, + $user, + provedSecondFactor: Requirement::aal2()->isMetBy($attempt->verifications), + trust: $this->earnedTrust($attempt), + ); + + $new = $device?->wasRecentlyCreated === true; - $new = $device?->wasRecentlyCreated === true; + $this->sessions->start($request, $user, $device, $this->assurance->level(), remembered: $attempt->remember); - $this->sessions->start($request, $user, $device, $this->assurance->level(), remembered: $attempt->remember); + $ended = $this->changedMeanwhile($user) || ! $attempt->keepsItsAuthenticators(); + } catch (Throwable $e) { + $this->out($request, onlyThisBrowser: true); + + throw $e; + } - // A password reset or change, or an email change or its undo, signs - // out the sessions registered by then. This one was still being - // checked, and is only registered now, so look again: with the new - // password or address saved, it ends here. - if ($this->changedMeanwhile($user)) { + // A password reset or change, an email change or its undo, or a + // sign-in method taken off the account signs out the sessions + // registered by then. This one was still being checked, and is only + // registered now, so it was looked at again: with the new password + // or address saved, or a method this sign in proved gone, it ends + // here. + if ($ended) { // The change stopped trusting every device before this one was // recorded, so whatever trust it was just given goes too. $this->sessions->distrustDevices($user); @@ -78,8 +94,10 @@ public function complete(Request $request, Attempt $attempt): void // "Was this you?" for anything suspicious since they last signed in. // A browser the account hasn't used before could be whoever caused - // them, so they wait for one it has. - $request->session()->flash('keyring.alerts', $new ? [] : $this->log->pullAlerts($user)->map(fn (SecurityEvent $event) => [ + // them, so they wait for one it has: one the account had already + // used when they happened. A browser first seen since could be + // whoever caused those, on its second visit. + $request->session()->flash('keyring.alerts', $new ? [] : $this->log->pullAlerts($user, since: $device?->created_at)->map(fn (SecurityEvent $event) => [ 'type' => $event->type, 'factor' => $event->factor, 'at' => $event->created_at->toIso8601String(), diff --git a/src/Models/PendingChange.php b/src/Models/PendingChange.php index 1bbe0208..47a89011 100644 --- a/src/Models/PendingChange.php +++ b/src/Models/PendingChange.php @@ -89,14 +89,20 @@ public static function lookupHash(string $value): string * be registered and leave a revert nowhere to put the address back. * Folding too much only keeps a similar address back while the * reservation lasts. + * + * Collations don't agree on "ß": MySQL's utf8mb4_general_ci takes it for + * "s", and utf8mb4_unicode_ci and utf8mb4_0900_ai_ci for "ss". So a run + * of "s" folds to one, and "klauß", "klaus" and "klauss" are all found + * as each other. */ public static function fold(string $value): string { $value = Keyring::normalizeUsername($value); $value = Normalizer::normalize($value, Normalizer::NFKD) ?: $value; $value = preg_replace('/[\p{M}\p{C}\s]+/u', '', $value) ?? $value; + $value = Str::lower(Str::transliterate($value, '')); - return Str::lower(Str::transliterate($value, '')); + return preg_replace('/s{2,}/', 's', $value) ?? $value; } protected function casts(): array diff --git a/src/Pipeline/AccountLimit.php b/src/Pipeline/AccountLimit.php index d4a6b081..9dc28993 100644 --- a/src/Pipeline/AccountLimit.php +++ b/src/Pipeline/AccountLimit.php @@ -19,6 +19,16 @@ class AccountLimit extends Limit /** How many lockouts in a day it takes for the next lock to hold until the limits are cleared. */ public ?int $holdAfter = null; + /** Whether it stands in for an account: the name it counts under found none. */ + public bool $unowned = false; + + public function unowned(bool $unowned = true): static + { + $this->unowned = $unowned; + + return $this; + } + public function quietly(bool $quiet = true): static { $this->quiet = $quiet; diff --git a/src/Pipeline/Steps/EnsureNotThrottled.php b/src/Pipeline/Steps/EnsureNotThrottled.php index ef6e7d7f..63b51e16 100644 --- a/src/Pipeline/Steps/EnsureNotThrottled.php +++ b/src/Pipeline/Steps/EnsureNotThrottled.php @@ -6,11 +6,14 @@ use Closure; use Illuminate\Cache\RateLimiting\Limit; +use Illuminate\Support\Arr; use Keyring\Contracts\PrimaryFactor; use Keyring\Events\AccountLocked; use Keyring\Events\Lockout; +use Keyring\Pipeline\AccountLimit; use Keyring\Pipeline\Context; use Keyring\Pipeline\Outcome; +use Keyring\Pipeline\SharedLimit; use Keyring\Support\Throttle; use Throwable; @@ -28,16 +31,31 @@ public function handle(Context $context, Closure $next): Context { $limits = $this->throttle->aim($context->factor->limits($context->request, $context->attempt), $context); - [$quiet, $limits] = $this->throttle->split($limits); + [$quiet, $announced] = $this->throttle->split($limits); + [$shared, $named] = Arr::partition($announced, fn (Limit $limit) => $limit instanceof SharedLimit); + [$shared, $named] = [array_values($shared), array_values($named)]; - if (($refusing = $this->throttle->hit($limits)) !== null) { - $retryAfter = $this->throttle->retryAfter($refusing); - - Lockout::dispatch($context->request, $context->factor->key(), $retryAfter); + // The address first, so an attempt it refuses is never counted + // against the account. + if (($refusing = $this->throttle->hit($shared)) !== null) { + return $this->lockedOut($context, $refusing); + } - return $context->lockout($retryAfter); + // A typed name that's refused says so, but not yet: whether a name + // is refused goes only by what was tried under it, so that it + // doesn't show which names have an account. The account behind it, + // if there is one, has limits of its own, and those decide whether + // the proof is looked at. So an owner who has just reset their + // password gets in with it under a name someone else got refused, + // and everyone without the password is answered as the name is. + $held = $this->throttle->hit($named); + + if ($held !== null && $quiet === []) { + return $this->lockedOut($context, $held); } + $limits = [...$shared, ...($held === null ? $named : [])]; + $context->throttleChecked = true; // A quiet limit's refusal isn't answered here. The attempt carries @@ -45,6 +63,11 @@ public function handle(Context $context, Closure $next): Context // limits that let it through. if (($refusing = $this->throttle->hit($quiet)) !== null) { $context->refuse($this->throttle->retryAfter($refusing)); + } elseif ($held !== null && array_all($quiet, fn (Limit $limit) => $limit instanceof AccountLimit && $limit->unowned)) { + // Nobody is behind the name, so there's no proof to look at: + // refused like an account whose own limits are used up, at the + // same cost. + $context->refuse($this->throttle->retryAfter($held)); } else { $limits = [...$limits, ...$quiet]; } @@ -59,11 +82,28 @@ public function handle(Context $context, Closure $next): Context match ($context->outcome) { Outcome::Failed => $this->failed($context, $limits), + // A name that was refused stays so: what it answers isn't + // changed by the account behind it signing in. Outcome::Challenge, Outcome::Complete => $this->throttle->succeeded($limits), default => $this->throttle->release($limits), }; - return $context; + // A quiet refusal has been announced to the app already, where the + // proof would have been checked. + return $held !== null && $context->outcome === Outcome::Failed + ? $this->lockedOut($context, $held, announce: ! $context->refused) + : $context; + } + + protected function lockedOut(Context $context, Limit $refusing, bool $announce = true): Context + { + $retryAfter = $this->throttle->retryAfter($refusing); + + if ($announce) { + Lockout::dispatch($context->request, $context->factor->key(), $retryAfter); + } + + return $context->lockout($retryAfter); } /** diff --git a/src/Pipeline/Verifier.php b/src/Pipeline/Verifier.php index 39a3f75d..0fee9d38 100644 --- a/src/Pipeline/Verifier.php +++ b/src/Pipeline/Verifier.php @@ -6,14 +6,13 @@ use Illuminate\Contracts\Container\Container; use Illuminate\Pipeline\Pipeline; -use Illuminate\Support\Timebox; use Keyring\Contracts\Responses\AuthenticatedResponse; use Keyring\Contracts\Responses\ChallengeResponse; use Keyring\Contracts\Responses\FailedResponse; use Keyring\Contracts\Responses\LockoutResponse; use Keyring\Events\Attempting; use Keyring\KeyringManager; -use Keyring\Support\Duration; +use Keyring\Support\Refusal; use Symfony\Component\HttpFoundation\Response; /** @@ -35,18 +34,14 @@ public function verify(Context $context): Context // Around every step, not just the one that checks the proof: what // the rate limits read and write, and what listeners do with a // failure, differ with whether the account exists and is locked. - return $this->container->make(Timebox::class)->call(function (Timebox $timebox) use ($context) { + return Refusal::timed(function () use ($context) { $context = new Pipeline($this->container) ->send($context) ->through($this->keyring->steps()) ->thenReturn(); - if (in_array($context->outcome, [Outcome::Challenge, Outcome::Complete], true)) { - $timebox->returnEarly(); - } - - return $context; - }, Duration::milliseconds(config('keyring.timebox')) * 1000); + return [$context, in_array($context->outcome, [Outcome::Challenge, Outcome::Complete], true)]; + }); } /** diff --git a/src/Risk/RiskLocks.php b/src/Risk/RiskLocks.php index edc73bc1..0fbc3863 100644 --- a/src/Risk/RiskLocks.php +++ b/src/Risk/RiskLocks.php @@ -6,6 +6,7 @@ use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Cache\Repository; +use Illuminate\Database\Eloquent\Model; /** * Temporary sign-in locks placed by risk actions. A password reset lifts @@ -32,8 +33,13 @@ public function unlock(Authenticatable $user): void $this->cache->forget($this->key($user)); } + /** + * By the model as well as the ID: two user models can have the same IDs, + * and a lock on one account isn't a lock on the other. Hashed, so it + * stays short whatever the model is called. + */ protected function key(Authenticatable $user): string { - return 'keyring:risk-lock:'.$user->getAuthIdentifier(); + return 'keyring:risk-lock:'.sha1(($user instanceof Model ? $user->getMorphClass() : $user::class).'|'.$user->getAuthIdentifier()); } } diff --git a/src/Sessions/CacheSessionRegistry.php b/src/Sessions/CacheSessionRegistry.php index 527ffbbf..008b8ba7 100644 --- a/src/Sessions/CacheSessionRegistry.php +++ b/src/Sessions/CacheSessionRegistry.php @@ -29,15 +29,29 @@ public function __construct( protected string $prefix = 'keyring:sessions:', ) {} + /** + * That a record was revoked or replaced is kept twice: in a key of its + * own, which a stale copy saved over the record can't undo, and in the + * record, so a store that drops one of the keys and keeps the other + * doesn't bring the session back. What the record already says is kept + * when the copy being saved doesn't know it. + */ public function save(RegisteredSession $session): void { - $this->cache->put($this->key($session->id), $session->with(['revokedAt' => null, 'replacedBy' => null, 'replacedAt' => null])->toArray(), $this->ttl($session)); + $stored = $this->cache->get($this->key($session->id)); + $data = $session->toArray(); + + foreach (['revoked_at', 'replaced_by', 'replaced_at'] as $ended) { + $data[$ended] ??= is_array($stored) ? ($stored[$ended] ?? null) : null; + } + + $this->cache->put($this->key($session->id), $data, $this->ttl($session)); if ($session->revokedAt !== null) { $this->cache->add($this->revokedKey($session->id), $session->revokedAt, $this->ttl($session)); } - $this->index($session->userId, function (array $ids) use ($session) { + $this->index($this->owner($session), function (array $ids) use ($session) { $ids[$session->id] = $session->expiresAt; return $ids; @@ -59,9 +73,9 @@ public function find(string $id): ?RegisteredSession return RegisteredSession::fromArray([ ...$data, - 'revoked_at' => $found[$this->revokedKey($id)] ?? ($everyone !== null && $data['authenticated_at'] <= $everyone ? $everyone : null), - 'replaced_by' => $found[$this->replacedKey($id)]['by'] ?? null, - 'replaced_at' => $found[$this->replacedKey($id)]['at'] ?? null, + 'revoked_at' => $found[$this->revokedKey($id)] ?? $data['revoked_at'] ?? ($everyone !== null && $data['authenticated_at'] <= $everyone ? $everyone : null), + 'replaced_by' => $found[$this->replacedKey($id)]['by'] ?? $data['replaced_by'] ?? null, + 'replaced_at' => $found[$this->replacedKey($id)]['at'] ?? $data['replaced_at'] ?? null, ]); } @@ -69,9 +83,9 @@ public function forUser(Authenticatable $user): Collection { $now = now()->getTimestamp(); - return new Collection(array_keys($this->ids((string) $user->getAuthIdentifier()))) + return new Collection(array_keys($this->ids($this->ownerKey(RegisteredSession::typeOf($user), (string) $user->getAuthIdentifier())))) ->map(fn (string $id) => $this->find($id)) - ->filter(fn (?RegisteredSession $session) => $session !== null && $session->isActive($now)) + ->filter(fn (?RegisteredSession $session) => $session !== null && $session->belongsTo($user) && $session->isActive($now)) ->sortByDesc(fn (RegisteredSession $session) => $session->lastActivityAt) ->values(); } @@ -98,7 +112,24 @@ public function prune(): int public function revoke(string $id): void { if ($session = $this->find($id)) { - $this->cache->add($this->revokedKey($id), now()->getTimestamp(), $this->ttl($session)); + $now = now()->getTimestamp(); + + $this->cache->add($this->revokedKey($id), $now, $this->ttl($session)); + $this->stamp($session, ['revoked_at' => $session->revokedAt ?? $now]); + } + } + + /** + * Write into the record what its own keys say ended it. + * + * @param array $ended + */ + protected function stamp(RegisteredSession $session, array $ended): void + { + $stored = $this->cache->get($this->key($session->id)); + + if (is_array($stored)) { + $this->cache->put($this->key($session->id), [...$stored, ...$ended], $this->ttl($session)); } } @@ -128,10 +159,12 @@ public function replace(string $id, RegisteredSession $successor, bool $revoke = if (! $replaced) { $this->cache->forget($this->key($successor->id)); + } else { + $this->stamp($session, ['replaced_by' => $successor->id, 'replaced_at' => $now, ...$revoke ? ['revoked_at' => $now] : []]); } // A replaced record is found by its ID, and never listed again. - $this->index($session->userId, fn (array $ids) => array_diff_key($ids, [($replaced ? $id : $successor->id) => true])); + $this->index($this->owner($session), fn (array $ids) => array_diff_key($ids, [($replaced ? $id : $successor->id) => true])); return $replaced; } @@ -162,28 +195,42 @@ protected function revokeWhere(Authenticatable $user, Closure $callback): int ->count(); } + /** + * What a user's list of sessions is kept under: the model and the ID, + * since two user models can have the same IDs. + */ + protected function owner(RegisteredSession $session): string + { + return $this->ownerKey($session->userType, $session->userId); + } + + protected function ownerKey(string $userType, string $userId): string + { + return sha1($userType.'|'.$userId); + } + /** * @return array */ - protected function ids(string $userId): array + protected function ids(string $owner): array { - return $this->cache->get($this->prefix.'user:'.$userId, []); + return $this->cache->get($this->prefix.'user:'.$owner, []); } /** * @param callable(array): array $change */ - protected function index(string $userId, callable $change): void + protected function index(string $owner, callable $change): void { - $update = function () use ($userId, $change) { + $update = function () use ($owner, $change) { $now = now()->getTimestamp(); - $ids = array_filter($change($this->ids($userId)), fn (int $expiresAt) => $expiresAt > $now); + $ids = array_filter($change($this->ids($owner)), fn (int $expiresAt) => $expiresAt > $now); - $this->cache->put($this->prefix.'user:'.$userId, $ids, max([0, ...$ids]) - $now + 60); + $this->cache->put($this->prefix.'user:'.$owner, $ids, max([0, ...$ids]) - $now + 60); }; $this->cache->getStore() instanceof LockProvider - ? $this->cache->getStore()->lock($this->prefix.'lock:'.$userId, 5)->block(5, $update) + ? $this->cache->getStore()->lock($this->prefix.'lock:'.$owner, 5)->block(5, $update) : $update(); } diff --git a/src/Sessions/DatabaseSessionRegistry.php b/src/Sessions/DatabaseSessionRegistry.php index f650f424..b71c0d21 100644 --- a/src/Sessions/DatabaseSessionRegistry.php +++ b/src/Sessions/DatabaseSessionRegistry.php @@ -133,7 +133,11 @@ public function prune(): int */ protected function activeFor(Authenticatable $user): Builder { - return $this->query()->where('user_id', (string) $user->getAuthIdentifier())->whereNull('revoked_at')->whereNull('replaced_by'); + return $this->query() + ->where('user_type', RegisteredSession::typeOf($user)) + ->where('user_id', (string) $user->getAuthIdentifier()) + ->whereNull('revoked_at') + ->whereNull('replaced_by'); } protected function query(): Builder diff --git a/src/Sessions/RegisteredSession.php b/src/Sessions/RegisteredSession.php index db3700a0..bed1905f 100644 --- a/src/Sessions/RegisteredSession.php +++ b/src/Sessions/RegisteredSession.php @@ -4,6 +4,8 @@ namespace Keyring\Sessions; +use Illuminate\Contracts\Auth\Authenticatable; +use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Str; use Keyring\Enums\Assurance; @@ -17,12 +19,17 @@ * * A remembered session is one "remember me" may bring back once Laravel's * own session has gone, so it's allowed to sit unused for longer. + * + * Whose it is takes the model as well as the ID (userType is the user's + * morph class), as everything else Keyring keeps for a user does: two user + * models can have the same IDs. */ final readonly class RegisteredSession { public function __construct( public string $id, public string $userId, + public string $userType, public string $guard, public ?string $deviceId, public Assurance $assurance, @@ -37,6 +44,22 @@ public function __construct( public bool $remembered = false, ) {} + /** + * Whether this is a session of that user: the same model and the same ID. + */ + public function belongsTo(Authenticatable $user): bool + { + return $this->userId === (string) $user->getAuthIdentifier() && $this->userType === self::typeOf($user); + } + + /** + * What a user's records carry as userType. + */ + public static function typeOf(Authenticatable $user): string + { + return $user instanceof Model ? $user->getMorphClass() : $user::class; + } + public function isActive(int $now): bool { return $this->revokedAt === null && $this->replacedBy === null && $this->expiresAt > $now; @@ -59,6 +82,7 @@ public function toArray(): array return [ 'id' => $this->id, 'user_id' => $this->userId, + 'user_type' => $this->userType, 'guard' => $this->guard, 'device_id' => $this->deviceId, 'assurance' => $this->assurance->value, @@ -95,6 +119,7 @@ public static function fromArray(array $data): self return new self( id: $data['id'], userId: (string) $data['user_id'], + userType: $data['user_type'], guard: $data['guard'], deviceId: $data['device_id'], assurance: Assurance::from((int) $data['assurance']), diff --git a/src/Sessions/SessionAssurance.php b/src/Sessions/SessionAssurance.php index 45400358..9a1e4e52 100644 --- a/src/Sessions/SessionAssurance.php +++ b/src/Sessions/SessionAssurance.php @@ -180,9 +180,9 @@ public function countingToward(Assurance $level): array */ public function lapse(): ?string { - $level = Assurance::tryFrom((int) $this->session->get(static::SIGNED_IN, 0)) ?? Assurance::None; + $level = $this->signedInLevel(); - if (! config('keyring.sessions.end_on_lapse') || $level === Assurance::None) { + if (! $this->endsOnLapse()) { return null; } @@ -195,6 +195,24 @@ public function lapse(): ?string return $from > now()->getTimestamp() - $this->sessions->absolute($level) ? 'idle' : 'expired'; } + /** + * The level this session signed in at. None for one Keyring didn't sign + * in itself, such as a session an app started with Auth::login(). + */ + public function signedInLevel(): Assurance + { + return Assurance::tryFrom((int) $this->session->get(static::SIGNED_IN, 0)) ?? Assurance::None; + } + + /** + * Whether this session is one sessions.end_on_lapse ends once the level + * it signed in at has gone. + */ + public function endsOnLapse(): bool + { + return config('keyring.sessions.end_on_lapse') && $this->signedInLevel() !== Assurance::None; + } + /** * The moment a verification must be no older than to count toward a * level: its overall limit ago, or when inactivity last lapsed it. diff --git a/src/Sessions/Sessions.php b/src/Sessions/Sessions.php index c996eb61..bcda461b 100644 --- a/src/Sessions/Sessions.php +++ b/src/Sessions/Sessions.php @@ -5,6 +5,7 @@ namespace Keyring\Sessions; use Closure; +use Illuminate\Auth\AuthenticationException; use Illuminate\Auth\Events\Login; use Illuminate\Auth\SessionGuard; use Illuminate\Contracts\Auth\Authenticatable; @@ -56,6 +57,7 @@ public function start(Request $request, Authenticatable $user, ?Device $device, $session = new RegisteredSession( id: Str::random(40), userId: (string) $user->getAuthIdentifier(), + userType: RegisteredSession::typeOf($user), guard: config('keyring.guard'), deviceId: $device?->id, assurance: $assurance, @@ -131,6 +133,38 @@ protected function holding(Authenticatable $user, Closure $change): mixed return $user instanceof Model ? RowLock::hold($user, fn () => $change()) : $change(); } + /** + * For a change only a signed-in session may make, called inside the + * transaction that saves it: hold the user's row until that transaction + * ends, so the change and a sign-out everywhere take turns, and refuse + * if this request's session has been ended since its middleware let it + * through (an email change undone, a password reset, a device reported). + * Without this a request already under way would still save its change + * after the account's owner had ended every session. Returns the user + * as the locked row has it. + * + * A request with no registered session is one Keyring isn't keeping + * track of, and is let through as before. + * + * @template TUser of Authenticatable&Model + * + * @param TUser $user + * @return TUser + * + * @throws AuthenticationException + */ + public function stillSignedIn(Request $request, Authenticatable&Model $user): Authenticatable&Model + { + $fresh = $user->newQueryWithoutScopes()->lockForUpdate()->whereKey($user->getKey())->first(); + $session = $request->hasSession() ? $this->current($request) : null; + + if (! $fresh instanceof Authenticatable || $session?->isActive(now()->getTimestamp()) === false || $session?->belongsTo($fresh) === false) { + throw new AuthenticationException; + } + + return $fresh; + } + /** * Carry a remembered session on in the new session its "remember me" * cookie signed in, under a new record and a new cookie. The cookie that @@ -299,6 +333,28 @@ public function revoke(Authenticatable $user, RegisteredSession $session): void }); } + /** + * End the session a record has become by now, holding the user's row so + * a move to a new record can't slip in between finding it and ending + * it: the move either lands first and is followed, or waits and finds + * its record ended. Returns the record that was ended, or null when + * there was nothing left to end. + */ + public function endLatest(Authenticatable $user, RegisteredSession $session): ?RegisteredSession + { + return $this->holding($user, function () use ($session) { + $current = $this->latest($this->registry->find($session->id)); + + if ($current === null || ! $current->isActive(now()->getTimestamp())) { + return null; + } + + $this->registry->revoke($current->id); + + return $current; + }); + } + public function current(Request $request): ?RegisteredSession { $id = $request->session()->get(self::KEY); @@ -553,12 +609,20 @@ public function cycleRememberToken(Authenticatable $user): void /** * Stop trusting the user's devices, or all but one, and stop any of them * counting as a known browser for rate limits until it signs in again. - * Does nothing when devices are off, so a security change can't fail on - * tables never used. + * + * With devices off the trust is still ended, in case it was given while + * they were on and they're turned on again: a browser trusted before a + * password reset would otherwise skip the second factor after it. That + * one update is the only thing that reaches for the table then, and a + * security change doesn't fail on an app that never made it. */ public function distrustDevices(Authenticatable $user, ?string $except = null): void { - if ($user instanceof Model && Features::enabled(Features::devices())) { + if (! $user instanceof Model) { + return; + } + + $distrust = function () use ($user, $except) { app(Throttle::class)->forgetBrowsers($user); $this->keyring->deviceModel()::query() @@ -566,7 +630,17 @@ public function distrustDevices(Authenticatable $user, ?string $except = null): ->whereNotNull('trusted_until') ->when($except, fn (Builder $query) => $query->whereKeyNot($except)) ->update(['trusted_until' => null]); + }; + + if (Features::enabled(Features::devices())) { + $distrust(); + + return; } + + // In a transaction of its own, so a table that isn't there leaves + // the caller's usable where a failed statement would end it. + rescue(fn () => $this->keyring->deviceModel()::query()->getConnection()->transaction($distrust), report: false); } public function registry(): SessionRegistry diff --git a/src/Support/Refusal.php b/src/Support/Refusal.php new file mode 100644 index 00000000..bd2f3303 --- /dev/null +++ b/src/Support/Refusal.php @@ -0,0 +1,61 @@ +call(function (Timebox $timebox) use ($work, $box, $started) { + [$result, $wentThrough] = $work(); + + if ($wentThrough) { + $timebox->returnEarly(); + } elseif (($took = intdiv(hrtime(true) - $started, 1000)) > $box) { + self::outran($took, $box); + } + + return $result; + }, $box); + } + + private static function outran(int $took, int $box): void + { + rescue(fn () => RateLimiter::attempt('keyring:timebox-outrun', 1, fn () => Log::warning(sprintf( + 'Keyring refused a request in %dms, longer than the %dms every refusal is held for (keyring.timebox), so how long a refusal takes may show whether an account exists. ' + .'The timebox has to be longer than one password hash takes on this server: raise keyring.timebox.', + intdiv($took, 1000), + intdiv($box, 1000), + )), 3600), report: false); + } +} diff --git a/src/Support/Throttle.php b/src/Support/Throttle.php index c4920176..93228a75 100644 --- a/src/Support/Throttle.php +++ b/src/Support/Throttle.php @@ -82,7 +82,7 @@ public function __construct( */ public function limitsFor(Factor $factor, Request $request, ?Attempt $attempt): array { - $typed = $attempt === null && $factor instanceof PrimaryFactor ? $this->typedUsername($request) : ''; + $typed = $attempt === null && $this->identifiesByUsername($factor) ? $this->typedUsername($request) : ''; $user = $attempt?->user() ?? ($typed === '' ? null : $this->keyring->findUser($request)); $account = match (true) { @@ -102,10 +102,10 @@ public function limitsFor(Factor $factor, Request $request, ?Attempt $attempt): return [ SharedLimit::perMinute(config('keyring.limits.per_ip'))->by($factor->key().'|ip|'.$request->ip().($known ? '|account|'.$account : '')), ...($typed === '' ? [] : [ - $this->perMinute($factor, 'typed:'.$typed.$since, $known), - ...($consecutive === null ? [] : [NameLimit::of($consecutive->share ?? PHP_INT_MAX, $factor->key(), 'typed:'.$typed.$since, $known)]), + $this->perMinute($factor, 'typed:'.$typed, $known), + ...($consecutive === null ? [] : [NameLimit::of($consecutive->share ?? PHP_INT_MAX, $factor->key(), 'typed:'.$typed, $known)]), ]), - ...array_map(fn (AccountLimit $limit) => $limit->quietly($typed !== ''), [ + ...array_map(fn (AccountLimit $limit) => $limit->quietly($typed !== '')->unowned($user === null), [ $this->perMinute($factor, $account.$since, $known), ...($consecutive === null ? [] : [$consecutive]), ]), @@ -224,7 +224,10 @@ public function retryAfter(Limit $limit): ?int */ public function failed(array $limits): bool { - $hold = false; + // The account's hold, and the typed name's. The name is only held + // for lockouts made under it: holding it for the account's would + // tell whoever typed it that another name is the same account's. + $hold = $named = false; foreach ($limits as $limit) { $key = $this->key($limit); @@ -249,7 +252,10 @@ public function failed(array $limits): bool $this->limiter->hit($this->lock($limit), min($longest, $limit->decaySeconds * 2 ** ($lockouts - 1))); $this->limiter->clear($key); - $hold = $hold || ($limit instanceof AccountLimit && $limit->holdAfter !== null && $lockouts >= $limit->holdAfter); + $reached = $limit instanceof AccountLimit && $limit->holdAfter !== null && $lockouts >= $limit->holdAfter; + + $hold = $hold || $reached; + $named = $named || ($reached && ! $limit->quiet); } $refused = false; @@ -257,7 +263,7 @@ public function failed(array $limits): bool // After the locks, which decide whether to hold. The typed name is // held in the cache, where it's counted, for as long as that lasts. foreach ($limits as $limit) { - if ($limit instanceof NameLimit && $hold) { + if ($limit instanceof NameLimit && $named) { $this->limiter->hit($this->lock($limit), $limit->decaySeconds); } @@ -376,14 +382,17 @@ public function forgetBrowsers(Authenticatable&Model $user): void * in, so starting again doesn't buy more, and sign ins, step-ups and * enrollments share the count. * + * Give it the user: an account is its model and its ID, and two user + * models can have the same IDs. A bare ID counts under the ID alone. + * * The key is hashed so it stays short whatever the factor is called and * however long the account's ID is: see key(). * * @throws ValidationException */ - public function sending(string $factor, int|string $userId): void + public function sending(string $factor, (Authenticatable&Model)|int|string $user): void { - $key = 'keyring-send:'.sha1($factor.'|'.$userId); + $key = 'keyring-send:'.sha1($factor.'|'.($user instanceof Model ? $this->accountOf($user) : $user)); if ($this->limiter->tooManyAttempts($key, config('keyring.limits.codes'))) { throw static::exception('code', $this->limiter->availableIn($key)); @@ -494,6 +503,16 @@ protected function consecutive(Factor $factor, (Authenticatable&Model)|null $use return ConsecutiveLimit::of($user, $factor->key(), $known, $cap === null ? null : (int) $cap, $elsewhere === null ? null : (int) $elsewhere); } + /** + * Whether the factor finds its user by the username field. A passkey + * doesn't: it goes by the credential, and a username sent along with + * one is nothing to count against the account it names. + */ + protected function identifiesByUsername(Factor $factor): bool + { + return $factor instanceof PrimaryFactor && array_key_exists($this->keyring->username(), $factor->identificationRules()); + } + protected function typedUsername(Request $request): string { return $this->keyring->normalizeUsername(Input::text($request, $this->keyring->username())); diff --git a/src/Testing/KeyringConformance.php b/src/Testing/KeyringConformance.php index 7f364960..ffd3e01a 100644 --- a/src/Testing/KeyringConformance.php +++ b/src/Testing/KeyringConformance.php @@ -21,6 +21,7 @@ use Keyring\Features; use Keyring\Http\Middleware\AuthenticateSession; use Keyring\Sessions\Sessions; +use Keyring\Support\Duration; /** * Checks that your Keyring setup (policy, factors, responses, pipeline @@ -140,6 +141,49 @@ public function test_keyring_takes_passwords_of_64_characters(): void ); } + /** + * The options production hashes passwords with, when your tests hash + * with less: Laravel's own phpunit.xml sets BCRYPT_ROUNDS=4. Bcrypt is + * timed at 12 rounds, a new app's setting, unless yours is higher. + * Return your own to time what production runs. + * + * @return array + */ + protected function keyringProductionHashOptions(): array + { + return Hash::getDefaultDriver() === 'bcrypt' ? ['rounds' => max(12, (int) config('hashing.bcrypt.rounds'))] : []; + } + + /** + * A refused sign in or reset is held for keyring.timebox so that how + * long it took doesn't say whether the account exists. Nothing is held + * shorter than the work already done, and the slowest thing a refusal + * does is hash a password, at a cost that differs between accounts while + * old hashes are being moved to a new one. So the wait only hides the + * difference while it's longer than a hash. + * + * This times one on the machine the tests run on, which is a guide and + * not your servers: slower ones need a longer timebox. + */ + public function test_keyring_holds_a_refusal_for_longer_than_a_password_hash_takes(): void + { + $timebox = Duration::milliseconds(config('keyring.timebox')); + + $took = min(array_map(function () { + $started = hrtime(true); + Hash::make(Str::random(32), $this->keyringProductionHashOptions()); + + return (hrtime(true) - $started) / 1_000_000; + }, range(1, 3))); + + $this->assertLessThan( + $timebox, + (int) ceil($took), + sprintf('One password hash took %dms here and keyring.timebox is %dms, so a refusal that hashes takes longer than one that doesn\'t, and shows which accounts exist. ', (int) ceil($took), $timebox) + .'Set keyring.timebox comfortably above what a hash takes on your servers, or return what production hashes with from keyringProductionHashOptions().', + ); + } + /** * Keyring's own limit on asking for a reset link is per sender. How * often one account can be sent one is the broker's "throttle", which is diff --git a/src/Testing/VirtualManufacturer.php b/src/Testing/VirtualManufacturer.php index 3b314efe..27fcefe2 100644 --- a/src/Testing/VirtualManufacturer.php +++ b/src/Testing/VirtualManufacturer.php @@ -60,13 +60,14 @@ public function __construct( /** * One of its keys, of the model with this AAGUID, attesting as "packed" - * or "fido-u2f". + * or "fido-u2f". It verifies its user unless told otherwise, except as + * "fido-u2f": those keys only ever say that someone touched them. */ - public function key(string $aaguid = '00000000-0000-0000-0000-000000000000', string $format = 'packed', bool $userVerification = true): VirtualAuthenticator + public function key(string $aaguid = '00000000-0000-0000-0000-000000000000', string $format = 'packed', ?bool $userVerification = null): VirtualAuthenticator { $aaguid = hex2bin(str_replace('-', '', $aaguid)) ?: throw new RuntimeException('An AAGUID is a UUID.'); - return new VirtualAuthenticator(userVerification: $userVerification, aaguid: $aaguid)->attestedBy($this, $format); + return new VirtualAuthenticator(userVerification: $userVerification ?? $format !== 'fido-u2f', aaguid: $aaguid)->attestedBy($this, $format); } /** diff --git a/src/WebAuthn/Ceremonies.php b/src/WebAuthn/Ceremonies.php index 2e89a5bf..c47e84bf 100644 --- a/src/WebAuthn/Ceremonies.php +++ b/src/WebAuthn/Ceremonies.php @@ -164,6 +164,10 @@ public function register(string $credential, string $options, Profile $profile): return null; } + if ($attested && $this->claimsMoreThanSigned($credential->response->attestationObject)) { + return null; + } + $record = AuthenticatorAttestationResponseValidator::create($this->steps($attested)->creationCeremony()) ->check($credential->response, $options, $this->relyingPartyId()); @@ -445,6 +449,23 @@ protected function vouchedFor(AttestationObject $attestation, Profile $profile): && app(Attestation::class)->verifies($attestation->attStmt, $aaguid); } + /** + * Whether an attested registration says something about the key that its + * statement doesn't sign. A "packed" statement signs all of the + * authenticator data. A "fido-u2f" one signs the credential and leaves + * out the flags: that the user was verified, that the key may sync, that + * it has. A U2F key sets none of them, so one that arrives set was put + * there on the way, and is what the key would be trusted for from then + * on. + */ + protected function claimsMoreThanSigned(AttestationObject $attestation): bool + { + $data = $attestation->authData; + + return $attestation->attStmt->fmt === 'fido-u2f' + && ($data->isUserVerified() || $data->isBackupEligible() || $data->isBackedUp()); + } + protected function steps(bool $attested = false): CeremonyStepManagerFactory { $origins = $this->origins(); diff --git a/tests/Concurrency/Helpers.php b/tests/Concurrency/Helpers.php index 8b4eaa0e..46e69651 100644 --- a/tests/Concurrency/Helpers.php +++ b/tests/Concurrency/Helpers.php @@ -56,13 +56,17 @@ function outcomes(array $results, mixed $value): int * @param list> $operations worker.php arguments * @param (Closure(): void)|null $meanwhile work to finish, holding the lock, before letting go * @param int|null $waiting how many of them should get as far as the lock, when the rest are turned away before it + * @param (Closure(): void)|null $hold what to hold in place of the row's lock, inside the transaction * @return list */ -function contend(Model $locked, array $operations, ?Closure $meanwhile = null, ?int $waiting = null): array +function contend(Model $locked, array $operations, ?Closure $meanwhile = null, ?int $waiting = null, ?Closure $hold = null): array { $connection = $locked->getConnection(); $connection->beginTransaction(); - $locked->newQuery()->lockForUpdate()->find($locked->getKey()); + + // The row, unless what the operations wait on is something else: a + // row this side has stored and not yet committed, say. + $hold === null ? $locked->newQuery()->lockForUpdate()->find($locked->getKey()) : $hold(); $env = ['DB_CONNECTION' => $connection->getName(), 'DB_DATABASE' => $connection->getDatabaseName()]; diff --git a/tests/Concurrency/RaceTest.php b/tests/Concurrency/RaceTest.php index ff0d0400..2db1d4a8 100644 --- a/tests/Concurrency/RaceTest.php +++ b/tests/Concurrency/RaceTest.php @@ -7,10 +7,12 @@ use Keyring\Enums\Assurance; use Keyring\Facades\Keyring; use Keyring\Models\Authenticator; +use Keyring\Models\Device; use Keyring\Models\FailureCount; use Keyring\Models\PendingChange; use Keyring\Sessions\RegisteredSession; use Keyring\Testing\VirtualAuthenticator; +use Keyring\Tests\Fixtures\User; use Keyring\WebAuthn\Ceremonies; use Keyring\WebAuthn\Profile; use ParagonIE\ConstantTime\Base64UrlSafe; @@ -187,11 +189,67 @@ ->and($second->fresh()->canRevert())->toBeFalse(); }); +// An undo, a reset and "this wasn't me" end the sessions holding the user's +// row. A request that was let through before waits there, and looks again. +it('refuses an email change from a session that is signed out while its request waits', function (bool $signedOut, mixed $expected) { + $user = taylor(); + $now = now()->getTimestamp(); + app(SessionRegistry::class)->save(new RegisteredSession('asking', (string) $user->id, $user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600)); + + [$requested] = contend($user, [['request-email-change', $user->id, 'asking']], fn () => $signedOut && app(SessionRegistry::class)->revokeAll($user)); + + expect($requested)->toBe($expected) + ->and(PendingChange::query()->count())->toBe($signedOut ? 0 : 1); +})->with([ + 'signed out meanwhile' => [true, 'signed out'], + 'still signed in' => [false, true], +]); + +// The same for a sign-in method: one saved by a request that was let through +// before its session ended would be the one thing an undo left behind. +it('refuses a sign-in method from a session that is signed out while its request waits', function (bool $signedOut, string $expected) { + $user = taylor(); + $now = now()->getTimestamp(); + app(SessionRegistry::class)->save(new RegisteredSession('asking', (string) $user->id, $user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600)); + + [$added] = contend($user, [['add-authenticator', $user->id, 'asking']], fn () => $signedOut && app(SessionRegistry::class)->revokeAll($user)); + + expect($added)->toBe($expected) + ->and(Authenticator::query()->where('factor', 'totp')->count())->toBe($signedOut ? 0 : 1); +})->with([ + 'signed out meanwhile' => [true, 'signed out'], + 'still signed in' => [false, 'added'], +]); + +// A browser someone else has signed in on keeps its cookie, so two sign ins +// to a second account from it would each store that account's device under +// the same token. The second finds the first's there, and carries on with it. +it('gives two sign ins at once from one browser the same device, and fails neither', function () { + $user = taylor(); + $other = User::create(['name' => 'Abigail', 'email' => 'abigail@example.com', 'password' => 'password']); + $token = str_repeat('a', 40); + $device = fn (User $owner) => Device::query()->forceCreate([ + 'authenticatable_type' => $owner->getMorphClass(), 'authenticatable_id' => $owner->id, + 'token_hash' => Device::hashToken($token), 'first_seen_at' => now(), 'last_seen_at' => now(), + ]); + $device($other); + + // Stored by the other sign in and not yet committed: this one has + // looked, found nothing, and waits at the unique index. + $stored = null; + [$recorded] = contend($user, [['record-device', $user->id, $token]], hold: function () use ($device, $user, &$stored) { + $stored = $device($user); + }); + + expect($recorded)->toBe($stored->id) + ->and(Device::query()->whereMorphedTo('authenticatable', $user)->count())->toBe(1); +}); + it('lets one of two requests use a "remember me" cookie, and starts one session between them', function () { $user = taylor(); $now = now()->getTimestamp(); $registry = app(SessionRegistry::class); - $registry->save(new RegisteredSession('remembered', (string) $user->id, 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600)); + $registry->save(new RegisteredSession('remembered', (string) $user->id, $user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600)); // Both read the record before either can replace it. $results = contend(sessionRow('remembered'), [ @@ -215,7 +273,7 @@ $registry = app(SessionRegistry::class); foreach (['older' => 120, 'newer' => 60] as $id => $ago) { - $registry->save(new RegisteredSession($id, (string) $user->id, 'web', null, Assurance::AAL1, null, null, $now - $ago, $now - $ago, $now + 3600)); + $registry->save(new RegisteredSession($id, (string) $user->id, $user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, $now - $ago, $now - $ago, $now + 3600)); } // Each waits for the user's row, so the second counts the first's session. @@ -233,7 +291,7 @@ $user = taylor(); $now = now()->getTimestamp(); $registry = app(SessionRegistry::class); - $registry->save(new RegisteredSession('remembered', (string) $user->id, 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600, remembered: true)); + $registry->save(new RegisteredSession('remembered', (string) $user->id, $user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600, remembered: true)); // Both wait for the user's row. Whichever goes first, the session ends: // signed out and then refused, or carried on and then signed out. @@ -247,11 +305,31 @@ ->and($registry->find($resumed ?? 'remembered')->revokedAt)->not->toBeNull(); }); +// A used cookie means two browsers held it, and the session ends for both. +// The one still on it may be carrying it on to a new record at that moment. +it('ends a reused "remember me" session wherever it has moved to by the time it is ended', function () { + $user = taylor(); + $now = now()->getTimestamp(); + $registry = app(SessionRegistry::class); + $registry->save(new RegisteredSession('remembered', (string) $user->id, $user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600, remembered: true)); + + // Both wait for the user's row. Carried on first, it's followed to the + // new record and ended there. Ended first, there's nothing to carry on. + [$resumed, $ended] = contend($user, [ + ['resume-session', 'remembered'], + ['end-latest', 'remembered'], + ]); + + expect($ended)->toBe($resumed ?? 'remembered') + ->and($registry->forUser($user))->toBeEmpty() + ->and($registry->find($ended)->revokedAt)->not->toBeNull(); +}); + it('signs out a session that moved to a new record while everyone was being signed out', function () { $user = taylor(); $now = now()->getTimestamp(); $registry = app(SessionRegistry::class); - $registry->save($session = new RegisteredSession('remembered', (string) $user->id, 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600, remembered: true)); + $registry->save($session = new RegisteredSession('remembered', (string) $user->id, $user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600, remembered: true)); // The sign-out comes to the record while "remember me" is carrying its // session on, and waits. By the time it gets the record, the session is diff --git a/tests/Concurrency/worker.php b/tests/Concurrency/worker.php index f7e0134a..113c1f4c 100644 --- a/tests/Concurrency/worker.php +++ b/tests/Concurrency/worker.php @@ -8,11 +8,13 @@ * as JSON. Usage: php worker.php */ +use Illuminate\Auth\AuthenticationException; use Illuminate\Http\Request; use Illuminate\Validation\ValidationException; use Keyring\Changes\AuthenticatorChanges; use Keyring\Changes\EmailChanges; use Keyring\Contracts\SessionRegistry; +use Keyring\Devices\DeviceManager; use Keyring\Enums\Assurance; use Keyring\Enums\Purpose; use Keyring\Facades\Keyring; @@ -88,13 +90,49 @@ return app(Sessions::class)->start($request, User::findOrFail($id), null, Assurance::AAL1)->id; })(), + 'add-authenticator' => (function () use ($id, $value) { + // A request its middleware let through as this session, saving + // a sign-in method it has just confirmed. + $request = Request::create('/user/authenticators/totp/confirm', 'POST'); + $request->setLaravelSession(app('session.store')); + $request->session()->put(Sessions::KEY, $value); + + $user = User::findOrFail($id); + + app(AuthenticatorChanges::class)->add($user, Keyring::factor('totp'), Authenticator::factory()->totp()->for($user, 'authenticatable')->make(), $request); + + return 'added'; + })(), + 'record-device' => (function () use ($id, $value) { + // A sign in from a browser carrying this device cookie. + $request = Request::create('/login', 'POST', cookies: ['known_device' => $value]); + $request->setLaravelSession(app('session.store')); + + return app(DeviceManager::class)->signIn($request, User::findOrFail($id))?->id; + })(), 'sign-out' => app(Sessions::class)->signOutEverywhere(User::findOrFail($id)), + 'end-latest' => (function () use ($id) { + // Read while the row is held, as a request that found the cookie used. + $session = app(SessionRegistry::class)->find($id); + + return app(Sessions::class)->endLatest(User::findOrFail($session->userId), $session)?->id; + })(), '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), + 'request-email-change' => (function () use ($id, $value) { + // A request its middleware let through as this session. + $request = Request::create('/user/email', 'POST'); + $request->setLaravelSession(app('session.store')); + $request->session()->put(Sessions::KEY, $value); + + return app(EmailChanges::class)->request(User::findOrFail($id), 'new@example.com', $request)?->id !== null; + })(), }; } catch (ValidationException) { $result = 'refused'; +} catch (AuthenticationException) { + $result = 'signed out'; } echo json_encode(['result' => $result]), "\n"; diff --git a/tests/Feature/AuthenticatorManagementTest.php b/tests/Feature/AuthenticatorManagementTest.php index fabd38b2..a40cfab8 100644 --- a/tests/Feature/AuthenticatorManagementTest.php +++ b/tests/Feature/AuthenticatorManagementTest.php @@ -10,6 +10,7 @@ use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Validator; use Illuminate\Testing\TestResponse; +use Keyring\Changes\AuthenticatorChanges; use Keyring\Concerns\HasKeyring; use Keyring\Contracts\SessionRegistry; use Keyring\Enums\Assurance; @@ -17,6 +18,7 @@ use Keyring\Enums\Purpose; use Keyring\Events\AuthenticatorAdded; use Keyring\Events\AuthenticatorRemoved; +use Keyring\Events\FactorVerified; use Keyring\Events\RecoveryCodesGenerated; use Keyring\Events\RecoveryCodeUsed; use Keyring\Facades\Keyring; @@ -25,7 +27,9 @@ use Keyring\Factors\Totp; use Keyring\Factors\WebAuthn; use Keyring\Login\Attempt; +use Keyring\Login\AttemptStore; use Keyring\Login\Requirement; +use Keyring\Login\Verification; use Keyring\Models\Authenticator; use Keyring\Notifications\AuthenticatorAdded as AuthenticatorAddedNotice; use Keyring\Notifications\RecoveryCodesGenerated as RecoveryCodesGeneratedNotice; @@ -173,6 +177,70 @@ ->assertJsonMissingPath('recoveryCodes'); }); +// A sign-in method taken off the account stops counting in every session it +// signed in. It counts for nothing in a sign in that hasn't finished either. +describe('a sign-in method removed while a sign in that proved it is under way', function () { + beforeEach(function () { + Route::middleware(['web', 'auth'])->get('/home', fn () => 'home'); + $this->totp = Authenticator::factory()->totp()->for($this->user, 'authenticatable')->create(); + + // Nobody is signed in yet. + $this->app['auth']->forgetGuards(); + $this->flushSession(); + }); + + it('ends a sign in that is waiting for its next step', function (Closure $remove) { + $this->post('/login', ['email' => 'taylor@example.com', 'password' => 'password'])->assertRedirect(route('keyring.login.challenge')); + + // One step further: the authenticator app proved, and more asked for. + $store = app(AttemptStore::class); + $attempt = $store->current(Purpose::Login); + $attempt->record(new Verification('totp', $this->totp->id, [Category::Possession], at: now()->getTimestamp())); + $store->save($attempt); + + expect($store->current(Purpose::Login))->not->toBeNull(); + + $remove($this->totp); + + $this->get(route('keyring.login.challenge'))->assertRedirect(route('login')); + expect(session()->has('keyring.attempt.login'))->toBeFalse(); + $this->assertGuest(); + })->with([ + // With another second factor beside it, so it isn't the last. + 'by its owner' => [function (Authenticator $totp) { + Authenticator::factory()->passkey()->for($totp->user(), 'authenticatable')->create(); + + app(AuthenticatorChanges::class)->remove($totp->user(), $totp->id); + }], + 'however it went' => [fn (Authenticator $totp) => $totp->delete()], + ]); + + it('ends a sign in it is removed in the middle of finishing', function () { + $this->post('/login', ['email' => 'taylor@example.com', 'password' => 'password'])->assertRedirect(route('keyring.login.challenge')); + + // Between the code being checked and the session being registered. + Event::listen(function (FactorVerified $event) { + if ($event->verification->factor === 'totp') { + $this->totp->delete(); + } + }); + + $this->post(route('keyring.login.verify', 'totp'), ['code' => totpCode($this->totp->secret)]) + ->assertSessionHasErrors(['email' => __('auth.failed')]); + + $this->assertGuest(); + expect(app(SessionRegistry::class)->forUser($this->user))->toBeEmpty(); + $this->get('/home')->assertRedirect('/login'); + }); + + it('still finishes a sign in whose methods are all there', function () { + $this->post('/login', ['email' => 'taylor@example.com', 'password' => 'password'])->assertRedirect(route('keyring.login.challenge')); + $this->post(route('keyring.login.verify', 'totp'), ['code' => totpCode($this->totp->secret)])->assertRedirect('/dashboard'); + + $this->assertAuthenticatedAs($this->user); + }); +}); + it('renames and picks the default', function () { $first = Authenticator::factory()->totp()->default()->for($this->user, 'authenticatable')->create(); $second = Authenticator::factory()->totp()->for($this->user, 'authenticatable')->create(); diff --git a/tests/Feature/CommandsTest.php b/tests/Feature/CommandsTest.php index 2397a9ab..a02d1132 100644 --- a/tests/Feature/CommandsTest.php +++ b/tests/Feature/CommandsTest.php @@ -288,6 +288,19 @@ ->not->toContain("\n \$this->app->make("); }); + // The config an app already has is left alone, so the provider written + // beside it can ask for something the config doesn't turn on. + it('says so when a config it kept leaves nobody able to set up the sign-in methods picked', function () { + file_put_contents(config_path('keyring.php'), " ['registration', 'email-verification']];\n"); + config(['keyring.features' => ['registration', 'email-verification']]); + + $this->artisan('keyring:install', ['--factor' => ['totp'], '--no-interaction' => true]) + ->expectsOutputToContain('Add Features::manageAuthenticators() to the features in config/keyring.php') + ->assertSuccessful(); + + expect(file_get_contents($this->sandbox.'/app/Providers/KeyringServiceProvider.php'))->toContain("\n Factors\\Totp::class,\n"); + }); + it('can run again without duplicating migrations or overwriting customised files', function () { $this->artisan('keyring:install', ['--no-interaction' => true])->assertSuccessful(); file_put_contents($this->sandbox.'/app/Providers/KeyringServiceProvider.php', 'save(new RegisteredSession('ended', (string) $user->id, 'web', null, Assurance::AAL1, null, null, 0, 0, now()->subMinute()->getTimestamp())); - $registry->save(new RegisteredSession('live', (string) $user->id, 'web', null, Assurance::AAL1, null, null, 0, 0, now()->addDay()->getTimestamp())); + $registry->save(new RegisteredSession('ended', (string) $user->id, $user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, 0, 0, now()->subMinute()->getTimestamp())); + $registry->save(new RegisteredSession('live', (string) $user->id, $user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, 0, 0, now()->addDay()->getTimestamp())); $this->artisan('keyring:prune')->assertSuccessful(); @@ -911,7 +924,7 @@ function passkeysTable(): void $now = now()->getTimestamp(); return tap( - new RegisteredSession($id, (string) $user->id, 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600)->with($with), + new RegisteredSession($id, (string) $user->id, $user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600)->with($with), fn (RegisteredSession $session) => app(SessionRegistry::class)->save($session), ); }; @@ -1067,7 +1080,7 @@ function passkeysTable(): void it('ends more sessions than it revokes in one go', function () { $now = now()->getTimestamp(); - DB::table('keyring_sessions')->insert(array_map(fn (int $n) => new RegisteredSession("session-{$n}", (string) $this->user->id, 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600)->toArray(), range(1, 1001))); + DB::table('keyring_sessions')->insert(array_map(fn (int $n) => new RegisteredSession("session-{$n}", (string) $this->user->id, $this->user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600)->toArray(), range(1, 1001))); $this->artisan('keyring:sign-out', ['--all' => true, '--force' => true])->assertSuccessful(); diff --git a/tests/Feature/ConformanceTest.php b/tests/Feature/ConformanceTest.php index ff8f2b12..3553d28c 100644 --- a/tests/Feature/ConformanceTest.php +++ b/tests/Feature/ConformanceTest.php @@ -224,6 +224,35 @@ public static function brokersWithoutAThrottle(): array ]; } + public function test_the_suite_fails_when_a_password_hash_takes_longer_than_the_timebox(): void + { + // Shorter than any hash at the cost production would run. + config(['keyring.timebox' => '1ms']); + + try { + $this->test_keyring_holds_a_refusal_for_longer_than_a_password_hash_takes(); + } catch (AssertionFailedError $failure) { + $this->assertStringContainsString('keyring.timebox is 1ms', $failure->getMessage()); + + return; + } + + $this->fail('A timebox shorter than a password hash went unnoticed.'); + } + + public function test_the_suite_times_a_hash_at_the_cost_production_runs_not_the_test_suites(): void + { + // What phpunit.xml gives the tests, and a new app's own setting. + config(['hashing.bcrypt.rounds' => 4]); + $this->assertSame(['rounds' => 12], $this->keyringProductionHashOptions()); + + config(['hashing.bcrypt.rounds' => 14]); + $this->assertSame(['rounds' => 14], $this->keyringProductionHashOptions()); + + config(['hashing.driver' => 'argon2id']); + $this->assertSame([], $this->keyringProductionHashOptions()); + } + public function test_the_suite_reads_the_throttle_of_the_broker_keyring_uses(): void { // The default broker has none, and it isn't the one that sends Keyring's links. diff --git a/tests/Feature/DeletingUsersTest.php b/tests/Feature/DeletingUsersTest.php index adccc5cf..1dd5c006 100644 --- a/tests/Feature/DeletingUsersTest.php +++ b/tests/Feature/DeletingUsersTest.php @@ -62,7 +62,7 @@ Schema::table('users', fn (Blueprint $table) => $table->softDeletes()); $user = SoftDeletingUser::create(['name' => 'Taylor', 'email' => 'taylor@example.com', 'password' => 'password']); Authenticator::factory()->totp()->for($user, 'authenticatable')->create(); - $session = new RegisteredSession('kept', (string) $user->id, 'web', null, Assurance::AAL1, null, null, 0, 0, now()->addHour()->getTimestamp()); + $session = new RegisteredSession('kept', (string) $user->id, $user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, 0, 0, now()->addHour()->getTimestamp()); app(SessionRegistry::class)->save($session); $user->delete(); diff --git a/tests/Feature/DevicesAndSessionsTest.php b/tests/Feature/DevicesAndSessionsTest.php index 41f8cca0..00e3f9de 100644 --- a/tests/Feature/DevicesAndSessionsTest.php +++ b/tests/Feature/DevicesAndSessionsTest.php @@ -2,10 +2,14 @@ declare(strict_types=1); +use Illuminate\Database\Eloquent\Attributes\Table; +use Illuminate\Database\Eloquent\Model; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Event; +use Illuminate\Support\Facades\Hash; +use Illuminate\Support\Facades\Password as Broker; use Illuminate\Support\Facades\Route; use Illuminate\Testing\TestResponse; use Keyring\Changes\AuthenticatorChanges; @@ -36,6 +40,7 @@ use Keyring\Risk\Checkpoint; use Keyring\Risk\Finding; use Keyring\Risk\RiskLocks; +use Keyring\Sessions\DatabaseSessionRegistry; use Keyring\Sessions\RegisteredSession; use Keyring\Sessions\Sessions; use Keyring\Tests\Fixtures\User; @@ -316,6 +321,43 @@ function activeSessions(): array })->with('registries'); }); +// The guard is signed in before the device is recorded and the session +// registered. If one of those fails, nobody is left signed in: a session +// that never had its closing checks isn't one to carry on with. +describe('a sign in that fails after the guard is signed in', function () { + it('leaves nobody signed in, and nothing registered', function () { + // The session registry fails as the session is being stored. + app()->bind(SessionRegistry::class, fn () => new class(app('db')->connection(), 'keyring_sessions') extends DatabaseSessionRegistry + { + public function save(RegisteredSession $session): void + { + throw new RuntimeException('The database went away.'); + } + }); + + $this->post('/login', ['email' => 'taylor@example.com', 'password' => 'password'])->assertServerError(); + + $this->assertGuest(); + expect(DB::table('keyring_sessions')->count())->toBe(0); + + app()->forgetInstance(SessionRegistry::class); + $this->get('/home')->assertRedirect('/login'); + expect(DB::table('keyring_sessions')->count())->toBe(0); + }); + + it('does not fail on a device describer of the app\'s that throws, or names a browser at length', function (Closure $describer, ?string $name) { + Keyring::describeDevicesUsing($describer); + + login()->assertRedirect('/dashboard'); + + $this->assertAuthenticatedAs($this->user); + expect(Device::query()->sole()->name)->toBe($name); + })->with([ + 'one that throws' => [fn () => throw new RuntimeException('No idea.'), null], + 'a very long name' => [fn () => str_repeat('a', 400), str_repeat('a', 255)], + ]); +}); + it('gives new device events a working "this wasn\'t me" link', function () { Event::fake([NewDeviceSignedIn::class, DeviceRevoked::class]); login(); @@ -387,6 +429,7 @@ function activeSessions(): array $other = new RegisteredSession( id: 'other', userId: (string) $this->user->id, + userType: $this->user->getMorphClass(), guard: 'web', deviceId: null, assurance: Assurance::AAL1, @@ -1032,6 +1075,56 @@ function expectNoTrustedDevices(): void }); }); +// Two user models can have the same IDs. A session is its user's by the +// model as well as the ID, like everything else Keyring keeps for a user. +describe('an app with two kinds of account whose ids overlap', function () { + beforeEach(function () { + $this->staff = staff(); + + $now = now()->getTimestamp(); + $session = fn (string $id, Model $user, ?string $device = null) => new RegisteredSession($id, (string) $user->getKey(), $user->getMorphClass(), 'web', $device, Assurance::AAL1, null, null, $now, $now, $now + 3600); + + $this->seed = function () use ($session) { + app(SessionRegistry::class)->save($session('users', $this->user, 'device')); + app(SessionRegistry::class)->save($session('staffs', $this->staff, 'device')); + }; + }); + + it('lists, counts and ends each account\'s sessions apart', function (string $driver, Closure $end) { + config(['keyring.sessions.driver' => $driver]); + ($this->seed)(); + $registry = app(SessionRegistry::class); + + expect($this->staff->getKey())->toBe($this->user->getKey()) + ->and($registry->forUser($this->user)->pluck('id')->all())->toBe(['users']) + ->and($registry->forUser($this->staff)->pluck('id')->all())->toBe(['staffs']); + + $end($this->staff); + + expect($registry->find('staffs')->revokedAt)->not->toBeNull() + ->and($registry->find('users')->revokedAt)->toBeNull() + ->and($registry->forUser($this->user)->pluck('id')->all())->toBe(['users']); + })->with(['database', 'cache'])->with([ + 'signing out everywhere' => [fn (Model $user) => app(Sessions::class)->signOutEverywhere($user)], + 'every session' => [fn (Model $user) => app(SessionRegistry::class)->revokeAll($user)], + 'a device\'s sessions' => [fn (Model $user) => app(SessionRegistry::class)->revokeDevice($user, 'device')], + 'deleting the account' => [fn (Model $user) => $user->delete()], + ]); + + it('does not carry one kind of account on with the other\'s session', function () { + Route::middleware(['web', 'auth'])->get('/home', fn () => 'home'); + + $this->post('/login', ['email' => 'taylor@example.com', 'password' => 'password'])->assertRedirect(); + $this->get('/home')->assertOk(); + + // The same guard handing back the other model, as an app that swaps + // its provider by domain would. + $this->actingAs($this->staff)->get('/home')->assertRedirect('/login'); + + expect(SecurityEvent::query()->where('type', 'session_ended')->sole()->meta['reason'])->toBe('other_user'); + }); +}); + describe('ending other sessions along with a change to how the user signs in', function () { beforeEach(function () { Event::fake([SessionsRevoked::class]); @@ -1044,7 +1137,7 @@ function expectNoTrustedDevices(): void $this->here = session(Sessions::KEY); $now = now()->getTimestamp(); - app(SessionRegistry::class)->save(new RegisteredSession('elsewhere', (string) $this->user->id, 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600)); + app(SessionRegistry::class)->save(new RegisteredSession('elsewhere', (string) $this->user->id, $this->user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600)); }; $this->expectOnlyThisSessionLeft = function () { @@ -1162,7 +1255,7 @@ function expectNoTrustedDevices(): void $here = session(Sessions::KEY); $id = session()->getId(); $now = now()->getTimestamp(); - $registry->save(new RegisteredSession('elsewhere', (string) $this->user->id, 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600)); + $registry->save(new RegisteredSession('elsewhere', (string) $this->user->id, $this->user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600)); $this->user->forceFill(['remember_token' => 'remembered'])->save(); $this->deleteJson(route('keyring.sessions.destroy-others'))->assertOk()->assertJsonPath('status', 'sessions-revoked'); @@ -1194,7 +1287,7 @@ function expectNoTrustedDevices(): void $now = now()->getTimestamp(); return tap( - new RegisteredSession($id, (string) ($user ?? $this->user)->id, 'web', null, Assurance::AAL1, '203.0.113.7', CHROME, $now - 600, $now - 300, $now + 3600)->with($with), + new RegisteredSession($id, (string) ($user ?? $this->user)->id, ($user ?? $this->user)->getMorphClass(), 'web', null, Assurance::AAL1, '203.0.113.7', CHROME, $now - 600, $now - 300, $now + 3600)->with($with), fn (RegisteredSession $session) => app(SessionRegistry::class)->save($session), ); }; @@ -1451,7 +1544,48 @@ function expectNoTrustedDevices(): void }); }); -it('never queries the devices table when devices are off', function () { +// Trust given while devices were on doesn't outlive a change that should end +// it, made while they were off: turning them back on would bring it back. +it('ends device trust on a change made while devices are off', function (Closure $change) { + $this->user->forceFill(['password' => Hash::make('a much longer passphrase')])->saveQuietly(); + $trusted = Device::query()->forceCreate([ + 'authenticatable_type' => $this->user->getMorphClass(), 'authenticatable_id' => $this->user->id, + 'token_hash' => hash('sha256', 'a trusted browser'), 'name' => 'Firefox', 'trusted_until' => now()->addMonth(), 'last_seen_at' => now(), + ]); + + withFeatures(array_values(array_diff(Features::all(), [Features::devices()]))); + $change($this->user); + + expect($trusted->fresh()->trusted_until)->toBeNull(); +})->with([ + 'a password reset' => [fn (User $user) => test()->post(route('password.update'), [ + 'token' => Broker::broker()->createToken($user), 'email' => $user->email, + 'password' => 'another passphrase altogether', 'password_confirmation' => 'another passphrase altogether', + ])->assertSessionHasNoErrors()], + 'a sign-out everywhere' => [fn (User $user) => app(Sessions::class)->signOutEverywhere($user)], +]); + +/** + * The devices of an app that turned the feature off and never ran its migration. + */ +#[Table(name: 'keyring_devices_never_made')] +class DeviceWithoutATable extends Device {} + +it('lets a change through on an app that never made the devices table', function () { + withFeatures(array_values(array_diff(Features::all(), [Features::devices()]))); + Keyring::useDeviceModel(DeviceWithoutATable::class); + + DB::transaction(function () { + app(Sessions::class)->signOutEverywhere($this->user); + + // The caller's transaction is still good for what follows. + $this->user->forceFill(['name' => 'Still here'])->save(); + }); + + expect($this->user->fresh()->name)->toBe('Still here'); +}); + +it('never queries the devices table when devices are off, but to end trust', function () { $totp = Authenticator::factory()->totp()->for($this->user, 'authenticatable')->create(); $backup = Authenticator::factory()->totp()->for($this->user, 'authenticatable')->create(); withFeatures(array_values(array_diff(Features::all(), [Features::devices()]))); @@ -1467,8 +1601,11 @@ function expectNoTrustedDevices(): void app(Sessions::class)->distrustDevices($this->user); app(Sessions::class)->signOutEverywhere($this->user); + $devices = array_values(array_unique(array_filter($queries, fn (string $sql) => str_contains($sql, 'keyring_devices')))); + expect($queries)->not->toBeEmpty() - ->and(array_filter($queries, fn (string $sql) => str_contains($sql, 'keyring_devices')))->toBe([]); + ->and($devices)->toHaveCount(1) + ->and($devices[0])->toMatch('/^update .keyring_devices. set .trusted_until. = \?/'); }); function riskySignal(Checkpoint $checkpoint): Signal diff --git a/tests/Feature/EmailChangeHardeningTest.php b/tests/Feature/EmailChangeHardeningTest.php index c31532ff..237d6fd1 100644 --- a/tests/Feature/EmailChangeHardeningTest.php +++ b/tests/Feature/EmailChangeHardeningTest.php @@ -2,7 +2,9 @@ declare(strict_types=1); +use Illuminate\Auth\AuthenticationException; use Illuminate\Database\Schema\Blueprint; +use Illuminate\Http\Request; use Illuminate\Notifications\AnonymousNotifiable; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; @@ -14,6 +16,7 @@ use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Str; +use Keyring\Changes\AuthenticatorChanges; use Keyring\Changes\EmailChanges; use Keyring\Contracts\SessionRegistry; use Keyring\Enums\Assurance; @@ -188,6 +191,96 @@ function confirmBoth(PendingChange $change, array $tokens): EmailConfirmation Event::assertDispatched(AuthenticatorRemoved::class, fn (AuthenticatorRemoved $event) => $event->authenticator->is($planted)); }); +// The removals are announced on the account as it is once the address is +// back, whatever sends the notice: an event carrying the copy loaded before +// that would have a notice that isn't queued go to the address taken off. +it('announces what an undo removed to the address it put back', function () { + Event::fake([AuthenticatorRemoved::class]); + $change = requestChange($this->user, 'attacker@example.com', Assurance::AAL2); + $tokens = tokensFor('attacker@example.com', 'taylor@example.com'); + + $this->travel(1)->minutes(); + Authenticator::factory()->passkey()->for($this->user, 'authenticatable')->create(); + + confirmBoth($change, $tokens); + expect($this->user->fresh()->email)->toBe('attacker@example.com'); + + app(EmailChanges::class)->revert($change->fresh(), $tokens['revert']); + + Event::assertDispatched(AuthenticatorRemoved::class, fn (AuthenticatorRemoved $event) => $event->user->email === 'taylor@example.com'); + Event::assertNotDispatched(AuthenticatorRemoved::class, fn (AuthenticatorRemoved $event) => $event->user->email === 'attacker@example.com'); +}); + +// A request already past its middleware when the undo starts. It either +// saves before the undo ends the sessions, where the undo's last look finds +// what it saved, or after, where it's refused. +describe('a request under way while a change is being undone', function () { + it('has what it saved in the meantime closed and removed by the undo', function () { + $change = requestChange($this->user, 'attacker@example.com', Assurance::AAL2); + $tokens = tokensFor('attacker@example.com', 'taylor@example.com'); + confirmBoth($change, $tokens); + + // Saved once the undo has looked for later changes and for sign-in + // methods to remove, and before it has ended the sessions. + $late = []; + PendingChange::updated(function (PendingChange $saved) use ($change, &$late) { + if ($saved->is($change) && $saved->wasChanged('reverted_at') && $late === []) { + $late['change'] = tap(new PendingChange([ + 'attribute' => 'email', + 'value' => 'again@example.com', + 'previous_value' => 'attacker@example.com', + 'confirm_token' => PendingChange::hashToken('confirm'), + 'revert_token' => PendingChange::hashToken('late'), + 'expires_at' => now()->addDay(), + ]), fn (PendingChange $late) => $late->authenticatable()->associate($this->user)->save()); + } + }); + Authenticator::deleted(function () use (&$late) { + $late['passkey'] ??= Authenticator::factory()->passkey()->for($this->user, 'authenticatable')->create(); + }); + + $this->travel(1)->minutes(); + Authenticator::factory()->totp()->for($this->user, 'authenticatable')->create(); + + expect(app(EmailChanges::class)->revert($change->fresh(), $tokens['revert']))->toBeTrue() + ->and($late)->toHaveKeys(['change', 'passkey']) + ->and($late['change']->fresh()->canRevert())->toBeFalse() + ->and(app(EmailChanges::class)->revert($late['change']->fresh(), 'late'))->toBeFalse() + ->and(app(EmailChanges::class)->confirm($late['change']->fresh(), 'confirm'))->toBe(EmailConfirmation::Invalid) + ->and(Authenticator::find($late['passkey']->id))->toBeNull() + ->and($this->user->fresh()->email)->toBe('taylor@example.com'); + }); + + it('is refused once the undo has ended its session', function (Closure $save) { + $this->post('/login', ['email' => 'taylor@example.com', 'password' => 'password'])->assertRedirect(); + $request = request(); + $request->setLaravelSession(session()->driver()); + + // What an undo, a reset or "this wasn't me" does while this request runs. + app(Sessions::class)->signOutEverywhere($this->user); + + expect(fn () => $save($this->user, $request))->toThrow(AuthenticationException::class) + ->and(PendingChange::query()->count())->toBe(0) + ->and(Authenticator::query()->count())->toBe(0); + })->with([ + 'an email change' => [fn (User $user, Request $request) => app(EmailChanges::class)->request($user, 'attacker@example.com', $request)], + 'a sign-in method' => [fn (User $user, Request $request) => app(AuthenticatorChanges::class)->add( + $user, + Keyring::factor('totp'), + Authenticator::factory()->totp()->for($user, 'authenticatable')->make(), + $request, + )], + ]); + + it('saves as usual while its session stands', function () { + $this->post('/login', ['email' => 'taylor@example.com', 'password' => 'password'])->assertRedirect(); + $request = request(); + $request->setLaravelSession(session()->driver()); + + expect(app(EmailChanges::class)->request($this->user, 'new@example.com', $request))->toBeInstanceOf(PendingChange::class); + }); +}); + it('removes sign-in methods added earlier in the session that asked for the change', function () { $before = Authenticator::factory()->totp()->for($this->user, 'authenticatable')->create(['created_at' => now()->subMonth()]); $this->post('/login', ['email' => 'taylor@example.com', 'password' => 'password']); @@ -574,6 +667,16 @@ function confirmBoth(PendingChange $change, array $tokens): EmailConfirmation 'a character that does not show' => "tay\u{00AD}lor@example.com", ]); + // Asked of MySQL 8.4: utf8mb4_general_ci takes "ß" for "s", and + // utf8mb4_unicode_ci and utf8mb4_0900_ai_ci take it for "ss". + it('is found under every spelling of a sharp s that some collation takes for it', function () { + expect(PendingChange::fold('klauß@example.com')) + ->toBe(PendingChange::fold('klaus@example.com')) + ->toBe(PendingChange::fold('klauss@example.com')) + ->toBe(PendingChange::fold('KLAUẞ@example.com')) + ->not->toBe(PendingChange::fold('klaut@example.com')); + }); + it('still lets a different address be registered', function (string $address) { $this->post('/logout'); @@ -604,6 +707,7 @@ function otherSession(User $user, string $id = 'other-session'): string app(SessionRegistry::class)->save(new RegisteredSession( id: $id, userId: (string) $user->getKey(), + userType: $user->getMorphClass(), guard: 'web', deviceId: null, assurance: Assurance::AAL1, @@ -724,7 +828,7 @@ function otherSession(User $user, string $id = 'other-session'): string expect(app(SessionRegistry::class)->find($other)->revokedAt)->toBeNull(); }); - it('does not touch device tables when devices are off', function () { + it('does not touch device tables when devices are off, but to end trust given while they were on', function () { withFeatures([Features::emailChanges()]); $change = requestChange($this->user, 'new@example.com'); $tokens = tokensFor('new@example.com', 'taylor@example.com'); @@ -732,7 +836,7 @@ function otherSession(User $user, string $id = 'other-session'): string confirmBoth($change, $tokens); - expect(collect(DB::getQueryLog())->pluck('query')->filter(fn (string $query) => str_contains($query, 'keyring_devices')))->toBeEmpty() + expect(collect(DB::getQueryLog())->pluck('query')->filter(fn (string $query) => str_contains($query, 'keyring_devices'))->reject(fn (string $query) => preg_match('/^update .keyring_devices. set .trusted_until. = \?/', $query) === 1)->all())->toBe([]) ->and($this->user->fresh()->email)->toBe('new@example.com'); }); diff --git a/tests/Feature/ExtendingTest.php b/tests/Feature/ExtendingTest.php index 18484c6e..aa07291b 100644 --- a/tests/Feature/ExtendingTest.php +++ b/tests/Feature/ExtendingTest.php @@ -224,7 +224,7 @@ class CustomConfirmEmailChange extends ConfirmEmailChange it('runs the app\'s own password action, with keyring\'s security work around it', function () { Keyring::updateUserPasswordsUsing(SymbolsRequired::class); - $other = new RegisteredSession('other', (string) $this->user->id, 'web', null, Assurance::AAL1, null, null, 0, 0, now()->addHour()->getTimestamp()); + $other = new RegisteredSession('other', (string) $this->user->id, $this->user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, 0, 0, now()->addHour()->getTimestamp()); app(SessionRegistry::class)->save($other); $this->actingAs($this->user)->withAssurance(Assurance::AAL1) @@ -280,7 +280,7 @@ class CustomConfirmEmailChange extends ConfirmEmailChange it('refuses a password action that saves nothing, before signing anyone out', function () { Keyring::updateUserPasswordsUsing(SavesNothing::class); - $other = new RegisteredSession('other', (string) $this->user->id, 'web', null, Assurance::AAL1, null, null, 0, 0, now()->addHour()->getTimestamp()); + $other = new RegisteredSession('other', (string) $this->user->id, $this->user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, 0, 0, now()->addHour()->getTimestamp()); app(SessionRegistry::class)->save($other); $this->withoutExceptionHandling()->actingAs($this->user)->withAssurance(Assurance::AAL1); diff --git a/tests/Feature/MailLimitsTest.php b/tests/Feature/MailLimitsTest.php index 464441f2..e2ac9f62 100644 --- a/tests/Feature/MailLimitsTest.php +++ b/tests/Feature/MailLimitsTest.php @@ -2,6 +2,7 @@ declare(strict_types=1); +use Illuminate\Auth\Notifications\VerifyEmail; use Illuminate\Support\Facades\Notification; use Illuminate\Support\Facades\Password; use Illuminate\Testing\TestResponse; @@ -193,3 +194,32 @@ function askToMoveTo(User $user, string $email): TestResponse Notification::assertSentTimes(EmailChangeNotice::class, 7); }); }); + +// The address an unverified account holds is whatever was typed when it +// registered. Asking for the link again mails it out of the same count the +// registration form has, not once for every time the form limit allows. +describe('asking for the verification link again', function () { + beforeEach(function () { + revealTakenAddresses(); + }); + + it('mails an unverified address five times an hour at most, registering included, and says when that is used up', function () { + $this->post('/register', ['name' => 'Someone', 'email' => 'Victim@Example.com', 'password' => 'a much longer passphrase', 'password_confirmation' => 'a much longer passphrase']) + ->assertSessionHasNoErrors(); + $user = User::query()->where('email', 'victim@example.com')->sole(); + + foreach (range(1, 8) as $ask) { + $this->travel(2)->minutes(); + $response = $this->actingAs($user)->postJson(route('verification.send')); + + $ask <= 4 ? $response->assertOk() : $response->assertStatus(429)->assertJsonValidationErrors('email'); + } + + Notification::assertSentToTimes($user, VerifyEmail::class, 5); + + $this->travel(61)->minutes(); + $this->actingAs($user)->postJson(route('verification.send'))->assertOk(); + + Notification::assertSentToTimes($user, VerifyEmail::class, 6); + }); +}); diff --git a/tests/Feature/OctaneTest.php b/tests/Feature/OctaneTest.php index 95393134..c6a48ba7 100644 --- a/tests/Feature/OctaneTest.php +++ b/tests/Feature/OctaneTest.php @@ -6,13 +6,23 @@ use Illuminate\Contracts\Foundation\Application; use Illuminate\Http\Request; use Illuminate\Support\Facades\Facade; +use Keyring\Changes\EmailChanges; +use Keyring\Changes\PasswordChanges; use Keyring\Contracts\Responses\LogoutResponse; +use Keyring\Enrollment\EnrollmentStore; use Keyring\Enums\Assurance; use Keyring\Enums\Purpose; use Keyring\Facades\Keyring; +use Keyring\Http\Controllers\AuthenticatorController; +use Keyring\Http\Controllers\ChallengeController; +use Keyring\Http\Controllers\EmailChangeController; +use Keyring\Http\Controllers\PasswordResetController; use Keyring\KeyringManager; use Keyring\Login\AttemptStore; +use Keyring\Login\SignIn; +use Keyring\Login\StepUp; use Keyring\Models\Authenticator; +use Keyring\Pipeline\Verifier; use Keyring\Sessions\SessionAssurance; // Octane boots the app once per worker and handles each request in a copy of @@ -121,3 +131,44 @@ public function toResponse($request) expect(Keyring::response(LogoutResponse::class)->app)->toBe($sandbox); }); + +// A route keeps the controller it made. Octane drops it after each request, +// and another worker might not: a controller holding the session of the +// request it was made for would then answer the next visitor from it. +it('gives a controller that outlives its request the stores of the request it is handling', function (string $controller, string $property, string $service) { + [$first] = octaneRequest($this->booted, []); + $kept = $first->make($controller); + $held = fn () => (fn () => $this->{$property})->call($kept); + $before = $held(); + + expect($before)->toBeInstanceOf($service); + + octaneRequest($this->booted, []); + + // Never the one it had for the request before. + expect($held())->toBeInstanceOf($service)->not->toBe($before); +})->with([ + 'a pending sign in' => [ChallengeController::class, 'attempts', AttemptStore::class], + 'a step-up' => [ChallengeController::class, 'stepUp', StepUp::class], + 'the pipeline' => [ChallengeController::class, 'verifier', Verifier::class], + 'a pending enrollment' => [AuthenticatorController::class, 'enrollments', EnrollmentStore::class], + 'signing in' => [AuthenticatorController::class, 'signIn', SignIn::class], + 'email changes' => [EmailChangeController::class, 'changes', EmailChanges::class], + 'password changes' => [PasswordResetController::class, 'passwords', PasswordChanges::class], +]); + +it('does not show a visitor the sign in another left waiting, through a controller the route kept', function () { + Authenticator::factory()->totp()->for($this->user, 'authenticatable')->create(); + + [$sandbox, $request] = octaneRequest($this->booted, ['email' => 'taylor@example.com', 'password' => 'password']); + $sandbox->make(KeyringManager::class)->attempt($request); + $kept = $sandbox->make(ChallengeController::class); + $waiting = fn () => (fn () => $this->attempts->current(Purpose::Login))->call($kept); + + expect($waiting()?->userId)->toBe($this->user->id); + + // Someone else, with no session of their own yet. + octaneRequest($this->booted, []); + + expect($waiting())->toBeNull(); +}); diff --git a/tests/Feature/PasswordHoldTest.php b/tests/Feature/PasswordHoldTest.php index 73031ef6..7887b1dc 100644 --- a/tests/Feature/PasswordHoldTest.php +++ b/tests/Feature/PasswordHoldTest.php @@ -4,11 +4,13 @@ use Illuminate\Contracts\Validation\UncompromisedVerifier; use Illuminate\Support\Facades\Event; +use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Password; use Illuminate\Support\Facades\Route; use Keyring\Changes\PasswordHolds; use Keyring\Enums\Assurance; use Keyring\Enums\Severity; +use Keyring\Events\PasswordChanged; use Keyring\Events\PasswordChangeRequired; use Keyring\Events\RiskAssessed; use Keyring\Facades\Keyring; @@ -97,6 +99,53 @@ function chooseNewPassword(string $current = 'password', string $new = 'a much l $this->get('/home')->assertOk(); }); +// A new hash of the same password is a different string, so the hash +// changing says nothing about the password. +it('keeps the hold when the password they were held for is saved again as the new one', function () { + Event::fake([PasswordChanged::class]); + $this->user->forceFill(['password' => Hash::make('a much longer passphrase 1')])->saveQuietly(); + Keyring::requirePasswordChange($this->user); + signInWithPassword('a much longer passphrase 1'); + + $this->putJson(route('user-password.update'), [ + 'current_password' => 'a much longer passphrase 1', + 'password' => 'a much longer passphrase 1', + 'password_confirmation' => 'a much longer passphrase 1', + ])->assertUnprocessable()->assertJsonValidationErrors(['password' => __('keyring::keyring.password_unchanged')]); + + expect(Keyring::requiresPasswordChange($this->user))->toBeTrue(); + Event::assertNotDispatched(PasswordChanged::class); + $this->get('/home')->assertRedirect('/settings/password'); + + chooseNewPassword('a much longer passphrase 1', 'another passphrase altogether'); + + expect(Keyring::requiresPasswordChange($this->user))->toBeFalse(); + Event::assertDispatchedTimes(PasswordChanged::class, 1); +}); + +it('keeps the hold through a reset to the same password, without telling the link\'s holder it was the same', function () { + $this->user->forceFill(['password' => Hash::make('a much longer passphrase 1')])->saveQuietly(); + Keyring::requirePasswordChange($this->user); + + $reset = fn (string $password) => $this->post(route('password.update'), [ + 'token' => Password::broker()->createToken($this->user), + 'email' => 'taylor@example.com', + 'password' => $password, + 'password_confirmation' => $password, + ]); + + // Answered like any reset: whoever holds the link learns nothing of the + // password it replaced. + $reset('a much longer passphrase 1')->assertSessionHasNoErrors()->assertRedirect(route('login')); + + expect(Keyring::requiresPasswordChange($this->user))->toBeTrue(); + + $this->travel(2)->minutes(); + $reset('another passphrase altogether')->assertSessionHasNoErrors(); + + expect(Keyring::requiresPasswordChange($this->user))->toBeFalse(); +}); + it('holds one hold per user however often evidence turns up', function () { Event::fake([PasswordChangeRequired::class]); diff --git a/tests/Feature/PasswordResetTest.php b/tests/Feature/PasswordResetTest.php index 722d717b..8846b0f1 100644 --- a/tests/Feature/PasswordResetTest.php +++ b/tests/Feature/PasswordResetTest.php @@ -7,6 +7,7 @@ use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Notification; use Illuminate\Support\Facades\Password; +use Illuminate\Support\Timebox; use Keyring\Changes\PasswordChanges; use Keyring\Contracts\SessionRegistry; use Keyring\Events\FactorVerified; @@ -34,6 +35,45 @@ ->and($errors->first())->toHaveKey('email')->not->toHaveKey('password'); }); +// The broker hashes a token only for an address with a link outstanding, and +// its own wait is 200ms on a timebox that a completed reset switches off for +// as long as the broker lives. Every refusal waits out Keyring's instead. +it('holds every refused reset for the timebox, and lets a good one straight through', function () { + config(['keyring.timebox' => '400ms']); + + $timebox = new class extends Timebox + { + /** @var list */ + public static array $calls = []; + + public function call(callable $callback, int $microseconds) + { + $result = parent::call($callback, 0); + self::$calls[] = [$microseconds, $this->earlyReturn]; + + return $result; + } + }; + $this->app->bind(Timebox::class, $timebox::class); + + $reset = fn (string $email, string $token) => $this->post(route('password.update'), [ + 'token' => $token, 'email' => $email, 'password' => 'a much longer passphrase', 'password_confirmation' => 'a much longer passphrase', + ]); + + $good = Password::broker()->createToken($this->plain); + Password::broker()->createToken($this->mfa); + + $reset('nobody@example.com', 'bogus'); + $reset('mfa@example.com', 'bogus'); + $reset('plain@example.com', $good)->assertSessionHasNoErrors(); + // After a reset has gone through on the same broker. + $reset('plain@example.com', 'bogus'); + + $keyrings = array_values(array_filter($timebox::$calls, fn (array $call) => $call[0] === 400_000)); + + expect(array_column($keyrings, 1))->toBe([false, false, true, false]); +}); + it('still applies the password rules once the token checks out', function () { $token = Password::broker()->createToken($this->plain); diff --git a/tests/Feature/RememberMeTest.php b/tests/Feature/RememberMeTest.php index 5a64f5c1..c2145740 100644 --- a/tests/Feature/RememberMeTest.php +++ b/tests/Feature/RememberMeTest.php @@ -661,6 +661,32 @@ function sessionEndedReasons(): array expect(sessionEndedReasons())->toBe(['risk']); }); + // The cookie is the browser's to send. Another account's value in it is + // no way to end that account's session. + it('ends only its own remembered session, whatever the cookie names', function (Closure $keepOut, string $driver) { + config(['keyring.sessions.driver' => $driver]); + $abigail = User::create(['name' => 'Abigail', 'email' => 'abigail@example.com', 'password' => 'password', 'email_verified_at' => now()]); + + $theirs = rememberedSignIn(email: 'abigail@example.com'); + $mine = rememberedSignIn(); + $keepOut($this->user); + + $this->flushSession(); + browser([...$mine, 'remembered_session' => $theirs['remembered_session']])->get('/home')->assertRedirect('/login'); + + expect(app(SessionRegistry::class)->find($theirs['remembered_session'])->revokedAt)->toBeNull() + ->and(app(SessionRegistry::class)->forUser($abigail))->toHaveCount(1); + + // Its own is still ended when it's the one named. + $this->flushSession(); + browser($mine)->get('/home')->assertRedirect('/login'); + + expect(app(SessionRegistry::class)->find($mine['remembered_session'])->revokedAt)->not->toBeNull(); + })->with([ + 'a risk lock' => [fn (User $user) => app(RiskLocks::class)->lock($user, 3600)], + 'the sign-in gate' => [fn (User $user) => Keyring::allowSignInWhen(fn (User $who) => ! $who->is($user))], + ])->with(['database', 'cache']); + it('stays refused once the lock is lifted', function () { $cookies = rememberedSignIn(); app(RiskLocks::class)->lock($this->user, 3600); @@ -1046,7 +1072,7 @@ function sessionEndedReasons(): array describe('replacing a session\'s record', function () { beforeEach(function () { - $this->session = fn (string $id, array $changes = []) => new RegisteredSession($id, (string) $this->user->id, 'web', null, Assurance::AAL1, null, null, 0, 0, now()->addHour()->getTimestamp())->with($changes); + $this->session = fn (string $id, array $changes = []) => new RegisteredSession($id, (string) $this->user->id, $this->user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, 0, 0, now()->addHour()->getTimestamp())->with($changes); }); it('happens once, and keeps only the record that did it', function (string $driver) { diff --git a/tests/Feature/RiskTest.php b/tests/Feature/RiskTest.php index 9576d4c6..a55037b3 100644 --- a/tests/Feature/RiskTest.php +++ b/tests/Feature/RiskTest.php @@ -285,6 +285,35 @@ function expectOwnerStillSignedIn(string $session): void $this->withHeader('User-Agent', CHROME)->get('/sensitive')->assertRedirect(route('keyring.confirm.challenge')); }); +// sessions.end_on_lapse ends a session when what it signed in with has gone, +// and a step-up is what makes it go. +it('ends the session instead where a session ends with the level it signed in at', function (bool $endOnLapse) { + config(['keyring.sessions.end_on_lapse' => $endOnLapse]); + Keyring::risk()->signals([SessionFingerprintChanged::class]); + $totp = Authenticator::factory()->totp()->for($this->user, 'authenticatable')->create(); + + $this->withHeader('User-Agent', FIREFOX)->post('/login', ['email' => 'taylor@example.com', 'password' => 'password']); + $this->withHeader('User-Agent', FIREFOX)->post(route('keyring.login.verify', 'totp'), ['code' => totpCode($totp->secret)])->assertRedirect('/dashboard'); + $this->withHeader('User-Agent', FIREFOX)->get('/home')->assertOk(); + + $moved = $this->withHeader('User-Agent', CHROME)->get('/home'); + + if (! $endOnLapse) { + $moved->assertOk(); + $this->assertAuthenticated(); + + return; + } + + $moved->assertRedirect('/login'); + $this->assertGuest(); + expect(SecurityEvent::where('type', 'session_ended')->sole()->meta['reason'])->toBe('risk'); + + // Not left for the timeouts to find, a day later. + $this->travel(2)->hours(); + $this->withHeader('User-Agent', CHROME)->get('/home')->assertRedirect('/login'); +})->with(['on' => true, 'off' => false]); + it('does not let a confirmation started before the session moved browser keep its proofs', function () { Keyring::risk()->signals([SessionFingerprintChanged::class]); Route::middleware(['web', 'auth', 'keyring:aal2'])->get('/billing', fn () => 'billing'); @@ -342,14 +371,25 @@ function expectOwnerStillSignedIn(string $session): void $this->post('/logout'); $totp = Authenticator::factory()->totp()->for($this->user, 'authenticatable')->create(); + $this->travel(1)->minutes(); signInAs(CHROME); $this->post(route('keyring.login.verify', 'totp'), ['code' => '000000']); + $newcomer = $this->post(route('keyring.login.verify', 'totp'), ['code' => totpCode($totp->secret)]) + ->assertSessionHas('keyring.alerts', []) + ->getCookie('known_device')->getValue(); + $this->post('/logout'); + + // Nor on that browser's second visit: it was first seen after the + // failure, so it could be whoever made it. + $this->travel(1)->minutes(); + signInAs(CHROME, cookies: ['known_device' => $newcomer]); $this->post(route('keyring.login.verify', 'totp'), ['code' => totpCode($totp->secret)]) ->assertSessionHas('keyring.alerts', []); $this->post('/logout'); + $this->travel(1)->minutes(); signInAs(cookies: ['known_device' => $device]); - $this->post(route('keyring.login.verify', 'totp'), ['code' => totpCode($totp->secret, 1)]) + $this->post(route('keyring.login.verify', 'totp'), ['code' => totpCode($totp->secret)]) ->assertSessionHas('keyring.alerts', fn ($alerts) => $alerts[0]['type'] === 'second_factor_failed'); expect(app(SecurityLog::class)->pullAlerts($this->user))->toBeEmpty(); diff --git a/tests/Feature/SessionHardeningTest.php b/tests/Feature/SessionHardeningTest.php index 65957d62..31e65156 100644 --- a/tests/Feature/SessionHardeningTest.php +++ b/tests/Feature/SessionHardeningTest.php @@ -9,6 +9,7 @@ use Illuminate\Testing\TestResponse; use Keyring\Contracts\SessionRegistry; use Keyring\Contracts\Signal; +use Keyring\Enums\Assurance; use Keyring\Facades\Keyring; use Keyring\Factors\Password; use Keyring\Factors\Totp; @@ -20,6 +21,7 @@ use Keyring\Risk\Finding; use Keyring\Risk\Signals\RepeatedFactorFailures; use Keyring\Risk\Signals\SessionFingerprintChanged; +use Keyring\Sessions\RegisteredSession; use Keyring\Sessions\SessionAssurance; use Keyring\Sessions\Sessions; use Keyring\Tests\Fixtures\SingleSignOn; @@ -328,6 +330,33 @@ function sessionCookies(TestResponse $response): array $this->get('/home')->assertRedirect('/login'); }); +// A store that evicts under memory pressure drops keys one at a time. That a +// session ended is kept in its record and in a key beside it, so losing +// either leaves it ended. +it('keeps a session ended when the cache store loses one of the keys that say so', function (string $lost) { + config(['keyring.sessions.driver' => 'cache']); + signInWith(); + $registry = app(SessionRegistry::class); + $id = session(Sessions::KEY); + $now = now()->getTimestamp(); + + $registry->revoke($id); + $next = new RegisteredSession('next', (string) $this->user->id, $this->user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600); + $registry->save($replaced = $next->with(['id' => 'replaced'])); + $registry->replace('replaced', $next->with(['id' => 'successor'])); + + Cache::forget('keyring:sessions:'.$id.$lost); + Cache::forget('keyring:sessions:replaced'.$lost); + + expect($registry->find($id)->revokedAt)->not->toBeNull() + ->and($registry->find('replaced')->replacedBy)->toBe('successor') + ->and($registry->find('replaced')->isActive($now))->toBeFalse() + // A stale copy saved over the record doesn't undo it either. + ->and(tap($registry, fn (SessionRegistry $registry) => $registry->save($replaced))->find('replaced')->replacedBy)->toBe('successor'); + + $this->get('/home')->assertRedirect('/login'); +})->with(['its revoked marker' => ':revoked', 'its replaced marker' => ':replaced']); + it('does not undo a revocation that lands while a request is being assessed', function (string $driver) { config(['keyring.sessions.driver' => $driver]); Keyring::risk()->signals([new RevokesDuringAssessment]); diff --git a/tests/Feature/StepUpTest.php b/tests/Feature/StepUpTest.php index 7e54fa09..be92c904 100644 --- a/tests/Feature/StepUpTest.php +++ b/tests/Feature/StepUpTest.php @@ -76,6 +76,10 @@ function signIn(): void config(['auth.defaults.guard' => 'web', 'keyring.guard' => 'web']); + // The staff session's record isn't this user's, and would end the + // session before the confirmation is looked at. Leave only that. + session()->forget(Sessions::KEY); + $this->actingAs($this->user, 'web') ->post(route('keyring.confirm.verify', 'totp'), ['code' => totpCode($totp->secret)]) ->assertRedirect(route('keyring.confirm.challenge')) diff --git a/tests/Feature/ThrottlingTest.php b/tests/Feature/ThrottlingTest.php index ce28554e..dd2738c8 100644 --- a/tests/Feature/ThrottlingTest.php +++ b/tests/Feature/ThrottlingTest.php @@ -7,6 +7,7 @@ use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Hash; +use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Notification; use Illuminate\Support\Facades\Password as PasswordBroker; use Illuminate\Support\Timebox; @@ -155,7 +156,8 @@ function account(string $email): User static $depth = 0; return $step->handle(new Context($request, Purpose::Login, Keyring::factor('password')), function (Context $context) use (&$attempt, &$verified, &$depth) { - $verified++; + // One a limit refused quietly carries on, and has no proof checked. + $verified += $context->refused ? 0 : 1; // Simulate nine more requests arriving while this one is still being verified. if ($depth++ === 0) { @@ -843,6 +845,41 @@ function lockOut(int $times, string $email = 'taylor@example.com', string $passw } } + // The hold is the account's. A name is only told it's held for + // lockouts made under it, or one name would give away the others. + it('holds the account without telling its other name, which answers like anyone\'s', function () { + Event::fake([AccountLocked::class]); + $this->user->update(['name' => 'tay']); + account('other@example.com'); + Keyring::findUsersUsing(fn (Request $request) => User::query() + ->where('email', $request->input('email')) + ->orWhere('name', $request->input('email')) + ->first()); + + lockOut(3, 'tay'); + $this->travel(7)->days(); + + $answers = fn (string $name) => array_map(function () use ($name) { + $response = $this->postJson('/login', ['email' => $name, 'password' => 'nope']); + + return [$response->status(), $response->json('errors.email.0')]; + }, range(1, 3)); + + $nobody = $answers('nobody@example.com'); + + expect($nobody[0])->toBe([422, __('auth.failed')]) + ->and($answers('taylor@example.com'))->toBe($nobody) + ->and($answers('other@example.com'))->toBe($nobody) + // The name the lockouts were made under says so. + ->and($this->postJson('/login', ['email' => 'tay', 'password' => 'nope'])->json('errors.email.0'))->toBe(__('keyring::keyring.locked')); + + // The account is still held, under every name, until it's reset. + $this->travel(7)->days(); + $this->postJson('/login', ['email' => 'taylor@example.com', 'password' => 'password'])->assertStatus(422); + $this->assertGuest(); + Event::assertDispatched(AccountLocked::class, fn (AccountLocked $event) => $event->user->is($this->user)); + }); + it('lifts each lock by itself until there have been that many in a day', function () { lockOut(2); @@ -1118,6 +1155,33 @@ function guessWith(?string $device): void ->and(collect($limits)->pluck('key')->implode(' '))->not->toContain('|cleared|'); }); +// The wait hides nothing longer than itself, and a password hash is as slow +// as the server's settings make it. Where a refusal outran the wait, the +// app's log says so, so whoever runs it learns the option is set too low. +it('reports a refusal that took longer than the timebox, once an hour', function () { + config(['keyring.timebox' => '1ms']); + account('taylor@example.com'); + Notification::fake(); + Log::spy(); + + // Slower than a millisecond, as a real hash is. + Event::listen(FactorFailed::class, fn () => usleep(3000)); + + $this->postJson('/login', ['email' => 'taylor@example.com', 'password' => 'nope'])->assertStatus(422); + $this->postJson('/login', ['email' => 'taylor@example.com', 'password' => 'nope'])->assertStatus(422); + + // One that goes through is never held, so there's nothing to outrun. + $this->postJson('/login', ['email' => 'taylor@example.com', 'password' => 'password'])->assertOk(); + + Log::shouldHaveReceived('warning')->once()->withArgs(fn (string $message) => str_contains($message, 'every refusal is held for (keyring.timebox)')); + + $this->travel(61)->minutes(); + $this->post('/logout'); + $this->postJson('/login', ['email' => 'taylor@example.com', 'password' => 'nope'])->assertStatus(422); + + Log::shouldHaveReceived('warning')->twice(); +}); + it('holds every refusal for the timebox, whichever limit refused it', function () { config(['keyring.limits.per_account' => 1, 'keyring.limits.per_ip' => 100]); account('taylor@example.com'); @@ -1377,8 +1441,9 @@ function countStatements(Closure $request): array $real = $statements('taylor@example.com'); - // A first failure, more of them, then the name's own 429. - expect(array_map(count(...), $real))->toBe([3, 3, 3, 0]) + // A first failure, more of them, then the name's own 429, which + // still asks whether the account behind the name is refused. + expect(array_map(count(...), $real))->toBe([3, 3, 3, 1]) ->and(array_map(count(...), $statements('nobody@example.com')))->toBe(array_map(count(...), $real)) ->and(FailureCount::query()->count())->toBe(1); }); @@ -1442,6 +1507,89 @@ function countStatements(Closure $request): array $this->postJson('/login', ['email' => 'tay', 'password' => 'a brand new passphrase'])->assertOk(); $this->assertAuthenticatedAs($this->user); }); + + // What a name answers goes by what was tried under it, and by + // nothing that happens to the account behind it: a name with no + // account has no reset, unlock or new password to be cleared by. + it('keeps answering the name as refused once the account\'s limits are cleared, to anyone without the password', function (Closure $clear) { + foreach (range(1, 3) as $attempt) { + guess('nobody@example.com'); + } + + $answer = fn (string $name) => Arr::only($this->postJson('/login', ['email' => $name, 'password' => 'nope'])->json(), ['message', 'errors']) + + ['status' => guess($name)]; + + $before = $answer('tay'); + + expect($before['status'])->toBe(429)->and($answer('nobody@example.com'))->toBe($before); + + $clear($this->user); + $this->flushSession(); + $this->app['auth']->forgetGuards(); + + expect($answer('tay'))->toBe($before) + ->and($answer('nobody@example.com'))->toBe($before); + $this->assertGuest(); + })->with([ + 'a reset' => [fn (User $user) => completeReset($user)], + 'an unlock' => [fn (User $user) => Keyring::unlock($user)], + ]); + + it('still lets the owner in under the refused name with the password, and leaves the name refused for everyone else', function () { + Keyring::unlock($this->user); + + $this->postJson('/login', ['email' => 'tay', 'password' => 'password'])->assertOk(); + $this->assertAuthenticatedAs($this->user); + + $this->post('/logout'); + $this->flushSession(); + $this->app['auth']->forgetGuards(); + + expect(guess('tay'))->toBe(429); + }); + + // Whatever is behind the name: an account whose own limits refuse + // too, one they were cleared for, or nobody. + it('spends one password hash on every answer a refused name gives', function (string $name, Closure $before) { + foreach (range(1, 3) as $attempt) { + guess('nobody@example.com'); + } + $before($this->user); + + $hashes = 0; + Hash::partialMock()->shouldReceive('make')->andReturnUsing(function () use (&$hashes) { + $hashes++; + + return 'hash'; + })->getMock()->shouldReceive('check')->andReturnUsing(function () use (&$hashes) { + $hashes++; + + return false; + }); + + expect(guess($name))->toBe(429)->and($hashes)->toBe(1); + })->with([ + 'an account whose own limits refuse too' => ['tay', fn () => null], + 'an account whose limits were cleared' => ['tay', fn (User $user) => Keyring::unlock($user)], + 'nobody' => ['nobody@example.com', fn () => null], + ]); + + it('counts guesses behind a refused name against the account, which refuses in its turn', function () { + Keyring::unlock($this->user); + Hash::spy(); + + // Three more wrong ones use the account's allowance up again... + foreach (range(1, 3) as $attempt) { + expect(guess('tay'))->toBe(429); + } + + Hash::shouldHaveReceived('check')->times(3); + + // ...and then the right password isn't looked at either. + expect(guess('tay', 'password'))->toBe(429); + Hash::shouldHaveReceived('check')->times(3); + $this->assertGuest(); + }); }); }); diff --git a/tests/Feature/WebAuthnAttestationTest.php b/tests/Feature/WebAuthnAttestationTest.php index c72c679c..f80f8e32 100644 --- a/tests/Feature/WebAuthnAttestationTest.php +++ b/tests/Feature/WebAuthnAttestationTest.php @@ -196,13 +196,24 @@ function refused(TestResponse $response, string $message = 'key_not_accepted'): }); it('adds an older key that attests as fido-u2f', function () { - attest($this->maker->key(format: 'fido-u2f', userVerification: false))->assertOk(); + attest($this->maker->key(format: 'fido-u2f'))->assertOk(); expect(Authenticator::query()->sole()) ->aaguid->toBe('00000000-0000-0000-0000-000000000000') ->attestation->toBe('basic'); }); +// A fido-u2f statement signs the credential, not the flags beside it. A U2F +// key sets none of them, so a registration that has one set says more than +// its maker vouched for, and would be trusted for it from then on. +it('refuses a fido-u2f key whose registration claims what its statement does not sign', function (int $flag) { + refused(attest($this->maker->key(format: 'fido-u2f'), answer: fn (array $credential) => tamper($credential, function (array $object) use ($flag) { + $object['authData'][32] = chr(ord($object['authData'][32]) | $flag); + + return $object; + }))); +})->with(['user verified' => 0x04, 'backup eligible' => 0x08, 'backed up' => 0x18]); + it('takes a root from a file of pem certificates', function () { $file = tempnam(sys_get_temp_dir(), 'keyring'); file_put_contents($file, new VirtualManufacturer()->root.$this->maker->root); @@ -297,6 +308,22 @@ function refused(TestResponse $response, string $message = 'key_not_accepted'): expect(Authenticator::query()->sole()->aaguid)->toBe(YUBIKEY); }); +// The list says which keys may be added. Narrowing it leaves the ones already +// added as they are, and clearing the column is how one stops counting. +it('keeps a key attested when its model leaves the list, until its column is cleared', function () { + attest($this->maker->key(YUBIKEY))->assertOk(); + $key = Authenticator::query()->sole(); + + $attested = fn (WebAuthn $factor) => tap($factor, fn () => Keyring::factors([Password::class, $factor]))->attested($key->refresh()); + + expect($attested(WebAuthn::securityKeys()->requireAttestation()->allowOnly([TITAN])))->toBeTrue() + ->and($attested(WebAuthn::securityKeys()))->toBeFalse(); + + Keyring::authenticatorModel()::query()->where('aaguid', YUBIKEY)->update(['attestation' => null]); + + expect($attested(WebAuthn::securityKeys()->requireAttestation()))->toBeFalse(); +}); + it('refuses a listed aaguid that nothing vouches for', function (Closure $key) { Keyring::factors([Password::class, WebAuthn::securityKeys()->requireAttestation()->allowOnly([YUBIKEY])]); diff --git a/tests/Feature/WebAuthnTest.php b/tests/Feature/WebAuthnTest.php index 5e8c8548..9ab25c5a 100644 --- a/tests/Feature/WebAuthnTest.php +++ b/tests/Feature/WebAuthnTest.php @@ -20,6 +20,7 @@ use Keyring\Login\Attempt; use Keyring\Login\Requirement; use Keyring\Models\Authenticator; +use Keyring\Models\FailureCount; use Keyring\Sessions\SessionAssurance; use Keyring\Support\KeyedHash; use Keyring\Testing\VirtualAuthenticator; @@ -98,6 +99,7 @@ function enroll(string $factor, VirtualAuthenticator $key, string $name = 'My ke // Staff accounts are made by admins, not registered, so needn't verify an email. config(['keyring.features' => array_values(array_diff(Features::all(), [Features::registration()]))]); $staff = staff(); + $this->flushSession(); $this->actingAs($staff)->withAssurance(Assurance::AAL2); $forStaff = $this->postJson(route('keyring.authenticators.store', 'passkey'))->assertOk()->json('enrollment.options.user.id'); @@ -153,6 +155,32 @@ function enroll(string $factor, VirtualAuthenticator $key, string $name = 'My ke 'Ed25519' => fn () => VirtualAuthenticator::eddsa(), ]); +// A passkey names its account by the credential. A username sent with one +// is nothing to count against whoever has that name. +it('counts nothing against an account whose username is sent along with someone else\'s passkey', function () { + config(['keyring.limits.per_account' => 2, 'keyring.limits.per_ip' => 1000, 'keyring.limits.consecutive' => 3]); + $key = new VirtualAuthenticator; + enroll('passkey', $key); + $this->post('/logout'); + $this->flushSession(); + $this->app['auth']->forgetGuards(); + + // Anyone, with a key the app has never seen. + foreach (range(1, 6) as $attempt) { + $options = $this->getJson(route('keyring.login.options', 'passkey'))->json('options'); + + $this->postJson(route('keyring.login.factor', 'passkey'), ['email' => 'taylor@example.com', 'credential' => new VirtualAuthenticator()->assert($options)]) + ->assertUnprocessable(); + } + + expect(FailureCount::query()->count())->toBe(0); + + // The account's own passkey still signs in. + $options = $this->getJson(route('keyring.login.options', 'passkey'))->json('options'); + $this->post(route('keyring.login.factor', 'passkey'), ['email' => 'taylor@example.com', 'credential' => $key->assert($options)])->assertRedirect('/dashboard'); + $this->assertAuthenticatedAs($this->user); +}); + it('fails a passkey that has no public key to check, like any other wrong proof', function () { $key = new VirtualAuthenticator; enroll('passkey', $key); diff --git a/tests/Fixtures/public-api.json b/tests/Fixtures/public-api.json index 04e5a9b1..9a6629c1 100644 --- a/tests/Fixtures/public-api.json +++ b/tests/Fixtures/public-api.json @@ -124,7 +124,7 @@ "enrollments": { "keep_for": "15m" }, - "timebox": "250ms", + "timebox": "500ms", "limits": { "per_account": 5, "per_ip": 20, From c41a21594892d610da60b5084fb65a6e4e7f8f2c Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Wed, 11 Nov 2026 19:22:51 +0000 Subject: [PATCH 2/9] docs: describe the behaviour the audit fixes changed --- CHANGELOG.md | 2 +- UPGRADE.md | 9 +++++++++ docs/configuration.md | 8 +++++--- docs/devices-and-sessions.md | 5 +++-- docs/passkeys.md | 5 +++++ docs/protected-changes.md | 2 +- docs/quick-start.md | 2 +- docs/recipes.md | 15 ++++++++++++++- docs/risk.md | 2 ++ docs/security-log-and-emails.md | 4 ++-- docs/security.md | 13 +++++++------ docs/sign-in-flow.md | 4 ++-- docs/testing.md | 3 ++- 13 files changed, 54 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 20dc1c52..b806682f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -45,7 +45,7 @@ The first release. Nothing is tagged yet. ### Rate Limits and Risk - Rate limits per account, per typed username and per IP address, with locks that double, a count of their own for browsers the account has signed in from, a cap on failures in a row kept in the database, and `limits.lock_after` to keep an account locked until its password is reset. -- A timebox around every verification, so a refusal takes the same time whatever the reason. +- A timebox around every verification, registration and refused password reset, so a refusal takes the same time whatever the reason. - Risk signals with an action for each level: a new device, a new country, impossible travel, a session turning up in another browser, repeated failed second factors, a sign in after several failures or after a long quiet period, a recently changed email address and a password found in a breach. A new app starts with the ones its features can feed, and a password found in a breach holds its user until they choose another. ### Logging and Emails diff --git a/UPGRADE.md b/UPGRADE.md index 123f0e5c..36ac2400 100644 --- a/UPGRADE.md +++ b/UPGRADE.md @@ -3,3 +3,12 @@ Keyring has no tagged release yet, so there's nothing to upgrade from. This guide starts with the first release, and will list anything you need to change when updating from one release to the next. What counts as a change you'd need to act on is in the README's [What's Stable](README.md#whats-stable). A test (`tests/Feature/PublicApiTest.php`) fails when a config default changes, or a route, middleware alias, facade method, contract, event or email type is renamed or removed, so one can't change without an entry here. + +## Before the First Release + +Changes made since the first installs from `dev-main`, for anyone already running one: + +- **`keyring_sessions` has a `user_type` column.** A session record now names its user's model as well as the ID, so two user models with the same IDs don't share sessions. Add `$table->string('user_type')` and an index on `['user_type', 'user_id']` to your published migration, and empty the table: everyone signs in again. A custom `SessionRegistry` has to store the new `userType` field and match on it in `forUser()`, `revokeAll()` and `revokeDevice()`. +- **`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. +- **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. diff --git a/docs/configuration.md b/docs/configuration.md index b92dfa91..170b0a9e 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -222,7 +222,7 @@ How long a user has to finish adding a sign-in method once they've started. See |---|---| | `driver` | `database`, `cache`, or the name of a driver you've added. | | `connection`, `table` | Used by the `database` driver. | -| `store` | The cache store used by the `cache` driver. `null` is your default store. | +| `store` | The cache store used by the `cache` driver. `null` is your default store. Use one that keeps its keys until they expire: a store that evicts under memory pressure can drop the list of a user's sessions, and a sign-out everywhere then misses the ones it listed. The `database` driver has no such store to depend on. | | `max` | How many sessions one account can have at once. A sign in beyond that ends the one unused longest. `null` for no limit. See [How Many Sessions](devices-and-sessions.md#how-many-sessions). | | `idle` | Inactivity allowed before a session ends. `null` leaves it to Laravel's session lifetime. | | `remember_idle` | The same, for a browser that ticked "remember me": how long it may stay away and still be signed back in, with nothing proved. `null` lets it stay away for the whole `absolute` limit. See [Inactivity and "Remember Me"](devices-and-sessions.md#inactivity-and-remember-me). | @@ -335,7 +335,7 @@ The table is `Features::securityLog()`, which is on by default. Without it the s 'keep_for' => '10m', ], -'timebox' => '250ms', +'timebox' => '500ms', 'limits' => [ 'per_account' => 5, @@ -355,7 +355,9 @@ The table is `Features::securityLog()`, which is on by default. Without it the s `pending_logins.keep_for` is how long a half-finished login or confirmation stays valid, as a [duration](#durations). It's also the `expiresAt` shown on the challenge page. -`timebox` is the minimum time a refused verification takes, so timing doesn't reveal whether an account exists or whether a password refused for another reason was right. It covers every pipeline step, so a request refused by a rate limit or by validation waits too. Verifications that go through return straight away. +`timebox` is the minimum time a refused verification takes, so timing doesn't reveal whether an account exists or whether a password refused for another reason was right. It covers every pipeline step, so a request refused by a rate limit or by validation waits too, and a registration and a refused password reset are held for it as well. Verifications that go through return straight away. + +It only hides what's shorter than it. The slowest thing a refusal does is hash a password, and not every refusal hashes one at the same cost: an account's password is checked at the cost its stored hash was made with, which differs from today's while old hashes are being moved to a new one, and a reset token is only checked for an address with a link outstanding. So keep `timebox` comfortably longer than one password hash takes on your servers. Bcrypt at 12 rounds takes around 200ms on current hardware and more on a small instance. Keyring tells you when it isn't: a refusal that took longer than `timebox` writes a warning to your app's log, at most once an hour, which is the check that sees your real hashing cost on your real servers. The [conformance suite](testing.md#the-conformance-suite) also times a hash where your tests run and fails when it doesn't fit, as an early guide. `limits` are the default attempts per minute for each factor, per account and per IP address, and `consecutive`, the failures in a row one of an account's authenticators allows before it's refused for that account (`null` for no cap, and 100 is the most NIST SP 800-63B-4 allows, Sec. 3.2.2). Those are counted in the `keyring_failure_counts` table, and nothing brings a refused authenticator back by itself: see [At the Cap](security.md#at-the-cap). `consecutive_elsewhere` is how many of them may come from browsers the account hasn't signed in from, which keeps the rest for the owner's own. It only applies with `Features::devices()` on, and `null` keeps nothing back. `remember_names_for` is how long the cache keeps the failures in a row counted under each typed username, which is what the sign-in form answers from. diff --git a/docs/devices-and-sessions.md b/docs/devices-and-sessions.md index ac4b2eeb..037312d2 100644 --- a/docs/devices-and-sessions.md +++ b/docs/devices-and-sessions.md @@ -316,7 +316,7 @@ Then set `sessions.driver` to `custom`. Keyring calls `replace()`, `revokeAll()` |---|---| | `save($session)` | Stores a new `RegisteredSession`. It must never clear a revocation made in the meantime, or what a record was replaced by. | | `find($id)` | The session, or `null`. | -| `forUser($user)` | The user's sessions that haven't expired, been revoked or been replaced, most recent first. | +| `forUser($user)` | The user's sessions that haven't expired, been revoked or been replaced, most recent first. A session is a user's by the model as well as the ID: match on the record's `userType` (`RegisteredSession::typeOf($user)`) and its `userId`, here and in `revokeAll()` and `revokeDevice()`, or two user models with the same IDs would share sessions. `$session->belongsTo($user)` checks both. | | `update($id, $changes)` | Changes only the named fields, such as `['lastActivityAt' => $now]` or `['assurance' => $level, 'expiresAt' => $at]`. Field names are as on `RegisteredSession`; `RegisteredSession::columns($changes)` turns them into snake case columns. Writing only these fields means a request can't write back a stale copy of the rest. | | `revoke($id)` | Revokes one session. | | `replace($id, $successor, $revoke = false)` | Moves a session to a new record: stores `$successor` and sets the old record's `replacedBy` and `replacedAt` (and revokes it, with `$revoke`). It only does so for a record that is neither revoked nor replaced, and returns whether it did. Of two calls for the same record at the same moment exactly one may return `true`, and the other's record must not be left behind: "remember me" being single use rests on this. The database driver uses one conditional `UPDATE` in a transaction, the cache driver the store's `add()`. | @@ -518,8 +518,9 @@ That isn't enough where the whole app is meant to be AAL2, or where you want NIS - A session ends on the first request after the level it **signed in at** runs out: after that level's `idle` without a request, or its `absolute` after the factors were proved. The user is signed out as for any other timeout, with the reason `idle` or `expired` on `SessionEnded`. - Proving every factor for that level again before then (any [step-up](step-up.md) that asks for them all) starts both limits over, as reauthenticating does in NIST. - A level reached later by a step-up still lapses on its own and takes nothing with it. A session that signed in with a password and stepped up for one page stays an AAL1 session. +- A [risk response](risk.md#responding-to-risk) that asks a signed-in session to step up ends it too: forgetting what the session proved is its level running out. The reason on `SessionEnded` is `risk`. - "Remember me" brings nothing back. Its cookie proves nothing, so there's no level for the session to carry on at: the browser signs in again. NIST doesn't accept such a cookie in place of authenticating either (Sec. 5.1), so leave the checkbox off your login page. -- Sessions signed in at AAL1 are unaffected: `idle` and `absolute` already end those. +- The timeouts leave sessions signed in at AAL1 as they were: `idle` and `absolute` already end those. [Recipes](recipes.md#an-app-whose-every-page-needs-aal2) has the full setup for an app whose every page needs AAL2. diff --git a/docs/passkeys.md b/docs/passkeys.md index 634e7457..47443063 100644 --- a/docs/passkeys.md +++ b/docs/passkeys.md @@ -172,6 +172,11 @@ A key reaches [AAL3](policies.md#assurance-levels) only when its factor uses `re - Keys added before the factor asked for attestation have nothing in that column and stay at AAL2. Their owners add them again to reach AAL3. - Take `requireAttestation()` off a factor and its keys stop reaching AAL3, whatever the column says. +- Narrowing [`allowOnly()`](#allowing-only-certain-models), or taking a root out of the list, only stops more of those keys being added. The ones already on accounts keep their level, so changing what you hand out doesn't lock out everyone holding the old model. When a model has to stop counting (it was found to be weak, say), clear the column for its keys, which leaves them as second factors at AAL2, or delete the rows to remove them: + + ```php + Keyring::authenticatorModel()::query()->where('aaguid', $aaguid)->update(['attestation' => null]); + ``` - The attestation is for the key. Its second factor still has to be its own user verification or a password: touching an attested key after signing in with a synced passkey is AAL2. NIST AAL3 also needs the authenticator validated to FIPS 140 (Sec. 2.3.2). Attestation says which model a key is, not whether that model was validated, so use `allowOnly()` to accept only the models you've checked. diff --git a/docs/protected-changes.md b/docs/protected-changes.md index 10ee8c29..3f87da80 100644 --- a/docs/protected-changes.md +++ b/docs/protected-changes.md @@ -231,7 +231,7 @@ While a user is held: - They can still sign in. Every signed-in request in the `web` group sends them to `password_change_url` with the `change-password` status. JSON requests get a `403` with that status and the URL as `redirect`. Without a `password_change_url`, they get a plain `403`. - That page is let through, for any method, and so are `PUT /user/password`, the [confirm page](step-up.md#the-confirm-flow) it may send them to, signing out and email verification. Nothing else is, including Keyring's other routes. -- The hold ends when the password changes: through `PUT /user/password`, or a [password reset](#resetting-the-password). If your app saves passwords itself, without `Features::updatePasswords()`, call `Keyring::cancelPasswordChange($user)` once it has saved a new one. +- The hold ends when the password changes: through `PUT /user/password`, or a [password reset](#resetting-the-password). It has to be a different password. `PUT /user/password` refuses the current one as the new one, for every user, and a reset to the same password goes through like any other but leaves the hold in place, so the form doesn't tell whoever holds the link that they guessed it. If your app saves passwords itself, without `Features::updatePasswords()`, call `Keyring::cancelPasswordChange($user)` once it has saved a new one, and check it's a new one first: nothing in that call does. - Signing out and in again changes nothing. The hold is a row in `keyring_password_holds`, not something in the session or the cache. - A hold placed by a request reaches that request's session at once. Other sessions that are already signed in hear of it within a minute. diff --git a/docs/quick-start.md b/docs/quick-start.md index dd28373d..f4fb8eb1 100644 --- a/docs/quick-start.md +++ b/docs/quick-start.md @@ -226,7 +226,7 @@ These are part of the foundation. You don't need to set them up, but you can cha | What | Default | Change it with | |---|---|---| | Rate limits on signing in | 5 a minute per account, 20 per IP, and an authenticator refused after 100 failures in a row until it's set up again | `limits` in [Configuration](configuration.md#pending-logins-timebox-and-rate-limits) | -| Failed checks take the same time, and so does every registration | 250ms | `timebox` | +| Failed checks take the same time, and so does every registration and refused password reset | 500ms | `timebox` | | Registration answers the same whether or not an address has an account | On | [`registration.reveal_taken`](sign-in-flow.md#registration) | | Password rules | 15 characters without a second factor, 8 with one. Common passwords and ones containing the user's or site's name are refused, and breached ones in production | [Password Rules](protected-changes.md#password-rules) | | A record of each session, with its IP address and browser, so Keyring can sign it out | Sessions end after two hours unused and 30 days after sign in. "Remember me" brings a browser back for up to 14 days away, with nothing proved, and only to a session that hasn't ended | `sessions` in [Configuration](configuration.md#sessions) | diff --git a/docs/recipes.md b/docs/recipes.md index 7b91f27a..248dea0e 100644 --- a/docs/recipes.md +++ b/docs/recipes.md @@ -442,16 +442,29 @@ What this gives you: **Match on the provider's ID, never on the email address.** Some providers let an account carry an address its owner hasn't proven, so matching on it would let someone sign in to whoever has that address in your app. -To link an account, send a signed-in user through the same redirect to a second callback that saves the ID. Put it behind `keyring.fresh`, since it adds a way to sign in: +To link an account, send a signed-in user through the same redirect to a second callback that saves the ID. It adds a way to sign in, so give it what Keyring's own routes for that have: `keyring.fresh`, and the rule that [the account's address is verified first](authenticators.md#who-may-enroll). Without the second, someone who registers an address that isn't theirs could link their own GitHub account to it, and still sign in after the real owner had reset the password: ```php Route::get('/settings/github/callback', function (Request $request) { + abort_unless(Keyring::allowsEnrollment($request->user()), 403); + $request->user()->forceFill(['github_id' => Socialite::driver('github')->user()->getId()])->save(); return to_route('security.edit'); })->middleware(['auth', 'keyring.fresh:15m']); ``` +Keyring doesn't know about the link, so nothing of Keyring's removes it. A password reset and an [undone email change](protected-changes.md#changing-the-email-address) take away the sign-in methods Keyring holds and leave `github_id` where it is. Clear it when the account is recovered, by listening for `PasswordReset` and `EmailChangeReverted`: + +```php +use Keyring\Events\EmailChangeReverted; +use Keyring\Events\PasswordReset; + +Event::listen([PasswordReset::class, EmailChangeReverted::class], function (PasswordReset|EmailChangeReverted $event) { + $event->user->forceFill(['github_id' => null])->save(); +}); +``` + To let people sign up with GitHub, create and link the user in the login callback before calling `Keyring::attempt()`, when no user has that ID yet. In tests, `Socialite::fake()` stands in for GitHub: diff --git a/docs/risk.md b/docs/risk.md index 8cf6acc9..3bf99673 100644 --- a/docs/risk.md +++ b/docs/risk.md @@ -216,6 +216,8 @@ Signals run at one or both checkpoints (`Keyring\Risk\Checkpoint`): When a request-time action does something without signing the session out (a step-up, say), Keyring updates the session's recorded IP and user agent, so the same change isn't acted on twice. A step-up also gives the session a new record and revokes the old one, so only the request that noticed the change carries on: an older copy of the session cookie, or a request that was already under way, is signed out instead of keeping what the session had proved. +With [`sessions.end_on_lapse`](devices-and-sessions.md#ending-a-session-with-its-level) on, a request-time step-up signs the session out instead, as `Action::reauthenticate()` does: there, a session doesn't outlive what it signed in with. + ## Configuring Signals `Keyring::risk()->signals([...])` replaces the signal list. To keep the ones already on and add to them, use `push()`: diff --git a/docs/security-log-and-emails.md b/docs/security-log-and-emails.md index 1b423bb4..07f6404a 100644 --- a/docs/security-log-and-emails.md +++ b/docs/security-log-and-emails.md @@ -215,7 +215,7 @@ Everything Keyring keeps, how it's protected and for how long is listed in [What ## "Was This You?" Alerts -After a successful sign in, Keyring flashes `keyring.alerts` to the session: a list of log entries worth asking the user about, which they haven't seen yet. Each one is shown once. With `Features::devices()` on, a browser the account hasn't signed in on before gets none, since it could be whoever caused them; they wait for one it has. +After a successful sign in, Keyring flashes `keyring.alerts` to the session: a list of log entries worth asking the user about, which they haven't seen yet. Each one is shown once. With `Features::devices()` on, a browser only gets the ones logged after the account first used it. A browser it hasn't signed in on before gets none, and one first used since they happened doesn't get those, since it could be whoever caused them; they wait for a browser the account already had. ```json [ @@ -225,7 +225,7 @@ After a successful sign in, Keyring flashes `keyring.alerts` to the session: a l The types that become alerts are listed in `security_log.alerts`: by default `second_factor_failed`, `device_reported`, `email_change_reverted`, `clone_suspected` and `remember_me_reused`. Any [entry type](#entry-types) can go there. A `second_factor_failed` alert is the classic sign that someone else knows the password. -To read them yourself, call `Keyring\Activity\SecurityLog::pullAlerts($user)`. It returns the unseen alert entries, newest first, and marks them seen, so each comes back once. +To read them yourself, call `Keyring\Activity\SecurityLog::pullAlerts($user)`. It returns the unseen alert entries, newest first, and marks them seen, so each comes back once. Pass a time as `since:` to take only those logged after it. Share them through your Inertia middleware to show a banner: diff --git a/docs/security.md b/docs/security.md index 2a803dbe..779197d5 100644 --- a/docs/security.md +++ b/docs/security.md @@ -46,10 +46,10 @@ Guarantees about a [feature](quick-start.md#adding-features), such as devices or - A wrong password and an unknown account give the same error, on the same field, with the same status code. - A sign-in only succeeds for a user Keyring's guard would load back through its provider. A passkey that belongs to another model (say, staff when the guard signs in users) fails like an unknown one, even when the IDs match. -- Every refused verification takes at least `timebox` (250ms by default), and unknown accounts still run a password hash, so timing doesn't reveal which accounts exist. The timebox is around the whole pipeline: the rate limits, the proof, the risk checks and whatever listens for a failure, so a `429` waits it out too. That includes a right password turned down by a risk lock or a risk response, which answers like a wrong one. +- Every refused verification takes at least `timebox` (500ms by default), and unknown accounts still run a password hash, so timing doesn't reveal which accounts exist. A hash for a name with no account is made at today's cost, where an account's is checked at its stored hash's, so the wait is what covers the difference, and it only can while it's [longer than a hash takes](configuration.md#pending-logins-timebox-and-rate-limits). A refused password reset is held for it too. The timebox is around the whole pipeline: the rate limits, the proof, the risk checks and whatever listens for a failure, so a `429` waits it out too. That includes a right password turned down by a risk lock or a risk response, which answers like a wrong one. - A password longer than its stored hash can check (72 bytes for bcrypt) fails like a wrong one, with the same error, timing and throttling, wherever Keyring checks a password: signing in, step-up, removing the last second factor and the current password on a change. The over-long value never reaches the hasher. - Passwords are put in Unicode's NFC form before they're measured, hashed or checked, so one set on a device that composes characters one way still works on a device that composes them another. -- 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, 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. +- 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). @@ -62,7 +62,7 @@ Guarantees about a [feature](quick-start.md#adding-features), such as devices or Every factor has its own limits, checked in the pipeline before the proof is looked at: - **Per account**: `limits.per_account` attempts a minute (5). The account is the user: Keyring finds who a typed username belongs to before it counts, so every way of typing it shares one limit, guesses at login and when confirming count together, and two accounts never share a count however alike their usernames look. Browsers the account has signed in from before (they carry one of its device cookies) count in a bucket of their own, so someone guessing from elsewhere can't lock the owner out, an idea taken from the OWASP Community page on device cookies. They share that one bucket between them: a device cookie is made at every sign in from a new browser, so someone who could once sign in may hold any number, and with a bucket each they'd get the account's allowance of guesses once per cookie. A browser stops counting as known when a password reset or change, or a sign-out everywhere, takes the account back, until it signs in again. -- **Per typed username**: a sign in that names its account is counted under the name as typed as well, with the same numbers, whether or not anyone has it. Only this count says so when it refuses (the `429`). The account's own limit refuses quietly: the attempt is answered like a wrong password, in the same time, without the password being looked at. So a name is answered from its own history, and locking an account under one name doesn't show which other names belong to it, or which names have an account at all. +- **Per typed username**: a sign in that names its account is counted under the name as typed as well, with the same numbers, whether or not anyone has it. Only this count says so when it refuses (the `429`). The account's own limit refuses quietly: the attempt is answered like a wrong password, in the same time, without the password being looked at. So a name is answered from its own history, and locking an account under one name doesn't show which other names belong to it, or which names have an account at all. Nothing that happens to the account changes what its name answers either: after a password reset, a new password or `Keyring::unlock()`, a name that was refused goes on being refused to anyone without the password, as a name with no account would. The owner still gets in: behind a refused name the account's own limits decide whether the password is looked at, the right one signs in, and a wrong one is answered as the name was. Only a factor that finds its user by the username counts under it. A passkey goes by its credential, so a username sent along with one counts against nobody. - **Per IP address**: `limits.per_ip` attempts a minute (20), shared by every account on that address. A browser carrying the account's device cookie counts per IP for that account alone, so others on a shared address can't hold it up, and an attacker holding several of the account's device cookies still gets one count. Behind a load balancer, configure Laravel's [trusted proxies](#trusted-proxies), or every user shares the balancer's address. - **In a row**: `limits.consecutive` failures (100, the most NIST SP 800-63B-4 allows, Sec. 3.2.2) on one of an account's authenticators, however slowly they come. Each authenticator app, security key and set of recovery codes has a count of its own, and so does the password. They're counted in the database, so clearing the cache doesn't start them over, and at the cap the authenticator is refused for the account until that's dealt with: nothing brings it back by itself (see [At the Cap](#at-the-cap)). `null` turns the cap off. Without it, guessing just under the per-minute limit would never stop. With `Features::devices()` on, browsers the account hasn't signed in from may only make `limits.consecutive_elsewhere` (80) of those failures. The rest are kept for the owner's own browsers, so someone guessing elsewhere can't use the whole cap up, and the two never add up to more than it. @@ -116,7 +116,7 @@ An account locked that many times within a day on a factor that can start a sign The lock ends with a completed password reset, a new password chosen while signed in, or `Keyring::unlock($user)`. It's kept in the database beside the failures in a row, so neither time nor a cleared cache lifts it. -It follows the other limits' rules. Browsers the account has signed in from before are locked and held apart from everyone else, so the owner isn't locked out of a browser they already use. A name nobody has locks the same way and gets the same answer, from the cache, for `limits.remember_names_for`: after that a held name is answered like a wrong password, while the account stays locked. Second factors are never held, because a password reset wouldn't clear them: they keep the cap. That includes security keys, which only ever come second. A hold placed by wrong passwords on a confirm page, by a signed-in session, lands on the account's own limit, which the sign-in form refuses quietly: there the right password is answered as wrong, with no hint that a reset would help, so tell the user with the `account_locked` notice, or from `AccountLocked` yourself. +It follows the other limits' rules. Browsers the account has signed in from before are locked and held apart from everyone else, so the owner isn't locked out of a browser they already use. A name nobody has locks the same way and gets the same answer, from the cache, for `limits.remember_names_for`: after that a held name is answered like a wrong password, while the account stays locked. Second factors are never held, because a password reset wouldn't clear them: they keep the cap. That includes security keys, which only ever come second. A name is only told it's held for lockouts made under that name. A hold reached under another name of the same account, or placed by wrong passwords on a confirm page, by a signed-in session, lands on the account's own limit, which the sign-in form refuses quietly: there the right password is answered as wrong, with no hint that a reset would help, so tell the user with the `account_locked` notice, or from `AccountLocked` yourself. It's off by default: the cap ends the guessing either way, and this only gets someone who guesses fast there sooner, in a quarter of an hour in place of a day and a half. @@ -546,8 +546,8 @@ The operations below are the expensive ones, each with what stops a stranger fro | Operation | When | What bounds it | |---|---|---| -| One password hash (bcrypt or Argon2id, at your cost setting) | Every password attempt the limits let through, including for a name with no account, which spends a hash on a random password so both take the same time | The [rate limits](#rate-limiting) are checked first, and a refused attempt hashes nothing: 5 a minute per account and per typed name, 20 a minute per IP address, with locks that double. The account's own limit refuses quietly, and that refusal still spends a hash so it takes as long as a wrong password, until the typed name's limit or the IP address's answers with a `429`. Hashing a new password on registration, a change or a reset is behind the `keyring` limiter, 6 a minute. | -| A worker held for `timebox` (250ms) | Every refused verification, a `429` included | It's a sleep, not CPU, but it does hold a PHP worker, and Keyring doesn't bound how many: a rate-limited request waits like any other refusal, or the limits would show in the timing. What bounds it sits in front of PHP: the connection and request limits of your web server or load balancer, and the size of the worker pool. Lowering `timebox` gives each worker back sooner and makes timing less even. | +| One password hash (bcrypt or Argon2id, at your cost setting) | Every password attempt the limits let through, including for a name with no account, which spends a hash on a random password so both take the same time | The [rate limits](#rate-limiting) are checked first: 5 a minute per account and per typed name, 20 a minute per IP address, with locks that double. An attempt the IP address's limit refuses hashes nothing. One the account's own limit refuses quietly still spends a hash, so it takes as long as a wrong password, and so does one a typed name's limit refuses with a `429`: behind a refused name the password is either checked or a hash is spent in its place, so the `429` costs the same whether the name has an account, and whether that account's limits were cleared since. The IP address's limit bounds how many of those one address can ask for. Hashing a new password on registration, a change or a reset is behind the `keyring` limiter, 6 a minute. | +| A worker held for `timebox` (500ms) | Every refused verification, a `429` included | It's a sleep, not CPU, but it does hold a PHP worker, and Keyring doesn't bound how many: a rate-limited request waits like any other refusal, or the limits would show in the timing. What bounds it sits in front of PHP: the connection and request limits of your web server or load balancer, and the size of the worker pool. Lowering `timebox` gives each worker back sooner and makes timing less even. | | The breached-password lookup, an HTTPS request to Have I Been Pwned | Setting a password, in production by default (`passwords.uncompromised`); and at every password sign in if you add the `BreachedPassword` risk signal, which isn't on by default | Behind the `keyring` limiter for new passwords, and the sign-in limits for the signal. Laravel's verifier gives up after 30 seconds and then lets the password through, so an outage slows these requests rather than failing them. With `passwords.refuse_unchecked`, Keyring asks itself, gives up after 10 seconds and refuses the password. Turn the check off, or bind an `UncompromisedVerifier` of your own with a shorter timeout, if that's too long to hold a worker. | | WebAuthn verification: decoding the response and checking one signature | Adding a key, and every sign in or step-up with one | At sign in, the factor's rate limits, checked before the response is read; adding a key is behind the `keyring` limiter and a fresh verification. Usernameless options are limited to 60 a minute per IP address. An RSA key is bounded to 16,384 bits by the library, since the work grows with the key. | | Attestation: a certificate chain of at most six, checked against each root you list for the model | Adding a key to a factor with `requireAttestation()` | The `keyring` limiter on enrollment, the cap on chain length, and nothing being fetched: no revocation lookups, no metadata download. | @@ -660,6 +660,7 @@ Each of these is a choice. The reason is given once, here, and the [requirement- ### Other Limits +- **The `cache` session registry is as good as its store.** A session's record says whether it was revoked or replaced, and so does a key beside it, so losing either leaves the session ended. The list of a user's sessions is one key, though, and a store that drops it (Redis or Memcached evicting under memory pressure, a replica promoted without its latest writes) leaves those sessions out of the sessions list and of a sign-out everywhere until they next expire. Use a store that doesn't evict, or the `database` driver, which is the default. - **Lockouts still reach new browsers.** Someone who knows a user's email can keep that account locked by guessing faster than the per-minute limit, and after 80 wrong passwords in a row (20 minutes at the quickest) the password is refused from every browser the account hasn't signed in from until its owner resets it. See [At the Cap](#at-the-cap). If they guess under one of the account's names and the owner types another, the owner is told the password is wrong rather than to wait, because saying more would tell a stranger the two names are one account. With `Features::devices()` on, browsers the owner has signed in from before keep their own limit and keep working. Without devices, the lock reaches every browser while the guessing goes on, and so does the cap. A password reset clears the password's counts and locks, but not a second factor's. - **Which browsers are known is kept in the cache.** A browser stops counting as known when the account is taken back, and that's recorded in the limiter's cache store with the mark a reset replaces. If the store loses its keys, a browser from before the reset counts as known again. It still can't pass the cap: known browsers and everyone else share it. - **A run of failures can begin with a few at once.** Once a kind of browser (the account's own, or everyone else) has failures on record, each of its attempts is counted before its proof is looked at. Its first aren't, so that an ordinary sign in writes nothing, and as many as the per-minute limit lets through at once (`limits.per_account`, 5) can be checked together. Each is counted when it fails. With the defaults that can't pass the cap. It could if `limits.consecutive_elsewhere`, or what's left of `limits.consecutive` above it, were set lower than `limits.per_account`. diff --git a/docs/sign-in-flow.md b/docs/sign-in-flow.md index c9ce5231..99cb355c 100644 --- a/docs/sign-in-flow.md +++ b/docs/sign-in-flow.md @@ -34,7 +34,7 @@ Signing in is a short state machine: 2. Keyring asks the [policy](policies.md) what they need. If that's met, they're signed in. 3. Otherwise Keyring regenerates the session ID, saves a pending **attempt** in the session and sends them to the challenge page, which asks for the next factor. They repeat until the requirement is met. -The pending attempt is encrypted JSON in the session. It lasts `pending_logins.keep_for` (10 minutes by default), and ends early if the user's password or email address changes meanwhile, so a reset also stops someone who already got past the old password, or if `keyring.guard` is no longer the guard it started under. After that, the user is sent back to the login page with `keyring::keyring.expired`. +The pending attempt is encrypted JSON in the session. It lasts `pending_logins.keep_for` (10 minutes by default), and ends early if the user's password or email address changes meanwhile, so a reset also stops someone who already got past the old password, if a sign-in method it has already proved is taken off the account, or if `keyring.guard` is no longer the guard it started under. After that, the user is sent back to the login page with `keyring::keyring.expired`. [Step-up](step-up.md) uses the same challenge page and the same pipeline, with the purpose `confirm` instead of `login`. @@ -279,7 +279,7 @@ By default (`registration.reveal_taken` is `false`), nobody can use the form to - **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. -- The whole request takes at least `timebox` (250ms), whether the form was refused, an account was created or the address was taken, and both of the last two hash one password. No email is sent before the response. +- The whole request takes at least `timebox` (500ms), whether the form was refused, an account was created or the address was taken, and both of the last two hash one password. No email is sent before the response. - Registration keeps the `keyring` rate limiter: six a minute per IP address. A new user can't sign in until their address is verified. If they could, anyone could register an address with a password of their own and try to sign in with it: success would mean the address was free. So until then a correct password is answered like a wrong one, in the same time. diff --git a/docs/testing.md b/docs/testing.md index 931841bb..eb7489cd 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -28,7 +28,7 @@ abstract class TestCase extends BaseTestCase New passwords are only checked against Have I Been Pwned in production, so tests make no network calls. See [Passwords](configuration.md#passwords). -`InteractsWithKeyring` also swaps in an instant timebox for every test that uses it, so failed factor checks don't wait the usual 250ms. Tests without the trait wait the full `timebox` on every failed verification. +`InteractsWithKeyring` also swaps in an instant timebox for every test that uses it, so failed factor checks don't wait the usual 500ms. Tests without the trait wait the full `timebox` on every failed verification. ## Acting at an Assurance Level @@ -281,6 +281,7 @@ The suite checks that: - every route that uses the `auth` middleware for Keyring's guard also runs [`keyring.session`](devices-and-sessions.md#the-session-middleware), so a session that was revoked or timed out doesn't keep working there, - passwords of 64 characters are allowed: `passwords.max` is at least 64, and the hasher isn't bcrypt, which stops at 72 bytes, - the password broker Keyring uses has a `throttle`, so one account can't be sent [a reset link](protected-changes.md#resetting-the-password) as often as anyone asks (skipped without `Features::resetPasswords()`), +- one password hash takes less time than [`timebox`](configuration.md#pending-logins-timebox-and-rate-limits), which is what keeps a refusal that hashes from taking longer than one that doesn't. It times a hash where the tests run, so it's a guide to your servers and not a measurement of them. Bcrypt is timed at 12 rounds, or yours if higher, since a test suite usually runs with fewer: return what production hashes with from `keyringProductionHashOptions()` if that isn't it, - no mandatory pipeline step was removed or replaced with `dangerouslyRemove()` or `dangerouslyReplace()`. If you take out a [mandatory step](sign-in-flow.md#mandatory-steps) on purpose, return its class from `keyringAcknowledgedDangerousSteps()` in your test class. If your `CreatesNewUsers` action validates fields other than `name`, `email`, `password` and `password_confirmation`, return a form it accepts from `keyringRegistration(string $email)`. From 0ff9dec8ea8b2ce35f3aabc9a1686ab6a5ad3c94 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Wed, 11 Nov 2026 19:32:07 +0000 Subject: [PATCH 3/9] chore(ci): wait for mysql's real server before running its job --- bin/ci | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/bin/ci b/bin/ci index 69e74efe..c4e9a09f 100755 --- a/bin/ci +++ b/bin/ci @@ -72,9 +72,11 @@ mysql() { docker run -d --rm --name "$name" -e MYSQL_DATABASE=keyring -e MYSQL_ROOT_PASSWORD=password \ -p "127.0.0.1:$port:3306" mysql:8.4 >/dev/null || return 1 - # It answers a ping before it takes connections, so ask it a question. + # It answers a ping before it takes connections, so ask it a question, + # and over TCP: while it sets itself up it runs a first server that only + # listens on its socket, then stops it and starts the real one. for _ in $(seq 60); do - docker exec "$name" mysql -ppassword -e 'select 1' keyring >/dev/null 2>&1 && break + docker exec "$name" mysql --protocol=tcp -h127.0.0.1 -ppassword -e 'select 1' keyring >/dev/null 2>&1 && break sleep 2 done From 0a0b36d875e25580aceba9479e0ead053b58138f Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Wed, 11 Nov 2026 19:56:24 +0000 Subject: [PATCH 4/9] fix(passwords): set a first password as a change, and finish a reset over a hash the app won't check --- UPGRADE.md | 1 + src/Changes/PasswordChanges.php | 30 ++++++++++++--- src/Http/Controllers/PasswordController.php | 3 +- tests/Feature/PasswordHoldTest.php | 42 +++++++++++++++++++++ 4 files changed, 69 insertions(+), 7 deletions(-) diff --git a/UPGRADE.md b/UPGRADE.md index 36ac2400..6ec20f16 100644 --- a/UPGRADE.md +++ b/UPGRADE.md @@ -10,5 +10,6 @@ Changes made since the first installs from `dev-main`, for anyone already runnin - **`keyring_sessions` has a `user_type` column.** A session record now names its user's model as well as the ID, so two user models with the same IDs don't share sessions. Add `$table->string('user_type')` and an index on `['user_type', 'user_id']` to your published migration, and empty the table: everyone signs in again. A custom `SessionRegistry` has to store the new `userType` field and match on it in `forUser()`, `revokeAll()` and `revokeDevice()`. - **`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). - **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. diff --git a/src/Changes/PasswordChanges.php b/src/Changes/PasswordChanges.php index 3f9b75a1..571e44fa 100644 --- a/src/Changes/PasswordChanges.php +++ b/src/Changes/PasswordChanges.php @@ -16,6 +16,7 @@ use Keyring\Support\PasswordRules; use Keyring\Support\Throttle; use LogicException; +use RuntimeException; /** * What always happens around a new password, whatever the app's action does @@ -96,10 +97,11 @@ public function reset(Authenticatable&Model $user, Closure $save, #[\SensitivePa * * A new hash isn't a new password: the same one hashes differently every * time. So the answer is whether the password itself changed, as far as - * can be told: from $old, a password known to have been the account's, - * checked against the new hash, or from $new, the one that was sent, - * checked against the old hash. With $keepHold the rest still happens - * for a password that didn't change, and only the hold is kept. + * can be told: from $old, a password said to have been the account's, + * checked against the old hash and the new, or from $new, the one that + * was sent, checked against the old hash. An account that had no + * 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. * * @param Closure(): void $save */ @@ -115,7 +117,9 @@ protected function save(Authenticatable&Model $user, Closure $save, #[\Sensitive throw new LogicException('The password action returned without saving a new password. Throw a ValidationException to refuse it.'); } - $changed = ! $this->matches($old, $after) && ! $this->matches($new, $before); + $changed = blank($before) || ! ( + ($this->matches($old, $before) && $this->matches($old, $after)) || $this->matches($new, $before) + ); if (! $changed && ! $keepHold) { return false; @@ -132,8 +136,22 @@ protected function save(Authenticatable&Model $user, Closure $save, #[\Sensitive return $changed; } + /** + * Whether the password is the one the hash was made from. A stored + * value the hasher won't check (another algorithm's hash, an imported + * one, a placeholder) matches nothing: the hasher throws for those, and + * by here the new password is already saved. + */ protected function matches(#[\SensitiveParameter] ?string $password, ?string $hash): bool { - return $password !== null && filled($hash) && Hash::check(PasswordRules::forVerifying($password, $hash), $hash); + if ($password === null || blank($hash)) { + return false; + } + + try { + return Hash::check(PasswordRules::forVerifying($password, $hash), $hash); + } catch (RuntimeException) { + return false; + } } } diff --git a/src/Http/Controllers/PasswordController.php b/src/Http/Controllers/PasswordController.php index 7b4611a5..1897c9b2 100644 --- a/src/Http/Controllers/PasswordController.php +++ b/src/Http/Controllers/PasswordController.php @@ -46,7 +46,8 @@ public function update(Request $request, UpdatesUserPasswords $updater, Password fn () => $updater->update($user, PasswordRules::normalizeInput(Input::all($request))), currentSession: $sessions->current($request)?->id, signOutOthers: $request->boolean('sign_out_others', true), - current: is_string($current = $request->input('current_password')) ? $current : null, + // 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, ); $sessions->rotate($request); diff --git a/tests/Feature/PasswordHoldTest.php b/tests/Feature/PasswordHoldTest.php index 7887b1dc..f6e584b6 100644 --- a/tests/Feature/PasswordHoldTest.php +++ b/tests/Feature/PasswordHoldTest.php @@ -3,6 +3,7 @@ declare(strict_types=1); use Illuminate\Contracts\Validation\UncompromisedVerifier; +use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Password; @@ -146,6 +147,47 @@ function chooseNewPassword(string $current = 'password', string $new = 'a much l expect(Keyring::requiresPasswordChange($this->user))->toBeFalse(); }); +// Nothing to be the same as: the field is only checked for an account that +// has a password, so what it holds proves nothing for one that hasn't. +it('sets a first password for an account that had none, whatever the current password field holds', function () { + Event::fake([PasswordChanged::class]); + $this->user->forceFill(['password' => null])->saveQuietly(); + Authenticator::factory()->passkey()->for($this->user, 'authenticatable')->create(); + + $this->actingAs($this->user->fresh())->withAssurance(Assurance::AAL2)->putJson(route('user-password.update'), [ + 'current_password' => 'a much longer passphrase 1', + 'password' => 'a much longer passphrase 1', + 'password_confirmation' => 'a much longer passphrase 1', + ])->assertOk(); + + expect(Hash::check('a much longer passphrase 1', $this->user->fresh()->password))->toBeTrue(); + Event::assertDispatchedTimes(PasswordChanged::class, 1); +}); + +// The hasher throws for a stored value it won't check, and by then the new +// password is saved: the reset has to finish, sessions, link and all. +it('finishes a reset for an account whose stored password is not a hash the app checks', function (string $stored) { + config(['hashing.bcrypt.verify' => true]); + DB::table('users')->where('id', $this->user->id)->update(['password' => $stored]); + Keyring::requirePasswordChange($this->user->fresh()); + $token = Password::broker()->createToken($this->user); + + $this->post(route('password.update'), [ + 'token' => $token, + 'email' => 'taylor@example.com', + 'password' => 'a much longer passphrase', + 'password_confirmation' => 'a much longer passphrase', + ])->assertSessionHasNoErrors()->assertRedirect(route('login')); + + expect(Hash::check('a much longer passphrase', $this->user->fresh()->password))->toBeTrue() + ->and(Password::broker()->tokenExists($this->user->fresh(), $token))->toBeFalse() + ->and(Keyring::requiresPasswordChange($this->user))->toBeFalse(); +})->with([ + 'an imported md5' => [md5('password')], + 'another algorithm\'s hash' => [password_hash('password', PASSWORD_ARGON2ID)], + 'a placeholder' => ['!'], +]); + it('holds one hold per user however often evidence turns up', function () { Event::fake([PasswordChangeRequired::class]); From f3448a5fc11d38a04a26d199ae7d8fa501eba206 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Wed, 11 Nov 2026 19:58:12 +0000 Subject: [PATCH 5/9] fix(devices): never recognise a browser by a device cookie it was handed --- docs/devices-and-sessions.md | 2 +- docs/security.md | 2 +- src/Devices/DeviceManager.php | 51 +++++++++--------------- tests/Feature/CookiesTest.php | 11 +++-- tests/Feature/DevicesAndSessionsTest.php | 50 ++++++++++++++++++++--- 5 files changed, 74 insertions(+), 42 deletions(-) diff --git a/docs/devices-and-sessions.md b/docs/devices-and-sessions.md index 037312d2..561d19be 100644 --- a/docs/devices-and-sessions.md +++ b/docs/devices-and-sessions.md @@ -65,7 +65,7 @@ An account keeps its 50 most recently seen devices (`devices.limit`). A sign in Each device records a readable name built from the user agent (the browser and the operating system, as in ":browser on :platform"), the last IP address and location, and when it was first and last seen. The user agent is never a factor. It's only a weak risk signal: `SessionFingerprintChanged` notices when a session's browser or platform changes. -A browser shared by several accounts has one cookie and a device for each account that signed in on it. Keyring only reuses a cookie that another account already has a device for. Anything else the browser sends is ignored and replaced with a new random token. Keyring can't tell which browser holds a cookie, so a value planted from another account's device is reused too, and the device counts as recognised, until a login on it proves a second factor. Every login that reaches AAL2 gives the browser a new cookie, so the previous one stops working. +A browser shared by several accounts has one cookie and a device for each account that signed in on it. An account's device never takes a value the browser sent: Keyring can't tell a cookie two accounts share from one that was placed in the browser holding a value someone else's device has, and taking it would get that someone's own browser recognised as this account's. So an account signing in on a browser for the first time gives it a new cookie, and the accounts already on that browser move to the new one with it. Every login that reaches AAL2 gives the browser a new cookie too, so the previous one stops working. ### Trusted Devices diff --git a/docs/security.md b/docs/security.md index 779197d5..68b2cbad 100644 --- a/docs/security.md +++ b/docs/security.md @@ -185,7 +185,7 @@ The failures in a row and the locks held until a reset are in your database eith - Devices are recognised by a random, httpOnly cookie, stored as a hash. A device is never a factor, only an input to your policy and risk signals. - Keyring's two cookies (the device cookie and the "remember me" one) are httpOnly and `SameSite=Lax`. Once the app is served over HTTPS (`APP_URL` is `https`, or `session.secure` is on) they are always `Secure` and carry the `__Host-` prefix, or `__Secure-` when your cookies are shared with subdomains. See [Keyring's Cookies](devices-and-sessions.md#keyrings-cookies). - Signing out everywhere also stops trusting the other devices and cancels pending email changes, so whoever had the account can't skip the second factor on a device they trusted or finish a change they started. -- A device is only trusted after a login that reached AAL2, never after the password alone or with an emailed code. A login that reaches AAL2, and any grant of trust, gives the browser a new cookie, so neither can rest on a cookie planted in the browser before the user signed in. +- A device is only trusted after a login that reached AAL2, never after the password alone or with an emailed code. An account's device never takes a cookie value the browser sent: the first sign in from a browser, a login that reaches AAL2 and any grant of trust each give it a new one. So being recognised, like being trusted, can't rest on a cookie placed in the browser before the user signed in, and whoever placed it isn't recognised as the account's browser from their own. - Every device stops being trusted when the password changes, an authenticator is removed, an email change is applied or a signed-in request places a risk lock. A lock placed by a login attempt doesn't, as above. ### Account Changes diff --git a/src/Devices/DeviceManager.php b/src/Devices/DeviceManager.php index aa63709d..1c193f94 100644 --- a/src/Devices/DeviceManager.php +++ b/src/Devices/DeviceManager.php @@ -80,7 +80,8 @@ public function signIn(Request $request, Authenticatable&Model $user, bool $prov 'last_seen_at' => now(), ]); - if ($provedSecondFactor) { + // A new device has just been given a token nobody else has seen. + if ($provedSecondFactor && $device->exists) { $this->rotateToken($request, $device); } elseif ($device->exists && ($earlier = $this->earlierToken($request)) !== null) { // Found by the cookie from before the app was served over HTTPS: @@ -148,16 +149,19 @@ protected function forgetOldest(Authenticatable&Model $user, Device $new): void */ protected function newDevice(Request $request, Authenticatable&Model $user): Device { - $token = $this->tokenForNewDevice($request, $user); + $device = new ($this->keyring->deviceModel())(['first_seen_at' => now()]); + $device->authenticatable()->associate($user); + + // Always a token of its own making. The browser may hold one + // already, another account's that has signed in on it, and it may + // hold one that was put there: the server can't tell which. Taking + // it would let whoever placed it be recognised as this account's + // browser from their own. So the account never takes a value the + // browser sent, and the accounts already on the browser move to the + // new one with it. + $this->rotateToken($request, $device); - $device = new ($this->keyring->deviceModel())([ - 'token_hash' => $this->keyring->deviceModel()::hashToken($token), - 'first_seen_at' => now(), - ]); - - $this->queueCookie($request, $token); - - return $device->authenticatable()->associate($user); + return $device; } /** @@ -235,28 +239,11 @@ public function cookie(): string } /** - * A new random token, unless another account already has a device with - * the one this browser sent: the cookie is shared by everyone signing in - * on the browser, so that one is kept. A value no account has is never - * stored. The server can't tell a shared cookie from one planted in this - * browser with a value another account holds, so a kept token only gets - * the device recognised until a login proves a second factor (rotateToken). - */ - protected function tokenForNewDevice(Request $request, Authenticatable&Model $user): string - { - $token = $this->token($request); - - // A revoked device starts over with a new token. - return $token !== null && $this->forBrowser($request)->isNotEmpty() && ! $this->query($user)->withToken($token)->exists() - ? $token - : Str::random(40); - } - - /** - * Neither trust nor a proven second factor may rest on a token the browser - * could have been handed, so both issue a new one. Everyone signed in on - * this browser moves to it together, or the cookie would stop matching - * their devices. + * Neither a new device, nor trust, nor a proven second factor may rest on + * a token the browser could have been handed, so each issues a new one. + * Everyone signed in on this browser moves to it together, or the cookie + * would stop matching their devices. A value no account has moves + * nobody. */ protected function rotateToken(Request $request, Device $device): void { diff --git a/tests/Feature/CookiesTest.php b/tests/Feature/CookiesTest.php index ef5fae83..699b4418 100644 --- a/tests/Feature/CookiesTest.php +++ b/tests/Feature/CookiesTest.php @@ -238,13 +238,18 @@ function servedOverHttps(): void it('never gives a new device the token of the old cookie', function () { // Anything on the domain could set a cookie without the prefix, so - // one holding another account's token is planted, not shared. + // one holding another account's token may be planted, not shared. A + // new device never takes a token the browser sent, under either + // name: it gets one of its own, and whoever was on the old one + // moves to it. User::create(['name' => 'Abigail', 'email' => 'abigail@example.com', 'password' => 'password', 'email_verified_at' => now()]); $response = signInHolding(['known_device' => $this->device], email: 'abigail@example.com'); + $new = $response->getCookie('__Host-known_device')->getValue(); - expect($response->getCookie('__Host-known_device')->getValue())->not->toBe($this->device) - ->and(Device::query()->withToken($this->device)->count())->toBe(1); + expect($new)->not->toBe($this->device) + ->and(Device::query()->withToken($this->device)->count())->toBe(0) + ->and(Device::query()->withToken($new)->count())->toBe(2); $response->assertCookieExpired('known_device'); }); diff --git a/tests/Feature/DevicesAndSessionsTest.php b/tests/Feature/DevicesAndSessionsTest.php index 00e3f9de..be0e2e93 100644 --- a/tests/Feature/DevicesAndSessionsTest.php +++ b/tests/Feature/DevicesAndSessionsTest.php @@ -752,16 +752,56 @@ function withAppHeaders(array $headers): void $abigail = fn (string $token) => test()->withHeader('User-Agent', FIREFOX)->withCookies(['known_device' => $token]) ->post('/login', ['email' => 'abigail@example.com', 'password' => 'password']); - $token = deviceCookie(login()); + $first = deviceCookie(login()); $this->post('/logout'); - $abigail($token); + + // A second account on the browser gives it a new cookie, and the first + // account's device moves to it too. + $shared = deviceCookie($abigail($first)); $this->post('/logout'); - $abigail($token); + + expect($shared)->not->toBe($first); + + $abigail($shared); $this->post('/logout'); - login(['known_device' => $token]); + login(['known_device' => $shared]); Event::assertDispatchedTimes(NewDeviceSignedIn::class, 2); - expect(Device::count())->toBe(2); + expect(Device::count())->toBe(2) + ->and(Device::query()->withToken($shared)->count())->toBe(2); +}); + +// The server can't tell a cookie two accounts share from one that was put in +// the browser, holding a value someone else's device has. So an account never +// takes a value the browser sent: whoever placed it would be recognised as +// that account's browser from their own, with no "new device" notice and +// with whatever a policy allows a browser it knows. +it('never recognises a browser by a device cookie that was planted in the account owner\'s', function () { + Keyring::require(fn (User $user, Attempt $attempt) => $attempt->isNewDevice() ? Requirement::aal2()->ifEnrolled() : Requirement::aal1()); + User::create(['name' => 'Mallory', 'email' => 'mallory@example.com', 'password' => 'password', 'email_verified_at' => now()]); + + // A real cookie, issued to someone else's own browser, then placed in + // the owner's. + $planted = deviceCookie($this->withHeader('User-Agent', CHROME)->post('/login', ['email' => 'mallory@example.com', 'password' => 'password'])); + $this->post('/logout'); + + // The owner signs in with a password alone, before they have a second factor. + $owners = deviceCookie(login(['known_device' => $planted])->assertRedirect('/dashboard')); + $this->post('/logout'); + + expect($owners)->not->toBe($planted) + ->and($this->user->devices()->sole()->token_hash)->toBe(hash('sha256', $owners)); + + Authenticator::factory()->totp()->for($this->user, 'authenticatable')->create(); + Event::fake([NewDeviceSignedIn::class]); + + // The other browser still holds the planted value, and now the password. + login(['known_device' => $planted])->assertRedirect(route('keyring.login.challenge')); + $this->assertGuest(); + + // The owner's own browser is the one that's known. + login(['known_device' => $owners])->assertRedirect('/dashboard'); + Event::assertNotDispatched(NewDeviceSignedIn::class); }); it('signs this session out when its own device is revoked', function () { From eb154cce2abd778b35f63bdf82e931e8f6939ca3 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Wed, 11 Nov 2026 20:14:10 +0000 Subject: [PATCH 6/9] fix(sessions): know a user's sessions by their table, and hold their row around a change a session makes --- UPGRADE.md | 2 +- docs/devices-and-sessions.md | 2 +- src/Changes/AuthenticatorChanges.php | 8 ++-- src/Changes/EmailChanges.php | 38 ++++++++-------- src/Devices/DeviceManager.php | 12 +---- src/Login/SignIn.php | 12 ++++- src/Sessions/CacheSessionRegistry.php | 4 +- src/Sessions/RegisteredSession.php | 12 +++-- src/Sessions/Sessions.php | 53 ++++++++++++++-------- tests/Concurrency/Helpers.php | 39 +++++++++------- tests/Concurrency/RaceTest.php | 39 +++------------- tests/Concurrency/worker.php | 8 ---- tests/Feature/CommandsTest.php | 8 ++-- tests/Feature/DeletingUsersTest.php | 2 +- tests/Feature/DevicesAndSessionsTest.php | 40 ++++++++++++++-- tests/Feature/EmailChangeHardeningTest.php | 2 +- tests/Feature/ExtendingTest.php | 4 +- tests/Feature/RememberMeTest.php | 2 +- tests/Feature/SessionHardeningTest.php | 41 ++++++++++++++++- 19 files changed, 194 insertions(+), 134 deletions(-) diff --git a/UPGRADE.md b/UPGRADE.md index 6ec20f16..4df67542 100644 --- a/UPGRADE.md +++ b/UPGRADE.md @@ -8,7 +8,7 @@ What counts as a change you'd need to act on is in the README's [What's Stable]( Changes made since the first installs from `dev-main`, for anyone already running one: -- **`keyring_sessions` has a `user_type` column.** A session record now names its user's model as well as the ID, so two user models with the same IDs don't share sessions. Add `$table->string('user_type')` and an index on `['user_type', 'user_id']` to your published migration, and empty the table: everyone signs in again. A custom `SessionRegistry` has to store the new `userType` field and match on it in `forUser()`, `revokeAll()` and `revokeDevice()`. +- **`keyring_sessions` has a `user_type` column.** A session record now says which table its user's ID is one of (the connection and table, as `RegisteredSession::typeOf($user)` gives it), so two user models with the same IDs don't share sessions. Add `$table->string('user_type')` and an index on `['user_type', 'user_id']` to your published migration, and empty the table: everyone signs in again. With the `cache` driver there's nothing to change: a record from before has no type, isn't found, and its browser signs in again. A custom `SessionRegistry` has to store the new `userType` field and match on it in `forUser()`, `revokeAll()` and `revokeDevice()`. - **`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). - **Saving the current password as the new one is refused** on `PUT /user/password`, with a validation error on `password`. diff --git a/docs/devices-and-sessions.md b/docs/devices-and-sessions.md index 561d19be..d267c6a0 100644 --- a/docs/devices-and-sessions.md +++ b/docs/devices-and-sessions.md @@ -316,7 +316,7 @@ Then set `sessions.driver` to `custom`. Keyring calls `replace()`, `revokeAll()` |---|---| | `save($session)` | Stores a new `RegisteredSession`. It must never clear a revocation made in the meantime, or what a record was replaced by. | | `find($id)` | The session, or `null`. | -| `forUser($user)` | The user's sessions that haven't expired, been revoked or been replaced, most recent first. A session is a user's by the model as well as the ID: match on the record's `userType` (`RegisteredSession::typeOf($user)`) and its `userId`, here and in `revokeAll()` and `revokeDevice()`, or two user models with the same IDs would share sessions. `$session->belongsTo($user)` checks both. | +| `forUser($user)` | The user's sessions that haven't expired, been revoked or been replaced, most recent first. A session is a user's by more than the ID: match on the record's `userType` (`RegisteredSession::typeOf($user)`, the connection and table the ID is one of) and its `userId`, here and in `revokeAll()` and `revokeDevice()`, or two user models with the same IDs would share sessions. `$session->belongsTo($user)` checks both. | | `update($id, $changes)` | Changes only the named fields, such as `['lastActivityAt' => $now]` or `['assurance' => $level, 'expiresAt' => $at]`. Field names are as on `RegisteredSession`; `RegisteredSession::columns($changes)` turns them into snake case columns. Writing only these fields means a request can't write back a stale copy of the rest. | | `revoke($id)` | Revokes one session. | | `replace($id, $successor, $revoke = false)` | Moves a session to a new record: stores `$successor` and sets the old record's `replacedBy` and `replacedAt` (and revokes it, with `$revoke`). It only does so for a record that is neither revoked nor replaced, and returns whether it did. Of two calls for the same record at the same moment exactly one may return `true`, and the other's record must not be left behind: "remember me" being single use rests on this. The database driver uses one conditional `UPDATE` in a transaction, the cache driver the store's `add()`. | diff --git a/src/Changes/AuthenticatorChanges.php b/src/Changes/AuthenticatorChanges.php index 36a9fb2a..128b5f1c 100644 --- a/src/Changes/AuthenticatorChanges.php +++ b/src/Changes/AuthenticatorChanges.php @@ -59,11 +59,7 @@ public function add(Authenticatable&Model $user, Enrollable $factor, Authenticat $recoverable = array_any($factor->categories($authenticator), fn (Category $category) => $category->authenticates()); $recovery = ! $isRecovery && $recoverable && ! $keyring->hasRecoveryCodes() ? $this->recoveryCodes() : null; - $authenticator->getConnection()->transaction(function () use ($factor, $user, $keyring, $authenticator, $isRecovery, $recovery, $request) { - if ($request !== null) { - $this->sessions->stillSignedIn($request, $user); - } - + $save = fn () => $authenticator->getConnection()->transaction(function () use ($factor, $user, $keyring, $authenticator, $isRecovery, $recovery) { if (! $factor->multiple()) { $replaced = $keyring->of($factor->key())->each->delete(); @@ -81,6 +77,8 @@ public function add(Authenticatable&Model $user, Enrollable $factor, Authenticat } }); + $request === null ? $save() : $this->sessions->whileSignedIn($request, $user, $save); + $isRecovery ? RecoveryCodesGenerated::dispatch($user, $authenticator) : AuthenticatorAdded::dispatch($user, $authenticator); diff --git a/src/Changes/EmailChanges.php b/src/Changes/EmailChanges.php index 9fb39545..691af524 100644 --- a/src/Changes/EmailChanges.php +++ b/src/Changes/EmailChanges.php @@ -98,24 +98,26 @@ public function request(Authenticatable&Model $user, string $email, Request $req // in first has saved its change where the undo's last look // closes it. The address is the row's, not the one this request // loaded before an undo moved it. - $current = (string) $this->sessions->stillSignedIn($request, $user)->getAttribute($this->attribute()); - - if ($email === $this->keyring->normalizeUsername($current)) { - return null; - } - - $change = new ($this->keyring->pendingChangeModel())([ - 'attribute' => $this->attribute(), - 'value' => $email, - 'previous_value' => $current, - 'confirm_token' => PendingChange::hashToken($tokens['confirm']), - 'current_token' => $needsCurrent ? PendingChange::hashToken($tokens['current']) : null, - 'revert_token' => PendingChange::hashToken($tokens['revert']), - 'signed_in_at' => $signedInAt, - 'expires_at' => Duration::fromNow(config('keyring.email_changes.confirmable_for')), - ]); - - return tap($change->authenticatable()->associate($user))->save(); + return $this->sessions->whileSignedIn($request, $user, function (Authenticatable&Model $user) use ($email, &$current, $tokens, $needsCurrent, $signedInAt) { + $current = (string) $user->getAttribute($this->attribute()); + + if ($email === $this->keyring->normalizeUsername($current)) { + return null; + } + + $change = new ($this->keyring->pendingChangeModel())([ + 'attribute' => $this->attribute(), + 'value' => $email, + 'previous_value' => $current, + 'confirm_token' => PendingChange::hashToken($tokens['confirm']), + 'current_token' => $needsCurrent ? PendingChange::hashToken($tokens['current']) : null, + 'revert_token' => PendingChange::hashToken($tokens['revert']), + 'signed_in_at' => $signedInAt, + 'expires_at' => Duration::fromNow(config('keyring.email_changes.confirmable_for')), + ]); + + return tap($change->authenticatable()->associate($user))->save(); + }); }); if ($change === null) { diff --git a/src/Devices/DeviceManager.php b/src/Devices/DeviceManager.php index 1c193f94..2778d246 100644 --- a/src/Devices/DeviceManager.php +++ b/src/Devices/DeviceManager.php @@ -8,7 +8,6 @@ use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Collection as EloquentCollection; use Illuminate\Database\Eloquent\Model; -use Illuminate\Database\UniqueConstraintViolationException; use Illuminate\Http\Request; use Illuminate\Support\Collection; use Illuminate\Support\Str; @@ -93,16 +92,7 @@ public function signIn(Request $request, Authenticatable&Model $user, bool $prov $device->trusted_until = Duration::fromNow($for); } - try { - // In a transaction of its own, so a refused insert leaves one - // the caller has open usable. - $device->getConnection()->transaction(fn () => $device->save()); - } catch (UniqueConstraintViolationException $e) { - // Two sign ins at once from a browser the account hadn't used, - // carrying the same cookie: the other stored the device first, - // and this one carries on with it. - $device = ($device->exists ? null : $this->query($user)->where('token_hash', $device->token_hash)->first()) ?? throw $e; - } + $device->save(); if ($device->wasRecentlyCreated) { $this->forgetOldest($user, $device); diff --git a/src/Login/SignIn.php b/src/Login/SignIn.php index fca62cf3..7cf35f92 100644 --- a/src/Login/SignIn.php +++ b/src/Login/SignIn.php @@ -70,7 +70,17 @@ public function complete(Request $request, Attempt $attempt): void $ended = $this->changedMeanwhile($user) || ! $attempt->keepsItsAuthenticators(); } catch (Throwable $e) { - $this->out($request, onlyThisBrowser: true); + // Whatever failed may fail again as the session is ended (the + // registry, say), and the guard has to be signed out all the + // same. + try { + $this->out($request, onlyThisBrowser: true); + } catch (Throwable) { + $guard = $this->keyring->guard(); + + $guard instanceof SessionGuard ? $guard->logoutCurrentDevice() : $guard->logout(); + $request->session()->invalidate(); + } throw $e; } diff --git a/src/Sessions/CacheSessionRegistry.php b/src/Sessions/CacheSessionRegistry.php index 008b8ba7..fa3c0524 100644 --- a/src/Sessions/CacheSessionRegistry.php +++ b/src/Sessions/CacheSessionRegistry.php @@ -63,7 +63,9 @@ public function find(string $id): ?RegisteredSession $found = $this->cache->many([$this->key($id), $this->revokedKey($id), $this->replacedKey($id), $this->everyoneKey()]); $data = $found[$this->key($id)] ?? null; - if (! is_array($data)) { + // A record from before records said whose table their ID is one of + // can't be told apart from another model's, so it's no session. + if (! is_array($data) || ! is_string($data['user_type'] ?? null)) { return null; } diff --git a/src/Sessions/RegisteredSession.php b/src/Sessions/RegisteredSession.php index bed1905f..92423795 100644 --- a/src/Sessions/RegisteredSession.php +++ b/src/Sessions/RegisteredSession.php @@ -20,9 +20,10 @@ * A remembered session is one "remember me" may bring back once Laravel's * own session has gone, so it's allowed to sit unused for longer. * - * Whose it is takes the model as well as the ID (userType is the user's - * morph class), as everything else Keyring keeps for a user does: two user - * models can have the same IDs. + * Whose it is takes more than the ID: two user models can have the same + * IDs. userType says which table the ID is one of. It's the table and not + * the class, so one account loaded as two classes (an Admin that extends + * User, on the users table) is still one account, as it is to the guard. */ final readonly class RegisteredSession { @@ -53,11 +54,12 @@ public function belongsTo(Authenticatable $user): bool } /** - * What a user's records carry as userType. + * What a user's records carry as userType: the connection and table + * their ID is unique in. A user that isn't a model has only its class. */ public static function typeOf(Authenticatable $user): string { - return $user instanceof Model ? $user->getMorphClass() : $user::class; + return $user instanceof Model ? $user->getConnection()->getName().':'.$user->getTable() : $user::class; } public function isActive(int $now): bool diff --git a/src/Sessions/Sessions.php b/src/Sessions/Sessions.php index bcda461b..896acd61 100644 --- a/src/Sessions/Sessions.php +++ b/src/Sessions/Sessions.php @@ -134,35 +134,50 @@ protected function holding(Authenticatable $user, Closure $change): mixed } /** - * For a change only a signed-in session may make, called inside the - * transaction that saves it: hold the user's row until that transaction - * ends, so the change and a sign-out everywhere take turns, and refuse - * if this request's session has been ended since its middleware let it - * through (an email change undone, a password reset, a device reported). + * Make a change only a signed-in session may make, holding the user's + * row so it and a sign-out everywhere take turns, and refusing if this + * request's session has been ended since its middleware let it through + * (an email change undone, a password reset, a device reported). * Without this a request already under way would still save its change - * after the account's owner had ended every session. Returns the user - * as the locked row has it. + * after the account's owner had ended every session. The change is + * given the user as the locked row has it. * - * A request with no registered session is one Keyring isn't keeping - * track of, and is let through as before. + * A session whose record has gone is an ended one, as it is to the + * session middleware. A request with no session, or one Keyring never + * registered, isn't one Keyring keeps track of, and is let through. * - * @template TUser of Authenticatable&Model + * The row is held on the user's own connection. Where what's being + * changed is kept on another, the two can't commit as one, and the lock + * goes a moment before the change is saved. And on MySQL, a caller + * that has already read inside a transaction of its own reads the + * registry as it was then: Keyring's routes open none. * - * @param TUser $user - * @return TUser + * @template TResult + * + * @param Closure(Authenticatable&Model): TResult $change + * @return TResult * * @throws AuthenticationException */ - public function stillSignedIn(Request $request, Authenticatable&Model $user): Authenticatable&Model + public function whileSignedIn(Request $request, Authenticatable&Model $user, Closure $change): mixed { - $fresh = $user->newQueryWithoutScopes()->lockForUpdate()->whereKey($user->getKey())->first(); - $session = $request->hasSession() ? $this->current($request) : null; + return RowLock::hold($user, function (?Model $fresh) use ($request, $change) { + if (! $fresh instanceof Authenticatable) { + throw new AuthenticationException; + } - if (! $fresh instanceof Authenticatable || $session?->isActive(now()->getTimestamp()) === false || $session?->belongsTo($fresh) === false) { - throw new AuthenticationException; - } + $id = $request->hasSession() ? $request->session()->get(self::KEY) : null; - return $fresh; + if (is_string($id)) { + $session = $this->registry->find($id); + + if ($session === null || ! $session->isActive(now()->getTimestamp()) || ! $session->belongsTo($fresh)) { + throw new AuthenticationException; + } + } + + return $change($fresh); + }); } /** diff --git a/tests/Concurrency/Helpers.php b/tests/Concurrency/Helpers.php index 46e69651..31ca123c 100644 --- a/tests/Concurrency/Helpers.php +++ b/tests/Concurrency/Helpers.php @@ -56,17 +56,13 @@ function outcomes(array $results, mixed $value): int * @param list> $operations worker.php arguments * @param (Closure(): void)|null $meanwhile work to finish, holding the lock, before letting go * @param int|null $waiting how many of them should get as far as the lock, when the rest are turned away before it - * @param (Closure(): void)|null $hold what to hold in place of the row's lock, inside the transaction * @return list */ -function contend(Model $locked, array $operations, ?Closure $meanwhile = null, ?int $waiting = null, ?Closure $hold = null): array +function contend(Model $locked, array $operations, ?Closure $meanwhile = null, ?int $waiting = null): array { $connection = $locked->getConnection(); $connection->beginTransaction(); - - // The row, unless what the operations wait on is something else: a - // row this side has stored and not yet committed, say. - $hold === null ? $locked->newQuery()->lockForUpdate()->find($locked->getKey()) : $hold(); + $locked->newQuery()->lockForUpdate()->find($locked->getKey()); $env = ['DB_CONNECTION' => $connection->getName(), 'DB_DATABASE' => $connection->getDatabaseName()]; @@ -86,20 +82,29 @@ function contend(Model $locked, array $operations, ?Closure $meanwhile = null, ? // Long enough for an operation that ignores the lock to finish. Sleep::usleep(500_000); - $running = fn () => count(array_filter($workers, fn (InvokedProcess|FakeInvokedProcess $worker) => $worker->running())); + // Let go whatever happens: a failed expectation that kept the lock would + // leave every later test waiting for the tables it holds. + try { + $running = fn () => count(array_filter($workers, fn (InvokedProcess|FakeInvokedProcess $worker) => $worker->running())); - // Those turned away before the lock get time to finish. The rest can't. - for ($deadline = microtime(true) + 15; $waiting !== null && $running() > $waiting && microtime(true) < $deadline;) { - Sleep::usleep(50_000); - } + // Those turned away before the lock get time to finish. The rest can't. + for ($deadline = microtime(true) + 15; $waiting !== null && $running() > $waiting && microtime(true) < $deadline;) { + Sleep::usleep(50_000); + } + + expect($running())->toBe($waiting ?? count($workers), 'An operation ran without waiting for the lock, or one that should have been turned away is waiting for it: '.implode('', array_map( + fn (InvokedProcess|FakeInvokedProcess $worker) => $worker->output().$worker->errorOutput(), + $workers, + ))); - expect($running())->toBe($waiting ?? count($workers), 'An operation ran without waiting for the lock, or one that should have been turned away is waiting for it: '.implode('', array_map( - fn (InvokedProcess|FakeInvokedProcess $worker) => $worker->output().$worker->errorOutput(), - $workers, - ))); + if ($meanwhile !== null) { + $meanwhile(); + } + } catch (Throwable $e) { + $connection->rollBack(); + array_map(fn (InvokedProcess|FakeInvokedProcess $worker) => $worker->running() && $worker->signal(SIGKILL), $workers); - if ($meanwhile !== null) { - $meanwhile(); + throw $e; } $connection->commit(); diff --git a/tests/Concurrency/RaceTest.php b/tests/Concurrency/RaceTest.php index 2db1d4a8..d5813924 100644 --- a/tests/Concurrency/RaceTest.php +++ b/tests/Concurrency/RaceTest.php @@ -7,7 +7,6 @@ use Keyring\Enums\Assurance; use Keyring\Facades\Keyring; use Keyring\Models\Authenticator; -use Keyring\Models\Device; use Keyring\Models\FailureCount; use Keyring\Models\PendingChange; use Keyring\Sessions\RegisteredSession; @@ -194,7 +193,7 @@ it('refuses an email change from a session that is signed out while its request waits', function (bool $signedOut, mixed $expected) { $user = taylor(); $now = now()->getTimestamp(); - app(SessionRegistry::class)->save(new RegisteredSession('asking', (string) $user->id, $user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600)); + app(SessionRegistry::class)->save(new RegisteredSession('asking', (string) $user->id, RegisteredSession::typeOf($user), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600)); [$requested] = contend($user, [['request-email-change', $user->id, 'asking']], fn () => $signedOut && app(SessionRegistry::class)->revokeAll($user)); @@ -210,7 +209,7 @@ it('refuses a sign-in method from a session that is signed out while its request waits', function (bool $signedOut, string $expected) { $user = taylor(); $now = now()->getTimestamp(); - app(SessionRegistry::class)->save(new RegisteredSession('asking', (string) $user->id, $user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600)); + app(SessionRegistry::class)->save(new RegisteredSession('asking', (string) $user->id, RegisteredSession::typeOf($user), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600)); [$added] = contend($user, [['add-authenticator', $user->id, 'asking']], fn () => $signedOut && app(SessionRegistry::class)->revokeAll($user)); @@ -221,35 +220,11 @@ 'still signed in' => [false, 'added'], ]); -// A browser someone else has signed in on keeps its cookie, so two sign ins -// to a second account from it would each store that account's device under -// the same token. The second finds the first's there, and carries on with it. -it('gives two sign ins at once from one browser the same device, and fails neither', function () { - $user = taylor(); - $other = User::create(['name' => 'Abigail', 'email' => 'abigail@example.com', 'password' => 'password']); - $token = str_repeat('a', 40); - $device = fn (User $owner) => Device::query()->forceCreate([ - 'authenticatable_type' => $owner->getMorphClass(), 'authenticatable_id' => $owner->id, - 'token_hash' => Device::hashToken($token), 'first_seen_at' => now(), 'last_seen_at' => now(), - ]); - $device($other); - - // Stored by the other sign in and not yet committed: this one has - // looked, found nothing, and waits at the unique index. - $stored = null; - [$recorded] = contend($user, [['record-device', $user->id, $token]], hold: function () use ($device, $user, &$stored) { - $stored = $device($user); - }); - - expect($recorded)->toBe($stored->id) - ->and(Device::query()->whereMorphedTo('authenticatable', $user)->count())->toBe(1); -}); - it('lets one of two requests use a "remember me" cookie, and starts one session between them', function () { $user = taylor(); $now = now()->getTimestamp(); $registry = app(SessionRegistry::class); - $registry->save(new RegisteredSession('remembered', (string) $user->id, $user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600)); + $registry->save(new RegisteredSession('remembered', (string) $user->id, RegisteredSession::typeOf($user), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600)); // Both read the record before either can replace it. $results = contend(sessionRow('remembered'), [ @@ -273,7 +248,7 @@ $registry = app(SessionRegistry::class); foreach (['older' => 120, 'newer' => 60] as $id => $ago) { - $registry->save(new RegisteredSession($id, (string) $user->id, $user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, $now - $ago, $now - $ago, $now + 3600)); + $registry->save(new RegisteredSession($id, (string) $user->id, RegisteredSession::typeOf($user), 'web', null, Assurance::AAL1, null, null, $now - $ago, $now - $ago, $now + 3600)); } // Each waits for the user's row, so the second counts the first's session. @@ -291,7 +266,7 @@ $user = taylor(); $now = now()->getTimestamp(); $registry = app(SessionRegistry::class); - $registry->save(new RegisteredSession('remembered', (string) $user->id, $user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600, remembered: true)); + $registry->save(new RegisteredSession('remembered', (string) $user->id, RegisteredSession::typeOf($user), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600, remembered: true)); // Both wait for the user's row. Whichever goes first, the session ends: // signed out and then refused, or carried on and then signed out. @@ -311,7 +286,7 @@ $user = taylor(); $now = now()->getTimestamp(); $registry = app(SessionRegistry::class); - $registry->save(new RegisteredSession('remembered', (string) $user->id, $user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600, remembered: true)); + $registry->save(new RegisteredSession('remembered', (string) $user->id, RegisteredSession::typeOf($user), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600, remembered: true)); // Both wait for the user's row. Carried on first, it's followed to the // new record and ended there. Ended first, there's nothing to carry on. @@ -329,7 +304,7 @@ $user = taylor(); $now = now()->getTimestamp(); $registry = app(SessionRegistry::class); - $registry->save($session = new RegisteredSession('remembered', (string) $user->id, $user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600, remembered: true)); + $registry->save($session = new RegisteredSession('remembered', (string) $user->id, RegisteredSession::typeOf($user), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600, remembered: true)); // The sign-out comes to the record while "remember me" is carrying its // session on, and waits. By the time it gets the record, the session is diff --git a/tests/Concurrency/worker.php b/tests/Concurrency/worker.php index 113c1f4c..6189434c 100644 --- a/tests/Concurrency/worker.php +++ b/tests/Concurrency/worker.php @@ -14,7 +14,6 @@ use Keyring\Changes\AuthenticatorChanges; use Keyring\Changes\EmailChanges; use Keyring\Contracts\SessionRegistry; -use Keyring\Devices\DeviceManager; use Keyring\Enums\Assurance; use Keyring\Enums\Purpose; use Keyring\Facades\Keyring; @@ -103,13 +102,6 @@ return 'added'; })(), - 'record-device' => (function () use ($id, $value) { - // A sign in from a browser carrying this device cookie. - $request = Request::create('/login', 'POST', cookies: ['known_device' => $value]); - $request->setLaravelSession(app('session.store')); - - return app(DeviceManager::class)->signIn($request, User::findOrFail($id))?->id; - })(), 'sign-out' => app(Sessions::class)->signOutEverywhere(User::findOrFail($id)), 'end-latest' => (function () use ($id) { // Read while the row is held, as a request that found the cookie used. diff --git a/tests/Feature/CommandsTest.php b/tests/Feature/CommandsTest.php index a02d1132..77beb31a 100644 --- a/tests/Feature/CommandsTest.php +++ b/tests/Feature/CommandsTest.php @@ -902,8 +902,8 @@ function passkeysTable(): void $recent = $event(1); $registry = app(SessionRegistry::class); - $registry->save(new RegisteredSession('ended', (string) $user->id, $user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, 0, 0, now()->subMinute()->getTimestamp())); - $registry->save(new RegisteredSession('live', (string) $user->id, $user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, 0, 0, now()->addDay()->getTimestamp())); + $registry->save(new RegisteredSession('ended', (string) $user->id, RegisteredSession::typeOf($user), 'web', null, Assurance::AAL1, null, null, 0, 0, now()->subMinute()->getTimestamp())); + $registry->save(new RegisteredSession('live', (string) $user->id, RegisteredSession::typeOf($user), 'web', null, Assurance::AAL1, null, null, 0, 0, now()->addDay()->getTimestamp())); $this->artisan('keyring:prune')->assertSuccessful(); @@ -924,7 +924,7 @@ function passkeysTable(): void $now = now()->getTimestamp(); return tap( - new RegisteredSession($id, (string) $user->id, $user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600)->with($with), + new RegisteredSession($id, (string) $user->id, RegisteredSession::typeOf($user), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600)->with($with), fn (RegisteredSession $session) => app(SessionRegistry::class)->save($session), ); }; @@ -1080,7 +1080,7 @@ function passkeysTable(): void it('ends more sessions than it revokes in one go', function () { $now = now()->getTimestamp(); - DB::table('keyring_sessions')->insert(array_map(fn (int $n) => new RegisteredSession("session-{$n}", (string) $this->user->id, $this->user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600)->toArray(), range(1, 1001))); + DB::table('keyring_sessions')->insert(array_map(fn (int $n) => new RegisteredSession("session-{$n}", (string) $this->user->id, RegisteredSession::typeOf($this->user), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600)->toArray(), range(1, 1001))); $this->artisan('keyring:sign-out', ['--all' => true, '--force' => true])->assertSuccessful(); diff --git a/tests/Feature/DeletingUsersTest.php b/tests/Feature/DeletingUsersTest.php index 1dd5c006..08893494 100644 --- a/tests/Feature/DeletingUsersTest.php +++ b/tests/Feature/DeletingUsersTest.php @@ -62,7 +62,7 @@ Schema::table('users', fn (Blueprint $table) => $table->softDeletes()); $user = SoftDeletingUser::create(['name' => 'Taylor', 'email' => 'taylor@example.com', 'password' => 'password']); Authenticator::factory()->totp()->for($user, 'authenticatable')->create(); - $session = new RegisteredSession('kept', (string) $user->id, $user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, 0, 0, now()->addHour()->getTimestamp()); + $session = new RegisteredSession('kept', (string) $user->id, RegisteredSession::typeOf($user), 'web', null, Assurance::AAL1, null, null, 0, 0, now()->addHour()->getTimestamp()); app(SessionRegistry::class)->save($session); $user->delete(); diff --git a/tests/Feature/DevicesAndSessionsTest.php b/tests/Feature/DevicesAndSessionsTest.php index be0e2e93..a58eb2c3 100644 --- a/tests/Feature/DevicesAndSessionsTest.php +++ b/tests/Feature/DevicesAndSessionsTest.php @@ -43,6 +43,7 @@ use Keyring\Sessions\DatabaseSessionRegistry; use Keyring\Sessions\RegisteredSession; use Keyring\Sessions\Sessions; +use Keyring\Tests\Fixtures\AdminUser; use Keyring\Tests\Fixtures\User; beforeEach(function () { @@ -333,6 +334,12 @@ public function save(RegisteredSession $session): void { throw new RuntimeException('The database went away.'); } + + // And is still away when the sign in is undone. + public function revoke(string $id): void + { + throw new RuntimeException('The database went away.'); + } }); $this->post('/login', ['email' => 'taylor@example.com', 'password' => 'password'])->assertServerError(); @@ -429,7 +436,7 @@ public function save(RegisteredSession $session): void $other = new RegisteredSession( id: 'other', userId: (string) $this->user->id, - userType: $this->user->getMorphClass(), + userType: RegisteredSession::typeOf($this->user), guard: 'web', deviceId: null, assurance: Assurance::AAL1, @@ -1122,7 +1129,7 @@ function expectNoTrustedDevices(): void $this->staff = staff(); $now = now()->getTimestamp(); - $session = fn (string $id, Model $user, ?string $device = null) => new RegisteredSession($id, (string) $user->getKey(), $user->getMorphClass(), 'web', $device, Assurance::AAL1, null, null, $now, $now, $now + 3600); + $session = fn (string $id, Model $user, ?string $device = null) => new RegisteredSession($id, (string) $user->getKey(), RegisteredSession::typeOf($user), 'web', $device, Assurance::AAL1, null, null, $now, $now, $now + 3600); $this->seed = function () use ($session) { app(SessionRegistry::class)->save($session('users', $this->user, 'device')); @@ -1151,6 +1158,29 @@ function expectNoTrustedDevices(): void 'deleting the account' => [fn (Model $user) => $user->delete()], ]); + // One account loaded as two classes is still one account, as it is to + // the guard: an Admin that extends User, on the users table. + it('takes one account for itself whichever of its classes it is loaded as', function (string $driver) { + config(['keyring.sessions.driver' => $driver]); + Route::middleware(['web', 'auth'])->get('/home', fn () => 'home'); + $admin = AdminUser::query()->findOrFail($this->user->id); + + $this->post('/login', ['email' => 'taylor@example.com', 'password' => 'password'])->assertRedirect(); + + // Signed in as the one, found and signed out as the other. + expect(app(SessionRegistry::class)->forUser($admin))->toHaveCount(1) + ->and(app(Sessions::class)->signOutEverywhere($admin))->toBe(1); + $this->get('/home')->assertRedirect('/login'); + + // And a session the app starts for the other carries on as the one. + $this->flushSession(); + $this->app['auth']->forgetGuards(); + Auth::login($admin); + $this->get('/home')->assertOk(); + $this->app['auth']->forgetGuards(); + $this->get('/home')->assertOk(); + })->with(['database', 'cache']); + it('does not carry one kind of account on with the other\'s session', function () { Route::middleware(['web', 'auth'])->get('/home', fn () => 'home'); @@ -1177,7 +1207,7 @@ function expectNoTrustedDevices(): void $this->here = session(Sessions::KEY); $now = now()->getTimestamp(); - app(SessionRegistry::class)->save(new RegisteredSession('elsewhere', (string) $this->user->id, $this->user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600)); + app(SessionRegistry::class)->save(new RegisteredSession('elsewhere', (string) $this->user->id, RegisteredSession::typeOf($this->user), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600)); }; $this->expectOnlyThisSessionLeft = function () { @@ -1295,7 +1325,7 @@ function expectNoTrustedDevices(): void $here = session(Sessions::KEY); $id = session()->getId(); $now = now()->getTimestamp(); - $registry->save(new RegisteredSession('elsewhere', (string) $this->user->id, $this->user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600)); + $registry->save(new RegisteredSession('elsewhere', (string) $this->user->id, RegisteredSession::typeOf($this->user), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600)); $this->user->forceFill(['remember_token' => 'remembered'])->save(); $this->deleteJson(route('keyring.sessions.destroy-others'))->assertOk()->assertJsonPath('status', 'sessions-revoked'); @@ -1327,7 +1357,7 @@ function expectNoTrustedDevices(): void $now = now()->getTimestamp(); return tap( - new RegisteredSession($id, (string) ($user ?? $this->user)->id, ($user ?? $this->user)->getMorphClass(), 'web', null, Assurance::AAL1, '203.0.113.7', CHROME, $now - 600, $now - 300, $now + 3600)->with($with), + new RegisteredSession($id, (string) ($user ?? $this->user)->id, RegisteredSession::typeOf(($user ?? $this->user)), 'web', null, Assurance::AAL1, '203.0.113.7', CHROME, $now - 600, $now - 300, $now + 3600)->with($with), fn (RegisteredSession $session) => app(SessionRegistry::class)->save($session), ); }; diff --git a/tests/Feature/EmailChangeHardeningTest.php b/tests/Feature/EmailChangeHardeningTest.php index 237d6fd1..bc59cf1c 100644 --- a/tests/Feature/EmailChangeHardeningTest.php +++ b/tests/Feature/EmailChangeHardeningTest.php @@ -707,7 +707,7 @@ function otherSession(User $user, string $id = 'other-session'): string app(SessionRegistry::class)->save(new RegisteredSession( id: $id, userId: (string) $user->getKey(), - userType: $user->getMorphClass(), + userType: RegisteredSession::typeOf($user), guard: 'web', deviceId: null, assurance: Assurance::AAL1, diff --git a/tests/Feature/ExtendingTest.php b/tests/Feature/ExtendingTest.php index aa07291b..54b7cc2f 100644 --- a/tests/Feature/ExtendingTest.php +++ b/tests/Feature/ExtendingTest.php @@ -224,7 +224,7 @@ class CustomConfirmEmailChange extends ConfirmEmailChange it('runs the app\'s own password action, with keyring\'s security work around it', function () { Keyring::updateUserPasswordsUsing(SymbolsRequired::class); - $other = new RegisteredSession('other', (string) $this->user->id, $this->user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, 0, 0, now()->addHour()->getTimestamp()); + $other = new RegisteredSession('other', (string) $this->user->id, RegisteredSession::typeOf($this->user), 'web', null, Assurance::AAL1, null, null, 0, 0, now()->addHour()->getTimestamp()); app(SessionRegistry::class)->save($other); $this->actingAs($this->user)->withAssurance(Assurance::AAL1) @@ -280,7 +280,7 @@ class CustomConfirmEmailChange extends ConfirmEmailChange it('refuses a password action that saves nothing, before signing anyone out', function () { Keyring::updateUserPasswordsUsing(SavesNothing::class); - $other = new RegisteredSession('other', (string) $this->user->id, $this->user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, 0, 0, now()->addHour()->getTimestamp()); + $other = new RegisteredSession('other', (string) $this->user->id, RegisteredSession::typeOf($this->user), 'web', null, Assurance::AAL1, null, null, 0, 0, now()->addHour()->getTimestamp()); app(SessionRegistry::class)->save($other); $this->withoutExceptionHandling()->actingAs($this->user)->withAssurance(Assurance::AAL1); diff --git a/tests/Feature/RememberMeTest.php b/tests/Feature/RememberMeTest.php index c2145740..a8442e17 100644 --- a/tests/Feature/RememberMeTest.php +++ b/tests/Feature/RememberMeTest.php @@ -1072,7 +1072,7 @@ function sessionEndedReasons(): array describe('replacing a session\'s record', function () { beforeEach(function () { - $this->session = fn (string $id, array $changes = []) => new RegisteredSession($id, (string) $this->user->id, $this->user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, 0, 0, now()->addHour()->getTimestamp())->with($changes); + $this->session = fn (string $id, array $changes = []) => new RegisteredSession($id, (string) $this->user->id, RegisteredSession::typeOf($this->user), 'web', null, Assurance::AAL1, null, null, 0, 0, now()->addHour()->getTimestamp())->with($changes); }); it('happens once, and keeps only the record that did it', function (string $driver) { diff --git a/tests/Feature/SessionHardeningTest.php b/tests/Feature/SessionHardeningTest.php index 31e65156..0e5c6ed0 100644 --- a/tests/Feature/SessionHardeningTest.php +++ b/tests/Feature/SessionHardeningTest.php @@ -2,8 +2,11 @@ declare(strict_types=1); +use Illuminate\Auth\AuthenticationException; use Illuminate\Http\Request; +use Illuminate\Support\Arr; use Illuminate\Support\Facades\Cache; +use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Notification; use Illuminate\Support\Facades\Route; use Illuminate\Testing\TestResponse; @@ -341,7 +344,7 @@ function sessionCookies(TestResponse $response): array $now = now()->getTimestamp(); $registry->revoke($id); - $next = new RegisteredSession('next', (string) $this->user->id, $this->user->getMorphClass(), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600); + $next = new RegisteredSession('next', (string) $this->user->id, RegisteredSession::typeOf($this->user), 'web', null, Assurance::AAL1, null, null, $now, $now, $now + 3600); $registry->save($replaced = $next->with(['id' => 'replaced'])); $registry->replace('replaced', $next->with(['id' => 'successor'])); @@ -357,6 +360,42 @@ function sessionCookies(TestResponse $response): array $this->get('/home')->assertRedirect('/login'); })->with(['its revoked marker' => ':revoked', 'its replaced marker' => ':replaced']); +// A record kept before records said whose table their ID is one of. It can't +// be told from another model's, so its browser signs in again. +it('signs out a session whose cache record is from before records said whose they are', function () { + config(['keyring.sessions.driver' => 'cache']); + signInWith(); + $key = 'keyring:sessions:'.session(Sessions::KEY); + + Cache::put($key, Arr::except(Cache::get($key), 'user_type'), 3600); + + $this->get('/home')->assertRedirect('/login'); + $this->assertGuest(); +}); + +// A session with a record that has gone is an ended one, to a request under +// way as it is to the session middleware. +it('refuses a change from a session whose record has gone', function (string $driver) { + config(['keyring.sessions.driver' => $driver]); + signInWith(); + $request = request(); + $request->setLaravelSession(session()->driver()); + $change = fn () => app(Sessions::class)->whileSignedIn($request, $this->user, fn () => 'saved'); + + expect($change())->toBe('saved'); + + $driver === 'database' + ? DB::table('keyring_sessions')->delete() + : Cache::forget('keyring:sessions:'.session(Sessions::KEY)); + + expect($change)->toThrow(AuthenticationException::class); + + // One Keyring never registered isn't one it keeps track of. + session()->forget(Sessions::KEY); + + expect($change())->toBe('saved'); +})->with('drivers'); + it('does not undo a revocation that lands while a request is being assessed', function (string $driver) { config(['keyring.sessions.driver' => $driver]); Keyring::risk()->signals([new RevokesDuringAssessment]); From 776e5433facc0000569221d83571eef8f1fdfe9e Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Wed, 11 Nov 2026 20:15:39 +0000 Subject: [PATCH 7/9] fix(limits): hold an account for its own lockouts only, and count a refused challenge against nothing --- UPGRADE.md | 1 + src/Pipeline/AccountLimit.php | 10 +++++ src/Pipeline/Steps/EnsureNotThrottled.php | 45 ++++++++++++++++------ src/Support/Throttle.php | 14 ++++--- tests/Feature/ThrottlingTest.php | 47 +++++++++++++++++++++++ 5 files changed, 99 insertions(+), 18 deletions(-) diff --git a/UPGRADE.md b/UPGRADE.md index 4df67542..a18e3de9 100644 --- a/UPGRADE.md +++ b/UPGRADE.md @@ -11,5 +11,6 @@ Changes made since the first installs from `dev-main`, for anyone already runnin - **`keyring_sessions` has a `user_type` column.** A session record now says which table its user's ID is one of (the connection and table, as `RegisteredSession::typeOf($user)` gives it), so two user models with the same IDs don't share sessions. Add `$table->string('user_type')` and an index on `['user_type', 'user_id']` to your published migration, and empty the table: everyone signs in again. With the `cache` driver there's nothing to change: a record from before has no type, isn't found, and its browser signs in again. A custom `SessionRegistry` has to store the new `userType` field and match on it in `forUser()`, `revokeAll()` and `revokeDevice()`. - **`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. - **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. diff --git a/src/Pipeline/AccountLimit.php b/src/Pipeline/AccountLimit.php index 9dc28993..735d9f26 100644 --- a/src/Pipeline/AccountLimit.php +++ b/src/Pipeline/AccountLimit.php @@ -19,9 +19,19 @@ class AccountLimit extends Limit /** How many lockouts in a day it takes for the next lock to hold until the limits are cleared. */ public ?int $holdAfter = null; + /** Whether it counts a name as it was typed, whoever has it, and not an account. */ + public bool $typed = false; + /** Whether it stands in for an account: the name it counts under found none. */ public bool $unowned = false; + public function typed(bool $typed = true): static + { + $this->typed = $typed; + + return $this; + } + public function unowned(bool $unowned = true): static { $this->unowned = $unowned; diff --git a/src/Pipeline/Steps/EnsureNotThrottled.php b/src/Pipeline/Steps/EnsureNotThrottled.php index 63b51e16..b6cc2681 100644 --- a/src/Pipeline/Steps/EnsureNotThrottled.php +++ b/src/Pipeline/Steps/EnsureNotThrottled.php @@ -35,6 +35,17 @@ public function handle(Context $context, Closure $next): Context [$shared, $named] = Arr::partition($announced, fn (Limit $limit) => $limit instanceof SharedLimit); [$shared, $named] = [array_values($shared), array_values($named)]; + // With no quiet limit there's nothing behind the ones that say so: + // they're asked together, and an attempt one of them refuses is + // counted against none, the address's included. + if ($quiet === []) { + if (($refusing = $this->throttle->hit($announced)) !== null) { + return $this->lockedOut($context, $refusing); + } + + return $this->counted($context, $next, $announced); + } + // The address first, so an attempt it refuses is never counted // against the account. if (($refusing = $this->throttle->hit($shared)) !== null) { @@ -49,11 +60,6 @@ public function handle(Context $context, Closure $next): Context // password gets in with it under a name someone else got refused, // and everyone without the password is answered as the name is. $held = $this->throttle->hit($named); - - if ($held !== null && $quiet === []) { - return $this->lockedOut($context, $held); - } - $limits = [...$shared, ...($held === null ? $named : [])]; $context->throttleChecked = true; @@ -72,6 +78,27 @@ public function handle(Context $context, Closure $next): Context $limits = [...$limits, ...$quiet]; } + // A name that was refused stays so when the attempt goes through: + // what it answers isn't changed by the account behind it signing in. + $context = $this->counted($context, $next, $limits); + + // A quiet refusal has been announced to the app already, where the + // proof would have been checked. + return $held !== null && $context->outcome === Outcome::Failed + ? $this->lockedOut($context, $held, announce: ! $context->refused) + : $context; + } + + /** + * Carry on down the pipeline with the attempt counted against these + * limits, and settle them by how it went. + * + * @param list $limits + */ + protected function counted(Context $context, Closure $next, array $limits): Context + { + $context->throttleChecked = true; + try { $context = $next($context); } catch (Throwable $e) { @@ -82,17 +109,11 @@ public function handle(Context $context, Closure $next): Context match ($context->outcome) { Outcome::Failed => $this->failed($context, $limits), - // A name that was refused stays so: what it answers isn't - // changed by the account behind it signing in. Outcome::Challenge, Outcome::Complete => $this->throttle->succeeded($limits), default => $this->throttle->release($limits), }; - // A quiet refusal has been announced to the app already, where the - // proof would have been checked. - return $held !== null && $context->outcome === Outcome::Failed - ? $this->lockedOut($context, $held, announce: ! $context->refused) - : $context; + return $context; } protected function lockedOut(Context $context, Limit $refusing, bool $announce = true): Context diff --git a/src/Support/Throttle.php b/src/Support/Throttle.php index 93228a75..9620d08c 100644 --- a/src/Support/Throttle.php +++ b/src/Support/Throttle.php @@ -102,7 +102,7 @@ public function limitsFor(Factor $factor, Request $request, ?Attempt $attempt): return [ SharedLimit::perMinute(config('keyring.limits.per_ip'))->by($factor->key().'|ip|'.$request->ip().($known ? '|account|'.$account : '')), ...($typed === '' ? [] : [ - $this->perMinute($factor, 'typed:'.$typed, $known), + $this->perMinute($factor, 'typed:'.$typed, $known)->typed(), ...($consecutive === null ? [] : [NameLimit::of($consecutive->share ?? PHP_INT_MAX, $factor->key(), 'typed:'.$typed, $known)]), ]), ...array_map(fn (AccountLimit $limit) => $limit->quietly($typed !== '')->unowned($user === null), [ @@ -224,9 +224,11 @@ public function retryAfter(Limit $limit): ?int */ public function failed(array $limits): bool { - // The account's hold, and the typed name's. The name is only held - // for lockouts made under it: holding it for the account's would - // tell whoever typed it that another name is the same account's. + // The account's hold, and the typed name's, each for its own + // lockouts. Holding the name for the account's would tell whoever + // typed it that another name is the same account's. Holding the + // account for the name's would count lockouts from before its + // limits were cleared, which a name's count outlasts. $hold = $named = false; foreach ($limits as $limit) { @@ -254,8 +256,8 @@ public function failed(array $limits): bool $reached = $limit instanceof AccountLimit && $limit->holdAfter !== null && $lockouts >= $limit->holdAfter; - $hold = $hold || $reached; - $named = $named || ($reached && ! $limit->quiet); + $hold = $hold || ($reached && ! $limit->typed); + $named = $named || ($reached && $limit->typed); } $refused = false; diff --git a/tests/Feature/ThrottlingTest.php b/tests/Feature/ThrottlingTest.php index dd2738c8..a119e265 100644 --- a/tests/Feature/ThrottlingTest.php +++ b/tests/Feature/ThrottlingTest.php @@ -144,6 +144,30 @@ function account(string $email): User expect($statuses)->toBe([422, 422, 429]); }); +// A request the account's own limit refuses on a challenge is counted against +// nothing, the address included, or one person's retries would hold up +// everyone behind that address. +it('does not count a challenge the account\'s limit refuses against the address', function () { + config(['keyring.limits.per_account' => 2, 'keyring.limits.per_ip' => 6]); + $user = account('taylor@example.com'); + $totp = Authenticator::factory()->totp()->for($user, 'authenticatable')->create(); + $neighbour = account('abigail@example.com'); + $theirs = Authenticator::factory()->totp()->for($neighbour, 'authenticatable')->create(); + + $this->post('/login', ['email' => 'taylor@example.com', 'password' => 'password'])->assertRedirect(route('keyring.login.challenge')); + + foreach (range(1, 8) as $attempt) { + $this->postJson(route('keyring.login.verify', 'totp'), ['code' => '000000', 'authenticator' => $totp->id]) + ->assertStatus($attempt <= 2 ? 422 : 429); + } + + // Someone else at the same address, with a wrong code of their own. + $this->flushSession(); + $this->app['auth']->forgetGuards(); + $this->post('/login', ['email' => 'abigail@example.com', 'password' => 'password'])->assertRedirect(route('keyring.login.challenge')); + $this->postJson(route('keyring.login.verify', 'totp'), ['code' => '000000', 'authenticator' => $theirs->id])->assertStatus(422); +}); + it('counts overlapping attempts before verifying them', function () { config(['keyring.limits.per_account' => 5, 'keyring.limits.per_ip' => 100]); account('taylor@example.com'); @@ -880,6 +904,29 @@ function lockOut(int $times, string $email = 'taylor@example.com', string $passw Event::assertDispatched(AccountLocked::class, fn (AccountLocked $event) => $event->user->is($this->user)); }); + // A name's count outlasts a reset, so that what the name answers doesn't + // change with the account behind it. The account's hold goes by its + // own lockouts, which a reset starts over. + it('starts the count of lockouts over when the account\'s limits are cleared', function (Closure $clear, string $password) { + Event::fake([AccountLocked::class]); + + lockOut(2); + $clear($this->user); + $this->travel(10)->minutes(); + + // The first lockout since: an old browser still trying the old password. + lockOut(1, password: 'the old password'); + $this->travel(1)->hours(); + $this->flushSession(); + $this->app['auth']->forgetGuards(); + + $this->post('/login', ['email' => 'taylor@example.com', 'password' => $password])->assertRedirect('/dashboard'); + Event::assertNotDispatched(AccountLocked::class); + })->with([ + 'a reset' => [fn (User $user) => completeReset($user), 'a brand new passphrase'], + 'an unlock' => [fn (User $user) => Keyring::unlock($user), 'password'], + ]); + it('lifts each lock by itself until there have been that many in a day', function () { lockOut(2); From e7160506ab9888cc4d55ae3662ad53d56a70a4f3 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Wed, 11 Nov 2026 20:29:32 +0000 Subject: [PATCH 8/9] style(passwords): name what an unchanged password is --- src/Changes/PasswordChanges.php | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/Changes/PasswordChanges.php b/src/Changes/PasswordChanges.php index 571e44fa..420b1eb9 100644 --- a/src/Changes/PasswordChanges.php +++ b/src/Changes/PasswordChanges.php @@ -117,9 +117,8 @@ protected function save(Authenticatable&Model $user, Closure $save, #[\Sensitive throw new LogicException('The password action returned without saving a new password. Throw a ValidationException to refuse it.'); } - $changed = blank($before) || ! ( - ($this->matches($old, $before) && $this->matches($old, $after)) || $this->matches($new, $before) - ); + $same = ($this->matches($old, $before) && $this->matches($old, $after)) || $this->matches($new, $before); + $changed = blank($before) || ! $same; if (! $changed && ! $keepHold) { return false; From 1091bee2ebef926119445202c9a2a414d945eb79 Mon Sep 17 00:00:00 2001 From: Charlie Joseph Date: Wed, 11 Nov 2026 20:30:59 +0000 Subject: [PATCH 9/9] docs: say who the email change undo trusts and what that costs --- docs/protected-changes.md | 2 ++ docs/security.md | 2 ++ 2 files changed, 4 insertions(+) diff --git a/docs/protected-changes.md b/docs/protected-changes.md index 3f87da80..297c9f63 100644 --- a/docs/protected-changes.md +++ b/docs/protected-changes.md @@ -152,6 +152,8 @@ The current address can revert the change while it's pending, and for `email_cha 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. +**Who the undo trusts.** The link is for an owner who has lost everything but their old mailbox: someone got into the account, added a passkey of their own and moved the address. So it asks for nothing but the link, and it takes away the sign-in methods that are too new to be surely the owner's. That works both ways. Whoever reads the old mailbox can press it, and when the change was the owner's own, moving away from a mailbox someone else can read, the undo removes a second factor the owner added in that window, and a password reset through the same mailbox then signs in without one. Keyring can't tell the two people apart: each holds exactly the old mailbox. `established_after` is where the line sits. A sign-in method the account has had for longer than that, added before the session that asked signed in, survives an undo, so a second factor set up a week or more before changing address is safe from it. When the change had applied, the new address is told it was undone, so the owner hears of it there. Shorten `revertable_for` and `established_after` if your users are likelier to be leaving a mailbox they've lost than to have their session taken, and lengthen them for the opposite. + ### The Old Address Is Reserved While a change can still be reverted, nobody else can take the address it replaced. Otherwise someone who changed the address could register a new account with the old one, and the owner's revert would have nowhere to put it back. That goes for lookalikes too: an address that differs only in case, accents, letter width or characters that don't show is held back with it, because MySQL's and MariaDB's default collations take those for the same address and their unique index would refuse to give it back. Another account asking to move to it gets the same "address in use" email as for any taken address. [Registration](sign-in-flow.md#registration) counts it as taken too, so it's answered like any address that has an account. Where your own code creates users or gives them a new address (an admin screen, an import), `Keyring\Rules\UnreservedAddress` refuses it with Laravel's "has already been taken" message, so use it next to `Rule::unique()`: diff --git a/docs/security.md b/docs/security.md index 68b2cbad..9bc1d868 100644 --- a/docs/security.md +++ b/docs/security.md @@ -660,6 +660,8 @@ Each of these is a choice. The reason is given once, here, and the [requirement- ### Other Limits +- **The undo link for an email change trusts the old mailbox.** It has to: it's there for an owner who has nothing else left. So someone who reads the old mailbox can undo a change the owner made, which also removes sign-in methods added in the week before it or since the session that asked signed in, and can then reset the password by email. A second factor older than that survives. See [Reverting](protected-changes.md#reverting) for why the line sits there and how to move it. + - **The `cache` session registry is as good as its store.** A session's record says whether it was revoked or replaced, and so does a key beside it, so losing either leaves the session ended. The list of a user's sessions is one key, though, and a store that drops it (Redis or Memcached evicting under memory pressure, a replica promoted without its latest writes) leaves those sessions out of the sessions list and of a sign-out everywhere until they next expire. Use a store that doesn't evict, or the `database` driver, which is the default. - **Lockouts still reach new browsers.** Someone who knows a user's email can keep that account locked by guessing faster than the per-minute limit, and after 80 wrong passwords in a row (20 minutes at the quickest) the password is refused from every browser the account hasn't signed in from until its owner resets it. See [At the Cap](#at-the-cap). If they guess under one of the account's names and the owner types another, the owner is told the password is wrong rather than to wait, because saying more would tell a stranger the two names are one account. With `Features::devices()` on, browsers the owner has signed in from before keep their own limit and keep working. Without devices, the lock reaches every browser while the guessing goes on, and so does the cap. A password reset clears the password's counts and locks, but not a second factor's. - **Which browsers are known is kept in the cache.** A browser stops counting as known when the account is taken back, and that's recorded in the limiter's cache store with the mark a reset replaces. If the store loses its keys, a browser from before the reset counts as known again. It still can't pass the cap: known browsers and everyone else share it.