Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
196 changes: 196 additions & 0 deletions app/Filament/Admin/Resources/Activities/ActivityResource.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
<?php

namespace App\Filament\Admin\Resources\Activities;

use App\Enums\TablerIcon;
use App\Filament\Admin\Resources\Activities\Pages\ListActivities;
use App\Filament\Admin\Resources\Users\Pages\EditUser;
use App\Filament\Components\Tables\Columns\DateTimeColumn;
use App\Models\ActivityLog;
use App\Models\ActivityLogSubject;
use App\Models\User;
use App\Traits\Filament\CanCustomizePages;
use App\Traits\Filament\CanCustomizeRelations;
use App\Traits\Filament\CanModifyTable;
use BackedEnum;
use Exception;
use Filament\Actions\ViewAction;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\KeyValue;
use Filament\Forms\Components\TextInput;
use Filament\Infolists\Components\TextEntry;
use Filament\Resources\Pages\PageRegistration;
use Filament\Resources\Resource;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Enums\PaginationMode;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Auth\Access\Response;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Arr;
use Illuminate\Support\HtmlString;
use Illuminate\Support\Str;

class ActivityResource extends Resource
{
use CanCustomizePages;
use CanCustomizeRelations;
use CanModifyTable;

protected static ?string $model = ActivityLog::class;

protected static string|BackedEnum|null $navigationIcon = TablerIcon::Stack;

/**
* @throws Exception
*/
public static function defaultTable(Table $table): Table
{
return $table
->paginated([25, 50])
->defaultPaginationPageOption(25)
// Simple pagination skips the COUNT(*) over the whole activity log.
->paginationMode(PaginationMode::Simple)
->columns([
TextColumn::make('event')
->label(trans('admin/activity.event'))
->html()
->description(fn ($state) => $state)
->icon(fn (ActivityLog $activityLog) => $activityLog->getIcon())
->formatStateUsing(fn (ActivityLog $activityLog) => $activityLog->getLabel()),
TextColumn::make('user')
->label(trans('admin/activity.user'))
->state(fn (ActivityLog $activityLog) => self::actorName($activityLog))
->tooltip(fn (ActivityLog $activityLog) => $activityLog->getIp() ?? '')
->url(fn (ActivityLog $activityLog) => $activityLog->actor instanceof User && user()?->can('update', $activityLog->actor) ? EditUser::getUrl(['record' => $activityLog->actor]) : '')
->grow(false),
TextColumn::make('subjects')
->label(trans('admin/activity.subject'))
->state(fn (ActivityLog $activityLog) => $activityLog->subjects
->map(fn (ActivityLogSubject $subject) => class_basename($subject->subject_type) . ' #' . $subject->subject_id)
->unique()
->join(', '))
->grow(false),
DateTimeColumn::make('timestamp')
->label(trans('admin/activity.timestamp'))
->since()
->sortable()
->grow(false),
])
->defaultSort('timestamp', 'desc')
->recordActions([
ViewAction::make()
Comment thread
coderabbitai[bot] marked this conversation as resolved.
// Flatten before the form fills: KeyValue's state cast mistakes a nested
// assoc (first value an array) for its own row format and blanks it.
->mutateRecordDataUsing(function (array $data) {
$data['properties'] = collect(Arr::dot($data['properties'] ?? []))
->map(fn ($value) => is_bool($value) || is_null($value) ? var_export($value, true) : $value)
->all();
Comment on lines +89 to +91

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High Activities/ActivityResource.php:89

The View modal exposes properties['ip'] to users who only have view activityLog, so they can read client IPs without seeIps activityLog. Because line 89 forwards the raw properties array to KeyValue, the permission enforced by getIp() is bypassed; remove ip from the modal data unless the viewer has seeIps activityLog.

-                        $data['properties'] = collect(Arr::dot($data['properties'] ?? []))
-                            ->map(fn ($value) => is_bool($value) || is_null($value) ? var_export($value, true) : $value)
+                        $data['properties'] = collect(Arr::dot($data['properties'] ?? []))
+                            ->reject(fn ($value, $key) => $key === 'ip' && ! (user()?->can('seeIps activityLog') ?? false))
+                            ->map(fn ($value) => is_bool($value) || is_null($value) ? var_export($value, true) : $value)
🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
In file @app/Filament/Admin/Resources/Activities/ActivityResource.php around lines 89-91:

The View modal exposes `properties['ip']` to users who only have `view activityLog`, so they can read client IPs without `seeIps activityLog`. Because line 89 forwards the raw properties array to `KeyValue`, the permission enforced by `getIp()` is bypassed; remove `ip` from the modal data unless the viewer has `seeIps activityLog`.

Evidence trail:
Reviewed commit: 3bdb4795. `app/Filament/Admin/Resources/Activities/ActivityResource.php:88-110,151-167`; `app/Services/Activity/ActivityLogService.php:121-129`; `app/Listeners/Auth/PasswordResetListener.php:10-15`; `app/Models/ActivityLog.php:188-190`; `app/Models/Role.php:59-70,121-148`.


return $data;
})
->schema([
TextEntry::make('event')
->label(trans('admin/activity.event'))
->state(fn (ActivityLog $activityLog) => new HtmlString($activityLog->getLabel())),
TextInput::make('user')
->label(trans('admin/activity.user'))
->formatStateUsing(function (ActivityLog $activityLog) {
$user = self::actorName($activityLog);
$ip = $activityLog->getIp();

return $ip ? "$user - $ip" : $user;
}),
DateTimePicker::make('timestamp')
->label(trans('admin/activity.timestamp')),
KeyValue::make('properties')
->label(trans('admin/activity.metadata')),
]),
])
->filters([
// Options come from the translated event names and the morph map rather
// than SELECT DISTINCT, which scans the whole log on every page load.
SelectFilter::make('event')
->label(trans('admin/activity.event'))
->options(fn () => collect(Arr::dot(trans('activity')))->keys()->map(fn (string $key) => Str::replaceFirst('.', ':', $key))->sort()->mapWithKeys(fn (string $event) => [$event => $event]))
->searchable(),
SelectFilter::make('actor_id')
->label(trans('admin/activity.user'))
->searchable()
->getSearchResultsUsing(fn (string $search) => User::where('username', 'like', "%$search%")->orWhere('email', 'like', "%$search%")->limit(50)->pluck('username', 'id'))
->getOptionLabelUsing(fn ($value) => User::find($value)?->username),
SelectFilter::make('subject_type')
->label(trans('admin/activity.subject'))
->options(fn () => collect(Relation::morphMap())->mapWithKeys(fn (string $class, string $alias) => [$alias => class_basename($class)])->sort())
->query(fn (Builder $query, array $data) => $query->when($data['value'], fn (Builder $query, $value) => $query->whereHas('subjects', fn (Builder $query) => $query->where('subject_type', $value)))),
Filter::make('timestamp')
->schema([
DateTimePicker::make('from')
->label(trans('admin/activity.from')),
DateTimePicker::make('until')
->label(trans('admin/activity.until')),
])
->query(fn (Builder $query, array $data) => $query
->when($data['from'], fn (Builder $query, $value) => $query->where('timestamp', '>=', $value))
->when($data['until'], fn (Builder $query, $value) => $query->where('timestamp', '<=', $value))),
]);
}

/** @return Builder<ActivityLog> */
public static function getEloquentQuery(): Builder
{
// Deliberately unscoped (and ignoring activity.hide_admin_activity):
// this is the panel-wide audit view for admins holding "view activityLog".
return ActivityLog::with(['actor', 'apiKey'])
->whereNotIn('event', ActivityLog::DISABLED_EVENTS);
}

public static function canViewAny(): bool
{
return user()?->can('view activityLog') ?? false;
}

public static function canAccess(): bool
{
return static::canViewAny();
}

/**
* ActivityLogPolicy::view() checks the server-panel subuser permission,
* which never applies here; the admin viewer is gated by "view activityLog".
*/
public static function getViewAuthorizationResponse(Model $record): Response
{
return static::canViewAny() ? Response::allow() : Response::deny();
}

/** @return array<string, PageRegistration> */
public static function getDefaultPages(): array
{
return [
'index' => ListActivities::route('/'),
];
}

public static function getNavigationLabel(): string
{
return trans('admin/activity.title');
}

public static function getNavigationGroup(): ?string
{
return trans('admin/dashboard.advanced');
}

private static function actorName(ActivityLog $activityLog): string
{
if (!$activityLog->actor instanceof User) {
return $activityLog->actor_id === null ? trans('admin/activity.system') : trans('admin/activity.deleted_user');
}

return "{$activityLog->actor->username} ({$activityLog->actor->email})";
}
}
21 changes: 21 additions & 0 deletions app/Filament/Admin/Resources/Activities/Pages/ListActivities.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

