diff --git a/resources/boost/skills/saucebase-auth-development/SKILL.md b/resources/boost/skills/saucebase-auth-development/SKILL.md index 1b59104..3b9631e 100644 --- a/resources/boost/skills/saucebase-auth-development/SKILL.md +++ b/resources/boost/skills/saucebase-auth-development/SKILL.md @@ -18,7 +18,7 @@ Authentication, registration, magic link (passwordless), passkeys (WebAuthn, via | Service | `SocialiteService` — all OAuth logic (find/create user, link/disconnect accounts) | | Requests | `LoginRequest` (credential validation + rate limiting), `RegisterRequest` (password hashing in `passedValidation`), `UpdateProfileInfoRequest`, `UpdateProfileAvatarRequest`, `UpdatePasswordRequest` | | Exceptions | `AuthException` (credentials, throttle), `SocialiteException` (disconnect, account linking, provider validation, registration disabled) | -| Listeners | `AssignUserRole` (Registered), `UpdateUserLastLogin` (Login), `Impersonation` (`EnterImpersonation` — session history), `SendLoginNotification` (`ReturningUserAuthenticated`), `SendWelcomeNotification` (Registered) | +| Listeners | `AssignUserRole` (Registered), `UpdateUserLastLogin` (Login), `FingerprintPasswordlessSession` (Login), `Impersonation` (`EnterImpersonation` — session history), `SendLoginNotification` (`ReturningUserAuthenticated`), `SendWelcomeNotification` (Registered) | | Notifications | `WelcomeNotification` (Registered), `MagicLinkNotification` (passwordless login link with configured expiry), `LoginNotification` (new sign-in, only when `login_notification_enabled`), `PasskeyAddedNotification` (always, when a passkey is added) | | Events | `ReturningUserAuthenticated` — dispatched by password, magic-link and social sign-in, not by registration | | Middleware | `EnsureRegistrationEnabled`, `EnsureMagicLinkEnabled`, `EnsurePasskeysEnabled`, `EnsureSocialiteProviderEnabled` — each 404s its routes while the setting is off | @@ -59,8 +59,26 @@ changed. `email_verified_at` is deliberately **not** in the User model's `$filla request payload can grant itself a verified address; `SocialiteService` sets it with `forceFill()`. -Changing a password does **not** yet end other sessions — that needs `AuthenticateSession` -in the `web` group, which is an app-wide change awaiting a regression pass (sc-714). +### A Password Change Ends Every Other Session +`AuthServiceProvider::boot()` appends Laravel's `AuthenticateSession` to the `web` group: each +session keeps a fingerprint of the password hash and is signed out when it stops matching. So +a change (`PasswordController`), a reset and a magic-link takeover all end the other sessions +and remember-me cookies (sc-714). Registered by the module, like tenancy's guards: one an app +had to add by hand would fail open when forgotten. + +- `PasswordController::update()` saves the new hash, then calls `Auth::logoutOtherDevices()` + with the new password (it checks that password against the stored one, so the order matters): + this device's remember-me cookie is re-issued with the new hash, and the session regenerated. +- `AuthenticateSession` skips users with **no** password (social sign-ups). That is why the + magic-link takeover stores an unusable random password rather than null. +- Signing in stores no fingerprint for such a user either, so a first password would leave + their sessions open. `FingerprintPasswordlessSession` (on `Login`) stores the fingerprint of + no password instead, through the guard's own `hashPasswordForCookie(null)`: setting one then + ends those sessions like any change (sc-1259). Laravel's middleware is not replaced. +- Impersonation is unaffected: `stechstudio/filament-impersonate` clears the `password_hash_*` + keys on enter and leave. +- Tests stand in for another device with a session holding the old fingerprint: + `withSession(['password_hash_web' => Auth::guard('web')->hashPasswordForCookie($oldHash)])`. Note that `User` does not implement `MustVerifyEmail` (the import is commented out), so the `verified` middleware is currently a pass-through and the verification routes are not @@ -152,7 +170,7 @@ Uses `stechstudio/filament-impersonate`. Session stores history at `impersonatio `MagicLinkController::authenticate()` hashes the incoming token and consumes it in one atomic `UPDATE` (unused and unexpired only), so a link works once even under concurrent clicks, then logs in the user and redirects to the intended URL or home. -The link proves the inbox, so a magic sign-in to an **unverified** account marks it verified and clears, in one transaction, its password, remember token, connected providers and passkeys. Anyone can register someone else's address with a password of their own (pre-hijack) and, since `verified` lets an unverified user through, connect a provider or add a passkey too: none of it may outlive the owner's proof. A genuine social sign-up is unverified too (sc-713), so it loses its provider link at that proof and reconnects from Settings. A verified account keeps all of them. The account is locked and read again for that: if its address changed, or the link was voided, since the link was opened, it verifies nothing and signs no one in. The attacker's open sessions end only once sc-714 adds `AuthenticateSession`. +The link proves the inbox, so a magic sign-in to an **unverified** account marks it verified and, in one transaction, replaces its password with an unusable random one and clears its remember token, connected providers and passkeys. Anyone can register someone else's address with a password of their own (pre-hijack) and, since `verified` lets an unverified user through, connect a provider or add a passkey too: none of it may outlive the owner's proof. A genuine social sign-up is unverified too (sc-713), so it loses its provider link at that proof and reconnects from Settings. A verified account keeps all of them. The account is locked and read again for that: if its address changed, or the link was voided, since the link was opened, it verifies nothing and signs no one in. The new password ends the pre-registrant's open sessions (`AuthenticateSession`, above); the owner sets their own through "Forgot password". Changing a user's email through an Eloquent save deletes their outstanding magic links (`User::updated` in `AuthServiceProvider`), since a link proves only the inbox it reached. Query-builder and mass updates fire no model events and leave the links valid: such a write must delete the user's `MagicLinkToken` rows itself. `ProfileController::updateInfo()` saves the address, voids the links and drops the verification in one transaction. diff --git a/resources/js/vue/components/ForgotPasswordForm.vue b/resources/js/vue/components/ForgotPasswordForm.vue index 49bed5e..3d7133b 100644 --- a/resources/js/vue/components/ForgotPasswordForm.vue +++ b/resources/js/vue/components/ForgotPasswordForm.vue @@ -23,9 +23,11 @@ defineProps<{ data-testid="forgot-password-form" disable-while-processing :reset-on-success="['email']" + v-slot="{ errors }" > data-testid="login-form" disable-while-processing :reset-on-error="['password']" + v-slot="{ errors }" > { preserve-url :on-before="beforeProfileSave" :on-error="onProfileError" + v-slot="{ errors }" > { { disable-while-processing preserve-url :reset-on-success="true" + v-slot="{ errors }" > { { forceFill([ 'email_verified_at' => now(), - 'password' => null, + // Unusable, not null: `AuthenticateSession` skips users without a password, + // so null would leave the pre-registrant's sessions open. The owner sets + // their own through "Forgot password" (sc-714). + 'password' => Hash::make(Str::random(64)), 'remember_token' => Str::random(60), ])->save(); $locked->socialAccounts()->delete(); diff --git a/src/Http/Controllers/PasswordController.php b/src/Http/Controllers/PasswordController.php index d7f7c55..a8d3826 100644 --- a/src/Http/Controllers/PasswordController.php +++ b/src/Http/Controllers/PasswordController.php @@ -18,9 +18,14 @@ public function update(UpdatePasswordRequest $request): RedirectResponse { $user = Auth::user(); - $user->update([ - 'password' => Hash::make($request->validated()['password']), - ]); + $password = $request->validated()['password']; + $user->update(['password' => Hash::make($password)]); + + // Re-issues this device's remember-me cookie with the new hash (it checks the password + // it is given against the stored one, so it comes after the save): only the other + // devices keep the old fingerprint, and `AuthenticateSession` ends them. + Auth::logoutOtherDevices($password); + $request->session()->regenerate(); $user->notify(new PasswordChangedNotification); diff --git a/src/Listeners/FingerprintPasswordlessSession.php b/src/Listeners/FingerprintPasswordlessSession.php new file mode 100644 index 0000000..8ce2b49 --- /dev/null +++ b/src/Listeners/FingerprintPasswordlessSession.php @@ -0,0 +1,27 @@ +guard); + + if (! $guard instanceof SessionGuard || $event->user->getAuthPassword()) { + return; + } + + session()->put('password_hash_'.$event->guard, $guard->hashPasswordForCookie(null)); + } +} diff --git a/src/Notifications/WelcomeNotification.php b/src/Notifications/WelcomeNotification.php index 2a54557..acc9565 100644 --- a/src/Notifications/WelcomeNotification.php +++ b/src/Notifications/WelcomeNotification.php @@ -3,10 +3,12 @@ namespace Modules\Auth\Notifications; use Illuminate\Bus\Queueable; +use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Notification; -class WelcomeNotification extends Notification +/** Queued: sent in the request, a mail outage would stop registration's later listeners. */ +class WelcomeNotification extends Notification implements ShouldQueue { use Queueable; diff --git a/src/Providers/AuthServiceProvider.php b/src/Providers/AuthServiceProvider.php index 26144c1..aa4f5fc 100644 --- a/src/Providers/AuthServiceProvider.php +++ b/src/Providers/AuthServiceProvider.php @@ -5,7 +5,9 @@ use App\Models\User; use Filament\Facades\Filament; use Illuminate\Cache\RateLimiting\Limit; +use Illuminate\Contracts\Http\Kernel; use Illuminate\Http\Request; +use Illuminate\Session\Middleware\AuthenticateSession; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Gate; use Illuminate\Support\Facades\RateLimiter; @@ -38,6 +40,12 @@ public function boot(): void Gate::policy(User::class, UserPolicy::class); + // A session ends when its user's password changes (a change, a reset, a magic-link + // takeover): the session keeps a fingerprint of the hash and this compares it on every + // request. Registered here, like tenancy's guards: one an app had to add by hand would + // fail open when forgotten (sc-714). + $this->app->make(Kernel::class)->appendMiddlewareToGroup('web', AuthenticateSession::class); + // A magic link proves the inbox it was sent to. A new address voids the old links, // or one would sign in (and verify) an address it never reached. Every writer counts. User::updated(function (User $user): void { diff --git a/tests/Feature/MagicLinkTest.php b/tests/Feature/MagicLinkTest.php index 9fcd59e..8d5d06c 100644 --- a/tests/Feature/MagicLinkTest.php +++ b/tests/Feature/MagicLinkTest.php @@ -4,6 +4,8 @@ use App\Models\User; use Illuminate\Foundation\Testing\RefreshDatabase; +use Illuminate\Support\Facades\Auth; +use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Notification; use Illuminate\Support\Str; use Modules\Auth\Models\MagicLinkToken; @@ -111,10 +113,32 @@ public function test_a_magic_link_to_an_unverified_account_verifies_it_and_drops $user->refresh(); $this->assertAuthenticatedAs($user); $this->assertNotNull($user->email_verified_at); - $this->assertNull($user->password); + $this->assertFalse(Hash::check('attackers-password', (string) $user->password)); $this->assertNotSame($rememberToken, $user->remember_token); } + /** + * The pre-registrant may still be signed in elsewhere. A null password would leave that + * session open (`AuthenticateSession` skips users without one), so an unusable random one + * replaces it; the owner sets their own through "Forgot password" (sc-714). + */ + public function test_a_magic_link_signs_out_the_pre_registrants_open_sessions(): void + { + $user = User::factory()->unverified()->create(['password' => bcrypt('attackers-password')]); + $attacker = Auth::guard('web')->hashPasswordForCookie($user->getAuthPassword()); + $plainToken = Str::random(64); + MagicLinkToken::create(['user_id' => $user->id, 'token' => hash('sha256', $plainToken), 'expires_at' => now()->addMinutes(15)]); + + $this->get(route('magic-link.authenticate', $plainToken)); + + $this->flushSession(); + $this->actingAs($user->fresh()) + ->withSession(['password_hash_web' => $attacker]) + ->get(route('dashboard')) + ->assertRedirect(route('login')); + $this->assertGuest(); + } + /** * Before the proof, whoever registered the address could also connect their own provider * account or add a passkey (`verified` lets an unverified user through): neither outlives it. diff --git a/tests/Feature/PasswordResetTest.php b/tests/Feature/PasswordResetTest.php index c4ca129..82ee702 100644 --- a/tests/Feature/PasswordResetTest.php +++ b/tests/Feature/PasswordResetTest.php @@ -3,6 +3,7 @@ namespace Modules\Auth\Tests\Feature; use Illuminate\Foundation\Testing\RefreshDatabase; +use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Password; use Inertia\Testing\AssertableInertia as Assert; @@ -83,6 +84,40 @@ public function test_user_can_reset_password_with_valid_token(): void $this->assertTrue(Hash::check('newpassword123', $user->fresh()->getAuthPassword())); } + /** A reset is the way back in after a stolen password: the thief's session ends with it (sc-714). */ + public function test_a_password_reset_signs_out_sessions_on_other_devices(): void + { + $user = $this->createUser(); + $otherDevice = Auth::guard('web')->hashPasswordForCookie($user->getAuthPassword()); + + $this->post(route('password.store'), [ + 'token' => Password::createToken($user), + 'email' => $user->email, + 'password' => 'newpassword123', + 'password_confirmation' => 'newpassword123', + ])->assertRedirect(route('login')); + + $this->actingAs($user->fresh()) + ->withSession(['password_hash_web' => $otherDevice]) + ->get(route('dashboard')) + ->assertRedirect(route('login')); + $this->assertGuest(); + } + + /** Signing in stores the fingerprint itself: a session that never made a second request still ends. */ + public function test_a_session_that_only_signed_in_ends_when_the_password_changes(): void + { + $user = $this->createUser(); + + $this->post('/auth/login', ['email' => $user->email, 'password' => 'password']); + + $this->assertAuthenticatedAs($user); + $this->assertSame( + Auth::guard('web')->hashPasswordForCookie($user->getAuthPassword()), + session('password_hash_web'), + ); + } + public function test_reset_password_fails_with_invalid_token(): void { $user = $this->createUser(); diff --git a/tests/Feature/PasswordUpdateTest.php b/tests/Feature/PasswordUpdateTest.php index 5eebfac..2731a6d 100644 --- a/tests/Feature/PasswordUpdateTest.php +++ b/tests/Feature/PasswordUpdateTest.php @@ -3,6 +3,7 @@ namespace Modules\Auth\Tests\Feature; use Illuminate\Foundation\Testing\RefreshDatabase; +use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Notification; use Modules\Auth\Notifications\PasswordChangedNotification; @@ -29,6 +30,44 @@ public function test_user_can_update_password_with_correct_current_password(): v $this->assertTrue(Hash::check('newpassword123', $user->fresh()->getAuthPassword())); } + /** Whoever had the old password keeps no session after the change (sc-714). */ + public function test_changing_the_password_signs_out_other_sessions(): void + { + Notification::fake(); + $user = $this->createUser(); + $otherDevice = Auth::guard('web')->hashPasswordForCookie($user->getAuthPassword()); + + $this->actingAs($user)->put(route('settings.profile.password.update'), [ + 'current_password' => 'password', + 'password' => 'newpassword123', + 'password_confirmation' => 'newpassword123', + ])->assertSessionHasNoErrors()->assertRedirect(); + + $this->flushSession(); + $this->actingAs($user->fresh()) + ->withSession(['password_hash_web' => $otherDevice]) + ->get(route('dashboard')) + ->assertRedirect(route('login')); + $this->assertGuest(); + } + + /** The other half: the session that made the change stays signed in. */ + public function test_the_session_that_changed_the_password_stays_signed_in(): void + { + Notification::fake(); + $user = $this->createUser(); + + $this->actingAs($user)->get(route('dashboard')); + $this->put(route('settings.profile.password.update'), [ + 'current_password' => 'password', + 'password' => 'newpassword123', + 'password_confirmation' => 'newpassword123', + ])->assertSessionHasNoErrors()->assertRedirect(); + + $this->get(route('dashboard')); + $this->assertAuthenticatedAs($user); + } + /** Signed up through a provider: there is no current password to give, so none is asked. */ public function test_a_user_without_a_password_can_set_one(): void { @@ -39,11 +78,47 @@ public function test_a_user_without_a_password_can_set_one(): void $this->actingAs($user)->put(route('settings.profile.password.update'), [ 'password' => 'newpassword123', 'password_confirmation' => 'newpassword123', - ])->assertSessionHasNoErrors(); + ])->assertSessionHasNoErrors()->assertRedirect(); $this->assertTrue(Hash::check('newpassword123', $user->fresh()->getAuthPassword())); } + /** A session signed in while the account had no password ends when it gets one (sc-1259). */ + public function test_a_first_password_signs_out_sessions_opened_without_one(): void + { + Notification::fake(); + $user = $this->createUser(); + $user->forceFill(['password' => null])->save(); + + Auth::guard('web')->login($user); + $otherDevice = session('password_hash_web'); + $this->flushSession(); + + $this->actingAs($user)->put(route('settings.profile.password.update'), [ + 'password' => 'newpassword123', + 'password_confirmation' => 'newpassword123', + ])->assertSessionHasNoErrors()->assertRedirect(); + + $this->flushSession(); + $this->actingAs($user->fresh()) + ->withSession(['password_hash_web' => $otherDevice]) + ->get(route('dashboard')) + ->assertRedirect(route('login')); + $this->assertGuest(); + } + + /** Until then, nothing changes for an account without a password. */ + public function test_an_account_without_a_password_stays_signed_in(): void + { + $user = $this->createUser(); + $user->forceFill(['password' => null])->save(); + + Auth::guard('web')->login($user); + $this->withSession(['password_hash_web' => session('password_hash_web')])->get(route('dashboard')); + + $this->assertAuthenticatedAs($user); + } + /** Like adding a passkey: a password set while impersonating would outlive the impersonation. */ public function test_a_first_password_cannot_be_set_while_impersonating(): void { diff --git a/tests/Feature/RegisterTest.php b/tests/Feature/RegisterTest.php index 79f7a9e..1a0ebb1 100644 --- a/tests/Feature/RegisterTest.php +++ b/tests/Feature/RegisterTest.php @@ -3,6 +3,7 @@ namespace Modules\Auth\Tests\Feature; use App\Models\User; +use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Notification; @@ -166,6 +167,12 @@ public function test_welcome_notification_is_sent_on_registration(): void Notification::assertSentTo($user, WelcomeNotification::class); } + /** Sent in the request, a mail outage would stop the listeners after it: the role, the workspace. */ + public function test_the_welcome_notification_is_queued(): void + { + $this->assertInstanceOf(ShouldQueue::class, new WelcomeNotification); + } + public function test_registration_does_not_send_login_notification(): void { Notification::fake();