security: Andere Geräte abmelden, IP-weites Login-Limit, dauerhafte Sperrmarke, Passwortregeln, CSP im Melde-Modus

Restliche Phase 4 aus dem Sicherheitsaudit 07.10.2026:

- Sicherheitsseite: „Andere Geräte abmelden“ rotiert remember_token und
  beendet alle anderen Sessions, die aktuelle bleibt (nicht während einer
  Impersonation).
- LoginIpThrottle: 20 Fehlversuche je IP in 15 Minuten über alle Konten.
  Gezählt über das Failed-Event, damit Livewire-Login und Fortifys
  POST /login denselben Zähler teilen; Erfolg setzt ihn nicht zurück.
- Sperrmarke für Sessions in users.sessions_revoked_at_ms statt nur im
  Cache — übersteht cache:clear. Die alte Cache-Marke zählt übergangsweise
  mit und kann im nächsten Release entfallen.
- Neue und geänderte Passwörter: mindestens 12 Zeichen, in Produktion
  zusätzlich uncompromised() (HIBP, k-Anonymität). Bestehende bleiben gültig.
- Content-Security-Policy-Report-Only in Produktion; Meldungen über
  /csp-report nach storage/logs/csp-*.log, je Meldung höchstens einmal pro
  Stunde, ohne Query und tokenartige Pfadsegmente.

Migration: users.sessions_revoked_at_ms (users hat FULLTEXT, 25 MB, Sekunden).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kevin Adametz 2026-10-08 13:02:49 +00:00
parent f92d1e0462
commit c751d4e9d2
27 changed files with 601 additions and 39 deletions

View file

