TenantAtlas/tests/Feature/Filament/RestoreExecutionTest.php
ahmido bcf4996a1e feat/049-backup-restore-job-orchestration (#56)
Summary

This PR implements Spec 049 – Backup/Restore Job Orchestration: all critical Backup/Restore execution paths are job-only, idempotent, tenant-scoped, and observable via run records + DB notifications (Phase 1). The UI no longer performs heavy Graph work inside request/Filament actions for these flows.

Why

We want predictable UX and operations at MSP scale:
	•	no timeouts / long-running requests
	•	reproducible run state + per-item results
	•	safe error persistence (no secrets / no token leakage)
	•	strict tenant isolation + auditability for write paths

What changed

Foundational (Runs + Idempotency + Observability)
	•	Added a shared RunIdempotency helper (dedupe while queued/running).
	•	Added a read-only BulkOperationRuns surface (list + view) for status/progress.
	•	Added DB notifications for run status changes (with “View run” link).

US1 – Policy “Capture snapshot” is job-only
	•	Policy detail “Capture snapshot” now:
	•	creates/reuses a run (dedupe key: tenant + policy.capture_snapshot + policy DB id)
	•	dispatches a queued job
	•	returns immediately with notification + link to run detail
	•	Graph capture work moved fully into the job; request path stays Graph-free.

US3 – Restore runs orchestration is job-only + safe
	•	Live restore execution is queued and updates RestoreRun status/progress.
	•	Per-item outcomes are persisted deterministically (per internal DB record).
	•	Audit logging is written for live restore.
	•	Preview/dry-run is enforced as read-only (no writes).

Tenant isolation / authorization (non-negotiable)
	•	Run list/view/start are tenant-scoped and policy-guarded (cross-tenant access => 403, not 404).
	•	Explicit Pest tests cover cross-tenant denial and start authorization.

Tests / Verification
	•	./vendor/bin/pint --dirty
	•	Targeted suite (examples):
	•	policy capture snapshot queued + idempotency tests
	•	restore orchestration + audit logging + preview read-only tests
	•	run authorization / tenant isolation tests

Notes / Scope boundaries
	•	Phase 1 UX = DB notifications + run detail page. A global “progress widget” is tracked as Phase 2 and not required for merge.
	•	Resilience/backoff is tracked in tasks but can be iterated further after merge.

Review focus
	•	Dedupe behavior for queued/running runs (reuse vs create-new)
	•	Tenant scoping & policy gates for all run surfaces
	•	Restore safety: audit event + preview no-writes

Co-authored-by: Ahmed Darrazi <ahmeddarrazi@adsmac.local>
Reviewed-on: #56
2026-01-11 15:59:06 +00:00

633 lines
20 KiB
PHP

<?php
use App\Models\BackupItem;
use App\Models\BackupSet;
use App\Models\Policy;
use App\Models\PolicyVersion;
use App\Models\Tenant;
use App\Models\User;
use App\Services\Graph\GraphClientInterface;
use App\Services\Graph\GraphResponse;
use App\Services\Intune\FoundationMappingService;
use App\Services\Intune\RestoreService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Mockery\MockInterface;
uses(RefreshDatabase::class);
test('restore execution applies items and records audit log', function () {
app()->bind(GraphClientInterface::class, fn () => new class implements GraphClientInterface
{
public function listPolicies(string $policyType, array $options = []): GraphResponse
{
return new GraphResponse(true, []);
}
public function getPolicy(string $policyType, string $policyId, array $options = []): GraphResponse
{
return new GraphResponse(true, ['payload' => []]);
}
public function getOrganization(array $options = []): GraphResponse
{
return new GraphResponse(true, []);
}
public function applyPolicy(string $policyType, string $policyId, array $payload, array $options = []): GraphResponse
{
return new GraphResponse(true, []);
}
public function request(string $method, string $path, array $options = []): GraphResponse
{
return new GraphResponse(true, []);
}
public function getServicePrincipalPermissions(array $options = []): GraphResponse
{
return new GraphResponse(true, []);
}
});
config()->set('graph_contracts.types.deviceConfiguration.assignments_payload_key', 'assignments');
$tenant = Tenant::create([
'tenant_id' => 'tenant-1',
'name' => 'Tenant One',
'metadata' => [],
]);
$policy = Policy::create([
'tenant_id' => $tenant->id,
'external_id' => 'policy-1',
'policy_type' => 'deviceConfiguration',
'display_name' => 'Policy A',
'platform' => 'windows',
]);
$backupSet = BackupSet::create([
'tenant_id' => $tenant->id,
'name' => 'Backup',
'status' => 'completed',
'item_count' => 1,
]);
$backupItem = BackupItem::create([
'tenant_id' => $tenant->id,
'backup_set_id' => $backupSet->id,
'policy_id' => $policy->id,
'policy_identifier' => $policy->external_id,
'policy_type' => $policy->policy_type,
'platform' => $policy->platform,
'payload' => [
'foo' => 'bar',
'roleScopeTagIds' => ['0', 'scope-1'],
],
'metadata' => [
'scope_tag_ids' => ['0', 'scope-1'],
'scope_tag_names' => ['Default', 'Verbund-1'],
],
'assignments' => [
[
'target' => [
'@odata.type' => '#microsoft.graph.groupAssignmentTarget',
'groupId' => 'group-1',
'group_display_name' => 'Group One',
],
'intent' => 'apply',
],
],
]);
$user = User::factory()->create(['email' => 'tester@example.com']);
$this->actingAs($user);
$service = app(RestoreService::class);
$run = $service->execute(
tenant: $tenant,
backupSet: $backupSet,
selectedItemIds: [$backupItem->id],
dryRun: false,
actorEmail: $user->email,
actorName: $user->name,
);
expect($run->status)->toBe('completed');
$result = $run->results['items'][$backupItem->id] ?? null;
expect($result)->not->toBeNull();
expect($result['status'] ?? null)->toBe('applied');
$this->assertDatabaseHas('audit_logs', [
'action' => 'restore.executed',
'resource_id' => (string) $run->id,
]);
expect(PolicyVersion::where('policy_id', $policy->id)->count())->toBe(1);
$version = PolicyVersion::where('policy_id', $policy->id)->first();
expect($version)->not->toBeNull();
expect($version->scope_tags)->toBe([
'ids' => ['0', 'scope-1'],
'names' => ['Default', 'Verbund-1'],
]);
expect($version->assignments)->toBe($backupItem->assignments);
});
test('restore execution records foundation mappings', function () {
config()->set('tenantpilot.foundation_types', [
[
'type' => 'assignmentFilter',
'label' => 'Assignment Filter',
'category' => 'Foundations',
'platform' => 'all',
'endpoint' => 'deviceManagement/assignmentFilters',
'backup' => 'full',
'restore' => 'enabled',
'risk' => 'low',
],
]);
$tenant = Tenant::factory()->create();
$backupSet = BackupSet::factory()->for($tenant)->create();
$backupItem = BackupItem::factory()
->for($tenant)
->for($backupSet)
->state([
'policy_id' => null,
'policy_identifier' => 'filter-1',
'policy_type' => 'assignmentFilter',
'platform' => 'all',
'payload' => [
'id' => 'filter-1',
'displayName' => 'Filter One',
],
'metadata' => [
'displayName' => 'Filter One',
],
])
->create();
$entries = [
[
'type' => 'assignmentFilter',
'sourceId' => 'filter-1',
'sourceName' => 'Filter One',
'decision' => 'created',
'targetId' => 'filter-2',
'targetName' => 'Filter One',
],
];
$this->mock(FoundationMappingService::class, function (MockInterface $mock) use ($entries) {
$mock->shouldReceive('map')
->twice()
->andReturn([
'entries' => $entries,
'mapping' => ['filter-1' => 'filter-2'],
'failed' => 0,
'skipped' => 0,
]);
});
$user = User::factory()->create(['email' => 'tester@example.com']);
$this->actingAs($user);
$service = app(RestoreService::class);
$run = $service->execute(
tenant: $tenant,
backupSet: $backupSet,
selectedItemIds: [$backupItem->id],
dryRun: false,
actorEmail: $user->email,
actorName: $user->name,
);
expect($run->status)->toBe('completed');
expect($run->results['foundations'] ?? [])->toHaveCount(1);
expect(($run->results['foundations'][0]['decision'] ?? null))->toBe('created');
$this->assertDatabaseHas('audit_logs', [
'action' => 'restore.foundation.created',
'resource_id' => (string) $run->id,
]);
});
test('restore execution records compliance notification mapping outcomes', function () {
app()->bind(GraphClientInterface::class, fn () => new class implements GraphClientInterface
{
public function listPolicies(string $policyType, array $options = []): GraphResponse
{
return new GraphResponse(true, []);
}
public function getPolicy(string $policyType, string $policyId, array $options = []): GraphResponse
{
return new GraphResponse(true, ['payload' => []]);
}
public function getOrganization(array $options = []): GraphResponse
{
return new GraphResponse(true, []);
}
public function applyPolicy(string $policyType, string $policyId, array $payload, array $options = []): GraphResponse
{
return new GraphResponse(true, []);
}
public function request(string $method, string $path, array $options = []): GraphResponse
{
return new GraphResponse(true, []);
}
public function getServicePrincipalPermissions(array $options = []): GraphResponse
{
return new GraphResponse(true, []);
}
});
$tenant = Tenant::create([
'tenant_id' => 'tenant-3',
'name' => 'Tenant Three',
'metadata' => [],
]);
$policy = Policy::create([
'tenant_id' => $tenant->id,
'external_id' => 'policy-3',
'policy_type' => 'deviceCompliancePolicy',
'display_name' => 'Compliance Policy',
'platform' => 'windows',
]);
$backupSet = BackupSet::create([
'tenant_id' => $tenant->id,
'name' => 'Backup',
'status' => 'completed',
'item_count' => 1,
]);
$backupItem = BackupItem::create([
'tenant_id' => $tenant->id,
'backup_set_id' => $backupSet->id,
'policy_id' => $policy->id,
'policy_identifier' => $policy->external_id,
'policy_type' => $policy->policy_type,
'platform' => $policy->platform,
'payload' => [
'scheduledActionsForRule' => [
[
'ruleName' => 'Password',
'scheduledActionConfigurations' => [
[
'actionType' => 'notification',
'notificationTemplateId' => 'template-1',
],
],
],
],
],
]);
$user = User::factory()->create(['email' => 'tester@example.com']);
$this->actingAs($user);
$service = app(RestoreService::class);
$run = $service->execute(
tenant: $tenant,
backupSet: $backupSet,
selectedItemIds: [$backupItem->id],
dryRun: false,
actorEmail: $user->email,
actorName: $user->name,
);
expect($run->status)->toBe('partial');
$result = $run->results['items'][$backupItem->id] ?? null;
expect($result)->not->toBeNull();
expect($result['status'] ?? null)->toBe('partial');
expect($result['compliance_action_summary']['skipped'] ?? null)->toBe(1);
$this->assertDatabaseHas('audit_logs', [
'action' => 'restore.compliance.actions.mapped',
'resource_id' => (string) $run->id,
]);
});
test('restore execution applies scope tags even without foundation mapping', function () {
$client = new class implements GraphClientInterface
{
public array $applied = [];
public function listPolicies(string $policyType, array $options = []): GraphResponse
{
return new GraphResponse(true, []);
}
public function getPolicy(string $policyType, string $policyId, array $options = []): GraphResponse
{
return new GraphResponse(true, ['payload' => []]);
}
public function getOrganization(array $options = []): GraphResponse
{
return new GraphResponse(true, []);
}
public function applyPolicy(string $policyType, string $policyId, array $payload, array $options = []): GraphResponse
{
$this->applied[] = [
'policyType' => $policyType,
'policyId' => $policyId,
'payload' => $payload,
'options' => $options,
];
return new GraphResponse(true, []);
}
public function request(string $method, string $path, array $options = []): GraphResponse
{
return new GraphResponse(true, []);
}
public function getServicePrincipalPermissions(array $options = []): GraphResponse
{
return new GraphResponse(true, []);
}
};
app()->instance(GraphClientInterface::class, $client);
$tenant = Tenant::factory()->create([
'tenant_id' => 'tenant-scope-tags',
'name' => 'Tenant Scope Tags',
'status' => 'active',
'metadata' => [],
]);
$policy = Policy::create([
'tenant_id' => $tenant->id,
'external_id' => 'app-1',
'policy_type' => 'mobileApp',
'display_name' => 'Mozilla Firefox',
'platform' => 'all',
]);
$backupSet = BackupSet::create([
'tenant_id' => $tenant->id,
'name' => 'Backup',
'status' => 'completed',
'item_count' => 1,
]);
$backupItem = BackupItem::create([
'tenant_id' => $tenant->id,
'backup_set_id' => $backupSet->id,
'policy_id' => $policy->id,
'policy_identifier' => $policy->external_id,
'policy_type' => $policy->policy_type,
'platform' => $policy->platform,
'payload' => [
'@odata.type' => '#microsoft.graph.winGetApp',
'displayName' => 'Mozilla Firefox',
'roleScopeTagIds' => ['0', 'tag-1'],
],
]);
$user = User::factory()->create(['email' => 'tester@example.com']);
$this->actingAs($user);
$service = app(RestoreService::class);
$run = $service->execute(
tenant: $tenant,
backupSet: $backupSet,
selectedItemIds: [$backupItem->id],
dryRun: false,
actorEmail: $user->email,
actorName: $user->name,
);
expect($run->status)->toBe('completed');
expect($client->applied)->toHaveCount(1);
expect($client->applied[0]['policyType'])->toBe('mobileApp');
expect($client->applied[0]['policyId'])->toBe('app-1');
expect($client->applied[0]['payload']['roleScopeTagIds'])->toBe(['0', 'tag-1']);
});
test('restore execution creates an autopilot profile when missing', function () {
$graphClient = new class implements GraphClientInterface
{
public int $applyCalls = 0;
public int $getCalls = 0;
public int $createCalls = 0;
public array $createPayloads = [];
public function listPolicies(string $policyType, array $options = []): GraphResponse
{
return new GraphResponse(true, []);
}
public function getPolicy(string $policyType, string $policyId, array $options = []): GraphResponse
{
$this->getCalls++;
return new GraphResponse(false, [], 404, [], [], [
'error_code' => 'ResourceNotFound',
'error_message' => 'Resource not found.',
]);
}
public function getOrganization(array $options = []): GraphResponse
{
return new GraphResponse(true, []);
}
public function applyPolicy(string $policyType, string $policyId, array $payload, array $options = []): GraphResponse
{
$this->applyCalls++;
return new GraphResponse(false, [], 500, [], [], [
'error_code' => 'InternalServerError',
'error_message' => 'An internal server error has occurred.',
]);
}
public function request(string $method, string $path, array $options = []): GraphResponse
{
if ($method === 'POST' && str_contains($path, 'windowsAutopilotDeploymentProfiles')) {
$this->createCalls++;
$this->createPayloads[] = $options['json'] ?? [];
return new GraphResponse(true, ['id' => 'autopilot-created']);
}
return new GraphResponse(true, []);
}
public function getServicePrincipalPermissions(array $options = []): GraphResponse
{
return new GraphResponse(true, []);
}
};
app()->instance(GraphClientInterface::class, $graphClient);
$tenant = Tenant::factory()->create([
'tenant_id' => 'tenant-1',
'name' => 'Tenant One',
'metadata' => [],
]);
$backupSet = BackupSet::factory()->for($tenant)->create([
'status' => 'completed',
'item_count' => 1,
]);
$backupItem = BackupItem::factory()
->for($tenant)
->for($backupSet)
->state([
'policy_id' => null,
'policy_identifier' => 'autopilot-1',
'policy_type' => 'windowsAutopilotDeploymentProfile',
'platform' => 'windows',
'payload' => [
'@odata.type' => '#microsoft.graph.azureADWindowsAutopilotDeploymentProfile',
'displayName' => 'Autopilot Profile',
'language' => 'en-US',
],
])
->create();
$user = User::factory()->create(['email' => 'tester@example.com']);
$this->actingAs($user);
$service = app(RestoreService::class);
$run = $service->execute(
tenant: $tenant,
backupSet: $backupSet,
selectedItemIds: [$backupItem->id],
dryRun: false,
actorEmail: $user->email,
actorName: $user->name,
);
expect($graphClient->applyCalls)->toBe(1);
expect($graphClient->getCalls)->toBe(1);
expect($graphClient->createCalls)->toBe(1);
expect($graphClient->createPayloads[0]['displayName'] ?? null)->toBe('Restored_Autopilot Profile');
expect($run->status)->toBe('completed');
$result = $run->results['items'][$backupItem->id] ?? null;
expect($result)->not->toBeNull();
expect($result['status'] ?? null)->toBe('applied');
expect($result['created_policy_id'] ?? null)->toBe('autopilot-created');
});
test('restore execution creates missing policy using contracts', function () {
$graphClient = new class implements GraphClientInterface
{
public int $applyCalls = 0;
public int $createCalls = 0;
public array $createPayloads = [];
public function listPolicies(string $policyType, array $options = []): GraphResponse
{
return new GraphResponse(true, []);
}
public function getPolicy(string $policyType, string $policyId, array $options = []): GraphResponse
{
return new GraphResponse(true, ['payload' => []]);
}
public function getOrganization(array $options = []): GraphResponse
{
return new GraphResponse(true, []);
}
public function applyPolicy(string $policyType, string $policyId, array $payload, array $options = []): GraphResponse
{
$this->applyCalls++;
return new GraphResponse(false, [], 404, [], [], [
'error_code' => 'ResourceNotFound',
'error_message' => 'Resource not found.',
]);
}
public function request(string $method, string $path, array $options = []): GraphResponse
{
if ($method === 'POST' && $path === 'deviceManagement/deviceCompliancePolicies') {
$this->createCalls++;
$this->createPayloads[] = $options['json'] ?? [];
return new GraphResponse(true, ['id' => 'compliance-created']);
}
return new GraphResponse(true, []);
}
public function getServicePrincipalPermissions(array $options = []): GraphResponse
{
return new GraphResponse(true, []);
}
};
app()->instance(GraphClientInterface::class, $graphClient);
$tenant = Tenant::factory()->create([
'tenant_id' => 'tenant-4',
'name' => 'Tenant Four',
'metadata' => [],
]);
$backupSet = BackupSet::factory()->for($tenant)->create([
'status' => 'completed',
'item_count' => 1,
]);
$backupItem = BackupItem::factory()
->for($tenant)
->for($backupSet)
->state([
'policy_id' => null,
'policy_identifier' => 'compliance-1',
'policy_type' => 'deviceCompliancePolicy',
'platform' => 'windows',
'payload' => [
'@odata.type' => '#microsoft.graph.windows10CompliancePolicy',
'displayName' => 'Compliance Policy',
'description' => 'Test policy',
],
])
->create();
$user = User::factory()->create(['email' => 'tester@example.com']);
$this->actingAs($user);
$service = app(RestoreService::class);
$run = $service->execute(
tenant: $tenant,
backupSet: $backupSet,
selectedItemIds: [$backupItem->id],
dryRun: false,
actorEmail: $user->email,
actorName: $user->name,
);
expect($graphClient->applyCalls)->toBe(1);
expect($graphClient->createCalls)->toBe(1);
expect($graphClient->createPayloads[0]['displayName'] ?? null)->toBe('Restored_Compliance Policy');
expect($run->status)->toBe('completed');
$result = $run->results['items'][$backupItem->id] ?? null;
expect($result)->not->toBeNull();
expect($result['status'] ?? null)->toBe('applied');
expect($result['created_policy_id'] ?? null)->toBe('compliance-created');
});