TenantAtlas/app/Services/Intune/BackupService.php
Ahmed Darrazi 6d14d2544f feat: TenantPilot v1 - Complete implementation (Phases 1-12)
Complete implementation of TenantPilot v1 Intune Management Platform with
comprehensive backup, versioning, and restore capabilities.

CONSTITUTION & SPEC
- Ratified constitution v1.0.0 with 7 core principles
- Complete spec.md with 7 user stories (US1-7)
- Detailed plan.md with constitution compliance check
- Task breakdown with 125+ tasks across 12 phases

CORE FEATURES (US1-4)
- Policy inventory with Graph-based sync (US1)
- Backup creation with immutable JSONB snapshots (US2)
- Version history with diff viewer (human + JSON) (US3)
- Defensive restore with preview/dry-run (US4)

TENANT MANAGEMENT (US6-7)
- Full tenant CRUD with Entra ID app configuration
- Admin consent callback flow integration
- Tenant connectivity verification
- Permission health status monitoring
- 'Highlander' pattern: single current tenant with is_current flag

GRAPH ABSTRACTION
- Complete isolation layer (7 classes)
- GraphClientInterface with mockable implementations
- Error mapping, logging, and standardized responses
- Rate-limit aware design

DOMAIN SERVICES
- BackupService: immutable snapshot creation
- RestoreService: preview, selective restore, conflict detection
- VersionService: immutable version capture
- VersionDiff: human-readable and structured diffs
- PolicySyncService: Graph-based policy import
- TenantConfigService: connectivity testing
- TenantPermissionService: permission health checks
- AuditLogger: comprehensive audit trail

DATA MODEL
- 11 migrations with tenant-aware schema
- 8 Eloquent models with proper relationships
- SoftDeletes on Tenant, BackupSet, BackupItem, PolicyVersion, RestoreRun
- JSONB storage for snapshots, metadata, permissions
- Encrypted storage for client secrets
- Partial unique index for is_current tenant

FILAMENT ADMIN UI
- 5 main resources: Tenant, Policy, PolicyVersion, BackupSet, RestoreRun
- RelationManagers: Versions (Policy), BackupItems (BackupSet)
- Actions: Verify config, Admin consent, Make current, Delete/Force delete
- Filters: Status, Type, Platform, Archive state
- Permission panel with status indicators
- ActionGroup pattern for cleaner row actions

HOUSEKEEPING (Phases 10-12)
- Soft delete with archive status for all entities
- Force delete protection (blocks if dependencies exist)
- Tenant deactivation with cascade prevention
- Audit logging for all delete operations

TESTING
- 36 tests passing (125 assertions, 11.21s)
- Feature tests: Policy, Backup, Restore, Version, Tenant, Housekeeping
- Unit tests: VersionDiff, TenantCurrent, Permissions, Scopes
- Full TDD coverage for critical flows

CONFIGURATION
- config/tenantpilot.php: 10+ policy types with metadata
- config/intune_permissions.php: required Graph permissions
- config/graph.php: Graph client configuration

SAFETY & COMPLIANCE
- Constitution compliance: 7/7 principles ✓
- Safety-first operations: preview, confirmation, validation
- Immutable versioning: no in-place modifications
- Defensive restore: dry-run, selective, conflict detection
- Comprehensive auditability: all critical operations logged
- Tenant-aware architecture: multi-tenant ready
- Graph abstraction: isolated, mockable, testable
- Spec-driven development: spec → plan → tasks → implementation

OPERATIONAL READINESS
- Laravel Sail for local development
- Dokploy deployment documentation
- Queue/worker ready architecture
- Migration safety notes
- Environment variable documentation

Tests: 36 passed
Duration: 11.21s
Status: Production-ready (98% complete)
2025-12-12 02:27:54 +01:00

283 lines
8.8 KiB
PHP