@ -25,8 +25,8 @@ test('a self registration is recorded in the activity log', function () {
Livewire::test('auth.register')
->set('name', 'Verlauf Tester')
->set('email', 'verlauf@example.com')
->set('password', 'password')
->set('password_confirmation', 'password')
->set('password', 'sicheres-passwort-2026')
->set('password_confirmation', 'sicheres-passwort-2026')
->set('terms_accepted', true)
->call('register');

View file

@ -1,11 +1,14 @@
<?php
use App\Actions\Admin\UserImpersonation;
use App\Enums\SecurityChange;
use App\Mail\SecurityChangeNotice;
use App\Models\MagicLink;
use App\Models\User;
use App\Services\Auth\SessionRevocation;
use Database\Seeders\RolesAndPermissionsSeeder;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\Route;
@ -131,3 +134,71 @@ test('livewire requests pass the session revocation check', function () {
expect($route)->not->toBeNull()
->and($route->gatherMiddleware())->toContain('web');
});
test('logging out other devices keeps this session and ends every other one', function () {
/** @var TestCase $this */
[$user, $otherSessionStamp] = accountWithOtherSession();
$this->actingAs($user)->withSession([SessionRevocation::SESSION_KEY => $otherSessionStamp]);
Livewire::test('customer.security')
->call('logoutOtherDevices')
->assertHasNoErrors();
$this->get(route('me.security'))->assertSuccessful();
$this->withSession([SessionRevocation::SESSION_KEY => $otherSessionStamp])
->get(route('me.security'))
->assertRedirect(route('login'));
$this->assertGuest();
// Remember-Cookies anderer Geräte werden ungültig, das Passwort bleibt.
$user->refresh();
expect($user->remember_token)->not->toBe('old-remember-token')
->and(Hash::check('password', $user->password))->toBeTrue()
->and($user->tokens()->count())->toBe(1);
});
test('other devices cannot be logged out during impersonation', function () {
/** @var TestCase $this */
[$user] = accountWithOtherSession();
$admin = User::factory()->create();
$this->actingAs($user)->withSession([UserImpersonation::SessionKey => $admin->id]);
Livewire::test('customer.security')
->call('logoutOtherDevices')
->assertForbidden();
expect($user->fresh()->remember_token)->toBe('old-remember-token')
->and($user->fresh()->sessions_revoked_at_ms)->toBeNull();
});
test('the revocation mark is stored on the account and survives a cache flush', function () {
/** @var TestCase $this */
[$user, $otherSessionStamp] = accountWithOtherSession();
$revokedAt = app(SessionRevocation::class)->revokeAllFor($user);
Cache::flush();
expect($user->fresh()->sessions_revoked_at_ms)->toBe($revokedAt);
$this->actingAs($user->fresh())
->withSession([SessionRevocation::SESSION_KEY => $otherSessionStamp])
->get(route('me.security'))
->assertRedirect(route('login'));
$this->assertGuest();
});
test('a revocation from before v1.6.0 that only lives in the cache still applies', function () {
/** @var TestCase $this */
[$user, $otherSessionStamp] = accountWithOtherSession();
Cache::put('auth.sessions-revoked-at.'.$user->id, now()->getTimestampMs(), now()->addHour());
$this->actingAs($user->fresh())
->withSession([SessionRevocation::SESSION_KEY => $otherSessionStamp])
->get(route('me.security'))
->assertRedirect(route('login'));
$this->assertGuest();
});

View file

@ -53,8 +53,8 @@ test('password can be reset with valid token', function () {
Notification::assertSentTo($user, ResetPassword::class, function ($notification) use ($user) {
$response = Livewire::test('auth.reset-password', ['token' => $notification->token])
->set('email', $user->email)
->set('password', 'password')
->set('password_confirmation', 'password')
->set('password', 'sicheres-passwort-2026')
->set('password_confirmation', 'sicheres-passwort-2026')
->call('resetPassword');
$response

View file

@ -25,8 +25,8 @@ test('new users register inactive and are sent to the verification notice', func
Livewire::test('auth.register')
->set('name', 'Test User')
->set('email', 'test@example.com')
->set('password', 'password')
->set('password_confirmation', 'password')
->set('password', 'sicheres-passwort-2026')
->set('password_confirmation', 'sicheres-passwort-2026')
->set('terms_accepted', true)
->call('register')
->assertHasNoErrors()
@ -55,8 +55,8 @@ test('registration requires accepting the terms', function () {
Livewire::test('auth.register')
->set('name', 'Test User')
->set('email', 'terms@example.com')
->set('password', 'password')
->set('password_confirmation', 'password')
->set('password', 'sicheres-passwort-2026')
->set('password_confirmation', 'sicheres-passwort-2026')
->set('terms_accepted', false)
->call('register')
->assertHasErrors(['terms_accepted']);

View file

@ -27,6 +27,7 @@ test('every topic channel writes its own daily file with the shared retention',
'ki' => ['ki', 'ki'],
'monitoring' => ['monitoring', 'monitoring'],
'market' => ['market', 'market'],
'csp' => ['csp', 'csp'],
'admin_slow' => ['admin_slow', 'admin-slow'],
]);

View file

@ -2,12 +2,18 @@
use App\Models\Company;
use App\Models\User;
use App\Services\Auth\LoginIpThrottle;
use Database\Seeders\RolesAndPermissionsSeeder;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Process;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rules\Password;
use Livewire\Livewire;
use Tests\TestCase;
@ -148,3 +154,138 @@ test('the test suite never sends real ntfy pushes', function () {
->and(config('monitoring.alerts.ntfy.topic'))->toBeEmpty()
->and(config('monitoring.alerts.ntfy.token'))->toBeEmpty();
});
test('too many failed logins from one ip block further logins for every account', function () {
/** @var TestCase $this */
$user = User::factory()->create(['is_active' => true]);
foreach (range(1, LoginIpThrottle::MAX_FAILURES) as $i) {
Livewire::test('auth.login')
->set('email', "unbekannt{$i}@example.test")
->set('password', 'falsches-passwort')
->call('login')
->assertHasErrors(['email']);
}
// Richtige Zugangsdaten eines anderen Kontos helfen von dieser IP nicht.
Livewire::test('auth.login')
->set('email', $user->email)
->set('password', 'password')
->call('login')
->assertHasErrors(['email']);
$this->assertGuest();
});
test('the fortify login post shares the per-ip limit', function () {
/** @var TestCase $this */
$user = User::factory()->create(['is_active' => true]);
foreach (range(1, LoginIpThrottle::MAX_FAILURES) as $i) {
$this->postJson('/login', ['email' => "unbekannt{$i}@example.test", 'password' => 'falsch'])->assertUnprocessable();
}
$this->postJson('/login', ['email' => $user->email, 'password' => 'password'])
->assertStatus(429)
->assertHeader('Retry-After');
$this->assertGuest();
});
test('failed logins below the per-ip limit do not block other accounts', function () {
/** @var TestCase $this */
$user = User::factory()->create(['is_active' => true]);
$throttle = app(LoginIpThrottle::class);
foreach (range(1, LoginIpThrottle::MAX_FAILURES - 1) as $i) {
$throttle->recordFailure('127.0.0.1');
}
Livewire::test('auth.login')
->set('email', $user->email)
->set('password', 'password')
->call('login')
->assertHasNoErrors();
$this->assertAuthenticatedAs($user);
});
test('new passwords need at least twelve characters', function () {
/** @var TestCase $this */
$user = User::factory()->create(['is_active' => true]);
$this->actingAs($user);
Livewire::test('customer.security')
->set('current_password', 'password')
->set('password', 'kurz-12345')
->set('password_confirmation', 'kurz-12345')
->call('updatePassword')
->assertHasErrors(['password']);
expect(Hash::check('password', $user->fresh()->password))->toBeTrue();
});
test('in production new passwords are checked against known leaks', function () {
$password = 'korrekt-pferd-batterie';
$hash = strtoupper(sha1($password));
Http::fake(['api.pwnedpasswords.com/range/'.substr($hash, 0, 5) => Http::response(substr($hash, 5).":42\r\n")]);
app()->instance('env', 'production');
try {
expect(Validator::make(['password' => $password], ['password' => Password::defaults()])->fails())->toBeTrue()
->and(Validator::make(['password' => 'ein-anderes-passwort'], ['password' => Password::defaults()])->fails())->toBeFalse();
} finally {
app()->instance('env', 'testing');
}
});
test('html responses carry a report-only content security policy when enabled', function () {
/** @var TestCase $this */
$this->get('https://presseecho.test/de')->assertHeaderMissing('Content-Security-Policy-Report-Only');
config()->set('security.csp.report_only', true);
$policy = $this->get('https://presseecho.test/de')
->assertHeaderMissing('Content-Security-Policy')
->headers->get('Content-Security-Policy-Report-Only');
expect($policy)->toContain("default-src 'self'")
->toContain("object-src 'none'")
->toContain("frame-ancestors 'self'")
->toContain('report-uri /csp-report');
$this->getJson('/api/v1/categories')->assertHeaderMissing('Content-Security-Policy-Report-Only');
});
test('csp reports are logged once per hour without query strings or tokens', function () {
/** @var TestCase $this */
config()->set('security.csp.report_only', true);
$logged = [];
Log::shouldReceive('channel')->with('csp')->andReturnSelf();
Log::shouldReceive('warning')->andReturnUsing(function (string $message, array $context) use (&$logged) {
$logged[] = $context;
});
$report = json_encode(['csp-report' => [
'document-uri' => 'https://pressekonto.test/magic-login/'.str_repeat('a1B2', 10).'?signature=geheim',
'effective-directive' => 'script-src-elem',
'blocked-uri' => 'https://evil.example/x.js?k=1',
'line-number' => 3,
]]);
foreach (range(1, 2) as $i) {
$this->call('POST', '/csp-report', [], [], [], ['CONTENT_TYPE' => 'application/csp-report'], $report)->assertNoContent();
}
expect($logged)->toHaveCount(1)
->and($logged[0]['document'])->toBe('https://pressekonto.test/magic-login/[Filtered]')
->and($logged[0]['blocked'])->toBe('https://evil.example/x.js')
->and($logged[0]['directive'])->toBe('script-src-elem');
$this->call('POST', '/csp-report', [], [], [], ['CONTENT_TYPE' => 'application/csp-report'], 'kein json')->assertNoContent();
expect($logged)->toHaveCount(1);
});

View file

@ -74,7 +74,7 @@ abstract class TestCase extends BaseTestCase
{
$testing = config('logging.channels.testing');
foreach (['billing', 'ki', 'monitoring', 'market'] as $channel) {
foreach (['billing', 'ki', 'monitoring', 'market', 'csp'] as $channel) {
config()->set("logging.channels.{$channel}", $testing);
}
}