TenantAtlas/tests/Feature/BackupScheduling/BackupScheduleLifecycleAuthorizationTest.php
ahmido 1f3619bd16 feat: tenant-owned query canon and wrong-tenant guards (#180)
## Summary
- introduce a shared tenant-owned query and record-resolution canon for first-slice Filament resources
- harden direct views, row actions, bulk actions, relation managers, and workspace-admin canonical viewers against wrong-tenant access
- add registry-backed rollout metadata, search posture handling, architectural guards, and focused Pest coverage for scope parity and 404/403 semantics

## Included
- Spec 150 package under `specs/150-tenant-owned-query-canon-and-wrong-tenant-guards/`
- shared support classes: `TenantOwnedModelFamilies`, `TenantOwnedQueryScope`, `TenantOwnedRecordResolver`
- shared Filament concern: `InteractsWithTenantOwnedRecords`
- resource/page/policy hardening across findings, policies, policy versions, backup schedules, backup sets, restore runs, inventory items, and Entra groups
- additional regression coverage for canonical tenant state, wrong-tenant record resolution, relation-manager congruence, and action-surface guardrails

## Validation
- `vendor/bin/sail artisan test --compact` passed
- full suite result: `2733 passed, 8 skipped`
- formatting applied with `vendor/bin/sail bin pint --dirty --format agent`

## Notes
- Livewire v4.0+ compliant via existing Filament v5 stack
- provider registration remains in `bootstrap/providers.php`
- globally searchable first-slice posture: Entra groups scoped; policies and policy versions explicitly disabled
- destructive actions continue to use confirmation and policy authorization
- no new Filament assets added; existing deployment flow remains unchanged, including `php artisan filament:assets` when registered assets are used

Co-authored-by: Ahmed Darrazi <ahmed.darrazi@live.de>
Reviewed-on: #180
2026-03-18 08:33:13 +00:00

175 lines
6.8 KiB
PHP

<?php
use App\Filament\Resources\BackupScheduleResource;
use App\Filament\Resources\BackupScheduleResource\Pages\ListBackupSchedules;
use App\Models\BackupSchedule;
use App\Models\Tenant;
use App\Support\Auth\UiTooltips;
use Filament\Actions\Action;
use Filament\Facades\Filament;
use Filament\Tables\Filters\TrashedFilter;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Support\Facades\Gate;
use Livewire\Features\SupportTesting\Testable;
use Livewire\Livewire;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
function getBackupScheduleEmptyStateAction(Testable $component, string $name): ?Action
{
foreach ($component->instance()->getTable()->getEmptyStateActions() as $action) {
if ($action instanceof Action && $action->getName() === $name) {
return $action;
}
}
return null;
}
it('returns 404 for non-members trying to access schedule lifecycle pages', function () {
$tenant = Tenant::factory()->create();
[$user] = createUserWithTenant(role: 'owner');
$this->actingAs($user)
->get(BackupScheduleResource::getUrl('index', tenant: $tenant))
->assertNotFound();
});
it('treats members without manage capability as forbidden for archive and restore', function () {
[$user, $tenant] = createUserWithTenant(role: 'readonly');
$schedule = BackupSchedule::query()->create([
'tenant_id' => $tenant->id,
'name' => 'Lifecycle auth readonly',
'is_enabled' => true,
'timezone' => 'UTC',
'frequency' => 'daily',
'time_of_day' => '01:00:00',
'days_of_week' => null,
'policy_types' => ['deviceConfiguration'],
'include_foundations' => true,
'retention_keep_last' => 30,
]);
$this->actingAs($user);
Filament::setTenant($tenant, true);
Livewire::test(ListBackupSchedules::class)
->assertTableActionDisabled('archive', $schedule)
->assertTableActionExists('archive', fn (Action $action): bool => $action->getTooltip() === UiTooltips::insufficientPermission(), $schedule)
->callTableAction('archive', $schedule);
expect(function () use ($user, $schedule): void {
Gate::forUser($user)->authorize('delete', $schedule);
})->toThrow(AuthorizationException::class);
$schedule->delete();
Livewire::test(ListBackupSchedules::class)
->filterTable(TrashedFilter::class, false)
->assertTableActionDisabled('restore', BackupSchedule::withTrashed()->findOrFail($schedule->id))
->assertTableActionExists('restore', fn (Action $action): bool => $action->getTooltip() === UiTooltips::insufficientPermission(), BackupSchedule::withTrashed()->findOrFail($schedule->id));
expect(function () use ($user, $schedule): void {
Gate::forUser($user)->authorize('restore', $schedule->fresh());
})->toThrow(AuthorizationException::class);
});
it('disables backup schedule create in the empty state for members without manage capability', function (): void {
[$user, $tenant] = createUserWithTenant(role: 'readonly');
$this->actingAs($user);
Filament::setTenant($tenant, true);
$component = Livewire::test(ListBackupSchedules::class)
->assertTableEmptyStateActionsExistInOrder(['create']);
$action = getBackupScheduleEmptyStateAction($component, 'create');
expect($action)->not->toBeNull();
expect($action?->isDisabled())->toBeTrue();
expect($action?->getTooltip())->toBe('You do not have permission to create backup schedules.');
});
it('treats members without tenant delete capability as forbidden for force delete', function () {
[$user, $tenant] = createUserWithTenant(role: 'manager');
$schedule = BackupSchedule::query()->create([
'tenant_id' => $tenant->id,
'name' => 'Force delete forbidden',
'is_enabled' => true,
'timezone' => 'UTC',
'frequency' => 'daily',
'time_of_day' => '01:00:00',
'days_of_week' => null,
'policy_types' => ['deviceConfiguration'],
'include_foundations' => true,
'retention_keep_last' => 30,
]);
$schedule->delete();
$this->actingAs($user);
Filament::setTenant($tenant, true);
Livewire::test(ListBackupSchedules::class)
->filterTable(TrashedFilter::class, false)
->assertTableActionDisabled('forceDelete', BackupSchedule::withTrashed()->findOrFail($schedule->id))
->assertTableActionExists('forceDelete', fn (Action $action): bool => $action->getTooltip() === UiTooltips::insufficientPermission(), BackupSchedule::withTrashed()->findOrFail($schedule->id));
expect(function () use ($user, $schedule): void {
Gate::forUser($user)->authorize('forceDelete', $schedule->fresh());
})->toThrow(AuthorizationException::class);
});
it('returns 404 and mutates nothing when forged foreign-tenant schedule keys are mounted', function (): void {
[$user, $tenant] = createUserWithTenant(role: 'owner');
$foreignTenant = Tenant::factory()->create();
$activeForeignSchedule = BackupSchedule::query()->create([
'tenant_id' => $foreignTenant->id,
'name' => 'Foreign active schedule',
'is_enabled' => true,
'timezone' => 'UTC',
'frequency' => 'daily',
'time_of_day' => '01:00:00',
'days_of_week' => null,
'policy_types' => ['deviceConfiguration'],
'include_foundations' => true,
'retention_keep_last' => 30,
]);
$trashedForeignSchedule = BackupSchedule::query()->create([
'tenant_id' => $foreignTenant->id,
'name' => 'Foreign trashed schedule',
'is_enabled' => true,
'timezone' => 'UTC',
'frequency' => 'daily',
'time_of_day' => '01:00:00',
'days_of_week' => null,
'policy_types' => ['deviceConfiguration'],
'include_foundations' => true,
'retention_keep_last' => 30,
]);
$trashedForeignSchedule->delete();
$this->actingAs($user);
Filament::setTenant($tenant, true);
$activeComponent = Livewire::test(ListBackupSchedules::class);
expect(fn () => $activeComponent->instance()->mountTableAction('archive', (string) $activeForeignSchedule->getKey()))
->toThrow(NotFoundHttpException::class);
$trashedComponent = Livewire::test(ListBackupSchedules::class)
->filterTable(TrashedFilter::class, false);
expect(fn () => $trashedComponent->instance()->mountTableAction('restore', (string) $trashedForeignSchedule->getKey()))
->toThrow(NotFoundHttpException::class);
expect(fn () => $trashedComponent->instance()->mountTableAction('forceDelete', (string) $trashedForeignSchedule->getKey()))
->toThrow(NotFoundHttpException::class);
expect($activeForeignSchedule->fresh()?->trashed())->toBeFalse();
expect(BackupSchedule::withTrashed()->find($trashedForeignSchedule->getKey()))->not->toBeNull();
});