feat(auth): harden authentication and add configurable two-factor support

This commit is contained in:
2026-07-31 03:12:46 +02:00
parent 235d5f646c
commit e47243f7dc
51 changed files with 2904 additions and 1359 deletions

View File

@@ -0,0 +1,226 @@
<?php
use App\Models\User;
use App\Notifications\PasswordChangedNotification;
use App\Notifications\QueuedResetPasswordNotification;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Password;
uses(RefreshDatabase::class);
beforeEach(function () {
config([
'auth-ui.features.email_verification' => false,
'auth-ui.features.two_factor_required' => false,
]);
});
it('returns the same password-reset response for existing and unknown accounts', function () {
Notification::fake();
$user = User::factory()->create(['email' => 'known@example.com']);
$expectedMessage = 'If an account exists for that email address, a password reset link has been sent.';
$this->post('/forgot-password', ['email' => 'known@example.com'])
->assertSessionHas('status', $expectedMessage)
->assertSessionDoesntHaveErrors();
$this->withServerVariables(['REMOTE_ADDR' => '192.0.2.2'])
->post('/forgot-password', ['email' => 'unknown@example.com'])
->assertSessionHas('status', $expectedMessage)
->assertSessionDoesntHaveErrors();
Notification::assertSentTo($user, QueuedResetPasswordNotification::class);
});
it('invalidates existing sessions and notifies the user after password reset', function () {
Notification::fake();
config(['session.driver' => 'database']);
$user = User::factory()->create(['email' => 'reset@example.com']);
DB::table('sessions')->insert([
[
'id' => 'existing-session-one',
'user_id' => $user->id,
'ip_address' => '192.0.2.10',
'user_agent' => 'Test',
'payload' => 'payload',
'last_activity' => now()->timestamp,
],
[
'id' => 'existing-session-two',
'user_id' => $user->id,
'ip_address' => '192.0.2.11',
'user_agent' => 'Test',
'payload' => 'payload',
'last_activity' => now()->timestamp,
],
]);
$token = Password::createToken($user);
$this->post('/reset-password', [
'token' => $token,
'email' => $user->email,
'password' => 'a completely new secure password',
'password_confirmation' => 'a completely new secure password',
])->assertRedirect('/login');
$user->refresh();
expect(DB::table('sessions')->where('user_id', $user->id)->count())->toBe(0)
->and(Hash::check('a completely new secure password', $user->password))->toBeTrue()
->and($user->auth_session_version)->toBe(1);
Notification::assertSentTo($user, PasswordChangedNotification::class);
});
it('stores new passwords with Argon2id', function () {
$this->post('/register', [
'username' => 'argon-user',
'first_name' => 'Argon',
'last_name' => 'User',
'email' => 'argon@example.com',
'password' => 'correct horse battery staple',
'password_confirmation' => 'correct horse battery staple',
])->assertRedirect('/dashboard');
$user = User::where('email', 'argon@example.com')->firstOrFail();
expect(password_get_info($user->password)['algoName'])->toBe('argon2id');
});
it('rejects new passwords shorter than fifteen characters', function () {
$this->post('/register', [
'username' => 'short-password',
'first_name' => 'Short',
'last_name' => 'Password',
'email' => 'short@example.com',
'password' => 'too-short',
'password_confirmation' => 'too-short',
])->assertSessionHasErrors('password');
$this->assertDatabaseMissing('users', ['email' => 'short@example.com']);
});
it('rejects password hashes created with an unexpected algorithm', function () {
$user = User::factory()->create(['email' => 'unexpected-hash@example.com']);
DB::table('users')->where('id', $user->id)->update([
'password' => password_hash('correct-password', PASSWORD_BCRYPT, ['cost' => 4]),
]);
$this->post('/login', [
'login' => 'unexpected-hash@example.com',
'password' => 'correct-password',
])->assertSessionHasErrors('login');
$this->assertGuest();
expect(password_get_info($user->fresh()->password)['algoName'])->toBe('bcrypt');
});
it('enforces account-aware login throttling across different IP addresses', function () {
User::factory()->create([
'email' => 'limited@example.com',
'password' => 'correct-password',
]);
foreach (range(1, 10) as $attempt) {
$this->withServerVariables(['REMOTE_ADDR' => "192.0.2.{$attempt}"])
->post('/login', [
'login' => 'limited@example.com',
'password' => 'wrong-password',
])
->assertSessionHasErrors('login');
}
$this->withServerVariables(['REMOTE_ADDR' => '192.0.2.11'])
->post('/login', [
'login' => 'limited@example.com',
'password' => 'wrong-password',
])
->assertTooManyRequests();
});
it('adds browser security headers and prevents caching secret-bearing pages', function () {
$this->get('/')
->assertHeader('X-Content-Type-Options', 'nosniff')
->assertHeader('X-Frame-Options', 'DENY')
->assertHeader('Referrer-Policy', 'strict-origin-when-cross-origin')
->assertHeader('Permissions-Policy');
$response = $this->get('/login')
->assertHeader('Cache-Control')
->assertHeader('Pragma', 'no-cache');
expect($response->headers->get('Cache-Control'))->toContain('no-store');
});
it('adds CSP and HSTS to secure production responses', function () {
$previousEnvironment = $this->app->environment();
$this->app->instance('env', 'production');
try {
$this->withServerVariables([
'HTTPS' => 'on',
'REQUEST_SCHEME' => 'https',
'SERVER_PORT' => 443,
])
->get('https://localhost/')
->assertHeader('Content-Security-Policy')
->assertHeader(
'Strict-Transport-Security',
'max-age=63072000; includeSubDomains; preload'
);
} finally {
$this->app->instance('env', $previousEnvironment);
}
});
it('ends an authenticated session at its absolute expiry', function () {
$user = User::factory()->create();
$this->actingAs($user)
->withSession(['auth.absolute_expires_at' => now()->subSecond()->timestamp])
->get('/dashboard')
->assertRedirect('/login')
->assertSessionHas('error', 'Your session has expired. Please sign in again.');
$this->assertGuest();
});
it('records the session version and absolute expiry after login', function () {
$user = User::factory()->create([
'email' => 'session-version@example.com',
'password' => 'correct horse battery staple',
'auth_session_version' => 3,
]);
$response = $this->post('/login', [
'login' => $user->email,
'password' => 'correct horse battery staple',
])->assertRedirect('/dashboard')
->assertSessionHas('auth.session_version', 3);
expect($response->getSession()->get('auth.absolute_expires_at'))
->toBeGreaterThan(now()->timestamp);
});
it('revokes an authenticated session when its user session version is stale', function () {
$user = User::factory()->create(['auth_session_version' => 2]);
$this->actingAs($user)
->withSession([
'auth.session_version' => 1,
'auth.absolute_expires_at' => now()->addHour()->timestamp,
])
->get('/dashboard')
->assertRedirect('/login')
->assertSessionHas(
'error',
'Your session is no longer valid. Please sign in again.'
);
$this->assertGuest();
});

