$ip]; } function failLogin(string $ip, int $times = 1): void { for ($i = 0; $i < $times; $i++) { request()->server->set('REMOTE_ADDR', $ip); event(new Failed('web', null, ['email' => 'nobody@example.com'])); } } describe('what is switched on', function () { it('has the tables, routes and rights of the audit log', function () { expect(Route::has('manager.audit.index'))->toBeTrue() ->and(Schema::hasTable('manager_audit_logs'))->toBeTrue() ->and(Schema::hasTable('manager_ip_bans'))->toBeTrue() ->and(Manager::permissionValues())->toContain('audit.view', 'audit.manage'); }); it('gives every route of the manager a name in the log', function () { $labelled = [...array_keys(Manager::actions()), ...array_keys(Manager::views())]; $missing = collect(Route::getRoutes()->getRoutes()) ->filter(fn ($route) => str_starts_with($route->uri(), config('manager.path').'/') || $route->uri() === config('manager.path')) ->map(fn ($route) => $route->getName()) ->filter(fn ($name) => is_string($name) && str_starts_with($name, 'manager.')) ->map(fn ($name) => substr($name, 8)) // The login and the built files are outside `auth` (nobody is known there); a logout is logged by Laravel's Logout event. ->reject(fn ($name) => $name === '' || in_array($name, [...$labelled, 'assets', 'login', 'login.store', 'logout'], true)) ->values()->all(); expect($missing)->toBe([]); }); }); describe('logins', function () { it('writes down a login, a logout and a failed login', function () { $user = makeUser(name: 'Ada'); event(new Login('web', $user, false)); event(new Logout('web', $user)); event(new Failed('web', $user, ['email' => $user->email])); expect(AuditLog::orderBy('id')->pluck('event')->all())->toBe(['login', 'logout', 'login_failed']); expect(AuditLog::where('event', 'login')->sole()->user_name)->toBe('Ada'); expect(AuditLog::where('event', 'login_failed')->sole()->email)->toBe($user->email); }); it('bans an address after too many failed logins, and not one that is never banned', function () { failLogin('10.0.0.5', 9); expect(IpBan::count())->toBe(0); failLogin('10.0.0.5'); $ban = IpBan::sole(); expect($ban->ip)->toBe('10.0.0.5')->and($ban->automatic)->toBeTrue()->and($ban->whole_site)->toBeFalse(); failLogin('10.9.9.9', 30); expect(IpBan::where('ip', '10.9.9.9')->exists())->toBeFalse(); }); it('does not ban by itself when the rule is off', function () { AuditSetting::current()->forceFill(['id' => 1, 'auto_ban' => false])->save(); failLogin('10.0.0.6', 30); expect(IpBan::count())->toBe(0); }); }); describe('what an account does', function () { beforeEach(fn () => $this->actingAs(makeUser(['posts.view', 'posts.write'], name: 'Writer'))); it('writes down a change with what it made', function () { $this->postJson('/manager/posts', ['title' => 'Hello', 'body' => 'Text', 'is_published' => false])->assertCreated(); $line = AuditLog::where('event', 'action')->sole(); expect($line->summary)->toBe('Created a post') ->and($line->user_name)->toBe('Writer') ->and($line->subject_type)->toBe('post') ->and($line->subject_label)->toBe('Hello') ->and($line->ip)->not->toBeNull(); }); it('writes down a page that is opened once within five minutes', function () { $this->getJson('/manager/posts')->assertOk(); $this->getJson('/manager/posts')->assertOk(); expect(AuditLog::where('event', 'viewed')->sole()->summary)->toBe('Opened the posts'); }); it('writes down what the account was not allowed to do, and not a form with a mistake', function () { $this->deleteJson('/manager/posts/1')->assertForbidden(); $this->postJson('/manager/posts', [])->assertStatus(422); expect(AuditLog::where('event', 'refused')->sole()->summary)->toBe('Was not allowed: deleted a post') ->and(AuditLog::where('event', 'action')->count())->toBe(0); }); it('never keeps what was typed, only the fields a module listed', function () { $this->actingAs(makeUser(['posts.view', 'posts.labels'])); $this->postJson('/manager/labels', ['type' => 'tag', 'name' => 'secret-ish', 'password' => 'hunter2'])->assertCreated(); $line = AuditLog::where('action', 'labels.store')->sole(); expect($line->details)->toBe(['input' => ['type' => 'tag', 'name' => 'secret-ish']]); expect(json_encode(AuditLog::all()))->not->toContain('hunter2'); }); }); describe('subjects of changes and deletes', function () { it('names what was changed and what was deleted', function () { $this->actingAs(makeUser(['posts.view', 'posts.write', 'posts.delete'], name: 'Editor')); $post = Post::create(['title' => 'Old title', 'slug' => 'old', 'body' => 'x']); $this->putJson("/manager/posts/{$post->id}", ['title' => 'New title', 'body' => 'x', 'is_published' => false])->assertOk(); $this->deleteJson("/manager/posts/{$post->id}")->assertOk(); expect(AuditLog::where('action', 'posts.update')->sole()->subject_label)->toBe('New title') ->and(AuditLog::where('action', 'posts.destroy')->sole()->subject_label)->toBe('New title'); }); }); describe('the prune schedule', function () { it('runs daily when the audit log is on', function () { $commands = collect(app(Schedule::class)->events())->map(fn ($event) => $event->command)->implode(' '); expect($commands)->toContain('manager:audit-prune'); }); }); describe('seeing the log', function () { it('needs audit.view', function () { $this->actingAs(makeUser()); $this->getJson('/manager/audit')->assertForbidden(); $this->actingAs(makeUser(['audit.view'])); $this->getJson('/manager/audit')->assertOk()->assertJsonPath('can_manage', false); }); it('filters the lines and pages through them', function () { $user = makeUser(['audit.view'], name: 'Viewer'); event(new Failed('web', null, ['email' => 'a@example.com'])); event(new Login('web', $user, false)); $this->actingAs($user); $this->getJson('/manager/audit?show=failed')->assertOk() ->assertJsonCount(1, 'entries')->assertJsonPath('entries.0.event', 'login_failed') ->assertJsonPath('summary.logins', 1)->assertJsonPath('summary.failed', 1); }); it('links a line to its post only while the post exists', function () { $post = Post::create(['title' => 'Linked', 'slug' => 'linked', 'body' => 'x']); $this->actingAs(makeUser(['audit.view', 'posts.write'])); $this->postJson('/manager/posts', ['title' => 'Another', 'body' => 'x', 'is_published' => false])->assertCreated(); $url = $this->getJson('/manager/audit?show=actions')->json('entries.0.subject.url'); expect($url)->toBe('/manager/posts/'.Post::where('title', 'Another')->value('id').'/edit')->and($post->exists)->toBeTrue(); }); }); describe('bans', function () { beforeEach(fn () => $this->actingAs(makeUser(['audit.view', 'audit.manage'], name: 'Boss'))); it('bans by hand, writes it down, and lifts it again', function () { $this->postJson('/manager/audit/bans', ['ip' => '10.1.1.1', 'reason' => 'Scraper', 'minutes' => 0])->assertCreated(); $ban = IpBan::sole(); expect($ban->automatic)->toBeFalse()->and($ban->expires_at)->toBeNull()->and($ban->user_name)->toBe('Boss'); expect(AuditLog::where('action', 'audit.bans.store')->sole()->subject_label)->toBe('10.1.1.1'); $this->deleteJson("/manager/audit/bans/{$ban->id}")->assertOk(); expect(IpBan::count())->toBe(0); }); it('needs audit.manage to ban', function () { $this->actingAs(makeUser(['audit.view'])); $this->postJson('/manager/audit/bans', ['ip' => '10.1.1.1', 'minutes' => 0])->assertForbidden(); }); it('refuses to ban yourself or an address that is never banned', function () { $this->postJson('/manager/audit/bans', ['ip' => '127.0.0.1', 'minutes' => 0])->assertStatus(422)->assertJsonValidationErrors('ip'); $this->postJson('/manager/audit/bans', ['ip' => '10.9.9.9', 'minutes' => 0])->assertStatus(422)->assertJsonValidationErrors('ip'); expect(IpBan::count())->toBe(0); }); it('bans and lifts a whole group of addresses', function () { foreach (['10.2.0.1', '10.2.0.2', '127.0.0.1'] as $ip) { $this->putJson('/manager/audit/notes', ['ip' => $ip, 'note' => 'farm', 'group' => 'Farm'])->assertOk(); } $this->postJson('/manager/audit/groups/ban', ['group' => 'Farm', 'minutes' => 60])->assertCreated() ->assertJsonPath('banned', 2)->assertJsonPath('skipped', 1); expect(IpBan::count())->toBe(2); $this->postJson('/manager/audit/groups/unban', ['group' => 'Farm'])->assertOk()->assertJsonPath('lifted', 2); expect(IpBan::count())->toBe(0); }); it('writes and removes the note about an address', function () { $this->putJson('/manager/audit/notes', ['ip' => '::1', 'note' => 'home'])->assertOk(); expect(IpNote::sole()->note)->toBe('home'); $this->putJson('/manager/audit/notes', ['ip' => '::1', 'note' => '', 'group' => ''])->assertOk(); expect(IpNote::count())->toBe(0); }); it('keeps the log no longer than the site promises', function () { $rules = ['auto_ban' => true, 'max_failures' => 5, 'window_minutes' => 10, 'ban_minutes' => 0]; $this->putJson('/manager/audit/settings', [...$rules, 'keep_days' => 91])->assertStatus(422)->assertJsonValidationErrors('keep_days'); $this->putJson('/manager/audit/settings', [...$rules, 'keep_days' => 30])->assertOk(); expect(AuditSetting::current()->rules()['keep_days'])->toBe(30); }); }); describe('a banned address', function () { it('is kept out of the manager with a 403, or a 429 when it was banned by itself', function () { app(IpBans::class)->ban('10.3.0.1', 'Scraper', 0, null); failLogin('10.3.0.2', 10); $this->actingAs(makeUser(superAdmin: true)); $this->getJson('/manager/posts', fromAddress('10.3.0.1'))->assertForbidden(); $this->getJson('/manager/posts', fromAddress('10.3.0.2'))->assertStatus(429)->assertHeader('Retry-After'); $this->get('/manager/posts', fromAddress('10.3.0.1'))->assertForbidden()->assertSee('blocked from the manager'); $this->getJson('/manager/posts', fromAddress('10.3.0.9'))->assertOk(); expect(IpBan::where('ip', '10.3.0.1')->value('hits'))->toBe(2); }); it('gets the banned answer, not the login page, as a guest', function () { app(IpBans::class)->ban('10.3.2.1', null, 0, null); $this->getJson('/manager/posts', fromAddress('10.3.2.1'))->assertForbidden(); $this->getJson('/manager/posts', fromAddress('10.3.2.2'))->assertUnauthorized(); }); it('is let back in when the ban ends or is lifted on the server', function () { app(IpBans::class)->ban('10.3.1.1', null, 10, null); $this->actingAs(makeUser(superAdmin: true)); $this->travel(11)->minutes(); $this->getJson('/manager/posts', fromAddress('10.3.1.1'))->assertOk(); app(IpBans::class)->ban('10.3.1.2', null, 0, null); $this->artisan('manager:unban', ['ip' => '10.3.1.2'])->assertSuccessful(); $this->getJson('/manager/posts', fromAddress('10.3.1.2'))->assertOk(); }); it('is kept off the whole site by a ban for the whole site, and no other address', function () { Route::get('/hello', fn () => 'hello'); app(IpBans::class)->ban('10.4.0.1', null, 0, null, wholeSite: true); app(IpBans::class)->ban('10.4.0.2', null, 0, null); $this->get('/hello', fromAddress('10.4.0.1'))->assertForbidden(); $this->get('/hello', fromAddress('10.4.0.2'))->assertOk(); $this->get('/hello', fromAddress('10.4.0.3'))->assertOk(); }); }); describe('pruning', function () { it('deletes old lines and ended bans, and keeps the notes', function () { AuditLog::create(['event' => 'login', 'summary' => 'old', 'created_at' => now()->subDays(120)]); AuditLog::create(['event' => 'login', 'summary' => 'new', 'created_at' => now()->subDays(10)]); IpBan::create(['ip' => '10.5.0.1', 'expires_at' => now()->subDays(100), 'created_at' => now()->subDays(101)]); IpBan::create(['ip' => '10.5.0.2', 'expires_at' => null, 'created_at' => now()->subDays(101)]); IpNote::create(['ip' => '10.5.0.1', 'note' => 'stays']); $this->artisan('manager:audit-prune')->assertSuccessful(); expect(AuditLog::pluck('summary')->all())->toBe(['new']) ->and(IpBan::pluck('ip')->all())->toBe(['10.5.0.2']) ->and(IpNote::count())->toBe(1); }); });