<?php
namespace App\Services\Intune;
use App\Models\BackupItem;
use App\Models\BackupSet;
use App\Models\Policy;
use App\Models\Tenant;
use App\Services\Graph\GraphClientInterface;
use App\Services\Graph\GraphErrorMapper;
use App\Services\Graph\GraphLogger;
use Carbon\CarbonImmutable;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Throwable;
class BackupService
{
public function __construct(
private readonly GraphClientInterface $graphClient,
private readonly GraphLogger $graphLogger,
private readonly AuditLogger $auditLogger,
private readonly VersionService $versionService,
) {}
/**
* Create a backup set with immutable snapshots for the provided policies.
*
* @param array<int> $policyIds
*/
public function createBackupSet(
Tenant $tenant,
array $policyIds,
?string $actorEmail = null,
?string $actorName = null,
?string $name = null,
): BackupSet {
$this->assertActiveTenant($tenant);
$policies = Policy::query()
->where('tenant_id', $tenant->id)
->whereIn('id', $policyIds)
->get();
$backupSet = DB::transaction(function () use ($tenant, $policies, $actorEmail, $name) {
$backupSet = BackupSet::create([
'tenant_id' => $tenant->id,
'name' => $name ?? CarbonImmutable::now()->format('Y-m-d H:i:s').' backup',
'created_by' => $actorEmail,
'status' => 'running',
'metadata' => [],
]);
$failures = [];
$itemsCreated = 0;
foreach ($policies as $policy) {
[$item, $failure] = $this->snapshotPolicy($tenant, $backupSet, $policy, $actorEmail);
if ($failure !== null) {
$failures[] = $failure;
continue;
}
if ($item !== null) {
$itemsCreated++;
}
}
$status = $this->resolveStatus($itemsCreated, $failures);
$backupSet->update([
'status' => $status,
'item_count' => $itemsCreated,
'completed_at' => CarbonImmutable::now(),
'metadata' => ['failures' => $failures],
]);
return $backupSet->refresh();
});
$this->auditLogger->log(
tenant: $tenant,
action: 'backup.created',
context: [
'metadata' => [
'backup_set_id' => $backupSet->id,
'item_count' => $backupSet->item_count,
'status' => $backupSet->status,
],
],
actorEmail: $actorEmail,
actorName: $actorName,
resourceType: 'backup_set',
resourceId: (string) $backupSet->id,
status: $backupSet->status === 'completed' ? 'success' : 'partial'
);
return $backupSet;
}
/**
* Add snapshots for additional policies to an existing backup set.
*
* @param array<int> $policyIds
*/
public function addPoliciesToSet(
Tenant $tenant,
BackupSet $backupSet,
array $policyIds,
?string $actorEmail = null,
?string $actorName = null,
): BackupSet {
$this->assertActiveTenant($tenant);
if ($backupSet->trashed() || $backupSet->tenant_id !== $tenant->id) {
throw new \RuntimeException('Backup set is archived or does not belong to the current tenant.');
}
$existingPolicyIds = $backupSet->items()->withTrashed()->pluck('policy_id')->filter()->all();
$policyIds = array_values(array_diff($policyIds, $existingPolicyIds));
if (empty($policyIds)) {
return $backupSet->refresh();
}
$policies = Policy::query()
->where('tenant_id', $tenant->id)
->whereIn('id', $policyIds)
->get();
$metadata = $backupSet->metadata ?? [];
$failures = $metadata['failures'] ?? [];
$itemsCreated = 0;
foreach ($policies as $policy) {
[$item, $failure] = $this->snapshotPolicy($tenant, $backupSet, $policy, $actorEmail);
if ($failure !== null) {
$failures[] = $failure;
continue;
}
if ($item !== null) {
$itemsCreated++;
}
}
$status = $this->resolveStatus($itemsCreated, $failures);
$backupSet->update([
'status' => $status,
'item_count' => $backupSet->items()->count(),
'completed_at' => CarbonImmutable::now(),
'metadata' => ['failures' => $failures],
]);
$this->auditLogger->log(
tenant: $tenant,
action: 'backup.items_added',
context: [
'metadata' => [
'backup_set_id' => $backupSet->id,
'added_count' => $itemsCreated,
'status' => $status,
],
],
actorEmail: $actorEmail,
actorName: $actorName,
resourceType: 'backup_set',
resourceId: (string) $backupSet->id,
status: $status === 'completed' ? 'success' : 'partial'
);
return $backupSet->refresh();
}
private function resolveStatus(int $itemsCreated, array $failures): string
{
return match (true) {
$itemsCreated === 0 && count($failures) > 0 => 'failed',
count($failures) > 0 => 'partial',
default => 'completed',
};
}
/**
* @return array{0:?BackupItem,1:?array{policy_id:int,reason:string,status:int|string|null}}
*/
private function snapshotPolicy(Tenant $tenant, BackupSet $backupSet, Policy $policy, ?string $actorEmail = null): array
{
$tenantIdentifier = $tenant->tenant_id ?? $tenant->external_id;
$context = [
'tenant' => $tenantIdentifier,
'policy_type' => $policy->policy_type,
'policy_id' => $policy->external_id,
];
$this->graphLogger->logRequest('get_policy', $context);
try {
$response = $this->graphClient->getPolicy($policy->policy_type, $policy->external_id, [
'tenant' => $tenantIdentifier,
'client_id' => $tenant->app_client_id,
'client_secret' => $tenant->app_client_secret,
'platform' => $policy->platform,
]);
} catch (Throwable $throwable) {
$mapped = GraphErrorMapper::fromThrowable($throwable, $context);
return [
null,
[
'policy_id' => $policy->id,
'reason' => $mapped->getMessage(),
'status' => $mapped->status,
],
];
}
$this->graphLogger->logResponse('get_policy', $response, $context);
$payload = $response->data['payload'] ?? $response->data;
$metadata = Arr::except($response->data, ['payload']);
if ($response->failed()) {
$reason = $response->warnings[0] ?? 'Graph request failed';
$failure = [
'policy_id' => $policy->id,
'reason' => $reason,
'status' => $response->status,
];
if (! config('graph.stub_on_failure')) {
return [null, $failure];
}
// Fallback to a stub payload for local/dev when Graph fails.
$payload = [
'id' => $policy->external_id,
'type' => $policy->policy_type,
'source' => 'stub',
'warning' => $reason,
];
$metadata['warnings'] = $response->warnings ?? [$reason];
}
$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' => $payload,
'metadata' => $metadata,
]);
$this->versionService->captureVersion(
policy: $policy,
payload: $payload,
createdBy: $actorEmail,
metadata: [
'source' => 'backup',
'backup_set_id' => $backupSet->id,
'backup_item_id' => $backupItem->id,
]
);
return [$backupItem, null];
}
private function assertActiveTenant(Tenant $tenant): void
{
if (! $tenant->isActive()) {
throw new \RuntimeException('Tenant is archived or inactive.');
}
}
}