TenantAtlas/tests/Feature/PermissionPosture/PermissionPostureFindingGeneratorTest.php
ahmido ef380b67d1 feat(104): Provider Permission Posture (#127)
Implements Spec 104: Provider Permission Posture.

What changed
- Generates permission posture findings after each tenant permission compare (queued)
- Stores immutable posture snapshots as StoredReports (JSONB payload)
- Adds global Finding resolved lifecycle (`resolved_at`, `resolved_reason`) with `resolve()` / `reopen()`
- Adds alert pipeline event type `permission_missing` (Alerts v1) and Filament option for Alert Rules
- Adds retention pruning command + daily schedule for StoredReports
- Adds badge mappings for `resolved` finding status and `permission_posture` finding type

UX fixes discovered during manual verification
- Hide “Diff” section for non-drift findings (only drift findings show diff)
- Required Permissions page: “Re-run verification” now links to Tenant view (not onboarding)
- Preserve Technical Details `<details>` open state across Livewire re-renders (Alpine state)

Verification
- Ran `vendor/bin/sail artisan test --compact --filter=PermissionPosture` (50 tests)
- Ran `vendor/bin/sail artisan test --compact --filter="FindingResolved|FindingBadge|PermissionMissingAlert"` (20 tests)
- Ran `vendor/bin/sail bin pint --dirty`

Filament v5 / Livewire v4 compliance
- Filament v5 + Livewire v4: no Livewire v3 usage.

Panel provider registration (Laravel 11+)
- No new panels added. Existing panel providers remain registered via `bootstrap/providers.php`.

Global search rule
- No changes to global-searchable resources.

Destructive actions
- No new destructive Filament actions were added in this PR.

Assets / deploy notes
- No new Filament assets registered. Existing deploy step `php artisan filament:assets` remains unchanged.

Test coverage
- New/updated Pest feature tests cover generator behavior, job integration, alerting, retention pruning, and resolved lifecycle.

Co-authored-by: Ahmed Darrazi <ahmed.darrazi@live.de>
Reviewed-on: #127
2026-02-21 22:32:52 +00:00

340 lines
13 KiB
PHP

<?php
declare(strict_types=1);
use App\Models\Finding;
use App\Models\StoredReport;
use App\Models\User;
use App\Services\PermissionPosture\PermissionPostureFindingGenerator;
use App\Services\PermissionPosture\PostureResult;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
function buildComparison(array $permissions, string $overallStatus = 'missing'): array
{
return [
'overall_status' => $overallStatus,
'permissions' => $permissions,
'last_refreshed_at' => now()->toIso8601String(),
];
}
function missingPermission(string $key, array $features = ['policy-sync']): array
{
return ['key' => $key, 'type' => 'application', 'status' => 'missing', 'features' => $features];
}
function grantedPermission(string $key, array $features = ['policy-sync']): array
{
return ['key' => $key, 'type' => 'application', 'status' => 'granted', 'features' => $features];
}
function errorPermission(string $key, array $features = []): array
{
return ['key' => $key, 'type' => 'application', 'status' => 'error', 'features' => $features];
}
// (1) Creates findings for missing permissions
it('creates findings for missing permissions with correct attributes', function (): void {
[$user, $tenant] = createUserWithTenant();
$generator = app(PermissionPostureFindingGenerator::class);
$comparison = buildComparison([
missingPermission('DeviceManagementApps.ReadWrite.All', ['policy-sync', 'backup']),
]);
$result = $generator->generate($tenant, $comparison);
expect($result)->toBeInstanceOf(PostureResult::class)
->and($result->findingsCreated)->toBe(1);
$finding = Finding::query()
->where('tenant_id', $tenant->getKey())
->where('finding_type', Finding::FINDING_TYPE_PERMISSION_POSTURE)
->first();
expect($finding)->not->toBeNull()
->and($finding->source)->toBe('permission_check')
->and($finding->subject_type)->toBe('permission')
->and($finding->subject_external_id)->toBe('DeviceManagementApps.ReadWrite.All')
->and($finding->severity)->toBe(Finding::SEVERITY_HIGH) // 2 features → high
->and($finding->status)->toBe(Finding::STATUS_NEW)
->and($finding->evidence_jsonb['permission_key'])->toBe('DeviceManagementApps.ReadWrite.All')
->and($finding->evidence_jsonb['actual_status'])->toBe('missing')
->and($finding->fingerprint)->not->toBeEmpty();
});
// (2) Auto-resolves finding when permission granted
it('auto-resolves finding when permission is granted', function (): void {
[$user, $tenant] = createUserWithTenant();
$generator = app(PermissionPostureFindingGenerator::class);
// First run: missing
$generator->generate($tenant, buildComparison([
missingPermission('Perm.A'),
]));
expect(Finding::query()->where('tenant_id', $tenant->getKey())->where('status', Finding::STATUS_NEW)->count())->toBe(1);
// Second run: granted
$result = $generator->generate($tenant, buildComparison([
grantedPermission('Perm.A'),
], 'granted'));
expect($result->findingsResolved)->toBe(1);
$finding = Finding::query()
->where('tenant_id', $tenant->getKey())
->where('finding_type', Finding::FINDING_TYPE_PERMISSION_POSTURE)
->first();
expect($finding->status)->toBe(Finding::STATUS_RESOLVED)
->and($finding->resolved_at)->not->toBeNull()
->and($finding->resolved_reason)->toBe('permission_granted');
});
// (3) Auto-resolves acknowledged finding preserving metadata
it('auto-resolves acknowledged finding preserving acknowledged metadata', function (): void {
[$user, $tenant] = createUserWithTenant();
$generator = app(PermissionPostureFindingGenerator::class);
$generator->generate($tenant, buildComparison([missingPermission('Perm.A')]));
$finding = Finding::query()->where('tenant_id', $tenant->getKey())->first();
$ackUser = User::factory()->create();
$finding->acknowledge($ackUser);
$result = $generator->generate($tenant, buildComparison([grantedPermission('Perm.A')], 'granted'));
$finding->refresh();
expect($result->findingsResolved)->toBe(1)
->and($finding->status)->toBe(Finding::STATUS_RESOLVED)
->and($finding->acknowledged_at)->not->toBeNull()
->and($finding->acknowledged_by_user_id)->toBe($ackUser->getKey());
});
// (4) No duplicates on idempotent run
it('does not create duplicates on idempotent run', function (): void {
[$user, $tenant] = createUserWithTenant();
$generator = app(PermissionPostureFindingGenerator::class);
$comparison = buildComparison([missingPermission('Perm.A')]);
$result1 = $generator->generate($tenant, $comparison);
$result2 = $generator->generate($tenant, $comparison);
expect($result1->findingsCreated)->toBe(1)
->and($result2->findingsCreated)->toBe(0)
->and($result2->findingsUnchanged)->toBe(1);
expect(Finding::query()->where('tenant_id', $tenant->getKey())->count())->toBe(1);
});
// (5) Re-opens resolved finding when permission revoked again
it('re-opens resolved finding when permission is revoked again', function (): void {
[$user, $tenant] = createUserWithTenant();
$generator = app(PermissionPostureFindingGenerator::class);
// Missing → resolve → missing again
$generator->generate($tenant, buildComparison([missingPermission('Perm.A')]));
$generator->generate($tenant, buildComparison([grantedPermission('Perm.A')], 'granted'));
$finding = Finding::query()->where('tenant_id', $tenant->getKey())->first();
expect($finding->status)->toBe(Finding::STATUS_RESOLVED);
$result = $generator->generate($tenant, buildComparison([missingPermission('Perm.A')]));
$finding->refresh();
expect($result->findingsReopened)->toBe(1)
->and($finding->status)->toBe(Finding::STATUS_NEW)
->and($finding->resolved_at)->toBeNull()
->and($finding->resolved_reason)->toBeNull();
});
// (6) Creates error finding for status=error permissions
it('creates error finding for status=error permissions', function (): void {
[$user, $tenant] = createUserWithTenant();
$generator = app(PermissionPostureFindingGenerator::class);
$result = $generator->generate($tenant, buildComparison([
errorPermission('Perm.Error'),
]));
expect($result->errorsRecorded)->toBe(1);
$finding = Finding::query()
->where('tenant_id', $tenant->getKey())
->where('finding_type', Finding::FINDING_TYPE_PERMISSION_POSTURE)
->first();
expect($finding)->not->toBeNull()
->and($finding->severity)->toBe(Finding::SEVERITY_LOW)
->and($finding->evidence_jsonb['check_error'])->toBeTrue()
->and($finding->evidence_jsonb['actual_status'])->toBe('error');
// Distinct fingerprint from missing findings
$generator->generate($tenant, buildComparison([
missingPermission('Perm.Error'),
]));
expect(Finding::query()->where('tenant_id', $tenant->getKey())->count())->toBe(2);
});
// (7) Severity derivation
it('derives severity from feature count', function (int $featureCount, string $expectedSeverity): void {
[$user, $tenant] = createUserWithTenant();
$generator = app(PermissionPostureFindingGenerator::class);
$features = array_map(fn (int $i): string => "feature-$i", range(1, max(1, $featureCount)));
if ($featureCount === 0) {
$features = [];
}
$generator->generate($tenant, buildComparison([
missingPermission('Perm.Sev', $features),
]));
$finding = Finding::query()
->where('tenant_id', $tenant->getKey())
->where('finding_type', Finding::FINDING_TYPE_PERMISSION_POSTURE)
->whereNull('resolved_at')
->first();
expect($finding->severity)->toBe($expectedSeverity);
})->with([
'0 features → low' => [0, Finding::SEVERITY_LOW],
'1 feature → medium' => [1, Finding::SEVERITY_MEDIUM],
'2 features → high' => [2, Finding::SEVERITY_HIGH],
'3+ features → critical' => [3, Finding::SEVERITY_CRITICAL],
'5 features → critical' => [5, Finding::SEVERITY_CRITICAL],
]);
// (8) Creates StoredReport with correct payload
it('creates StoredReport with correct payload', function (): void {
[$user, $tenant] = createUserWithTenant();
$generator = app(PermissionPostureFindingGenerator::class);
$comparison = buildComparison([
grantedPermission('Perm.A', ['a', 'b']),
missingPermission('Perm.B', ['c']),
]);
$result = $generator->generate($tenant, $comparison);
$report = StoredReport::query()->find($result->storedReportId);
expect($report)->not->toBeNull()
->and($report->report_type)->toBe(StoredReport::REPORT_TYPE_PERMISSION_POSTURE)
->and($report->tenant_id)->toBe($tenant->getKey())
->and($report->payload['posture_score'])->toBe(50)
->and($report->payload['required_count'])->toBe(2)
->and($report->payload['granted_count'])->toBe(1)
->and($report->payload)->toHaveKey('checked_at')
->and($report->payload['permissions'])->toHaveCount(2);
});
// (9) No findings when all granted
it('resolves open findings when all permissions are granted', function (): void {
[$user, $tenant] = createUserWithTenant();
$generator = app(PermissionPostureFindingGenerator::class);
$generator->generate($tenant, buildComparison([missingPermission('Perm.A')]));
expect(Finding::query()->where('tenant_id', $tenant->getKey())->where('status', Finding::STATUS_NEW)->count())->toBe(1);
$result = $generator->generate($tenant, buildComparison([grantedPermission('Perm.A')], 'granted'));
expect($result->findingsResolved)->toBe(1)
->and($result->findingsCreated)->toBe(0);
});
// (10) Produces alert events for new and reopened findings only
it('produces alert events for new and reopened findings only', function (): void {
[$user, $tenant] = createUserWithTenant();
$generator = app(PermissionPostureFindingGenerator::class);
// Run 1: create new finding → should produce alert event
$generator->generate($tenant, buildComparison([missingPermission('Perm.A')]));
$events = $generator->getAlertEvents();
expect($events)->toHaveCount(1)
->and($events[0]['event_type'])->toBe('permission_missing');
});
// (11) Generator reads permissions from comparison, not hardcoded
it('processes arbitrary permission keys from comparison', function (): void {
[$user, $tenant] = createUserWithTenant();
$generator = app(PermissionPostureFindingGenerator::class);
$generator->generate($tenant, buildComparison([
missingPermission('CustomPerm.ReadWrite.All', ['feature-x']),
]));
$finding = Finding::query()->where('tenant_id', $tenant->getKey())->first();
expect($finding->subject_external_id)->toBe('CustomPerm.ReadWrite.All');
});
// (12) All findings are scoped to tenant_id
it('scopes all findings to tenant_id', function (): void {
[$user1, $tenant1] = createUserWithTenant();
[$user2, $tenant2] = createUserWithTenant();
$generator = app(PermissionPostureFindingGenerator::class);
$generator->generate($tenant1, buildComparison([missingPermission('Perm.A')]));
$generator->generate($tenant2, buildComparison([missingPermission('Perm.A')]));
expect(Finding::query()->where('tenant_id', $tenant1->getKey())->count())->toBe(1)
->and(Finding::query()->where('tenant_id', $tenant2->getKey())->count())->toBe(1);
});
// (13) subject_type and subject_external_id set correctly
it('sets subject_type=permission and subject_external_id on all posture findings', function (): void {
[$user, $tenant] = createUserWithTenant();
$generator = app(PermissionPostureFindingGenerator::class);
$generator->generate($tenant, buildComparison([
missingPermission('DeviceManagementApps.ReadWrite.All'),
missingPermission('DeviceManagementConfiguration.ReadWrite.All'),
]));
$findings = Finding::query()
->where('tenant_id', $tenant->getKey())
->where('finding_type', Finding::FINDING_TYPE_PERMISSION_POSTURE)
->get();
foreach ($findings as $finding) {
expect($finding->subject_type)->toBe('permission')
->and($finding->subject_external_id)->not->toBeEmpty();
}
});
// (14) Stale findings auto-resolved for registry removals
it('auto-resolves stale findings for permissions removed from registry', function (): void {
[$user, $tenant] = createUserWithTenant();
$generator = app(PermissionPostureFindingGenerator::class);
// Run 1: Perm.A and Perm.B are missing
$generator->generate($tenant, buildComparison([
missingPermission('Perm.A'),
missingPermission('Perm.B'),
]));
expect(Finding::query()->where('tenant_id', $tenant->getKey())->where('status', Finding::STATUS_NEW)->count())->toBe(2);
// Run 2: Perm.B is no longer in the registry (only Perm.A remains)
$result = $generator->generate($tenant, buildComparison([
missingPermission('Perm.A'),
]));
expect($result->findingsResolved)->toBeGreaterThanOrEqual(1);
$stale = Finding::query()
->where('tenant_id', $tenant->getKey())
->where('finding_type', Finding::FINDING_TYPE_PERMISSION_POSTURE)
->whereJsonContains('evidence_jsonb->permission_key', 'Perm.B')
->first();
expect($stale->status)->toBe(Finding::STATUS_RESOLVED)
->and($stale->resolved_reason)->toBe('permission_removed_from_registry');
});