diff --git a/composer.json b/composer.json index 145857d..bb0a27e 100644 --- a/composer.json +++ b/composer.json @@ -24,7 +24,7 @@ "aliases": {} }, "branch-alias": { - "dev-dev": "3.9.x-dev" + "dev-dev": "3.x-dev" } }, "autoload": { @@ -40,7 +40,7 @@ } }, "require": { - "saucebase/core": "^3.0", + "saucebase/core": "^3.1", "laravel/socialite": "^5.31", "stechstudio/filament-impersonate": "^5.6.1", "laravel/passkeys": "^0.2.1" diff --git a/database/seeders/ShowcaseAuthDatabaseSeeder.php b/database/seeders/ShowcaseAuthDatabaseSeeder.php index 39e7183..a841ba2 100644 --- a/database/seeders/ShowcaseAuthDatabaseSeeder.php +++ b/database/seeders/ShowcaseAuthDatabaseSeeder.php @@ -4,8 +4,11 @@ use App\Models\User; use Illuminate\Database\Seeder; +use Saucebase\Core\Attributes\DemoAccount; use Spatie\Permission\Models\Role; +#[DemoAccount('chef@saucebase.dev', 'admin, sees everything', featured: true)] +#[DemoAccount('support@saucebase.dev', 'support staff: users and impersonation')] class ShowcaseAuthDatabaseSeeder extends Seeder { /** diff --git a/resources/boost/skills/saucebase-auth-development/SKILL.md b/resources/boost/skills/saucebase-auth-development/SKILL.md index 27625db..1b59104 100644 --- a/resources/boost/skills/saucebase-auth-development/SKILL.md +++ b/resources/boost/skills/saucebase-auth-development/SKILL.md @@ -152,6 +152,10 @@ 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`. + +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. + `AuthSettings` is auto-discovered from `src/Settings`, with defaults installed from `database/settings`. Magic links are disabled by default, with a 15-minute expiry once switched on. Administrators manage both values through the `AuthenticationSettings` @@ -236,7 +240,7 @@ npx playwright test --project="@auth*" # E2E ## Gotchas - `LoginRequest::validateCredentials()` validates without logging in — the controller handles `Auth::login()` separately -- Social sign-ups get **no** password (`users.password` is nullable), so `disconnectProvider()` refuses to remove their only provider until they add one; a made-up password let them lock themselves out (sc-1132). They are **not** marked verified: signing in with a provider is not proof of the address, and nobody has confirmed it (sc-713) +- Social sign-ups get **no** password (`users.password` is nullable), so `disconnectProvider()` refuses to remove their only provider until they add one (the Security panel's password form asks for no current password while `has_password` is false, and `UpdatePasswordRequest` excludes it); a made-up password let them lock themselves out (sc-1132). They are **not** marked verified: signing in with a provider is not proof of the address, and nobody has confirmed it (sc-713) - `SocialAccount::provider_token` and `provider_refresh_token` are cast `encrypted` and `$hidden`: they let the app act on the provider as the user. `1000_00_00_000007` encrypts rows stored before the cast (sc-1132) - A guest's social sign-in never links to an existing **unverified** account with the same email (`SocialiteException::unverifiedAccount()`): anyone can register with someone else's address, and linking would hand that account, and whoever knows its password, to the provider's owner. They sign in as before and connect the provider from Settings (sc-1130) - Socialite redirect/callback routes are outside both guest and auth middleware groups @@ -245,3 +249,4 @@ npx playwright test --project="@auth*" # E2E - Magic link authenticate route is outside both guest and auth middleware groups (link is clicked from email client) - `modal_enabled` is presentation only. Turning it off does not change what the routes do, only how they are reached — the canonical URLs work either way, which is why there is no separate modal route. - `registration_enabled` closes both signup paths: `EnsureRegistrationEnabled` 404s the register routes, and `SocialiteService::handleCallback()` throws `registrationDisabled()` rather than creating a new user (existing users still sign in). Login is deliberately not toggleable — disabling it would lock out admins. +- **An invitation opens closed sign-up for one address.** Core's `RegistrationInvite` (session) is set by the inviting module (tenancy's invitation page). While it holds an address, `EnsureRegistrationEnabled` lets the register routes through, the page gets `by_invitation: {email}` and passes it to `RegisterForm` as `invitedEmail` (a modal's props are not `usePage()`'s; email fixed, providers hidden), `RegisterRequest` refuses any other address while sign-up is closed, and the account starts verified (the invitation reached that inbox). Registering forgets it. Social sign-up for invitees is not covered (`registrationDisabled()` still applies). diff --git a/resources/js/react/components/RegisterForm.tsx b/resources/js/react/components/RegisterForm.tsx index 57ba6e2..80a9f5d 100644 --- a/resources/js/react/components/RegisterForm.tsx +++ b/resources/js/react/components/RegisterForm.tsx @@ -21,14 +21,19 @@ interface RegisterFormProps { * modal sitting on top of wherever the visitor just landed. */ modal?: boolean; + /** Arrived from an invitation: the account is for this address, fixed. */ + invitedEmail?: string; } -export default function RegisterForm({ modal }: RegisterFormProps) { +export default function RegisterForm({ + modal, + invitedEmail, +}: RegisterFormProps) { const t = useT(); const [showPassword, setShowPassword] = useState(false); const { data, setData, post, processing, errors } = useForm({ name: '', - email: '', + email: invitedEmail ?? '', password: '', password_confirmation: '', terms: false, @@ -58,7 +63,17 @@ export default function RegisterForm({ modal }: RegisterFormProps) { return ( <> - + {/* An invitation is for its address; a provider could sign up another one. */} + {invitedEmail ? ( +

+ {t('You were invited as :email.', { email: invitedEmail })} +

+ ) : ( + + )}
setData('email', e.target.value)} /> diff --git a/resources/js/react/pages/Register.tsx b/resources/js/react/pages/Register.tsx index b79d377..e2ee1d8 100644 --- a/resources/js/react/pages/Register.tsx +++ b/resources/js/react/pages/Register.tsx @@ -6,10 +6,13 @@ import AuthCardLayout from '../layouts/AuthCardLayout'; interface RegisterProps { modal?: boolean; + /** Reached from an invitation: the address the account is for. */ + by_invitation?: { email: string } | null; } /** Registration, as a page or a modal. See `Login.tsx` for the reasoning. */ -export default function Register({ modal }: RegisterProps) { +export default function Register({ modal, by_invitation }: RegisterProps) { + const invitedEmail = by_invitation?.email; const t = useT(); const settings = useSettings(); @@ -21,7 +24,7 @@ export default function Register({ modal }: RegisterProps) { app: settings.general.site_name, })} > - + ); } @@ -40,7 +43,7 @@ export default function Register({ modal }: RegisterProps) {

- + ); diff --git a/resources/js/react/pages/SettingsSecurity.tsx b/resources/js/react/pages/SettingsSecurity.tsx index 236730a..b847d34 100644 --- a/resources/js/react/pages/SettingsSecurity.tsx +++ b/resources/js/react/pages/SettingsSecurity.tsx @@ -499,7 +499,12 @@ export default function SettingsSecurity({ {/* Password */}
-

{t('Update Password')}

+ {/* Signed up through a provider: there is no password yet to give. */} +

+ {user.has_password + ? t('Update Password') + : t('Set a password')} +

{t( 'Ensure your account is using a long, random password to stay secure.', @@ -517,13 +522,17 @@ export default function SettingsSecurity({ > {({ errors }) => ( <> - + {user.has_password && ( + + )} - {t('Update Password')} + {user.has_password + ? t('Update Password') + : t('Set a password')}

diff --git a/resources/js/vue/components/RegisterForm.vue b/resources/js/vue/components/RegisterForm.vue index 2137633..4e44cdd 100644 --- a/resources/js/vue/components/RegisterForm.vue +++ b/resources/js/vue/components/RegisterForm.vue @@ -15,6 +15,8 @@ const props = defineProps<{ * of this form — see `AuthLink`. */ modal?: boolean; + /** Arrived from an invitation: the account is for this address, fixed. */ + invitedEmail?: string; }>(); const currentModal = useModal(); @@ -32,8 +34,10 @@ function handleSuccess(): void { const page = usePage(); const termsError = computed(() => page.props.errors?.terms); +const invitedEmail = computed(() => props.invitedEmail); + const nameRef = ref(''); -const emailRef = ref(''); +const emailRef = ref(invitedEmail.value ?? ''); const passwordRef = ref(''); const termsRef = ref(false); @@ -47,7 +51,16 @@ const canSubmit = computed( diff --git a/resources/js/vue/pages/SettingsSecurity.vue b/resources/js/vue/pages/SettingsSecurity.vue index eb655c7..f383dd4 100644 --- a/resources/js/vue/pages/SettingsSecurity.vue +++ b/resources/js/vue/pages/SettingsSecurity.vue @@ -444,7 +444,14 @@ const initiateDisconnect = async (provider: string) => {
-

{{ $t('Update Password') }}

+ +

+ {{ + props.user.has_password + ? $t('Update Password') + : $t('Set a password') + }} +

{{ $t( @@ -463,6 +470,7 @@ const initiateDisconnect = async (provider: string) => { :reset-on-success="true" > {

diff --git a/src/Http/Controllers/MagicLinkController.php b/src/Http/Controllers/MagicLinkController.php index fe91e00..4a055f8 100644 --- a/src/Http/Controllers/MagicLinkController.php +++ b/src/Http/Controllers/MagicLinkController.php @@ -7,6 +7,7 @@ use Illuminate\Http\Request; use Illuminate\Routing\Controllers\HasMiddleware; use Illuminate\Routing\Controllers\Middleware; +use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; use Inertia\Inertia; use Inertia\Response; @@ -101,6 +102,38 @@ public function authenticate(Request $request, string $token): \Symfony\Componen return redirect()->route('login')->with('error', __('auth::auth.magic-link-expired')); } + // The link proves the inbox. An unverified account may have been registered by someone + // else with this address (pre-hijack): it becomes the inbox owner's, and nothing set + // before that proof still opens it: password, remember-me, a connected provider or a + // passkey (`verified` lets an unverified user add both). Their other sessions end with sc-714. + if ($user->email_verified_at === null) { + $proved = DB::transaction(function () use ($user, $record): bool { + // Read again under lock: an address changed since the link was opened is not + // the inbox it reached. A change of address voids its links as it commits. + $locked = User::lockForUpdate()->find($user->getKey()); + + if ($locked?->email !== $user->email || ! MagicLinkToken::whereKey($record->getKey())->exists()) { + return false; + } + + $locked->forceFill([ + 'email_verified_at' => now(), + 'password' => null, + 'remember_token' => Str::random(60), + ])->save(); + $locked->socialAccounts()->delete(); + $locked->passkeys()->delete(); + + return true; + }); + + if (! $proved) { + return redirect()->route('login')->with('error', __('auth::auth.magic-link-expired')); + } + + $user->refresh(); + } + $this->signIn($request, $user); $intended = $request->query('intended'); diff --git a/src/Http/Controllers/ProfileController.php b/src/Http/Controllers/ProfileController.php index a0db810..df3eb8c 100644 --- a/src/Http/Controllers/ProfileController.php +++ b/src/Http/Controllers/ProfileController.php @@ -3,6 +3,7 @@ namespace Modules\Auth\Http\Controllers; use Illuminate\Http\RedirectResponse; +use Illuminate\Support\Facades\DB; use Illuminate\Validation\ValidationException; use Modules\Auth\Http\Requests\UpdateProfileAvatarRequest; use Modules\Auth\Http\Requests\UpdateProfileInfoRequest; @@ -42,12 +43,16 @@ public function updateInfo(UpdateProfileInfoRequest $request): RedirectResponse ]); } - $user->update($request->validated()); + // One change: the new address, its old links voided (`User::updated`) and its + // verification dropped. A failure in any part keeps the old address as it was. + DB::transaction(function () use ($user, $request): void { + $user->update($request->validated()); - // A new address has not been confirmed, whatever the old one had earned. - if ($user->wasChanged('email')) { - $user->forceFill(['email_verified_at' => null])->save(); - } + // A new address has not been confirmed, whatever the old one had earned. + if ($user->wasChanged('email')) { + $user->forceFill(['email_verified_at' => null])->save(); + } + }); Toast::success(__('Profile updated successfully!')); diff --git a/src/Http/Controllers/RegisterController.php b/src/Http/Controllers/RegisterController.php index d51e0a7..80cc1c3 100644 --- a/src/Http/Controllers/RegisterController.php +++ b/src/Http/Controllers/RegisterController.php @@ -11,6 +11,7 @@ use InertiaUI\Modal\Modal; use Modules\Auth\Http\Requests\RegisterRequest; use Saucebase\Core\Facades\Home; +use Saucebase\Core\RegistrationInvite; use Saucebase\Core\Toast; class RegisterController extends Controller @@ -20,7 +21,11 @@ class RegisterController extends Controller */ public function create(): Response|Modal { - return $this->pageOrModal('Auth::Register'); + $invited = RegistrationInvite::email(); + + return $this->pageOrModal('Auth::Register', [ + 'by_invitation' => $invited === null ? null : ['email' => $invited], + ]); } /** @@ -33,6 +38,12 @@ public function store(RegisterRequest $request): RedirectResponse $data = $request->only(['name', 'email', 'password']); $user = User::create($data); + // The invitation reached this inbox: the address is proven, and the invite is used up. + if (RegistrationInvite::allows($user->email)) { + $user->forceFill(['email_verified_at' => now()])->save(); + RegistrationInvite::forget(); + } + event(new Registered($user)); Auth::login($user); diff --git a/src/Http/Controllers/SocialiteController.php b/src/Http/Controllers/SocialiteController.php index 8fa9035..0fde131 100644 --- a/src/Http/Controllers/SocialiteController.php +++ b/src/Http/Controllers/SocialiteController.php @@ -46,6 +46,12 @@ public function callback(Request $request, string $provider): RedirectResponse } catch (SocialiteException $e) { Toast::error($e->getMessage()); + return redirect()->route('login'); + } catch (\Exception $e) { + // A cancelled sign-in, a stale state or the provider failing: as in the linking flow above. + Toast::error(trans('auth::socialite.error')); + report($e); + return redirect()->route('login'); } diff --git a/src/Http/Middleware/EnsureRegistrationEnabled.php b/src/Http/Middleware/EnsureRegistrationEnabled.php index a8155d6..e82b463 100644 --- a/src/Http/Middleware/EnsureRegistrationEnabled.php +++ b/src/Http/Middleware/EnsureRegistrationEnabled.php @@ -5,6 +5,7 @@ use Closure; use Illuminate\Http\Request; use Modules\Auth\Settings\AuthSettings; +use Saucebase\Core\RegistrationInvite; class EnsureRegistrationEnabled { @@ -12,7 +13,8 @@ public function __construct(private readonly AuthSettings $settings) {} public function handle(Request $request, Closure $next): mixed { - abort_unless($this->settings->registration_enabled, 404); + // Closed sign-up still lets an invited address in; RegisterRequest holds it to that address. + abort_unless($this->settings->registration_enabled || RegistrationInvite::email() !== null, 404); return $next($request); } diff --git a/src/Http/Requests/RegisterRequest.php b/src/Http/Requests/RegisterRequest.php index 21efbdb..53fce55 100644 --- a/src/Http/Requests/RegisterRequest.php +++ b/src/Http/Requests/RegisterRequest.php @@ -7,6 +7,8 @@ use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Hash; use Illuminate\Validation\Rules; +use Modules\Auth\Settings\AuthSettings; +use Saucebase\Core\RegistrationInvite; class RegisterRequest extends FormRequest { @@ -27,7 +29,13 @@ public function rules(): array { return [ 'name' => 'required|string|max:255', - 'email' => 'required|string|email|max:255|unique:'.User::class, + // bail: the invitation check below takes a string. + 'email' => ['bail', 'required', 'string', 'email', 'max:255', 'unique:'.User::class, function (string $attribute, string $email, \Closure $fail): void { + // Sign-up is closed: only the address the invitation was sent to. + if (! app(AuthSettings::class)->registration_enabled && ! RegistrationInvite::allows($email)) { + $fail(__('Use the address the invitation was sent to.')); + } + }], 'password' => ['required', Rules\Password::defaults()], 'terms' => ['accepted'], ]; diff --git a/src/Http/Requests/UpdatePasswordRequest.php b/src/Http/Requests/UpdatePasswordRequest.php index 2fb5a2b..46b6ff9 100644 --- a/src/Http/Requests/UpdatePasswordRequest.php +++ b/src/Http/Requests/UpdatePasswordRequest.php @@ -5,15 +5,20 @@ use Illuminate\Contracts\Validation\ValidationRule; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Validation\Rules\Password; +use STS\FilamentImpersonate\ImpersonateManager; class UpdatePasswordRequest extends FormRequest { /** * Determine if the user is authorized to make this request. */ + /** + * A first password is refused while impersonating, as adding a passkey is: it would + * outlive the impersonation as a way back into the account. + */ public function authorize(): bool { - return true; + return $this->user()?->getAuthPassword() || ! app(ImpersonateManager::class)->isImpersonating(); } /** @@ -24,7 +29,8 @@ public function authorize(): bool public function rules(): array { return [ - 'current_password' => ['required', 'current_password'], + // A user who signed up through a provider has none to give, so none is asked. + 'current_password' => $this->user()?->getAuthPassword() ? ['required', 'current_password'] : ['exclude'], 'password' => ['required', Password::defaults(), 'confirmed'], ]; } diff --git a/src/Providers/AuthServiceProvider.php b/src/Providers/AuthServiceProvider.php index 58f33fb..26144c1 100644 --- a/src/Providers/AuthServiceProvider.php +++ b/src/Providers/AuthServiceProvider.php @@ -11,6 +11,7 @@ use Illuminate\Support\Facades\RateLimiter; use Inertia\Inertia; use Laravel\Passkeys\Passkeys; +use Modules\Auth\Models\MagicLinkToken; use Modules\Auth\Policies\UserPolicy; use Modules\Auth\Services\SocialiteService; use Modules\Auth\Settings\AuthSettings; @@ -37,6 +38,14 @@ public function boot(): void Gate::policy(User::class, UserPolicy::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 { + if ($user->wasChanged('email')) { + MagicLinkToken::query()->where('user_id', $user->getKey())->delete(); + } + }); + // `throttle:passkeys`: its own counter, so a sign-in (two requests) does not // share the per-address budget of password and magic-link sign-in. Keyed by // user, falling back to the address for guests. diff --git a/tests/Feature/MagicLinkTest.php b/tests/Feature/MagicLinkTest.php index 2a5c0ad..9fcd59e 100644 --- a/tests/Feature/MagicLinkTest.php +++ b/tests/Feature/MagicLinkTest.php @@ -2,6 +2,7 @@ namespace Modules\Auth\Tests\Feature; +use App\Models\User; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Notification; use Illuminate\Support\Str; @@ -93,6 +94,101 @@ public function test_user_can_authenticate_with_valid_token(): void $response->assertRedirect(route('dashboard')); } + /** + * Pre-hijack: anyone can register someone else's address with a password of their own. + * The link proves the inbox, so the account is the inbox owner's: verified, and nothing + * set before that proof (the password, remember-me) still opens it. + */ + public function test_a_magic_link_to_an_unverified_account_verifies_it_and_drops_its_password(): void + { + $user = User::factory()->unverified()->create(['password' => bcrypt('attackers-password')]); + $rememberToken = $user->remember_token; + $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)); + + $user->refresh(); + $this->assertAuthenticatedAs($user); + $this->assertNotNull($user->email_verified_at); + $this->assertNull($user->password); + $this->assertNotSame($rememberToken, $user->remember_token); + } + + /** + * 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. + */ + public function test_a_magic_link_to_an_unverified_account_drops_its_providers_and_passkeys(): void + { + $user = User::factory()->unverified()->create(); + $user->socialAccounts()->create(['provider' => 'github', 'provider_id' => 'attackers-github']); + $user->passkeys()->create(['name' => 'Attacker', 'credential_id' => 'abc', 'credential' => []]); + $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->assertSame(0, $user->socialAccounts()->count()); + $this->assertSame(0, $user->passkeys()->count()); + } + + /** + * The address changes while the link is being opened: the change commits after the + * account is read but before it is verified. The link reached the old inbox only, so the + * new address stays unverified and nobody is signed in. + */ + public function test_an_address_changed_while_the_link_opens_is_not_verified_by_it(): void + { + $user = User::factory()->unverified()->create(['email' => 'old@example.com']); + $plainToken = Str::random(64); + MagicLinkToken::create(['user_id' => $user->id, 'token' => hash('sha256', $plainToken), 'expires_at' => now()->addMinutes(15)]); + + $changed = false; + User::retrieved(function (User $retrieved) use (&$changed): void { + if (! $changed) { + $changed = true; + // Another request's change of address, committed: its links go with it. + User::whereKey($retrieved->id)->update(['email' => 'new@example.com']); + MagicLinkToken::where('user_id', $retrieved->id)->delete(); + } + }); + + $this->get(route('magic-link.authenticate', $plainToken))->assertRedirect(route('login')); + + $this->assertGuest(); + $this->assertNull($user->fresh()->email_verified_at); + } + + /** + * A link proves the inbox it was sent to. Once the address changes, an older link would + * vouch for the new one (and verify it), so changing the email voids outstanding links. + */ + public function test_changing_the_email_voids_outstanding_magic_links(): void + { + $user = User::factory()->create(); + $plainToken = Str::random(64); + MagicLinkToken::create(['user_id' => $user->id, 'token' => hash('sha256', $plainToken), 'expires_at' => now()->addMinutes(15)]); + + $user->forceFill(['email' => 'victim@example.com', 'email_verified_at' => null])->save(); + $this->get(route('magic-link.authenticate', $plainToken)); + + $this->assertGuest(); + $this->assertNull($user->fresh()->email_verified_at); + } + + /** A verified account's own password stays: it was set by the inbox owner. */ + public function test_a_magic_link_keeps_a_verified_accounts_password(): void + { + $user = User::factory()->create(['password' => bcrypt('my-password')]); + $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->assertTrue(password_verify('my-password', $user->fresh()->password)); + } + public function test_returning_user_receives_login_notification_after_magic_link_authentication(): void { Notification::fake(); diff --git a/tests/Feature/PasswordUpdateTest.php b/tests/Feature/PasswordUpdateTest.php index ffb4270..5eebfac 100644 --- a/tests/Feature/PasswordUpdateTest.php +++ b/tests/Feature/PasswordUpdateTest.php @@ -6,6 +6,7 @@ use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Notification; use Modules\Auth\Notifications\PasswordChangedNotification; +use STS\FilamentImpersonate\ImpersonateManager; use Tests\TestCase; class PasswordUpdateTest extends TestCase @@ -28,6 +29,46 @@ public function test_user_can_update_password_with_correct_current_password(): v $this->assertTrue(Hash::check('newpassword123', $user->fresh()->getAuthPassword())); } + /** 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 + { + Notification::fake(); + $user = $this->createUser(); + $user->forceFill(['password' => null])->save(); + + $this->actingAs($user)->put(route('settings.profile.password.update'), [ + 'password' => 'newpassword123', + 'password_confirmation' => 'newpassword123', + ])->assertSessionHasNoErrors(); + + $this->assertTrue(Hash::check('newpassword123', $user->fresh()->getAuthPassword())); + } + + /** 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 + { + $user = $this->createUser(); + $user->forceFill(['password' => null])->save(); + + $this->actingAs($user) + ->withSession([ImpersonateManager::SESSION_KEY => $this->createUser()->id]) + ->put(route('settings.profile.password.update'), ['password' => 'newpassword123', 'password_confirmation' => 'newpassword123']) + ->assertForbidden(); + + $this->assertNull($user->fresh()->password); + } + + /** Having one, it is still the proof asked for. */ + public function test_a_user_with_a_password_must_give_it(): void + { + $user = $this->createUser(); + + $this->actingAs($user)->put(route('settings.profile.password.update'), [ + 'password' => 'newpassword123', + 'password_confirmation' => 'newpassword123', + ])->assertSessionHasErrors('current_password'); + } + public function test_password_changed_notification_is_sent(): void { Notification::fake(); diff --git a/tests/Feature/ProfileTest.php b/tests/Feature/ProfileTest.php index 1a3e927..a79ba27 100644 --- a/tests/Feature/ProfileTest.php +++ b/tests/Feature/ProfileTest.php @@ -90,6 +90,26 @@ public function test_changing_the_email_clears_the_verified_timestamp(): void $this->assertNull($user->fresh()->email_verified_at); } + /** The new address and its unverified state are one change: a failure keeps neither. */ + public function test_a_failed_email_change_keeps_the_old_address(): void + { + $user = $this->createUser(); + $user->forceFill(['email_verified_at' => now()])->save(); + $email = $user->email; + User::updated(fn () => throw new \RuntimeException('lock wait timeout')); + + $this->withoutExceptionHandling(); + try { + $this->actingAs($user)->patch(route('settings.profile.update-info'), [ + 'name' => $user->name, + 'email' => 'moved@example.com', + ]); + } catch (\RuntimeException) { + } + + $this->assertSame($email, User::find($user->id)->email); + } + public function test_keeping_the_same_email_keeps_the_verified_timestamp(): void { $user = $this->createUser(); diff --git a/tests/Feature/RegisterTest.php b/tests/Feature/RegisterTest.php index f49b10b..79f7a9e 100644 --- a/tests/Feature/RegisterTest.php +++ b/tests/Feature/RegisterTest.php @@ -9,6 +9,7 @@ use Modules\Auth\Notifications\LoginNotification; use Modules\Auth\Notifications\WelcomeNotification; use Modules\Auth\Settings\AuthSettings; +use Saucebase\Core\RegistrationInvite; use Tests\TestCase; class RegisterTest extends TestCase @@ -44,6 +45,71 @@ public function test_user_cannot_register_when_registration_is_disabled(): void $this->assertDatabaseMissing('users', ['email' => 'test@example.com']); } + // ── Invited while sign-up is closed (RegistrationInvite, set by e.g. tenancy) ── + + /** @return array */ + /** A malformed address is a validation error, not a 500 from the invitation check. */ + public function test_an_email_that_is_not_a_string_is_a_validation_error(): void + { + $this->post(route('register'), [...$this->signUp(''), 'email' => ['ana@example.com']]) + ->assertSessionHasErrors('email'); + + $this->assertGuest(); + } + + private function signUp(string $email): array + { + return ['name' => 'Ana', 'email' => $email, 'password' => 'password123', 'terms' => true]; + } + + public function test_an_invited_guest_reaches_the_closed_register_page_with_their_address(): void + { + $this->disableRegistration(); + + $this->withSession(['saucebase.registration_invite' => 'ana@example.com']) + ->get(route('register')) + ->assertOk() + ->assertInertia(fn ($page) => $page->where('by_invitation.email', 'ana@example.com')); + } + + /** The invitation came to that inbox, so the account starts verified and the invite is used up. */ + public function test_an_invited_guest_registers_their_address_verified(): void + { + $this->disableRegistration(); + RegistrationInvite::allow('ana@example.com'); + + $this->post(route('register'), $this->signUp('Ana@example.com'))->assertRedirect(); + + $this->assertNotNull(User::where('email', 'ana@example.com')->sole()->email_verified_at); + $this->assertNull(RegistrationInvite::email()); + } + + /** An invitation for one address opens sign-up for that address only. */ + public function test_an_invited_guest_cannot_register_another_address(): void + { + $this->disableRegistration(); + RegistrationInvite::allow('ana@example.com'); + + $this->post(route('register'), $this->signUp('someone@else.com'))->assertInvalid('email'); + + $this->assertDatabaseMissing('users', ['email' => 'someone@else.com']); + } + + /** With sign-up open, an invited address still starts verified; anyone else signs up as usual. */ + public function test_with_sign_up_open_only_the_invited_address_starts_verified(): void + { + RegistrationInvite::allow('ana@example.com'); + + $this->post(route('register'), $this->signUp('bob@example.com'))->assertRedirect(); + + $this->assertNull(User::where('email', 'bob@example.com')->sole()->email_verified_at); + } + + public function test_the_register_page_has_no_invitation_without_one(): void + { + $this->get(route('register'))->assertInertia(fn ($page) => $page->where('by_invitation', null)); + } + private function disableRegistration(): void { $settings = app(AuthSettings::class); diff --git a/tests/Feature/ShowcaseStaffTest.php b/tests/Feature/ShowcaseStaffTest.php index 6e17ea0..88a5335 100644 --- a/tests/Feature/ShowcaseStaffTest.php +++ b/tests/Feature/ShowcaseStaffTest.php @@ -7,6 +7,7 @@ use Illuminate\Support\Facades\Hash; use Modules\Auth\Database\Seeders\DatabaseSeeder; use Modules\Auth\Database\Seeders\ShowcaseAuthDatabaseSeeder; +use Saucebase\Core\Testing\AssertsDemoAccounts; use Tests\TestCase; /** @@ -15,6 +16,7 @@ */ class ShowcaseStaffTest extends TestCase { + use AssertsDemoAccounts; use RefreshDatabase; public function test_the_demo_adds_a_staff_account_for_this_module_only(): void @@ -42,4 +44,10 @@ public function test_demo_accounts_use_the_configured_demo_password(): void $this->assertTrue(Hash::check('not-the-old-default', User::where('email', 'support@saucebase.dev')->value('password'))); } + + /** The accounts the seeder declares (#[DemoAccount]) are the ones it creates. */ + public function test_every_declared_demo_account_is_created(): void + { + $this->assertDemoAccountsSeeded(ShowcaseAuthDatabaseSeeder::class); + } } diff --git a/tests/Feature/SocialiteCallbackTest.php b/tests/Feature/SocialiteCallbackTest.php index d596d63..a4f8f81 100644 --- a/tests/Feature/SocialiteCallbackTest.php +++ b/tests/Feature/SocialiteCallbackTest.php @@ -12,6 +12,7 @@ use Illuminate\Support\Facades\Notification; use Laravel\Socialite\Facades\Socialite; use Laravel\Socialite\Two\AbstractProvider; +use Laravel\Socialite\Two\InvalidStateException; use Laravel\Socialite\Two\User as SocialiteUser; use Mockery\MockInterface; use Modules\Auth\Models\SocialAccount; @@ -62,6 +63,19 @@ private function mockSocialiteDriver(SocialiteUser $socialiteUser): void ); } + /** A cancelled sign-in or a stale state comes back as an error from Socialite: the guest is told, not shown a 500. */ + public function test_a_failed_provider_callback_sends_the_guest_back_to_login(): void + { + $this->enableGithub(); + Socialite::shouldReceive('driver')->with('github')->andReturn( + \Mockery::mock(AbstractProvider::class, fn (MockInterface $mock) => $mock->shouldReceive('user')->andThrow(new InvalidStateException)), + ); + + $this->get(route('auth.socialite.callback', ['provider' => 'github']))->assertRedirect(route('login')); + + $this->assertGuest(); + } + public function test_social_callback_does_not_create_user_when_registration_is_disabled(): void { $settings = $this->enableGithub();