View File

@@ -8,6 +8,10 @@ use Illuminate\Support\Facades\URL;
uses(RefreshDatabase::class);
beforeEach(function () {
config(['auth-ui.features.two_factor_required' => false]);
});
it('does not send verification email when feature is disabled', function () {
config(['auth-ui.features.email_verification' => false]);
@@ -18,8 +22,8 @@ it('does not send verification email when feature is disabled', function () {
'first_name' => 'Test',
'last_name' => 'User',
'email' => 'test@example.com',
'password' => 'password123',
'password_confirmation' => 'password123',
'password' => 'correct horse battery staple',
'password_confirmation' => 'correct horse battery staple',
]);
Notification::assertNothingSent();
@@ -35,8 +39,8 @@ it('sends verification email when feature is enabled', function () {
'first_name' => 'Test',
'last_name' => 'User',
'email' => 'test@example.com',
'password' => 'password123',
'password_confirmation' => 'password123',
'password' => 'correct horse battery staple',
'password_confirmation' => 'correct horse battery staple',
]);
$user = User::where('email', 'test@example.com')->first();
@@ -135,8 +139,8 @@ it('redirects to verification notice after registration when feature is enabled'
'first_name' => 'New',
'last_name' => 'User',
'email' => 'new@example.com',
'password' => 'password123',
'password_confirmation' => 'password123',
'password' => 'correct horse battery staple',
'password_confirmation' => 'correct horse battery staple',
])->assertRedirect('/email/verify');
});
@@ -148,7 +152,7 @@ it('redirects to home after registration when feature is disabled', function ()
'first_name' => 'New',
'last_name' => 'User',
'email' => 'new@example.com',
'password' => 'password123',
'password_confirmation' => 'password123',
'password' => 'correct horse battery staple',
'password_confirmation' => 'correct horse battery staple',
])->assertRedirect('/dashboard');
});

