TenantAtlas/tests/Feature/Baselines/BaselineCompareFindingRecurrenceKeyTest.php
ahmido ef41c9193a feat: add Intune RBAC baseline compare support (#156)
## Summary
- add Intune RBAC Role Definition baseline scope support, capture references, compare classification, findings evidence, and landing/detail UI labels
- keep Intune Role Assignments explicitly excluded from baseline compare scope, summaries, findings, and restore messaging
- add focused Pest coverage for baseline scope selection, capture, compare behavior, recurrence, isolation, findings rendering, inventory anchoring, and RBAC summaries

## Verification
- `vendor/bin/sail bin pint --dirty --format agent`
- `vendor/bin/sail artisan test --compact tests/Unit/Inventory/InventoryPolicyTypeMetaBaselineSupportTest.php tests/Unit/Baselines/BaselinePolicyVersionResolverTest.php tests/Unit/Baselines/BaselineScopeTest.php tests/Unit/IntuneRoleDefinitionNormalizerTest.php tests/Feature/Baselines/BaselineCaptureRbacRoleDefinitionsTest.php tests/Feature/Baselines/BaselineCompareRbacRoleDefinitionsTest.php tests/Feature/Baselines/BaselineCompareDriftEvidenceContractRbacTest.php tests/Feature/Baselines/BaselineCompareCoverageGuardTest.php tests/Feature/Baselines/BaselineCompareCrossTenantMatchTest.php tests/Feature/Baselines/BaselineCompareFindingRecurrenceKeyTest.php tests/Feature/Baselines/BaselineCompareWhyNoFindingsReasonCodeTest.php tests/Feature/Filament/BaselineProfileFoundationScopeTest.php tests/Feature/Filament/BaselineSnapshotRbacRoleDefinitionsTest.php tests/Feature/Filament/BaselineCompareLandingRbacLabelsTest.php tests/Feature/Filament/FindingViewRbacEvidenceTest.php tests/Feature/Findings/FindingRecurrenceTest.php tests/Feature/Findings/DriftStaleAutoResolveTest.php tests/Feature/Inventory/InventorySyncButtonTest.php tests/Feature/Inventory/InventorySyncServiceTest.php tests/Feature/RunAuthorizationTenantIsolationTest.php`
- result: `71 passed (467 assertions)`

## Filament / Platform Notes
- Livewire compliance: unchanged and compatible with Livewire v4.0+
- Provider registration: no panel/provider changes; `bootstrap/providers.php` remains the registration location
- Global search: no new globally searchable resource added; existing global search behavior is unchanged
- Destructive actions: no new destructive actions introduced; existing confirmed actions remain unchanged
- Assets: no new Filament assets introduced; deploy asset handling remains unchanged, including `php artisan filament:assets`
- Testing plan covered: baseline profile scope, snapshot detail, compare job, findings recurrence, findings detail, compare landing labels, inventory sync anchoring, and tenant isolation

Co-authored-by: Ahmed Darrazi <ahmed.darrazi@live.de>
Reviewed-on: #156
2026-03-09 18:49:20 +00:00

391 lines
14 KiB
PHP

<?php
use App\Jobs\CompareBaselineToTenantJob;
use App\Models\BaselineProfile;
use App\Models\BaselineSnapshot;
use App\Models\BaselineSnapshotItem;
use App\Models\Finding;
use App\Models\InventoryItem;
use App\Services\Baselines\BaselineSnapshotIdentity;
use App\Services\Intune\AuditLogger;
use App\Services\OperationRunService;
use App\Support\Baselines\BaselineSubjectKey;
use App\Support\OperationRunType;
it('uses a stable recurrence key independent of hashes and snapshot id', function () {
[$user, $tenant] = createUserWithTenant(role: 'owner');
$profile = BaselineProfile::factory()->active()->create([
'workspace_id' => (int) $tenant->workspace_id,
'scope_jsonb' => ['policy_types' => ['deviceConfiguration'], 'foundation_types' => []],
]);
$displayName = 'Policy X';
$subjectKey = BaselineSubjectKey::fromDisplayName($displayName);
expect($subjectKey)->not->toBeNull();
$workspaceSafeExternalId = BaselineSubjectKey::workspaceSafeSubjectExternalId(
policyType: 'deviceConfiguration',
subjectKey: (string) $subjectKey,
);
$snapshot1 = BaselineSnapshot::factory()->create([
'workspace_id' => (int) $tenant->workspace_id,
'baseline_profile_id' => (int) $profile->getKey(),
'captured_at' => now()->subMinutes(2),
]);
BaselineSnapshotItem::factory()->create([
'baseline_snapshot_id' => (int) $snapshot1->getKey(),
'subject_type' => 'policy',
'subject_external_id' => $workspaceSafeExternalId,
'subject_key' => (string) $subjectKey,
'policy_type' => 'deviceConfiguration',
'baseline_hash' => hash('sha256', 'baseline-v1'),
'meta_jsonb' => [
'display_name' => $displayName,
'evidence' => [
'fidelity' => 'meta',
'source' => 'inventory',
'observed_at' => now()->toIso8601String(),
],
],
]);
$snapshot2 = BaselineSnapshot::factory()->create([
'workspace_id' => (int) $tenant->workspace_id,
'baseline_profile_id' => (int) $profile->getKey(),
'captured_at' => now()->subMinute(),
]);
BaselineSnapshotItem::factory()->create([
'baseline_snapshot_id' => (int) $snapshot2->getKey(),
'subject_type' => 'policy',
'subject_external_id' => $workspaceSafeExternalId,
'subject_key' => (string) $subjectKey,
'policy_type' => 'deviceConfiguration',
'baseline_hash' => hash('sha256', 'baseline-v2'),
'meta_jsonb' => [
'display_name' => $displayName,
'evidence' => [
'fidelity' => 'meta',
'source' => 'inventory',
'observed_at' => now()->toIso8601String(),
],
],
]);
$inventorySyncRun = createInventorySyncOperationRunWithCoverage(
tenant: $tenant,
statusByType: ['deviceConfiguration' => 'succeeded'],
);
InventoryItem::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'workspace_id' => (int) $tenant->workspace_id,
'external_id' => 'policy-x-uuid',
'policy_type' => 'deviceConfiguration',
'meta_jsonb' => ['odata_type' => '#microsoft.graph.deviceConfiguration', 'etag' => 'E_CURRENT_1'],
'display_name' => $displayName,
'last_seen_operation_run_id' => (int) $inventorySyncRun->getKey(),
'last_seen_at' => now(),
]);
$opService = app(OperationRunService::class);
$run1 = $opService->ensureRunWithIdentity(
tenant: $tenant,
type: OperationRunType::BaselineCompare->value,
identityInputs: ['baseline_profile_id' => (int) $profile->getKey()],
context: [
'baseline_profile_id' => (int) $profile->getKey(),
'baseline_snapshot_id' => (int) $snapshot1->getKey(),
'effective_scope' => ['policy_types' => ['deviceConfiguration'], 'foundation_types' => []],
],
initiator: $user,
);
$job = new CompareBaselineToTenantJob($run1);
$job->handle(
app(BaselineSnapshotIdentity::class),
app(AuditLogger::class),
$opService,
);
$finding = Finding::query()
->where('tenant_id', (int) $tenant->getKey())
->where('source', 'baseline.compare')
->sole();
expect($finding->recurrence_key)->not->toBeNull();
expect($finding->fingerprint)->toBe($finding->recurrence_key);
expect($finding->times_seen)->toBe(1);
$fingerprint = (string) $finding->fingerprint;
// Retry the same run ID (job retry): times_seen MUST NOT increment twice for the same run.
$job->handle(
app(BaselineSnapshotIdentity::class),
app(AuditLogger::class),
$opService,
);
$finding->refresh();
expect($finding->times_seen)->toBe(1);
expect((string) $finding->fingerprint)->toBe($fingerprint);
// Compare against a different baseline snapshot (hash changes), but recurrence identity stays stable.
$run2 = $opService->ensureRunWithIdentity(
tenant: $tenant,
type: OperationRunType::BaselineCompare->value,
identityInputs: ['baseline_profile_id' => (int) $profile->getKey()],
context: [
'baseline_profile_id' => (int) $profile->getKey(),
'baseline_snapshot_id' => (int) $snapshot2->getKey(),
'effective_scope' => ['policy_types' => ['deviceConfiguration'], 'foundation_types' => []],
],
initiator: $user,
);
(new CompareBaselineToTenantJob($run2))->handle(
app(BaselineSnapshotIdentity::class),
app(AuditLogger::class),
$opService,
);
$finding->refresh();
expect((string) $finding->fingerprint)->toBe($fingerprint);
expect($finding->times_seen)->toBe(2);
});
function rbacRecurrenceSnapshot(string $displayName, string $description, array $allowedActions): array
{
return [
'displayName' => $displayName,
'description' => $description,
'isBuiltIn' => false,
'rolePermissions' => [
[
'resourceActions' => [
[
'allowedResourceActions' => $allowedActions,
],
],
],
],
'roleScopeTagIds' => ['0'],
];
}
it('keeps intune role definition recurrence stable when the normalized diff fingerprint changes', function (): void {
[$user, $tenant] = createUserWithTenant(role: 'owner');
$profile = BaselineProfile::factory()->active()->create([
'workspace_id' => (int) $tenant->workspace_id,
'scope_jsonb' => [
'policy_types' => [],
'foundation_types' => ['intuneRoleDefinition'],
],
]);
$capturedAt = now()->subMinutes(5);
$displayName = 'Security Reader';
$externalId = 'rbac-role-stable';
$subjectKey = BaselineSubjectKey::forPolicy('intuneRoleDefinition', $displayName, $externalId);
$workspaceSafeExternalId = BaselineSubjectKey::workspaceSafeSubjectExternalIdForPolicy('intuneRoleDefinition', $displayName, $externalId);
expect($subjectKey)->not->toBeNull();
expect($workspaceSafeExternalId)->not->toBeNull();
$policy = \App\Models\Policy::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'external_id' => $externalId,
'policy_type' => 'intuneRoleDefinition',
'platform' => 'all',
'display_name' => $displayName,
]);
$baselineVersionOne = \App\Models\PolicyVersion::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'policy_id' => (int) $policy->getKey(),
'policy_type' => 'intuneRoleDefinition',
'platform' => 'all',
'version_number' => 1,
'captured_at' => $capturedAt->copy(),
'snapshot' => rbacRecurrenceSnapshot($displayName, 'Baseline v1', ['microsoft.intune/devices/read']),
'assignments' => [],
'scope_tags' => [],
]);
$baselineVersionTwo = \App\Models\PolicyVersion::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'policy_id' => (int) $policy->getKey(),
'policy_type' => 'intuneRoleDefinition',
'platform' => 'all',
'version_number' => 2,
'captured_at' => $capturedAt->copy()->addMinute(),
'snapshot' => rbacRecurrenceSnapshot($displayName, 'Baseline v2', ['microsoft.intune/devices/read']),
'assignments' => [],
'scope_tags' => [],
]);
$snapshot1 = BaselineSnapshot::factory()->create([
'workspace_id' => (int) $tenant->workspace_id,
'baseline_profile_id' => (int) $profile->getKey(),
'captured_at' => $capturedAt->copy(),
]);
$snapshot2 = BaselineSnapshot::factory()->create([
'workspace_id' => (int) $tenant->workspace_id,
'baseline_profile_id' => (int) $profile->getKey(),
'captured_at' => $capturedAt->copy()->addMinute(),
]);
$provider = app(\App\Services\Baselines\Evidence\ContentEvidenceProvider::class);
BaselineSnapshotItem::factory()->create([
'baseline_snapshot_id' => (int) $snapshot1->getKey(),
'subject_type' => 'policy',
'subject_external_id' => (string) $workspaceSafeExternalId,
'subject_key' => (string) $subjectKey,
'policy_type' => 'intuneRoleDefinition',
'baseline_hash' => $provider->fromPolicyVersion($baselineVersionOne, (string) $workspaceSafeExternalId)->hash,
'meta_jsonb' => [
'display_name' => $displayName,
'evidence' => [
'fidelity' => 'content',
'source' => 'policy_version',
'observed_at' => $baselineVersionOne->captured_at?->toIso8601String(),
],
'version_reference' => [
'policy_version_id' => (int) $baselineVersionOne->getKey(),
],
'rbac' => [
'is_built_in' => false,
'role_permission_count' => 1,
],
],
]);
BaselineSnapshotItem::factory()->create([
'baseline_snapshot_id' => (int) $snapshot2->getKey(),
'subject_type' => 'policy',
'subject_external_id' => (string) $workspaceSafeExternalId,
'subject_key' => (string) $subjectKey,
'policy_type' => 'intuneRoleDefinition',
'baseline_hash' => $provider->fromPolicyVersion($baselineVersionTwo, (string) $workspaceSafeExternalId)->hash,
'meta_jsonb' => [
'display_name' => $displayName,
'evidence' => [
'fidelity' => 'content',
'source' => 'policy_version',
'observed_at' => $baselineVersionTwo->captured_at?->toIso8601String(),
],
'version_reference' => [
'policy_version_id' => (int) $baselineVersionTwo->getKey(),
],
'rbac' => [
'is_built_in' => false,
'role_permission_count' => 1,
],
],
]);
$currentVersion = \App\Models\PolicyVersion::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'policy_id' => (int) $policy->getKey(),
'policy_type' => 'intuneRoleDefinition',
'platform' => 'all',
'version_number' => 3,
'captured_at' => $capturedAt->copy()->addMinutes(2),
'snapshot' => rbacRecurrenceSnapshot($displayName, 'Current drifted role', [
'microsoft.intune/devices/read',
'microsoft.intune/devices/delete',
]),
'assignments' => [],
'scope_tags' => [],
]);
$inventorySyncRun = createInventorySyncOperationRunWithCoverage(
tenant: $tenant,
statusByType: ['intuneRoleDefinition' => 'succeeded'],
foundationTypes: ['intuneRoleDefinition'],
);
InventoryItem::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'workspace_id' => (int) $tenant->workspace_id,
'external_id' => $externalId,
'policy_type' => 'intuneRoleDefinition',
'meta_jsonb' => [
'odata_type' => '#microsoft.graph.deviceAndAppManagementRoleDefinition',
'is_built_in' => false,
'role_permission_count' => 1,
],
'display_name' => $displayName,
'last_seen_operation_run_id' => (int) $inventorySyncRun->getKey(),
'last_seen_at' => now(),
]);
$opService = app(OperationRunService::class);
$run1 = $opService->ensureRunWithIdentity(
tenant: $tenant,
type: OperationRunType::BaselineCompare->value,
identityInputs: ['baseline_profile_id' => (int) $profile->getKey()],
context: [
'baseline_profile_id' => (int) $profile->getKey(),
'baseline_snapshot_id' => (int) $snapshot1->getKey(),
'effective_scope' => [
'policy_types' => [],
'foundation_types' => ['intuneRoleDefinition'],
],
],
initiator: $user,
);
(new CompareBaselineToTenantJob($run1))->handle(
app(BaselineSnapshotIdentity::class),
app(AuditLogger::class),
$opService,
);
$finding = Finding::query()
->where('tenant_id', (int) $tenant->getKey())
->where('source', 'baseline.compare')
->sole();
$fingerprint = (string) $finding->fingerprint;
$firstDiffFingerprint = (string) data_get($finding->evidence_jsonb, 'rbac_role_definition.diff_fingerprint');
expect($finding->recurrence_key)->toBe($fingerprint)
->and($firstDiffFingerprint)->not->toBe('');
$run2 = $opService->ensureRunWithIdentity(
tenant: $tenant,
type: OperationRunType::BaselineCompare->value,
identityInputs: ['baseline_profile_id' => (int) $profile->getKey()],
context: [
'baseline_profile_id' => (int) $profile->getKey(),
'baseline_snapshot_id' => (int) $snapshot2->getKey(),
'effective_scope' => [
'policy_types' => [],
'foundation_types' => ['intuneRoleDefinition'],
],
],
initiator: $user,
);
(new CompareBaselineToTenantJob($run2))->handle(
app(BaselineSnapshotIdentity::class),
app(AuditLogger::class),
$opService,
);
$finding->refresh();
expect((string) $finding->fingerprint)->toBe($fingerprint)
->and($finding->times_seen)->toBe(2)
->and((string) data_get($finding->evidence_jsonb, 'rbac_role_definition.diff_fingerprint'))->not->toBe($firstDiffFingerprint);
});