Compare commits

..

8 Commits

Author SHA1 Message Date
Lance Pioch
1c048ccf2d Fix listener to accept Filament event objects
- Change handle() signature to accept RecordCreated|RecordUpdated event objects
  instead of separate params (Laravel passes the event, not constructor args)
- Use [REDACTED] placeholder instead of silently dropping sensitive fields
- Expand redacted fields list with current_password, daemon_token, _token
- Update tests to construct proper event objects
2026-02-07 22:04:06 -05:00
Lance Pioch
bdf8a9151c Add tests for AdminActivityListener 2026-02-07 09:21:17 -05:00
Lance Pioch
67e13c646a Add admin activity logging for CRUD operations
Log create, update, and delete actions performed in the admin panel
using Filament's RecordCreated/RecordUpdated events and a DeleteAction
before() hook. Sensitive fields (passwords, tokens) are redacted from
stored properties.
2026-02-06 10:56:04 -05:00
Lance Pioch
b1a39f1724 Handle X-Forwarded-Proto in .htaccess for SSL-terminating proxies (#2171) 2026-02-06 09:54:24 -05:00
Lance Pioch
6a548c09a0 Clarify OAuth error when provider account has no linked email (#2179) 2026-02-06 07:50:37 -05:00
Lance Pioch
55bda569cc Implement flexible caching for node statuses (#2174) 2026-02-06 07:50:20 -05:00
Lance Pioch
adf1249086 Fix Egg Feature modals not working (#2175) 2026-02-06 07:49:56 -05:00
Lance Pioch
dbf77bf146 Implement single file move to support Unix mv semantics (#1984) (#2176) 2026-02-06 07:49:40 -05:00
13 changed files with 330 additions and 73 deletions

View File

@@ -78,11 +78,15 @@ class Console extends Page
$feature = data_get($data, 'key');
$feature = $this->featureService->get($feature);
if (!$feature || $this->getMountedAction()) {
if (!$feature) {
return;
}
$this->mountAction($feature->getId());
sleep(2); // TODO find a better way
if ($this->getMountedAction()) {
$this->replaceMountedAction($feature->getId());
} else {
$this->mountAction($feature->getId());
}
}
public function getWidgetData(): array

View File

@@ -209,16 +209,18 @@ class ListFiles extends ListRecords
->required()
->live(),
TextEntry::make('new_location')
->state(fn (Get $get, File $file) => resolve_path(join_paths($this->path, $get('location') ?? '/', $file->name))),
->state(fn (Get $get, File $file) => resolve_path(join_paths($this->path, str_ends_with($get('location') ?? '/', '/') ? join_paths($get('location') ?? '/', $file->name) : $get('location') ?? '/'))),
])
->action(function ($data, File $file) {
$location = $data['location'];
$files = [['to' => join_paths($location, $file->name), 'from' => $file->name]];
$endsWithSlash = str_ends_with($location, '/');
$to = $endsWithSlash ? join_paths($location, $file->name) : $location;
$files = [['to' => $to, 'from' => $file->name]];
$this->getDaemonFileRepository()->renameFiles($this->path, $files);
$oldLocation = join_paths($this->path, $file->name);
$newLocation = resolve_path(join_paths($this->path, $location, $file->name));
$newLocation = resolve_path(join_paths($this->path, $to));
Activity::event('server:file.rename')
->property('directory', $this->path)

View File

@@ -77,30 +77,17 @@ class SubuserResource extends Resource
$options = [];
$descriptions = [];
$translationPrefix = $data['translationPrefix'] ?? 'server/user.permissions.';
$customDescriptions = $data['descriptions'] ?? [];
foreach ($data['permissions'] as $permission) {
$options[$permission] = str($permission)->headline();
if (isset($customDescriptions[$permission])) {
$descriptions[$permission] = $customDescriptions[$permission];
} else {
$descKey = $translationPrefix . $data['name'] . '_' . str($permission)->replace('-', '_');
$descriptions[$permission] = trans()->has($descKey) ? trans($descKey) : null;
}
$descriptions[$permission] = trans('server/user.permissions.' . $data['name'] . '_' . str($permission)->replace('-', '_'));
$permissionsArray[$data['name']][] = $permission;
}
$tabLabelKey = $translationPrefix . $data['name'];
$groupDescKey = $translationPrefix . $data['name'] . '_desc';
$tabs[] = Tab::make($data['name'])
->label($data['label'] ?? (trans()->has($tabLabelKey) ? trans($tabLabelKey) : str($data['name'])->headline()))
->label(str($data['name'])->headline())
->schema([
Section::make()
->description($data['description'] ?? (trans()->has($groupDescKey) ? trans($groupDescKey) : null))
->description(trans('server/user.permissions.' . $data['name'] . '_desc'))
->icon($data['icon'])
->contained(false)
->schema([

View File

@@ -74,7 +74,7 @@ class OAuthController extends Controller
$email = $oauthUser->getEmail();
if (!$email) {
return $this->errorRedirect();
return $this->errorRedirect('No email was linked to your account on the OAuth provider.');
}
$user = User::whereEmail($email)->first();

View File

@@ -0,0 +1,72 @@
<?php
namespace App\Listeners;
use App\Facades\Activity;
use Filament\Facades\Filament;
use Filament\Resources\Events\RecordCreated;
use Filament\Resources\Events\RecordUpdated;
use Illuminate\Support\Str;
class AdminActivityListener
{
protected const REDACTED_FIELDS = [
'password',
'password_confirmation',
'current_password',
'token',
'secret',
'api_key',
'daemon_token',
'_token',
];
public function handle(RecordCreated|RecordUpdated $event): void
{
if (Filament::getCurrentPanel()?->getId() !== 'admin') {
return;
}
$record = $event->getRecord();
$page = $event->getPage();
$data = $event->getData();
$resourceClass = $page::getResource();
$modelClass = $resourceClass::getModel();
$slug = Str::kebab(class_basename($modelClass));
$action = $event instanceof RecordCreated ? 'create' : 'update';
$properties = $this->redactSensitiveFields($data);
Activity::event("admin:$slug.$action")
->subject($record)
->property($properties)
->log();
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
protected function redactSensitiveFields(array $data): array
{
$redacted = [];
foreach ($data as $key => $value) {
if (in_array($key, self::REDACTED_FIELDS, true)) {
$redacted[$key] = '[REDACTED]';
continue;
}
if (is_array($value)) {
$redacted[$key] = $this->redactSensitiveFields($value);
} else {
$redacted[$key] = $value;
}
}
return $redacted;
}
}

View File

@@ -358,7 +358,7 @@ class Node extends Model implements Validatable
'disk_used' => 0,
];
return cache()->remember("nodes.$this->id.statistics", now()->addSeconds(360), function () use ($default) {
return cache()->flexible("nodes.$this->id.statistics", [5, 30], function () use ($default) {
try {
$data = Http::daemon($this)

View File

@@ -33,17 +33,11 @@ class Subuser extends Model implements Validatable
*/
public const RESOURCE_NAME = 'server_subuser';
/** @var array<string, array{name: string, hidden?: ?bool, icon?: ?string, permissions: string[], translationPrefix?: string, label?: string, description?: string, descriptions?: array<string, string>}> */
/** @var array<string, array{name: string, hidden: ?bool, icon: ?string, permissions: string[]}> */
protected static array $customPermissions = [];
/**
* @param string[] $permissions
* @param ?string $label Custom label for the permission tab (overrides translation lookup)
* @param ?string $description Custom description for the permission group (overrides translation lookup)
* @param ?array<string, string> $descriptions Custom descriptions keyed by permission name (overrides translation lookup)
* @param ?string $translationPrefix Translation prefix for looking up labels/descriptions (e.g. 'my-plugin::permissions.')
*/
public static function registerCustomPermissions(string $name, array $permissions, ?string $icon = null, ?bool $hidden = null, ?string $translationPrefix = null, ?string $label = null, ?string $description = null, ?array $descriptions = null): void
/** @param string[] $permissions */
public static function registerCustomPermissions(string $name, array $permissions, ?string $icon = null, ?bool $hidden = null): void
{
$customPermission = static::$customPermissions[$name] ?? [];
@@ -58,22 +52,6 @@ class Subuser extends Model implements Validatable
$customPermission['hidden'] = $hidden;
}
if (!is_null($translationPrefix)) {
$customPermission['translationPrefix'] = $translationPrefix;
}
if (!is_null($label)) {
$customPermission['label'] = $label;
}
if (!is_null($description)) {
$customPermission['description'] = $description;
}
if (!is_null($descriptions)) {
$customPermission['descriptions'] = array_merge($customPermission['descriptions'] ?? [], $descriptions);
}
static::$customPermissions[$name] = $customPermission;
}
@@ -115,7 +93,7 @@ class Subuser extends Model implements Validatable
return $this->belongsTo(User::class);
}
/** @return array<array{name: string, hidden: bool, icon: string, permissions: string[], translationPrefix?: ?string, label?: ?string, description?: ?string, descriptions?: array<string, string>}> */
/** @return array<array{name: string, hidden: bool, icon: string, permissions: string[]}> */
public static function allPermissionData(): array
{
$allPermissions = [];
@@ -128,28 +106,22 @@ class Subuser extends Model implements Validatable
'hidden' => $subuserPermission->isHidden(),
'icon' => $subuserPermission->getIcon(),
'permissions' => array_merge($allPermissions[$group]['permissions'] ?? [], [$permission]),
'translationPrefix' => null,
'label' => null,
'description' => null,
'descriptions' => [],
];
}
foreach (static::$customPermissions as $customPermission) {
$name = $customPermission['name'];
$existing = $allPermissions[$name] ?? null;
$groupData = $allPermissions[$name] ?? [];
$allPermissions[$name] = [
$groupData = [
'name' => $name,
'hidden' => $customPermission['hidden'] ?? ($existing !== null ? $existing['hidden'] : false),
'icon' => $customPermission['icon'] ?? ($existing !== null ? $existing['icon'] : null),
'permissions' => array_unique(array_merge($existing !== null ? $existing['permissions'] : [], $customPermission['permissions'])),
'translationPrefix' => ($customPermission['translationPrefix'] ?? null) ?? ($existing !== null ? $existing['translationPrefix'] : null),
'label' => ($customPermission['label'] ?? null) ?? ($existing !== null ? $existing['label'] : null),
'description' => ($customPermission['description'] ?? null) ?? ($existing !== null ? $existing['description'] : null),
'descriptions' => array_merge($existing !== null ? $existing['descriptions'] : [], $customPermission['descriptions'] ?? []),
'hidden' => $customPermission['hidden'] ?? $groupData['hidden'] ?? false,
'icon' => $customPermission['icon'] ?? $groupData['icon'],
'permissions' => array_unique(array_merge($groupData['permissions'] ?? [], $customPermission['permissions'])),
];
$allPermissions[$name] = $groupData;
}
return array_values($allPermissions);

View File

@@ -2,7 +2,10 @@
namespace App\Providers;
use App\Listeners\AdminActivityListener;
use App\Listeners\DispatchWebhooks;
use Filament\Resources\Events\RecordCreated;
use Filament\Resources\Events\RecordUpdated;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
@@ -15,5 +18,7 @@ class EventServiceProvider extends ServiceProvider
'eloquent.created*' => [DispatchWebhooks::class],
'eloquent.deleted*' => [DispatchWebhooks::class],
'eloquent.updated*' => [DispatchWebhooks::class],
RecordCreated::class => [AdminActivityListener::class],
RecordUpdated::class => [AdminActivityListener::class],
];
}

View File

@@ -4,12 +4,14 @@ namespace App\Providers\Filament;
use App\Enums\CustomizationKey;
use App\Enums\TablerIcon;
use App\Facades\Activity;
use Filament\Actions\Action;
use Filament\Actions\CreateAction;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Actions\View\ActionsIconAlias;
use Filament\Actions\ViewAction;
use Filament\Facades\Filament;
use Filament\Forms\Components\Field;
use Filament\Forms\Components\KeyValue;
use Filament\Forms\Components\Repeater;
@@ -29,8 +31,10 @@ use Filament\Support\View\SupportIconAlias;
use Filament\Tables\View\TablesIconAlias;
use Filament\View\PanelsIconAlias;
use Filament\View\PanelsRenderHook;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
use Livewire\Component;
use Livewire\Livewire;
@@ -132,6 +136,18 @@ class FilamentServiceProvider extends ServiceProvider
$action->iconButton();
$action->iconSize(IconSize::ExtraLarge);
}
$action->before(function (Model $record) {
if (Filament::getCurrentPanel()?->getId() !== 'admin') {
return;
}
$slug = Str::kebab(class_basename($record));
Activity::event("admin:$slug.delete")
->subject($record)
->log();
});
});
CreateAction::configureUsing(function (CreateAction $action) {

View File

@@ -122,4 +122,51 @@ return [
],
'crashed' => 'Server crashed',
],
'admin' => [
'user' => [
'create' => 'Created user <b>:username</b>',
'update' => 'Updated user <b>:username</b>',
'delete' => 'Deleted user <b>:username</b>',
],
'server' => [
'create' => 'Created server <b>:name</b>',
'update' => 'Updated server <b>:name</b>',
'delete' => 'Deleted server <b>:name</b>',
],
'node' => [
'create' => 'Created node <b>:name</b>',
'update' => 'Updated node <b>:name</b>',
'delete' => 'Deleted node <b>:name</b>',
],
'egg' => [
'create' => 'Created egg <b>:name</b>',
'update' => 'Updated egg <b>:name</b>',
'delete' => 'Deleted egg <b>:name</b>',
],
'role' => [
'create' => 'Created role <b>:name</b>',
'update' => 'Updated role <b>:name</b>',
'delete' => 'Deleted role <b>:name</b>',
],
'database-host' => [
'create' => 'Created database host <b>:name</b>',
'update' => 'Updated database host <b>:name</b>',
'delete' => 'Deleted database host <b>:name</b>',
],
'mount' => [
'create' => 'Created mount <b>:name</b>',
'update' => 'Updated mount <b>:name</b>',
'delete' => 'Deleted mount <b>:name</b>',
],
'webhook-configuration' => [
'create' => 'Created webhook <b>:description</b>',
'update' => 'Updated webhook <b>:description</b>',
'delete' => 'Deleted webhook <b>:description</b>',
],
'api-key' => [
'create' => 'Created API key',
'update' => 'Updated API key',
'delete' => 'Deleted API key',
],
],
];

View File

@@ -17,16 +17,6 @@ return [
'notification_failed' => 'Failed to invite user!',
'permissions' => [
'title' => 'Permissions',
'control' => 'Control',
'user' => 'User',
'file' => 'File',
'backup' => 'Backup',
'schedule' => 'Schedule',
'database' => 'Database',
'allocation' => 'Allocation',
'startup' => 'Startup',
'settings' => 'Settings',
'activity' => 'Activity',
'activity_desc' => 'Permissions that control a user\'s access to the server activity logs.',
'startup_desc' => 'Permissions that control a user\'s ability to view this server\'s startup parameters.',
'settings_desc' => 'Permissions that control a user\'s ability to modify this server\'s settings.',

View File

@@ -5,6 +5,10 @@
RewriteEngine On
# Handle X-Forwarded-Proto Header
RewriteCond %{HTTP:X-Forwarded-Proto} =https [NC]
RewriteRule .* - [E=HTTPS:on]
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

View File

@@ -0,0 +1,158 @@
<?php
use App\Events\ActivityLogged;
use App\Filament\Admin\Resources\Eggs\Pages\CreateEgg;
use App\Filament\Admin\Resources\Eggs\Pages\EditEgg;
use App\Filament\Admin\Resources\Nodes\Pages\CreateNode;
use App\Filament\Admin\Resources\Nodes\Pages\EditNode;
use App\Listeners\AdminActivityListener;
use App\Models\Egg;
use App\Models\Node;
use App\Models\Role;
use Filament\Facades\Filament;
use Filament\Resources\Events\RecordCreated;
use Filament\Resources\Events\RecordUpdated;
use Illuminate\Support\Facades\Event;
function pageInstance(string $class): object
{
return (new ReflectionClass($class))->newInstanceWithoutConstructor();
}
function createEvent(object $record, array $data, object $page): RecordCreated
{
return new RecordCreated($record, $data, $page);
}
function updateEvent(object $record, array $data, object $page): RecordUpdated
{
return new RecordUpdated($record, $data, $page);
}
beforeEach(function () {
[$this->admin] = generateTestAccount([]);
$this->admin = $this->admin->syncRoles(Role::getRootAdmin());
$this->actingAs($this->admin);
Filament::setCurrentPanel('admin');
});
it('logs create activity for an egg', function () {
$egg = Egg::first();
$listener = new AdminActivityListener();
$listener->handle(createEvent($egg, ['name' => 'Test Egg'], pageInstance(CreateEgg::class)));
$this->assertActivityLogged('admin:egg.create');
});
it('logs update activity for an egg', function () {
$egg = Egg::first();
$listener = new AdminActivityListener();
$listener->handle(updateEvent($egg, ['name' => 'Updated Egg'], pageInstance(EditEgg::class)));
$this->assertActivityLogged('admin:egg.update');
});
it('logs create activity for a node', function () {
$node = Node::first();
$listener = new AdminActivityListener();
$listener->handle(createEvent($node, ['name' => 'Test Node'], pageInstance(CreateNode::class)));
$this->assertActivityLogged('admin:node.create');
});
it('logs update activity for a node', function () {
$node = Node::first();
$listener = new AdminActivityListener();
$listener->handle(updateEvent($node, ['name' => 'Updated Node'], pageInstance(EditNode::class)));
$this->assertActivityLogged('admin:node.update');
});
it('does not log activity for non-admin panels', function () {
Filament::setCurrentPanel('app');
$egg = Egg::first();
$listener = new AdminActivityListener();
$listener->handle(createEvent($egg, ['name' => 'Test'], pageInstance(CreateEgg::class)));
Event::assertNotDispatched(ActivityLogged::class);
});
it('sets the record as the activity subject', function () {
$egg = Egg::first();
$listener = new AdminActivityListener();
$listener->handle(createEvent($egg, ['name' => 'Test'], pageInstance(CreateEgg::class)));
$this->assertActivityFor('admin:egg.create', $this->admin, $egg);
});
it('redacts sensitive fields from activity properties', function () {
$egg = Egg::first();
$data = [
'name' => 'Visible',
'password' => 'should-be-redacted',
'password_confirmation' => 'should-be-redacted',
'token' => 'should-be-redacted',
'secret' => 'should-be-redacted',
'api_key' => 'should-be-redacted',
];
$listener = new AdminActivityListener();
$listener->handle(updateEvent($egg, $data, pageInstance(EditEgg::class)));
Event::assertDispatched(ActivityLogged::class, function (ActivityLogged $event) {
$properties = $event->model->properties;
expect($properties)->toHaveKey('name', 'Visible')
->toHaveKey('password', '[REDACTED]')
->toHaveKey('password_confirmation', '[REDACTED]')
->toHaveKey('token', '[REDACTED]')
->toHaveKey('secret', '[REDACTED]')
->toHaveKey('api_key', '[REDACTED]');
return true;
});
});
it('redacts sensitive fields in nested arrays', function () {
$egg = Egg::first();
$data = [
'name' => 'Visible',
'nested' => [
'safe' => 'value',
'password' => 'should-be-redacted',
'token' => 'should-be-redacted',
],
];
$listener = new AdminActivityListener();
$listener->handle(updateEvent($egg, $data, pageInstance(EditEgg::class)));
Event::assertDispatched(ActivityLogged::class, function (ActivityLogged $event) {
$properties = $event->model->properties;
expect($properties['nested'])->toHaveKey('safe', 'value')
->toHaveKey('password', '[REDACTED]')
->toHaveKey('token', '[REDACTED]');
return true;
});
});
it('generates kebab-case event names from model class names', function () {
$node = Node::first();
$listener = new AdminActivityListener();
$listener->handle(createEvent($node, ['name' => 'Test'], pageInstance(CreateNode::class)));
$this->assertActivityLogged('admin:node.create');
});