TenantAtlas/tests/Feature/Baselines/BaselineCaptureTest.php
Ahmed Darrazi 04d61cbad0 feat: baseline drift engine v1
- Implement Spec 116 baseline capture/compare + coverage guard\n- Add UI surfaces and widgets for baseline compare\n- Add tests and research report
2026-03-02 23:01:39 +01:00

419 lines
15 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\Models\OperationRun;
use App\Services\Baselines\BaselineCaptureService;
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\BaselineProfileStatus;
use Illuminate\Support\Facades\Queue;
// --- T031: Capture enqueue + precondition tests ---
it('enqueues capture for an active profile and creates an operation run', function () {
Queue::fake();
[$user, $tenant] = createUserWithTenant(role: 'owner');
$profile = BaselineProfile::factory()->active()->create([
'workspace_id' => $tenant->workspace_id,
'scope_jsonb' => ['policy_types' => ['deviceConfiguration'], 'foundation_types' => []],
]);
/** @var BaselineCaptureService $service */
$service = app(BaselineCaptureService::class);
$result = $service->startCapture($profile, $tenant, $user);
expect($result['ok'])->toBeTrue();
expect($result)->toHaveKey('run');
/** @var OperationRun $run */
$run = $result['run'];
expect($run->type)->toBe('baseline_capture');
expect($run->status)->toBe('queued');
expect($run->tenant_id)->toBe((int) $tenant->getKey());
$context = is_array($run->context) ? $run->context : [];
expect($context['baseline_profile_id'])->toBe((int) $profile->getKey());
expect($context['source_tenant_id'])->toBe((int) $tenant->getKey());
expect($context)->toHaveKey('effective_scope');
$effectiveScope = is_array($context['effective_scope'] ?? null) ? $context['effective_scope'] : [];
expect($effectiveScope['policy_types'])->toBe(['deviceConfiguration']);
expect($effectiveScope['foundation_types'])->toBe([]);
expect($effectiveScope['all_types'])->toBe(['deviceConfiguration']);
expect($effectiveScope['foundations_included'])->toBeFalse();
Queue::assertPushed(CaptureBaselineSnapshotJob::class);
});
it('rejects capture for a draft profile with reason code', function () {
Queue::fake();
[$user, $tenant] = createUserWithTenant(role: 'owner');
$profile = BaselineProfile::factory()->create([
'workspace_id' => $tenant->workspace_id,
'status' => BaselineProfileStatus::Draft->value,
]);
$service = app(BaselineCaptureService::class);
$result = $service->startCapture($profile, $tenant, $user);
expect($result['ok'])->toBeFalse();
expect($result['reason_code'])->toBe('baseline.capture.profile_not_active');
Queue::assertNotPushed(CaptureBaselineSnapshotJob::class);
expect(OperationRun::query()->where('type', 'baseline_capture')->count())->toBe(0);
});
it('rejects capture for an archived profile with reason code', function () {
Queue::fake();
[$user, $tenant] = createUserWithTenant(role: 'owner');
$profile = BaselineProfile::factory()->archived()->create([
'workspace_id' => $tenant->workspace_id,
]);
$service = app(BaselineCaptureService::class);
$result = $service->startCapture($profile, $tenant, $user);
expect($result['ok'])->toBeFalse();
expect($result['reason_code'])->toBe('baseline.capture.profile_not_active');
Queue::assertNotPushed(CaptureBaselineSnapshotJob::class);
expect(OperationRun::query()->where('type', 'baseline_capture')->count())->toBe(0);
});
it('rejects capture for a tenant from a different workspace', function () {
Queue::fake();
[$user, $tenant] = createUserWithTenant(role: 'owner');
[$otherUser, $otherTenant] = createUserWithTenant(role: 'owner');
$profile = BaselineProfile::factory()->active()->create([
'workspace_id' => $tenant->workspace_id,
]);
$service = app(BaselineCaptureService::class);
$result = $service->startCapture($profile, $otherTenant, $user);
expect($result['ok'])->toBeFalse();
expect($result['reason_code'])->toBe('baseline.capture.missing_source_tenant');
Queue::assertNotPushed(CaptureBaselineSnapshotJob::class);
});
// --- T032: Concurrent capture reuses active run [EC-004] ---
it('reuses an existing active run for the same profile/tenant instead of creating a new one', function () {
Queue::fake();
[$user, $tenant] = createUserWithTenant(role: 'owner');
$profile = BaselineProfile::factory()->active()->create([
'workspace_id' => $tenant->workspace_id,
'scope_jsonb' => ['policy_types' => ['deviceConfiguration'], 'foundation_types' => []],
]);
$service = app(BaselineCaptureService::class);
$result1 = $service->startCapture($profile, $tenant, $user);
$result2 = $service->startCapture($profile, $tenant, $user);
expect($result1['ok'])->toBeTrue();
expect($result2['ok'])->toBeTrue();
expect($result1['run']->getKey())->toBe($result2['run']->getKey());
expect(OperationRun::query()->where('type', 'baseline_capture')->count())->toBe(1);
});
// --- Snapshot dedupe + capture job execution ---
it('creates a snapshot with items when the capture job executes', function () {
[$user, $tenant] = createUserWithTenant(role: 'owner');
$profile = BaselineProfile::factory()->active()->create([
'workspace_id' => $tenant->workspace_id,
'scope_jsonb' => ['policy_types' => ['deviceConfiguration'], 'foundation_types' => []],
]);
InventoryItem::factory()->create([
'tenant_id' => $tenant->getKey(),
'workspace_id' => $tenant->workspace_id,
'external_id' => 'policy-a',
'policy_type' => 'deviceConfiguration',
'meta_jsonb' => ['odata_type' => '#microsoft.graph.deviceConfiguration', 'etag' => 'E1'],
]);
InventoryItem::factory()->create([
'tenant_id' => $tenant->getKey(),
'workspace_id' => $tenant->workspace_id,
'external_id' => 'policy-b',
'policy_type' => 'deviceConfiguration',
'meta_jsonb' => ['odata_type' => '#microsoft.graph.deviceConfiguration', 'etag' => 'E2'],
]);
InventoryItem::factory()->create([
'tenant_id' => $tenant->getKey(),
'workspace_id' => $tenant->workspace_id,
'external_id' => 'policy-c',
'policy_type' => 'deviceConfiguration',
'meta_jsonb' => ['odata_type' => '#microsoft.graph.deviceConfiguration', 'etag' => 'E3'],
]);
$opService = app(OperationRunService::class);
$run = $opService->ensureRunWithIdentity(
tenant: $tenant,
type: 'baseline_capture',
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,
);
$job = new CaptureBaselineSnapshotJob($run);
$job->handle(
app(BaselineSnapshotIdentity::class),
app(InventoryMetaContract::class),
app(AuditLogger::class),
$opService,
);
$run->refresh();
expect($run->status)->toBe('completed');
expect($run->outcome)->toBe('succeeded');
$counts = is_array($run->summary_counts) ? $run->summary_counts : [];
expect((int) ($counts['total'] ?? 0))->toBe(3);
expect((int) ($counts['succeeded'] ?? 0))->toBe(3);
$snapshot = BaselineSnapshot::query()
->where('baseline_profile_id', $profile->getKey())
->first();
expect($snapshot)->not->toBeNull();
expect(BaselineSnapshotItem::query()->where('baseline_snapshot_id', $snapshot->getKey())->count())->toBe(3);
$builder = app(InventoryMetaContract::class);
$hasher = app(DriftHasher::class);
$items = BaselineSnapshotItem::query()
->where('baseline_snapshot_id', $snapshot->getKey())
->orderBy('subject_external_id')
->get();
expect($items->pluck('subject_external_id')->all())->toBe(['policy-a', 'policy-b', 'policy-c']);
foreach ($items as $item) {
/** @var BaselineSnapshotItem $item */
$inventory = InventoryItem::query()
->where('tenant_id', $tenant->getKey())
->where('policy_type', $item->policy_type)
->where('external_id', $item->subject_external_id)
->first();
expect($inventory)->not->toBeNull();
$contract = $builder->build(
policyType: (string) $inventory->policy_type,
subjectExternalId: (string) $inventory->external_id,
metaJsonb: is_array($inventory->meta_jsonb) ? $inventory->meta_jsonb : [],
);
expect($item->baseline_hash)->toBe($hasher->hashNormalized($contract));
$meta = is_array($item->meta_jsonb) ? $item->meta_jsonb : [];
expect($meta)->toHaveKey('meta_contract');
expect($meta['meta_contract'])->toBe($contract);
}
$profile->refresh();
expect($profile->active_snapshot_id)->toBe((int) $snapshot->getKey());
});
it('dedupes snapshots when content is unchanged', function () {
[$user, $tenant] = createUserWithTenant(role: 'owner');
$profile = BaselineProfile::factory()->active()->create([
'workspace_id' => $tenant->workspace_id,
'scope_jsonb' => ['policy_types' => ['deviceConfiguration'], 'foundation_types' => []],
]);
InventoryItem::factory()->count(2)->create([
'tenant_id' => $tenant->getKey(),
'workspace_id' => $tenant->workspace_id,
'policy_type' => 'deviceConfiguration',
'meta_jsonb' => ['odata_type' => '#microsoft.graph.deviceConfiguration', 'stable_field' => 'value'],
]);
$opService = app(OperationRunService::class);
$idService = app(BaselineSnapshotIdentity::class);
$metaContract = app(InventoryMetaContract::class);
$auditLogger = app(AuditLogger::class);
$run1 = $opService->ensureRunWithIdentity(
tenant: $tenant,
type: 'baseline_capture',
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,
);
$job1 = new CaptureBaselineSnapshotJob($run1);
$job1->handle($idService, $metaContract, $auditLogger, $opService);
$snapshotCountAfterFirst = BaselineSnapshot::query()
->where('baseline_profile_id', $profile->getKey())
->count();
expect($snapshotCountAfterFirst)->toBe(1);
$run2 = OperationRun::create([
'workspace_id' => (int) $tenant->workspace_id,
'tenant_id' => (int) $tenant->getKey(),
'user_id' => (int) $user->getKey(),
'initiator_name' => $user->name,
'type' => 'baseline_capture',
'status' => 'queued',
'outcome' => 'pending',
'run_identity_hash' => hash('sha256', 'second-run-'.now()->timestamp),
'context' => [
'baseline_profile_id' => (int) $profile->getKey(),
'source_tenant_id' => (int) $tenant->getKey(),
'effective_scope' => ['policy_types' => ['deviceConfiguration'], 'foundation_types' => []],
],
]);
$job2 = new CaptureBaselineSnapshotJob($run2);
$job2->handle($idService, $metaContract, $auditLogger, $opService);
$snapshotCountAfterSecond = BaselineSnapshot::query()
->where('baseline_profile_id', $profile->getKey())
->count();
expect($snapshotCountAfterSecond)->toBe(1);
});
// --- EC-005: Empty scope produces empty snapshot without errors ---
it('captures an empty snapshot when no inventory items match the scope', function () {
[$user, $tenant] = createUserWithTenant(role: 'owner');
$profile = BaselineProfile::factory()->active()->create([
'workspace_id' => $tenant->workspace_id,
'scope_jsonb' => ['policy_types' => ['nonExistentPolicyType'], 'foundation_types' => []],
]);
$opService = app(OperationRunService::class);
$run = $opService->ensureRunWithIdentity(
tenant: $tenant,
type: 'baseline_capture',
identityInputs: ['baseline_profile_id' => (int) $profile->getKey()],
context: [
'baseline_profile_id' => (int) $profile->getKey(),
'source_tenant_id' => (int) $tenant->getKey(),
'effective_scope' => ['policy_types' => ['nonExistentPolicyType'], 'foundation_types' => []],
],
initiator: $user,
);
$job = new CaptureBaselineSnapshotJob($run);
$job->handle(
app(BaselineSnapshotIdentity::class),
app(InventoryMetaContract::class),
app(AuditLogger::class),
$opService,
);
$run->refresh();
expect($run->status)->toBe('completed');
expect($run->outcome)->toBe('succeeded');
$counts = is_array($run->summary_counts) ? $run->summary_counts : [];
expect((int) ($counts['total'] ?? 0))->toBe(0);
expect((int) ($counts['failed'] ?? 0))->toBe(0);
$snapshot = BaselineSnapshot::query()
->where('baseline_profile_id', $profile->getKey())
->first();
expect($snapshot)->not->toBeNull();
expect(BaselineSnapshotItem::query()->where('baseline_snapshot_id', $snapshot->getKey())->count())->toBe(0);
});
it('captures all inventory items when scope has empty policy_types (all types)', function () {
[$user, $tenant] = createUserWithTenant(role: 'owner');
$profile = BaselineProfile::factory()->active()->create([
'workspace_id' => $tenant->workspace_id,
'scope_jsonb' => ['policy_types' => [], 'foundation_types' => []],
]);
InventoryItem::factory()->create([
'tenant_id' => $tenant->getKey(),
'workspace_id' => $tenant->workspace_id,
'policy_type' => 'deviceConfiguration',
]);
InventoryItem::factory()->create([
'tenant_id' => $tenant->getKey(),
'workspace_id' => $tenant->workspace_id,
'policy_type' => 'deviceCompliancePolicy',
]);
// Foundation types are excluded by default (unless foundation_types is selected).
InventoryItem::factory()->create([
'tenant_id' => $tenant->getKey(),
'workspace_id' => $tenant->workspace_id,
'policy_type' => 'assignmentFilter',
]);
$opService = app(OperationRunService::class);
$run = $opService->ensureRunWithIdentity(
tenant: $tenant,
type: 'baseline_capture',
identityInputs: ['baseline_profile_id' => (int) $profile->getKey()],
context: [
'baseline_profile_id' => (int) $profile->getKey(),
'source_tenant_id' => (int) $tenant->getKey(),
'effective_scope' => ['policy_types' => [], 'foundation_types' => []],
],
initiator: $user,
);
$job = new CaptureBaselineSnapshotJob($run);
$job->handle(
app(BaselineSnapshotIdentity::class),
app(InventoryMetaContract::class),
app(AuditLogger::class),
$opService,
);
$run->refresh();
expect($run->status)->toBe('completed');
$counts = is_array($run->summary_counts) ? $run->summary_counts : [];
expect((int) ($counts['total'] ?? 0))->toBe(2);
$snapshot = BaselineSnapshot::query()
->where('baseline_profile_id', $profile->getKey())
->first();
expect($snapshot)->not->toBeNull();
expect(BaselineSnapshotItem::query()->where('baseline_snapshot_id', $snapshot->getKey())->count())->toBe(2);
});