TenantAtlas/tests/Feature/Baselines/BaselineCaptureTest.php

444 lines
17 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 App\Support\Baselines\BaselineSubjectKey;
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' => []],
]);
$inventoryA = InventoryItem::factory()->create([
'tenant_id' => $tenant->getKey(),
'workspace_id' => $tenant->workspace_id,
'external_id' => 'policy-a',
'policy_type' => 'deviceConfiguration',
'display_name' => 'Policy A',
'meta_jsonb' => ['odata_type' => '#microsoft.graph.deviceConfiguration', 'etag' => 'E1'],
]);
$inventoryB = InventoryItem::factory()->create([
'tenant_id' => $tenant->getKey(),
'workspace_id' => $tenant->workspace_id,
'external_id' => 'policy-b',
'policy_type' => 'deviceConfiguration',
'display_name' => 'Policy B',
'meta_jsonb' => ['odata_type' => '#microsoft.graph.deviceConfiguration', 'etag' => 'E2'],
]);
$inventoryC = InventoryItem::factory()->create([
'tenant_id' => $tenant->getKey(),
'workspace_id' => $tenant->workspace_id,
'external_id' => 'policy-c',
'policy_type' => 'deviceConfiguration',
'display_name' => 'Policy C',
'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();
$subjectKeyA = BaselineSubjectKey::fromDisplayName((string) $inventoryA->display_name);
$subjectKeyB = BaselineSubjectKey::fromDisplayName((string) $inventoryB->display_name);
$subjectKeyC = BaselineSubjectKey::fromDisplayName((string) $inventoryC->display_name);
expect($subjectKeyA)->not->toBeNull();
expect($subjectKeyB)->not->toBeNull();
expect($subjectKeyC)->not->toBeNull();
$expectedSubjectExternalIds = [
BaselineSubjectKey::workspaceSafeSubjectExternalId((string) $inventoryA->policy_type, (string) $subjectKeyA),
BaselineSubjectKey::workspaceSafeSubjectExternalId((string) $inventoryB->policy_type, (string) $subjectKeyB),
BaselineSubjectKey::workspaceSafeSubjectExternalId((string) $inventoryC->policy_type, (string) $subjectKeyC),
];
sort($expectedSubjectExternalIds, SORT_STRING);
expect($items->pluck('subject_external_id')->all())->toBe($expectedSubjectExternalIds);
$inventoryBySubjectKey = [
(string) $subjectKeyA => $inventoryA,
(string) $subjectKeyB => $inventoryB,
(string) $subjectKeyC => $inventoryC,
];
foreach ($items as $item) {
/** @var BaselineSnapshotItem $item */
$inventory = $inventoryBySubjectKey[(string) $item->subject_key] ?? null;
expect($inventory)->not->toBeNull();
$contractSubjectExternalId = (string) ($inventory->external_id ?? '');
$contract = $builder->build(
policyType: (string) $inventory->policy_type,
subjectExternalId: $contractSubjectExternalId,
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(data_get($meta, 'display_name'))->toBe((string) ($inventory->display_name ?? ''));
expect(data_get($meta, 'evidence.fidelity'))->toBe('meta');
expect(data_get($meta, 'evidence.source'))->toBe('inventory');
expect(data_get($meta, 'meta_contract'))->toBeNull();
}
$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);
});