TenantAtlas/tests/Feature/Baselines/BaselineCompareCoverageGuardTest.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

485 lines
18 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\Models\OperationRun;
use App\Services\Baselines\BaselineSnapshotIdentity;
use App\Services\Baselines\InventoryMetaContract;
use App\Services\Drift\DriftHasher;
use App\Services\Intune\AuditLogger;
use App\Services\OperationRunService;
use App\Support\Baselines\BaselineSubjectKey;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\OperationRunType;
it('skips findings for uncovered types and marks compare partially_succeeded', function (): void {
[$user, $tenant] = createUserWithTenant(role: 'owner');
$profile = BaselineProfile::factory()->active()->create([
'workspace_id' => (int) $tenant->workspace_id,
'scope_jsonb' => [
'policy_types' => ['deviceConfiguration', 'deviceCompliancePolicy'],
'foundation_types' => [],
],
]);
$snapshot = BaselineSnapshot::factory()->create([
'workspace_id' => (int) $tenant->workspace_id,
'baseline_profile_id' => (int) $profile->getKey(),
]);
$profile->update(['active_snapshot_id' => (int) $snapshot->getKey()]);
$builder = app(InventoryMetaContract::class);
$hasher = app(DriftHasher::class);
$coveredContract = $builder->build(
policyType: 'deviceConfiguration',
subjectExternalId: 'covered-uuid',
metaJsonb: ['odata_type' => '#microsoft.graph.deviceConfiguration', 'etag' => 'E_BASELINE'],
);
$coveredDisplayName = 'Covered Policy';
$coveredSubjectKey = BaselineSubjectKey::fromDisplayName($coveredDisplayName);
expect($coveredSubjectKey)->not->toBeNull();
$coveredWorkspaceSafeExternalId = BaselineSubjectKey::workspaceSafeSubjectExternalId('deviceConfiguration', (string) $coveredSubjectKey);
BaselineSnapshotItem::factory()->create([
'baseline_snapshot_id' => (int) $snapshot->getKey(),
'subject_type' => 'policy',
'subject_external_id' => $coveredWorkspaceSafeExternalId,
'subject_key' => (string) $coveredSubjectKey,
'policy_type' => 'deviceConfiguration',
'baseline_hash' => $hasher->hashNormalized($coveredContract),
'meta_jsonb' => ['display_name' => $coveredDisplayName],
]);
$uncoveredContract = $builder->build(
policyType: 'deviceCompliancePolicy',
subjectExternalId: 'uncovered-uuid',
metaJsonb: ['odata_type' => '#microsoft.graph.deviceCompliancePolicy', 'etag' => 'E_BASELINE'],
);
$uncoveredDisplayName = 'Uncovered Policy';
$uncoveredSubjectKey = BaselineSubjectKey::fromDisplayName($uncoveredDisplayName);
expect($uncoveredSubjectKey)->not->toBeNull();
$uncoveredWorkspaceSafeExternalId = BaselineSubjectKey::workspaceSafeSubjectExternalId('deviceCompliancePolicy', (string) $uncoveredSubjectKey);
BaselineSnapshotItem::factory()->create([
'baseline_snapshot_id' => (int) $snapshot->getKey(),
'subject_type' => 'policy',
'subject_external_id' => $uncoveredWorkspaceSafeExternalId,
'subject_key' => (string) $uncoveredSubjectKey,
'policy_type' => 'deviceCompliancePolicy',
'baseline_hash' => $hasher->hashNormalized($uncoveredContract),
'meta_jsonb' => ['display_name' => $uncoveredDisplayName],
]);
$inventorySyncRun = OperationRun::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'workspace_id' => (int) $tenant->workspace_id,
'type' => OperationRunType::InventorySync->value,
'status' => OperationRunStatus::Completed->value,
'outcome' => OperationRunOutcome::PartiallySucceeded->value,
'completed_at' => now(),
'context' => [
'inventory' => [
'coverage' => [
'policy_types' => [
'deviceConfiguration' => ['status' => 'succeeded'],
'deviceCompliancePolicy' => ['status' => 'failed'],
],
'foundation_types' => [],
],
],
],
]);
InventoryItem::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'workspace_id' => (int) $tenant->workspace_id,
'external_id' => 'covered-uuid',
'policy_type' => 'deviceConfiguration',
'meta_jsonb' => ['odata_type' => '#microsoft.graph.deviceConfiguration', 'etag' => 'E_CURRENT'],
'display_name' => $coveredDisplayName,
'last_seen_operation_run_id' => (int) $inventorySyncRun->getKey(),
'last_seen_at' => now(),
]);
$operationRuns = app(OperationRunService::class);
$compareRun = $operationRuns->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) $snapshot->getKey(),
'effective_scope' => [
'policy_types' => ['deviceConfiguration', 'deviceCompliancePolicy'],
'foundation_types' => [],
],
],
initiator: $user,
);
(new CompareBaselineToTenantJob($compareRun))->handle(
app(BaselineSnapshotIdentity::class),
app(AuditLogger::class),
$operationRuns,
);
$compareRun->refresh();
expect($compareRun->status)->toBe('completed');
expect($compareRun->outcome)->toBe(OperationRunOutcome::PartiallySucceeded->value);
$counts = is_array($compareRun->summary_counts) ? $compareRun->summary_counts : [];
expect((int) ($counts['errors_recorded'] ?? 0))->toBe(1);
$findings = Finding::query()
->where('tenant_id', (int) $tenant->getKey())
->where('source', 'baseline.compare')
->get();
expect($findings)->toHaveCount(1);
expect((string) data_get($findings->first(), 'evidence_jsonb.change_type'))->toBe('different_version');
});
it('emits zero findings when there is no completed inventory sync run (fail-safe)', function (): void {
[$user, $tenant] = createUserWithTenant(role: 'owner');
$profile = BaselineProfile::factory()->active()->create([
'workspace_id' => (int) $tenant->workspace_id,
'scope_jsonb' => [
'policy_types' => ['deviceConfiguration'],
'foundation_types' => [],
],
]);
$snapshot = BaselineSnapshot::factory()->create([
'workspace_id' => (int) $tenant->workspace_id,
'baseline_profile_id' => (int) $profile->getKey(),
]);
$builder = app(InventoryMetaContract::class);
$hasher = app(DriftHasher::class);
$contract = $builder->build(
policyType: 'deviceConfiguration',
subjectExternalId: 'policy-uuid',
metaJsonb: ['odata_type' => '#microsoft.graph.deviceConfiguration', 'etag' => 'E_BASELINE'],
);
BaselineSnapshotItem::factory()->create([
'baseline_snapshot_id' => (int) $snapshot->getKey(),
'subject_type' => 'policy',
'subject_external_id' => 'policy-uuid',
'policy_type' => 'deviceConfiguration',
'baseline_hash' => $hasher->hashNormalized($contract),
]);
InventoryItem::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'workspace_id' => (int) $tenant->workspace_id,
'external_id' => 'policy-uuid',
'policy_type' => 'deviceConfiguration',
'meta_jsonb' => ['odata_type' => '#microsoft.graph.deviceConfiguration', 'etag' => 'E_CURRENT'],
'display_name' => 'Policy Changed',
]);
$operationRuns = app(OperationRunService::class);
$compareRun = $operationRuns->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) $snapshot->getKey(),
'effective_scope' => [
'policy_types' => ['deviceConfiguration'],
'foundation_types' => [],
],
],
initiator: $user,
);
(new CompareBaselineToTenantJob($compareRun))->handle(
app(BaselineSnapshotIdentity::class),
app(AuditLogger::class),
$operationRuns,
);
$compareRun->refresh();
expect($compareRun->status)->toBe('completed');
expect($compareRun->outcome)->toBe(OperationRunOutcome::PartiallySucceeded->value);
$counts = is_array($compareRun->summary_counts) ? $compareRun->summary_counts : [];
expect((int) ($counts['errors_recorded'] ?? 0))->toBe(1);
expect((int) ($counts['total'] ?? -1))->toBe(0);
expect(
Finding::query()
->where('tenant_id', (int) $tenant->getKey())
->where('source', 'baseline.compare')
->count()
)->toBe(0);
});
it('emits zero findings when coverage payload is missing (fail-safe)', function (): void {
[$user, $tenant] = createUserWithTenant(role: 'owner');
$profile = BaselineProfile::factory()->active()->create([
'workspace_id' => (int) $tenant->workspace_id,
'scope_jsonb' => [
'policy_types' => ['deviceConfiguration'],
'foundation_types' => [],
],
]);
$snapshot = BaselineSnapshot::factory()->create([
'workspace_id' => (int) $tenant->workspace_id,
'baseline_profile_id' => (int) $profile->getKey(),
]);
OperationRun::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'workspace_id' => (int) $tenant->workspace_id,
'type' => OperationRunType::InventorySync->value,
'status' => OperationRunStatus::Completed->value,
'outcome' => OperationRunOutcome::Succeeded->value,
'completed_at' => now(),
'context' => [
'selection_hash' => 'latest',
],
]);
BaselineSnapshotItem::factory()->create([
'baseline_snapshot_id' => (int) $snapshot->getKey(),
'subject_type' => 'policy',
'subject_external_id' => 'policy-uuid',
'policy_type' => 'deviceConfiguration',
'baseline_hash' => hash('sha256', 'baseline'),
]);
InventoryItem::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'workspace_id' => (int) $tenant->workspace_id,
'external_id' => 'policy-uuid',
'policy_type' => 'deviceConfiguration',
'meta_jsonb' => ['odata_type' => '#microsoft.graph.deviceConfiguration', 'etag' => 'E_CURRENT'],
'display_name' => 'Policy Changed',
]);
$operationRuns = app(OperationRunService::class);
$compareRun = $operationRuns->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) $snapshot->getKey(),
'effective_scope' => [
'policy_types' => ['deviceConfiguration'],
'foundation_types' => [],
],
],
initiator: $user,
);
(new CompareBaselineToTenantJob($compareRun))->handle(
app(BaselineSnapshotIdentity::class),
app(AuditLogger::class),
$operationRuns,
);
$compareRun->refresh();
expect($compareRun->outcome)->toBe(OperationRunOutcome::PartiallySucceeded->value);
$counts = is_array($compareRun->summary_counts) ? $compareRun->summary_counts : [];
expect((int) ($counts['errors_recorded'] ?? 0))->toBe(1);
expect((int) ($counts['total'] ?? -1))->toBe(0);
expect(
Finding::query()
->where('tenant_id', (int) $tenant->getKey())
->where('source', 'baseline.compare')
->count()
)->toBe(0);
});
it('emits a warning and zero findings when effective scope expands to zero types', function (): void {
[$user, $tenant] = createUserWithTenant(role: 'owner');
$profile = BaselineProfile::factory()->active()->create([
'workspace_id' => (int) $tenant->workspace_id,
'scope_jsonb' => [
'policy_types' => ['unsupported_type'],
'foundation_types' => [],
],
]);
$snapshot = BaselineSnapshot::factory()->create([
'workspace_id' => (int) $tenant->workspace_id,
'baseline_profile_id' => (int) $profile->getKey(),
]);
$operationRuns = app(OperationRunService::class);
$compareRun = $operationRuns->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) $snapshot->getKey(),
'effective_scope' => [
'policy_types' => ['unsupported_type'],
'foundation_types' => [],
],
],
initiator: $user,
);
(new CompareBaselineToTenantJob($compareRun))->handle(
app(BaselineSnapshotIdentity::class),
app(AuditLogger::class),
$operationRuns,
);
$compareRun->refresh();
expect($compareRun->outcome)->toBe(OperationRunOutcome::PartiallySucceeded->value);
$supportedTypeCount = collect(config('tenantpilot.supported_policy_types', []))
->filter(fn (mixed $row): bool => is_array($row) && filled($row['type'] ?? null))
->count();
$counts = is_array($compareRun->summary_counts) ? $compareRun->summary_counts : [];
expect((int) ($counts['errors_recorded'] ?? 0))->toBe($supportedTypeCount);
expect((int) ($counts['total'] ?? -1))->toBe(0);
expect(
Finding::query()
->where('tenant_id', (int) $tenant->getKey())
->where('source', 'baseline.compare')
->count()
)->toBe(0);
});
it('suppresses intune role definition findings when RBAC foundation coverage is unproven', function (): void {
[$user, $tenant] = createUserWithTenant(role: 'owner');
$profile = BaselineProfile::factory()->active()->create([
'workspace_id' => (int) $tenant->workspace_id,
'scope_jsonb' => [
'policy_types' => ['deviceConfiguration'],
'foundation_types' => ['intuneRoleDefinition'],
],
]);
$snapshot = BaselineSnapshot::factory()->create([
'workspace_id' => (int) $tenant->workspace_id,
'baseline_profile_id' => (int) $profile->getKey(),
]);
$deviceConfigurationDisplayName = 'Covered Device Configuration';
$deviceConfigurationSubjectKey = BaselineSubjectKey::fromDisplayName($deviceConfigurationDisplayName);
expect($deviceConfigurationSubjectKey)->not->toBeNull();
$deviceConfigurationWorkspaceSafeExternalId = BaselineSubjectKey::workspaceSafeSubjectExternalId(
'deviceConfiguration',
(string) $deviceConfigurationSubjectKey,
);
$baselineHash = app(BaselineSnapshotIdentity::class)->hashItemContent(
policyType: 'deviceConfiguration',
subjectExternalId: 'device-config-covered',
metaJsonb: ['odata_type' => '#microsoft.graph.deviceConfiguration', 'etag' => 'E-STABLE'],
);
BaselineSnapshotItem::factory()->create([
'baseline_snapshot_id' => (int) $snapshot->getKey(),
'subject_type' => 'policy',
'subject_external_id' => $deviceConfigurationWorkspaceSafeExternalId,
'subject_key' => (string) $deviceConfigurationSubjectKey,
'policy_type' => 'deviceConfiguration',
'baseline_hash' => $baselineHash,
'meta_jsonb' => [
'display_name' => $deviceConfigurationDisplayName,
'evidence' => [
'fidelity' => 'meta',
'source' => 'inventory',
'observed_at' => now()->toIso8601String(),
],
],
]);
$inventorySyncRun = createInventorySyncOperationRunWithCoverage(
tenant: $tenant,
statusByType: [
'deviceConfiguration' => 'succeeded',
'intuneRoleDefinition' => 'failed',
],
foundationTypes: ['intuneRoleDefinition'],
attributes: [
'outcome' => OperationRunOutcome::PartiallySucceeded->value,
],
);
InventoryItem::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'workspace_id' => (int) $tenant->workspace_id,
'external_id' => 'device-config-covered',
'policy_type' => 'deviceConfiguration',
'display_name' => $deviceConfigurationDisplayName,
'meta_jsonb' => ['odata_type' => '#microsoft.graph.deviceConfiguration', 'etag' => 'E-STABLE'],
'last_seen_operation_run_id' => (int) $inventorySyncRun->getKey(),
'last_seen_at' => now(),
]);
$operationRuns = app(OperationRunService::class);
$compareRun = $operationRuns->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) $snapshot->getKey(),
'effective_scope' => [
'policy_types' => ['deviceConfiguration'],
'foundation_types' => ['intuneRoleDefinition'],
],
],
initiator: $user,
);
(new CompareBaselineToTenantJob($compareRun))->handle(
app(BaselineSnapshotIdentity::class),
app(AuditLogger::class),
$operationRuns,
);
$compareRun->refresh();
expect($compareRun->outcome)->toBe(OperationRunOutcome::PartiallySucceeded->value);
expect(data_get($compareRun->context, 'baseline_compare.reason_code'))->toBe('coverage_unproven');
expect(data_get($compareRun->context, 'baseline_compare.coverage.uncovered_types'))->toBe(['intuneRoleDefinition']);
expect(data_get($compareRun->context, 'baseline_compare.rbac_role_definitions'))->toBe([
'total_compared' => 0,
'unchanged' => 0,
'modified' => 0,
'missing' => 0,
'unexpected' => 0,
]);
expect(
Finding::query()
->where('tenant_id', (int) $tenant->getKey())
->where('source', 'baseline.compare')
->count()
)->toBe(0);
});