View File

@@ -5,6 +5,10 @@ use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function () {
config(['auth-ui.features.two_factor_required' => false]);
});
it('allows login with email and password', function () {
$user = User::factory()->create([
'email' => 'test@example.com',

View File

@@ -9,6 +9,7 @@ use Laravel\Socialite\Two\User as SocialiteUser;
uses(RefreshDatabase::class);
beforeEach(function () {
config(['auth-ui.features.two_factor_required' => false]);
config(['auth-ui.providers.github' => [
'label' => 'GitHub',
'icon' => 'i-simple-icons-github',

View File

@@ -1,8 +1,11 @@
<?php
use App\Models\User;
use App\Notifications\TwoFactorFailedNotification;
use App\Notifications\TwoFactorSecurityNotification;
use Database\Seeders\DatabaseSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Notification;
use Inertia\Testing\AssertableInertia as Assert;
use Laravel\Fortify\Actions\EnableTwoFactorAuthentication;
use Laravel\Fortify\Features;
@@ -18,7 +21,11 @@ beforeEach(function () {
'auth-ui.features.two_factor' => true,
'auth-ui.features.two_factor_required' => false,
'fortify.features' => [Features::twoFactorAuthentication()],
'fortify-options.two-factor-authentication' => ['confirm' => true],
'fortify-options.two-factor-authentication' => [
'confirm' => true,
'secret-length' => 32,
'window' => 0,
],
'auth-ui.providers.github' => [
'label' => 'GitHub',
'icon' => 'i-simple-icons-github',
@@ -81,12 +88,19 @@ it('redirects authenticated users to enrollment when two-factor setup is mandato
$this->actingAs($user)
->get('/dashboard')
->assertRedirect('/profile')
->assertRedirect('/two-factor-setup')
->assertSessionHas('error', 'Two-factor authentication is required before you can continue.');
$this->actingAs($user)
->get('/two-factor-setup')
->assertInertia(fn (Assert $page) => $page
->component('Auth/TwoFactorSetup')
->where('twoFactor.enabled', false)
->where('twoFactor.pending', false));
$this->actingAs($user)
->get('/profile')
->assertOk();
->assertRedirect('/two-factor-setup');
$this->actingAs($user)
->post('/logout')
@@ -94,20 +108,63 @@ it('redirects authenticated users to enrollment when two-factor setup is mandato
$this->assertGuest();
});
it('sends a password user directly to setup after login when enrollment is mandatory', function () {
config(['auth-ui.features.two_factor_required' => true]);
$user = User::factory()->create([
'email' => 'setup@example.com',
'password' => 'password123',
]);
$this->post('/login', [
'login' => 'setup@example.com',
'password' => 'password123',
])->assertRedirect('/two-factor-setup');
$this->assertAuthenticatedAs($user);
expect(session('url.intended'))->toEndWith('/dashboard');
});
it('keeps application access restricted while mandatory enrollment is pending', function () {
config(['auth-ui.features.two_factor_required' => true]);
$user = User::factory()->create(['password' => 'password123']);
$this->actingAs($user)
->post('/profile/two-factor', ['password' => 'password123'])
->assertRedirect('/profile');
->post('/two-factor-setup', ['password' => 'password123'])
->assertRedirect('/two-factor-setup');
expect($user->fresh()->two_factor_secret)->not->toBeNull()
->and($user->fresh()->hasEnabledTwoFactorAuthentication())->toBeFalse();
$this->actingAs($user)
->get('/dashboard')
->assertRedirect('/profile');
->assertRedirect('/two-factor-setup');
});
it('shows recovery codes before continuing after mandatory setup', function () {
config(['auth-ui.features.two_factor_required' => true]);
$user = User::factory()->create();
app(EnableTwoFactorAuthentication::class)($user);
$user->refresh();
$secret = Fortify::currentEncrypter()->decrypt($user->two_factor_secret);
$code = app(Google2FA::class)->getCurrentOtp($secret);
$this->actingAs($user)
->withSession(['url.intended' => '/dashboard'])
->post('/two-factor-setup/confirm', ['code' => $code])
->assertRedirect('/two-factor-setup')
->assertSessionHas('recoveryCodes', fn (array $codes) => count($codes) === 8);
$this->actingAs($user->fresh())
->get('/two-factor-setup')
->assertInertia(fn (Assert $page) => $page
->component('Auth/TwoFactorSetup')
->where('twoFactor.enabled', true));
$this->actingAs($user->fresh())
->withSession(['url.intended' => '/dashboard'])
->get('/two-factor-setup/complete')
->assertRedirect('/dashboard');
});
it('allows normal access after mandatory enrollment is complete', function () {
@@ -120,6 +177,21 @@ it('allows normal access after mandatory enrollment is complete', function () {
->assertOk();
});
it('does not allow mandatory two-factor authentication to be disabled', function () {
config(['auth-ui.features.two_factor_required' => true]);
$user = User::factory()->create(['password' => 'password123']);
$twoFactor = enableTwoFactorForTest($user);
$this->actingAs($user)
->delete('/profile/two-factor', [
'password' => 'password123',
'code' => $twoFactor['code'],
])
->assertForbidden();
expect($user->fresh()->hasEnabledTwoFactorAuthentication())->toBeTrue();
});
it('does not enforce the mandatory flag while the main two-factor feature is disabled', function () {
config([
'auth-ui.features.two_factor' => false,
@@ -131,6 +203,20 @@ it('does not enforce the mandatory flag while the main two-factor feature is dis
->assertOk();
});
it('does not expose mandatory setup endpoints when enrollment is optional', function () {
$user = User::factory()->create(['password' => 'password123']);
$this->actingAs($user)
->get('/two-factor-setup')
->assertNotFound();
$this->actingAs($user)
->post('/two-factor-setup', ['password' => 'password123'])
->assertNotFound();
expect($user->fresh()->two_factor_secret)->toBeNull();
});
it('blocks authenticated API requests until mandatory enrollment is complete', function () {
config(['auth-ui.features.two_factor_required' => true]);
$user = User::factory()->create();
@@ -140,7 +226,7 @@ it('blocks authenticated API requests until mandatory enrollment is complete', f
->assertForbidden()
->assertJson([
'message' => 'Two-factor authentication setup is required.',
'setup_url' => route('profile.show'),
'setup_url' => route('two-factor.setup'),
]);
enableTwoFactorForTest($user);
@@ -195,6 +281,7 @@ it('confirms enrollment and returns recovery codes once', function () {
});
it('holds password login until a valid authenticator code is supplied', function () {
Notification::fake();
$user = User::factory()->create([
'email' => 'test@example.com',
'password' => 'password123',
@@ -216,6 +303,7 @@ it('holds password login until a valid authenticator code is supplied', function
$this->post('/two-factor-challenge', ['code' => '000000'])
->assertSessionHasErrors('code');
$this->assertGuest();
Notification::assertSentTo($user, TwoFactorFailedNotification::class);
$challengeResponse = $this->post('/two-factor-challenge', ['code' => $twoFactor['code']]);
$challengeResponse->assertRedirect('/dashboard');
@@ -283,6 +371,94 @@ it('requires a valid second factor for social-only users to disable protection',
expect($user->fresh()->hasEnabledTwoFactorAuthentication())->toBeFalse();
});
it('requires both password and second factor for password users to disable protection', function () {
Notification::fake();
$user = User::factory()->create(['password' => 'password123']);
$twoFactor = enableTwoFactorForTest($user);
$this->actingAs($user)
->delete('/profile/two-factor', ['password' => 'password123'])
->assertSessionHasErrors('code');
expect($user->fresh()->hasEnabledTwoFactorAuthentication())->toBeTrue();
$this->actingAs($user)
->delete('/profile/two-factor', [
'password' => 'password123',
'code' => $twoFactor['code'],
])
->assertRedirect('/profile');
expect($user->fresh()->hasEnabledTwoFactorAuthentication())->toBeFalse();
Notification::assertSentTo($user, TwoFactorSecurityNotification::class);
});
it('requires both password and second factor to reveal recovery codes', function () {
$user = User::factory()->create(['password' => 'password123']);
$twoFactor = enableTwoFactorForTest($user);
$this->actingAs($user)
->post('/profile/two-factor/recovery-codes', [
'password' => 'password123',
'regenerate' => false,
])
->assertSessionHasErrors('code');
$this->actingAs($user)
->post('/profile/two-factor/recovery-codes', [
'password' => 'password123',
'code' => $twoFactor['code'],
'regenerate' => false,
])
->assertRedirect('/profile')
->assertSessionHas('recoveryCodes');
});
it('expires an unfinished second-factor login after five minutes', function () {
$user = User::factory()->create([
'email' => 'expires@example.com',
'password' => 'password123',
]);
enableTwoFactorForTest($user);
$this->post('/login', [
'login' => 'expires@example.com',
'password' => 'password123',
])->assertRedirect('/two-factor-challenge');
$this->travel(301)->seconds();
$this->get('/two-factor-challenge')
->assertRedirect('/login')
->assertSessionMissing('login.id')
->assertSessionMissing('login.started_at');
});
it('does not accept the same TOTP twice', function () {
$user = User::factory()->create([
'email' => 'replay@example.com',
'password' => 'password123',
]);
$twoFactor = enableTwoFactorForTest($user);
$this->post('/login', [
'login' => 'replay@example.com',
'password' => 'password123',
])->assertRedirect('/two-factor-challenge');
$this->post('/two-factor-challenge', ['code' => $twoFactor['code']])
->assertRedirect('/dashboard');
$this->post('/logout');
$this->post('/login', [
'login' => 'replay@example.com',
'password' => 'password123',
])->assertRedirect('/two-factor-challenge');
$this->post('/two-factor-challenge', ['code' => $twoFactor['code']])
->assertSessionHasErrors('code');
$this->assertGuest();
});
it('consumes recovery codes used to authorize a sensitive settings action', function () {
$user = User::factory()->social()->create();
$twoFactor = enableTwoFactorForTest($user);

View File

@@ -1,5 +1,7 @@
<?php
use Tests\TestCase;
/*
|--------------------------------------------------------------------------
| Test Case
@@ -11,7 +13,7 @@
|
*/
pest()->extend(Tests\TestCase::class)
pest()->extend(TestCase::class)
// ->use(Illuminate\Foundation\Testing\RefreshDatabase::class)
->in('Feature');