PR Body Implements Spec 065 “Tenant RBAC v1” with capabilities-first RBAC, tenant membership scoping (Option 3), and consistent Filament action semantics. Key decisions / rules Tenancy Option 3: tenant switching is tenantless (ChooseTenant), tenant-scoped routes stay scoped, non-members get 404 (not 403). RBAC model: canonical capability registry + role→capability map + Gates for each capability (no role-string checks in UI logic). UX policy: for tenant members lacking permission → actions are visible but disabled + tooltip (avoid click→403). Security still enforced server-side. What’s included Capabilities foundation: Central capability registry (Capabilities::*) Role→capability mapping (RoleCapabilityMap) Gate registration + resolver/manager updates to support tenant-scoped authorization Filament enforcement hardening across the app: Tenant registration & tenant CRUD properly gated Backup/restore/policy flows aligned to “visible-but-disabled” where applicable Provider operations (health check / inventory sync / compliance snapshot) guarded and normalized Directory groups + inventory sync start surfaces normalized Policy version maintenance actions (archive/restore/prune/force delete) gated SpecKit artifacts for 065: spec.md, plan/tasks updates, checklists, enforcement hitlist Security guarantees Non-member → 404 via tenant scoping/membership guards. Member without capability → 403 on execution, even if UI is disabled. No destructive actions execute without proper authorization checks. Tests Adds/updates Pest coverage for: Tenant scoping & membership denial behavior Role matrix expectations (owner/manager/operator/readonly) Filament surface checks (visible/disabled actions, no side effects) Provider/Inventory/Groups run-start authorization Verified locally with targeted vendor/bin/sail artisan test --compact … Deployment / ops notes No new services required. Safe change: behavior is authorization + UI semantics; no breaking route changes intended. Co-authored-by: Ahmed Darrazi <ahmeddarrazi@MacBookPro.fritz.box> Reviewed-on: #79
522 lines
25 KiB
PHP
522 lines
25 KiB
PHP
<?php
|
|
|
|
namespace App\Filament\Resources;
|
|
|
|
use App\Filament\Resources\BackupSetResource\Pages;
|
|
use App\Filament\Resources\BackupSetResource\RelationManagers\BackupItemsRelationManager;
|
|
use App\Jobs\BulkBackupSetDeleteJob;
|
|
use App\Jobs\BulkBackupSetForceDeleteJob;
|
|
use App\Jobs\BulkBackupSetRestoreJob;
|
|
use App\Models\BackupSet;
|
|
use App\Models\Tenant;
|
|
use App\Models\User;
|
|
use App\Services\Intune\AuditLogger;
|
|
use App\Services\Intune\BackupService;
|
|
use App\Services\OperationRunService;
|
|
use App\Services\Operations\BulkSelectionIdentity;
|
|
use App\Support\Auth\Capabilities;
|
|
use App\Support\Badges\BadgeDomain;
|
|
use App\Support\Badges\BadgeRenderer;
|
|
use App\Support\OperationRunLinks;
|
|
use App\Support\OpsUx\OperationUxPresenter;
|
|
use BackedEnum;
|
|
use Filament\Actions;
|
|
use Filament\Actions\ActionGroup;
|
|
use Filament\Actions\BulkAction;
|
|
use Filament\Actions\BulkActionGroup;
|
|
use Filament\Forms;
|
|
use Filament\Infolists;
|
|
use Filament\Notifications\Notification;
|
|
use Filament\Resources\Resource;
|
|
use Filament\Schemas\Schema;
|
|
use Filament\Tables;
|
|
use Filament\Tables\Contracts\HasTable;
|
|
use Filament\Tables\Filters\TrashedFilter;
|
|
use Filament\Tables\Table;
|
|
use Illuminate\Database\Eloquent\Collection;
|
|
use Illuminate\Support\Facades\Gate;
|
|
use UnitEnum;
|
|
|
|
class BackupSetResource extends Resource
|
|
{
|
|
protected static ?string $model = BackupSet::class;
|
|
|
|
protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-archive-box';
|
|
|
|
protected static string|UnitEnum|null $navigationGroup = 'Backups & Restore';
|
|
|
|
public static function canCreate(): bool
|
|
{
|
|
return ($tenant = Tenant::current()) instanceof Tenant
|
|
&& Gate::allows(Capabilities::TENANT_SYNC, $tenant);
|
|
}
|
|
|
|
public static function form(Schema $schema): Schema
|
|
{
|
|
return $schema
|
|
->schema([
|
|
Forms\Components\TextInput::make('name')
|
|
->label('Backup name')
|
|
->default(fn () => now()->format('Y-m-d H:i:s').' backup')
|
|
->required(),
|
|
]);
|
|
}
|
|
|
|
public static function table(Table $table): Table
|
|
{
|
|
return $table
|
|
->columns([
|
|
Tables\Columns\TextColumn::make('name')->searchable(),
|
|
Tables\Columns\TextColumn::make('status')
|
|
->badge()
|
|
->formatStateUsing(BadgeRenderer::label(BadgeDomain::BackupSetStatus))
|
|
->color(BadgeRenderer::color(BadgeDomain::BackupSetStatus))
|
|
->icon(BadgeRenderer::icon(BadgeDomain::BackupSetStatus))
|
|
->iconColor(BadgeRenderer::iconColor(BadgeDomain::BackupSetStatus)),
|
|
Tables\Columns\TextColumn::make('item_count')->label('Items'),
|
|
Tables\Columns\TextColumn::make('created_by')->label('Created by'),
|
|
Tables\Columns\TextColumn::make('completed_at')->dateTime()->since(),
|
|
Tables\Columns\TextColumn::make('created_at')->dateTime()->since(),
|
|
])
|
|
->filters([
|
|
Tables\Filters\TrashedFilter::make()
|
|
->label('Archived')
|
|
->placeholder('Active')
|
|
->trueLabel('All')
|
|
->falseLabel('Archived'),
|
|
])
|
|
->actions([
|
|
Actions\ViewAction::make()
|
|
->url(fn (BackupSet $record) => static::getUrl('view', ['record' => $record]))
|
|
->openUrlInNewTab(false),
|
|
ActionGroup::make([
|
|
Actions\Action::make('restore')
|
|
->label('Restore')
|
|
->color('success')
|
|
->icon('heroicon-o-arrow-uturn-left')
|
|
->requiresConfirmation()
|
|
->visible(fn (BackupSet $record): bool => $record->trashed())
|
|
->disabled(fn (): bool => ! (($tenant = Tenant::current()) instanceof Tenant
|
|
&& Gate::allows(Capabilities::TENANT_MANAGE, $tenant)))
|
|
->action(function (BackupSet $record, AuditLogger $auditLogger) {
|
|
$tenant = Tenant::current();
|
|
|
|
abort_unless($tenant instanceof Tenant && Gate::allows(Capabilities::TENANT_MANAGE, $tenant), 403);
|
|
|
|
$record->restore();
|
|
$record->items()->withTrashed()->restore();
|
|
|
|
if ($record->tenant) {
|
|
$auditLogger->log(
|
|
tenant: $record->tenant,
|
|
action: 'backup.restored',
|
|
resourceType: 'backup_set',
|
|
resourceId: (string) $record->id,
|
|
status: 'success',
|
|
context: ['metadata' => ['name' => $record->name]]
|
|
);
|
|
}
|
|
|
|
Notification::make()
|
|
->title('Backup set restored')
|
|
->success()
|
|
->send();
|
|
}),
|
|
Actions\Action::make('archive')
|
|
->label('Archive')
|
|
->color('danger')
|
|
->icon('heroicon-o-archive-box-x-mark')
|
|
->requiresConfirmation()
|
|
->visible(fn (BackupSet $record): bool => ! $record->trashed())
|
|
->disabled(fn (): bool => ! (($tenant = Tenant::current()) instanceof Tenant
|
|
&& Gate::allows(Capabilities::TENANT_MANAGE, $tenant)))
|
|
->action(function (BackupSet $record, AuditLogger $auditLogger) {
|
|
$tenant = Tenant::current();
|
|
|
|
abort_unless($tenant instanceof Tenant && Gate::allows(Capabilities::TENANT_MANAGE, $tenant), 403);
|
|
|
|
$record->delete();
|
|
|
|
if ($record->tenant) {
|
|
$auditLogger->log(
|
|
tenant: $record->tenant,
|
|
action: 'backup.deleted',
|
|
resourceType: 'backup_set',
|
|
resourceId: (string) $record->id,
|
|
status: 'success',
|
|
context: ['metadata' => ['name' => $record->name]]
|
|
);
|
|
}
|
|
|
|
Notification::make()
|
|
->title('Backup set archived')
|
|
->success()
|
|
->send();
|
|
}),
|
|
Actions\Action::make('forceDelete')
|
|
->label('Force delete')
|
|
->color('danger')
|
|
->icon('heroicon-o-trash')
|
|
->requiresConfirmation()
|
|
->visible(fn (BackupSet $record): bool => $record->trashed())
|
|
->disabled(fn (): bool => ! (($tenant = Tenant::current()) instanceof Tenant
|
|
&& Gate::allows(Capabilities::TENANT_DELETE, $tenant)))
|
|
->action(function (BackupSet $record, AuditLogger $auditLogger) {
|
|
$tenant = Tenant::current();
|
|
|
|
abort_unless($tenant instanceof Tenant && Gate::allows(Capabilities::TENANT_DELETE, $tenant), 403);
|
|
|
|
if ($record->restoreRuns()->withTrashed()->exists()) {
|
|
Notification::make()
|
|
->title('Cannot force delete backup set')
|
|
->body('Backup sets referenced by restore runs cannot be removed.')
|
|
->danger()
|
|
->send();
|
|
|
|
return;
|
|
}
|
|
|
|
if ($record->tenant) {
|
|
$auditLogger->log(
|
|
tenant: $record->tenant,
|
|
action: 'backup.force_deleted',
|
|
resourceType: 'backup_set',
|
|
resourceId: (string) $record->id,
|
|
status: 'success',
|
|
context: ['metadata' => ['name' => $record->name]]
|
|
);
|
|
}
|
|
|
|
$record->items()->withTrashed()->forceDelete();
|
|
$record->forceDelete();
|
|
|
|
Notification::make()
|
|
->title('Backup set permanently deleted')
|
|
->success()
|
|
->send();
|
|
}),
|
|
])->icon('heroicon-o-ellipsis-vertical'),
|
|
])
|
|
->bulkActions([
|
|
BulkActionGroup::make([
|
|
BulkAction::make('bulk_delete')
|
|
->label('Archive Backup Sets')
|
|
->icon('heroicon-o-archive-box-x-mark')
|
|
->color('danger')
|
|
->requiresConfirmation()
|
|
->disabled(fn (): bool => ! (($tenant = Tenant::current()) instanceof Tenant
|
|
&& Gate::allows(Capabilities::TENANT_MANAGE, $tenant)))
|
|
->hidden(function (HasTable $livewire): bool {
|
|
$trashedFilterState = $livewire->getTableFilterState(TrashedFilter::class) ?? [];
|
|
$value = $trashedFilterState['value'] ?? null;
|
|
|
|
$isOnlyTrashed = in_array($value, [0, '0', false], true);
|
|
|
|
return $isOnlyTrashed;
|
|
})
|
|
->modalDescription('This archives backup sets (soft delete). Already archived backup sets will be skipped.')
|
|
->form(function (Collection $records) {
|
|
if ($records->count() >= 10) {
|
|
return [
|
|
Forms\Components\TextInput::make('confirmation')
|
|
->label('Type DELETE to confirm')
|
|
->required()
|
|
->in(['DELETE'])
|
|
->validationMessages([
|
|
'in' => 'Please type DELETE to confirm.',
|
|
]),
|
|
];
|
|
}
|
|
|
|
return [];
|
|
})
|
|
->action(function (Collection $records) {
|
|
$tenant = Tenant::current();
|
|
$user = auth()->user();
|
|
$count = $records->count();
|
|
$ids = $records->pluck('id')->toArray();
|
|
|
|
if (! $tenant instanceof Tenant) {
|
|
return;
|
|
}
|
|
|
|
abort_unless(Gate::allows(Capabilities::TENANT_MANAGE, $tenant), 403);
|
|
|
|
$initiator = $user instanceof User ? $user : null;
|
|
|
|
/** @var BulkSelectionIdentity $selection */
|
|
$selection = app(BulkSelectionIdentity::class);
|
|
$selectionIdentity = $selection->fromIds($ids);
|
|
|
|
/** @var OperationRunService $runs */
|
|
$runs = app(OperationRunService::class);
|
|
|
|
$opRun = $runs->enqueueBulkOperation(
|
|
tenant: $tenant,
|
|
type: 'backup_set.delete',
|
|
targetScope: [
|
|
'entra_tenant_id' => (string) ($tenant->tenant_id ?? $tenant->external_id),
|
|
],
|
|
selectionIdentity: $selectionIdentity,
|
|
dispatcher: function ($operationRun) use ($tenant, $initiator, $ids): void {
|
|
BulkBackupSetDeleteJob::dispatch(
|
|
tenantId: (int) $tenant->getKey(),
|
|
userId: (int) ($initiator?->getKey() ?? 0),
|
|
backupSetIds: $ids,
|
|
operationRun: $operationRun,
|
|
);
|
|
},
|
|
initiator: $initiator,
|
|
extraContext: [
|
|
'backup_set_count' => $count,
|
|
],
|
|
emitQueuedNotification: false,
|
|
);
|
|
|
|
OperationUxPresenter::queuedToast('backup_set.delete')
|
|
->actions([
|
|
Actions\Action::make('view_run')
|
|
->label('View run')
|
|
->url(OperationRunLinks::view($opRun, $tenant)),
|
|
])
|
|
->send();
|
|
})
|
|
->deselectRecordsAfterCompletion(),
|
|
|
|
BulkAction::make('bulk_restore')
|
|
->label('Restore Backup Sets')
|
|
->icon('heroicon-o-arrow-uturn-left')
|
|
->color('success')
|
|
->requiresConfirmation()
|
|
->disabled(fn (): bool => ! (($tenant = Tenant::current()) instanceof Tenant
|
|
&& Gate::allows(Capabilities::TENANT_MANAGE, $tenant)))
|
|
->hidden(function (HasTable $livewire): bool {
|
|
$trashedFilterState = $livewire->getTableFilterState(TrashedFilter::class) ?? [];
|
|
$value = $trashedFilterState['value'] ?? null;
|
|
|
|
$isOnlyTrashed = in_array($value, [0, '0', false], true);
|
|
|
|
return ! $isOnlyTrashed;
|
|
})
|
|
->modalHeading(fn (Collection $records) => "Restore {$records->count()} backup sets?")
|
|
->modalDescription('Archived backup sets will be restored back to the active list. Active backup sets will be skipped.')
|
|
->action(function (Collection $records) {
|
|
$tenant = Tenant::current();
|
|
$user = auth()->user();
|
|
$count = $records->count();
|
|
$ids = $records->pluck('id')->toArray();
|
|
|
|
if (! $tenant instanceof Tenant) {
|
|
return;
|
|
}
|
|
|
|
abort_unless(Gate::allows(Capabilities::TENANT_MANAGE, $tenant), 403);
|
|
|
|
$initiator = $user instanceof User ? $user : null;
|
|
|
|
/** @var BulkSelectionIdentity $selection */
|
|
$selection = app(BulkSelectionIdentity::class);
|
|
$selectionIdentity = $selection->fromIds($ids);
|
|
|
|
/** @var OperationRunService $runs */
|
|
$runs = app(OperationRunService::class);
|
|
|
|
$opRun = $runs->enqueueBulkOperation(
|
|
tenant: $tenant,
|
|
type: 'backup_set.restore',
|
|
targetScope: [
|
|
'entra_tenant_id' => (string) ($tenant->tenant_id ?? $tenant->external_id),
|
|
],
|
|
selectionIdentity: $selectionIdentity,
|
|
dispatcher: function ($operationRun) use ($tenant, $initiator, $ids): void {
|
|
BulkBackupSetRestoreJob::dispatch(
|
|
tenantId: (int) $tenant->getKey(),
|
|
userId: (int) ($initiator?->getKey() ?? 0),
|
|
backupSetIds: $ids,
|
|
operationRun: $operationRun,
|
|
);
|
|
},
|
|
initiator: $initiator,
|
|
extraContext: [
|
|
'backup_set_count' => $count,
|
|
],
|
|
emitQueuedNotification: false,
|
|
);
|
|
|
|
OperationUxPresenter::queuedToast('backup_set.restore')
|
|
->actions([
|
|
Actions\Action::make('view_run')
|
|
->label('View run')
|
|
->url(OperationRunLinks::view($opRun, $tenant)),
|
|
])
|
|
->send();
|
|
})
|
|
->deselectRecordsAfterCompletion(),
|
|
|
|
BulkAction::make('bulk_force_delete')
|
|
->label('Force Delete Backup Sets')
|
|
->icon('heroicon-o-trash')
|
|
->color('danger')
|
|
->requiresConfirmation()
|
|
->disabled(fn (): bool => ! (($tenant = Tenant::current()) instanceof Tenant
|
|
&& Gate::allows(Capabilities::TENANT_DELETE, $tenant)))
|
|
->hidden(function (HasTable $livewire): bool {
|
|
$trashedFilterState = $livewire->getTableFilterState(TrashedFilter::class) ?? [];
|
|
$value = $trashedFilterState['value'] ?? null;
|
|
|
|
$isOnlyTrashed = in_array($value, [0, '0', false], true);
|
|
|
|
return ! $isOnlyTrashed;
|
|
})
|
|
->modalHeading(fn (Collection $records) => "Force delete {$records->count()} backup sets?")
|
|
->modalDescription('This is permanent. Only archived backup sets will be permanently deleted; active backup sets will be skipped.')
|
|
->form(function (Collection $records) {
|
|
if ($records->count() >= 10) {
|
|
return [
|
|
Forms\Components\TextInput::make('confirmation')
|
|
->label('Type DELETE to confirm')
|
|
->required()
|
|
->in(['DELETE'])
|
|
->validationMessages([
|
|
'in' => 'Please type DELETE to confirm.',
|
|
]),
|
|
];
|
|
}
|
|
|
|
return [];
|
|
})
|
|
->action(function (Collection $records) {
|
|
$tenant = Tenant::current();
|
|
$user = auth()->user();
|
|
$count = $records->count();
|
|
$ids = $records->pluck('id')->toArray();
|
|
|
|
if (! $tenant instanceof Tenant) {
|
|
return;
|
|
}
|
|
|
|
abort_unless(Gate::allows(Capabilities::TENANT_DELETE, $tenant), 403);
|
|
|
|
$initiator = $user instanceof User ? $user : null;
|
|
|
|
/** @var BulkSelectionIdentity $selection */
|
|
$selection = app(BulkSelectionIdentity::class);
|
|
$selectionIdentity = $selection->fromIds($ids);
|
|
|
|
/** @var OperationRunService $runs */
|
|
$runs = app(OperationRunService::class);
|
|
|
|
$opRun = $runs->enqueueBulkOperation(
|
|
tenant: $tenant,
|
|
type: 'backup_set.force_delete',
|
|
targetScope: [
|
|
'entra_tenant_id' => (string) ($tenant->tenant_id ?? $tenant->external_id),
|
|
],
|
|
selectionIdentity: $selectionIdentity,
|
|
dispatcher: function ($operationRun) use ($tenant, $initiator, $ids): void {
|
|
BulkBackupSetForceDeleteJob::dispatch(
|
|
tenantId: (int) $tenant->getKey(),
|
|
userId: (int) ($initiator?->getKey() ?? 0),
|
|
backupSetIds: $ids,
|
|
operationRun: $operationRun,
|
|
);
|
|
},
|
|
initiator: $initiator,
|
|
extraContext: [
|
|
'backup_set_count' => $count,
|
|
],
|
|
emitQueuedNotification: false,
|
|
);
|
|
|
|
OperationUxPresenter::queuedToast('backup_set.force_delete')
|
|
->actions([
|
|
Actions\Action::make('view_run')
|
|
->label('View run')
|
|
->url(OperationRunLinks::view($opRun, $tenant)),
|
|
])
|
|
->send();
|
|
})
|
|
->deselectRecordsAfterCompletion(),
|
|
]),
|
|
]);
|
|
}
|
|
|
|
public static function infolist(Schema $schema): Schema
|
|
{
|
|
return $schema
|
|
->schema([
|
|
Infolists\Components\TextEntry::make('name'),
|
|
Infolists\Components\TextEntry::make('status')
|
|
->badge()
|
|
->formatStateUsing(BadgeRenderer::label(BadgeDomain::BackupSetStatus))
|
|
->color(BadgeRenderer::color(BadgeDomain::BackupSetStatus))
|
|
->icon(BadgeRenderer::icon(BadgeDomain::BackupSetStatus))
|
|
->iconColor(BadgeRenderer::iconColor(BadgeDomain::BackupSetStatus)),
|
|
Infolists\Components\TextEntry::make('item_count')->label('Items'),
|
|
Infolists\Components\TextEntry::make('created_by')->label('Created by'),
|
|
Infolists\Components\TextEntry::make('completed_at')->dateTime(),
|
|
Infolists\Components\TextEntry::make('metadata')
|
|
->label('Metadata')
|
|
->formatStateUsing(fn ($state) => json_encode($state ?? [], JSON_PRETTY_PRINT))
|
|
->copyable()
|
|
->copyMessage('Metadata copied'),
|
|
]);
|
|
}
|
|
|
|
public static function getRelations(): array
|
|
{
|
|
return [
|
|
BackupItemsRelationManager::class,
|
|
];
|
|
}
|
|
|
|
public static function getPages(): array
|
|
{
|
|
return [
|
|
'index' => Pages\ListBackupSets::route('/'),
|
|
'create' => Pages\CreateBackupSet::route('/create'),
|
|
'view' => Pages\ViewBackupSet::route('/{record}'),
|
|
];
|
|
}
|
|
|
|
/**
|
|
* @return array{label:?string,category:?string,restore:?string,risk:?string}|array<string,mixed>
|
|
*/
|
|
private static function typeMeta(?string $type): array
|
|
{
|
|
if ($type === null) {
|
|
return [];
|
|
}
|
|
|
|
$types = array_merge(
|
|
config('tenantpilot.supported_policy_types', []),
|
|
config('tenantpilot.foundation_types', [])
|
|
);
|
|
|
|
return collect($types)
|
|
->firstWhere('type', $type) ?? [];
|
|
}
|
|
|
|
/**
|
|
* Create a backup set via the domain service instead of direct model mass-assignment.
|
|
*/
|
|
public static function createBackupSet(array $data): BackupSet
|
|
{
|
|
/** @var Tenant $tenant */
|
|
$tenant = Tenant::current();
|
|
|
|
/** @var BackupService $service */
|
|
$service = app(BackupService::class);
|
|
|
|
return $service->createBackupSet(
|
|
tenant: $tenant,
|
|
policyIds: $data['policy_ids'] ?? [],
|
|
name: $data['name'] ?? null,
|
|
actorEmail: auth()->user()?->email,
|
|
actorName: auth()->user()?->name,
|
|
includeAssignments: $data['include_assignments'] ?? false,
|
|
includeScopeTags: $data['include_scope_tags'] ?? false,
|
|
);
|
|
}
|
|
}
|