namespace App\Filament\Admin\Resources\Activities\Pages;

use App\Filament\Admin\Resources\Activities\ActivityResource;
use App\Traits\Filament\CanCustomizeHeaderActions;
use App\Traits\Filament\CanCustomizeHeaderWidgets;
use Filament\Resources\Pages\ListRecords;

class ListActivities extends ListRecords
{
use CanCustomizeHeaderActions;
use CanCustomizeHeaderWidgets;

protected static string $resource = ActivityResource::class;

public function getTitle(): string
{
return trans('admin/activity.title');
}
}
1 change: 1 addition & 0 deletions app/Models/Role.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ class Role extends BaseRole
'view',
],
'activityLog' => [
'view',
'seeIps',
],
'panelLog' => [
Expand Down
14 changes: 14 additions & 0 deletions lang/en/admin/activity.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

return [
'title' => 'Activity',
'event' => 'Event',
'user' => 'User',
'deleted_user' => 'Deleted User',
'system' => 'System',
'subject' => 'Subject',
'timestamp' => 'Timestamp',
'metadata' => 'Metadata',
'from' => 'From',
'until' => 'Until',
];
133 changes: 133 additions & 0 deletions tests/Filament/Admin/ListActivitiesTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
<?php

use App\Facades\Activity;
use App\Filament\Admin\Resources\Activities\Pages\ListActivities;
use App\Models\ActivityLog;
use App\Models\Role;
use Filament\Actions\Testing\TestAction;
use Filament\Facades\Filament;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Permission;

use function Pest\Livewire\livewire;

beforeEach(fn () => Filament::setCurrentPanel(Filament::getPanel('admin')));
afterEach(fn () => Filament::setCurrentPanel(null));

it('root admin can see activity from every panel', function () {
[$admin, $server] = generateTestAccount([]);
$admin = $admin->syncRoles(Role::getRootAdmin());

Activity::event('auth:success')->actor($admin)->log();
Activity::event('server:power.start')->subject($server)->log();

$this->actingAs($admin);
livewire(ListActivities::class)
->assertSuccessful()
->assertCountTableRecords(ActivityLog::count())
->assertCanSeeTableRecords(ActivityLog::all());
});

it('event filter narrows the table', function () {
[$admin] = generateTestAccount([]);
$admin = $admin->syncRoles(Role::getRootAdmin());

Activity::event('auth:success')->actor($admin)->log();
Activity::event('auth:fail')->log();

$this->actingAs($admin);
livewire(ListActivities::class)
->filterTable('event', 'auth:fail')
->assertCountTableRecords(1);
});

it('user without view activityLog is forbidden', function () {
$role = Role::factory()->create(['name' => 'IP Viewer', 'guard_name' => 'web']);
// seeIps alone must not grant access to the viewer.
$role->givePermissionTo(Permission::findOrCreate('seeIps activityLog', 'web'));
[$user] = generateTestAccount([]);
$user = $user->syncRoles($role);

$this->actingAs($user);
livewire(ListActivities::class)
->assertForbidden();
});

it('user with view activityLog can see the viewer', function () {
$role = Role::factory()->create(['name' => 'Auditor', 'guard_name' => 'web']);
$role->givePermissionTo(Permission::findOrCreate('view activityLog', 'web'));
[$user] = generateTestAccount([]);
$user = $user->syncRoles($role);

Activity::event('auth:success')->log();

$this->actingAs($user);
livewire(ListActivities::class)
->assertSuccessful()
->assertCountTableRecords(ActivityLog::count());
});

it('flattens nested properties for the metadata modal', function () {
[$admin] = generateTestAccount([]);
$admin = $admin->syncRoles(Role::getRootAdmin());

// Nested-only properties trip KeyValue's state cast without the flatten.
$log = Activity::event('settings:update')->property('changes', ['APP_NAME' => ['old' => 'A', 'new' => null]])->log();

$this->actingAs($admin);
livewire(ListActivities::class)
->mountAction(TestAction::make('view')->table($log))
->assertActionDataSet(['properties' => ['changes.APP_NAME.old' => 'A', 'changes.APP_NAME.new' => 'NULL']]);
});

it('user with view activityLog can open the properties modal', function () {
$role = Role::factory()->create(['name' => 'Modal Auditor', 'guard_name' => 'web']);
$role->givePermissionTo(Permission::findOrCreate('view activityLog', 'web'));
[$user] = generateTestAccount([]);
$user = $user->syncRoles($role);

$log = Activity::event('auth:success')->log();

$this->actingAs($user);
livewire(ListActivities::class)
->callAction(TestAction::make('view')->table($log))
->assertHasNoActionErrors();
});

it('subject filter narrows the table by morph alias', function () {
[$admin, $server] = generateTestAccount([]);
$admin = $admin->syncRoles(Role::getRootAdmin());

ActivityLog::query()->delete();
Activity::event('server:power.start')->subject($server)->log();
Activity::event('auth:success')->actor($admin)->log();

$this->actingAs($admin);
livewire(ListActivities::class)
->filterTable('subject_type', $server->getMorphClass())
->assertCountTableRecords(1);
});

it('does not query per row', function () {
[$admin, $server] = generateTestAccount([]);
$admin = $admin->syncRoles(Role::getRootAdmin());
$this->actingAs($admin);

$count = function () {
DB::flushQueryLog();
DB::enableQueryLog();
livewire(ListActivities::class)->assertSuccessful();

return count(DB::getQueryLog());
};

Activity::event('server:power.start')->subject($server)->log();
$count(); // Warm the permission and settings caches.
$baseline = $count();

foreach (range(1, 10) as $ignored) {
Activity::event('server:power.start')->subject($server)->log();
}

expect($count())->toBe($baseline);
});
Loading