TenantAtlas/tests/Feature/Baselines/BaselineCaptureAmbiguousMatchGapTest.php
ahmido da1adbdeb5 Spec 119: Drift cutover to Baseline Compare (golden master) (#144)
Implements Spec 119 (Drift Golden Master Cutover):

- Baseline Compare is the only drift writer (`source = baseline.compare`).
- Drift findings now store diff-compatible `evidence_jsonb` (summary.kind, baseline/current policy_version_id refs, fidelity + provenance).
- Findings UI renders one-sided diffs for `missing_policy`/`unexpected_policy` when a single ref exists; otherwise shows explicit “diff unavailable”.
- Removes legacy drift generator runtime (jobs/services/UI) and related tests.
- Adds one-time migration to delete legacy drift findings (`finding_type=drift` where source is null or != baseline.compare).
- Scopes baseline capture & landing duplicate warnings to latest completed inventory sync.
- Canonicalizes compliance `scheduledActionsForRule` drift signal and keeps legacy snapshots comparable.

Tests:
- `vendor/bin/sail artisan test --compact` (full suite per tasks)
- Focused pack: BaselinePolicyVersionResolverTest, BaselineCompareDriftEvidenceContractTest, DriftFindingDiffUnavailableTest, LegacyDriftFindingsCleanupMigrationTest, ComplianceNoncomplianceActionsDriftTest

Notes:
- Livewire v4+ / Filament v5 compatible (no legacy APIs).
- No new external dependencies.

Co-authored-by: Ahmed Darrazi <ahmed.darrazi@live.de>
Reviewed-on: #144
2026-03-06 14:30:49 +00:00

228 lines
8.5 KiB
PHP

<?php
use App\Jobs\CaptureBaselineSnapshotJob;
use App\Models\BaselineProfile;
use App\Models\BaselineSnapshot;
use App\Models\BaselineSnapshotItem;
use App\Models\InventoryItem;
use App\Services\Baselines\BaselineSnapshotIdentity;
use App\Services\Baselines\InventoryMetaContract;
use App\Services\Intune\AuditLogger;
use App\Services\OperationRunService;
use App\Support\Baselines\BaselineSubjectKey;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunType;
it('treats duplicate subject_key matches as an evidence gap and captures remaining subjects', 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 = 'Duplicate Policy';
$inventorySyncRun = createInventorySyncOperationRunWithCoverage(
tenant: $tenant,
statusByType: ['deviceConfiguration' => 'succeeded'],
);
InventoryItem::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'workspace_id' => (int) $tenant->workspace_id,
'external_id' => 'dup-1',
'policy_type' => 'deviceConfiguration',
'display_name' => $displayName,
'meta_jsonb' => ['etag' => 'E1'],
'last_seen_operation_run_id' => (int) $inventorySyncRun->getKey(),
'last_seen_at' => now(),
]);
InventoryItem::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'workspace_id' => (int) $tenant->workspace_id,
'external_id' => 'dup-2',
'policy_type' => 'deviceConfiguration',
'display_name' => $displayName,
'meta_jsonb' => ['etag' => 'E2'],
'last_seen_operation_run_id' => (int) $inventorySyncRun->getKey(),
'last_seen_at' => now(),
]);
InventoryItem::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'workspace_id' => (int) $tenant->workspace_id,
'external_id' => 'unique-1',
'policy_type' => 'deviceConfiguration',
'display_name' => 'Unique Policy',
'meta_jsonb' => ['etag' => 'E_UNIQUE'],
'last_seen_operation_run_id' => (int) $inventorySyncRun->getKey(),
'last_seen_at' => now(),
]);
$opService = app(OperationRunService::class);
$run = $opService->ensureRunWithIdentity(
tenant: $tenant,
type: OperationRunType::BaselineCapture->value,
identityInputs: ['baseline_profile_id' => (int) $profile->getKey()],
context: [
'baseline_profile_id' => (int) $profile->getKey(),
'source_tenant_id' => (int) $tenant->getKey(),
'effective_scope' => ['policy_types' => ['deviceConfiguration'], 'foundation_types' => []],
],
initiator: $user,
);
(new CaptureBaselineSnapshotJob($run))->handle(
app(BaselineSnapshotIdentity::class),
app(InventoryMetaContract::class),
app(AuditLogger::class),
$opService,
);
$run->refresh();
expect($run->status)->toBe('completed');
expect($run->outcome)->toBe(OperationRunOutcome::PartiallySucceeded->value);
$counts = is_array($run->summary_counts) ? $run->summary_counts : [];
expect((int) ($counts['total'] ?? 0))->toBe(1);
expect((int) ($counts['succeeded'] ?? 0))->toBe(1);
$context = is_array($run->context) ? $run->context : [];
expect(data_get($context, 'baseline_capture.gaps.by_reason.ambiguous_match'))->toBe(1);
$snapshot = BaselineSnapshot::query()
->where('baseline_profile_id', (int) $profile->getKey())
->sole();
expect(
BaselineSnapshotItem::query()
->where('baseline_snapshot_id', (int) $snapshot->getKey())
->count(),
)->toBe(1);
$subjectKey = BaselineSubjectKey::fromDisplayName('Unique Policy');
expect($subjectKey)->not->toBeNull();
$workspaceSafeExternalId = BaselineSubjectKey::workspaceSafeSubjectExternalId(
policyType: 'deviceConfiguration',
subjectKey: (string) $subjectKey,
);
BaselineSnapshotItem::query()
->where('baseline_snapshot_id', (int) $snapshot->getKey())
->where('subject_external_id', $workspaceSafeExternalId)
->sole();
});
it('ignores stale duplicate subject_key rows from older inventory sync runs', function () {
[$user, $tenant] = createUserWithTenant(role: 'owner');
$profile = BaselineProfile::factory()->active()->create([
'workspace_id' => (int) $tenant->workspace_id,
'scope_jsonb' => ['policy_types' => ['deviceConfiguration'], 'foundation_types' => []],
]);
$olderInventoryRun = createInventorySyncOperationRunWithCoverage(
tenant: $tenant,
statusByType: ['deviceConfiguration' => 'succeeded'],
attributes: [
'finished_at' => now()->subMinutes(10),
'completed_at' => now()->subMinutes(10),
],
);
$latestInventoryRun = createInventorySyncOperationRunWithCoverage(
tenant: $tenant,
statusByType: ['deviceConfiguration' => 'succeeded'],
attributes: [
'finished_at' => now(),
'completed_at' => now(),
],
);
InventoryItem::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'workspace_id' => (int) $tenant->workspace_id,
'external_id' => 'stale-standard',
'policy_type' => 'deviceConfiguration',
'display_name' => 'Standard',
'meta_jsonb' => ['etag' => 'E_STALE'],
'last_seen_operation_run_id' => (int) $olderInventoryRun->getKey(),
'last_seen_at' => now()->subMinutes(10),
]);
InventoryItem::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'workspace_id' => (int) $tenant->workspace_id,
'external_id' => 'current-standard',
'policy_type' => 'deviceConfiguration',
'display_name' => 'Standard',
'meta_jsonb' => ['etag' => 'E_CURRENT'],
'last_seen_operation_run_id' => (int) $latestInventoryRun->getKey(),
'last_seen_at' => now(),
]);
InventoryItem::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'workspace_id' => (int) $tenant->workspace_id,
'external_id' => 'current-unique',
'policy_type' => 'deviceConfiguration',
'display_name' => 'Unique Policy',
'meta_jsonb' => ['etag' => 'E_UNIQUE'],
'last_seen_operation_run_id' => (int) $latestInventoryRun->getKey(),
'last_seen_at' => now(),
]);
$opService = app(OperationRunService::class);
$run = $opService->ensureRunWithIdentity(
tenant: $tenant,
type: OperationRunType::BaselineCapture->value,
identityInputs: ['baseline_profile_id' => (int) $profile->getKey()],
context: [
'baseline_profile_id' => (int) $profile->getKey(),
'source_tenant_id' => (int) $tenant->getKey(),
'effective_scope' => ['policy_types' => ['deviceConfiguration'], 'foundation_types' => []],
],
initiator: $user,
);
(new CaptureBaselineSnapshotJob($run))->handle(
app(BaselineSnapshotIdentity::class),
app(InventoryMetaContract::class),
app(AuditLogger::class),
$opService,
);
$run->refresh();
expect($run->status)->toBe('completed');
expect($run->outcome)->toBe(OperationRunOutcome::Succeeded->value);
$counts = is_array($run->summary_counts) ? $run->summary_counts : [];
expect((int) ($counts['total'] ?? 0))->toBe(2);
expect((int) ($counts['succeeded'] ?? 0))->toBe(2);
$context = is_array($run->context) ? $run->context : [];
expect(data_get($context, 'baseline_capture.inventory_sync_run_id'))->toBe((int) $latestInventoryRun->getKey());
expect(data_get($context, 'baseline_capture.gaps.by_reason.ambiguous_match'))->toBeNull();
$snapshot = BaselineSnapshot::query()
->where('baseline_profile_id', (int) $profile->getKey())
->sole();
expect(
BaselineSnapshotItem::query()
->where('baseline_snapshot_id', (int) $snapshot->getKey())
->count(),
)->toBe(2);
$standardSubjectKey = BaselineSubjectKey::fromDisplayName('Standard');
expect($standardSubjectKey)->not->toBeNull();
$standardExternalId = BaselineSubjectKey::workspaceSafeSubjectExternalId(
policyType: 'deviceConfiguration',
subjectKey: (string) $standardSubjectKey,
);
BaselineSnapshotItem::query()
->where('baseline_snapshot_id', (int) $snapshot->getKey())
->where('subject_external_id', $standardExternalId)
->sole();
});