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)
401 lines
16 KiB
PHP
401 lines
16 KiB
PHP
<?php
|
|
|
|
namespace App\Filament\Resources;
|
|
|
|
use App\Filament\Resources\TenantResource\Pages;
|
|
use App\Models\Tenant;
|
|
use App\Services\Intune\AuditLogger;
|
|
use App\Services\Intune\TenantConfigService;
|
|
use App\Services\Intune\TenantPermissionService;
|
|
use BackedEnum;
|
|
use Filament\Actions;
|
|
use Filament\Actions\ActionGroup;
|
|
use Filament\Forms;
|
|
use Filament\Infolists;
|
|
use Filament\Notifications\Notification;
|
|
use Filament\Resources\Resource;
|
|
use Filament\Schemas\Schema;
|
|
use Filament\Tables;
|
|
use Filament\Tables\Table;
|
|
use UnitEnum;
|
|
|
|
class TenantResource extends Resource
|
|
{
|
|
protected static ?string $model = Tenant::class;
|
|
|
|
protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-building-office-2';
|
|
|
|
protected static string|UnitEnum|null $navigationGroup = 'Settings';
|
|
|
|
public static function form(Schema $schema): Schema
|
|
{
|
|
return $schema
|
|
->schema([
|
|
Forms\Components\TextInput::make('name')
|
|
->required()
|
|
->maxLength(255),
|
|
Forms\Components\TextInput::make('tenant_id')
|
|
->label('Tenant ID (GUID)')
|
|
->required()
|
|
->maxLength(255)
|
|
->unique(ignoreRecord: true),
|
|
Forms\Components\TextInput::make('domain')
|
|
->label('Primary domain')
|
|
->maxLength(255),
|
|
Forms\Components\TextInput::make('app_client_id')
|
|
->label('App Client ID')
|
|
->maxLength(255),
|
|
Forms\Components\TextInput::make('app_client_secret')
|
|
->label('App Client Secret')
|
|
->password()
|
|
->dehydrateStateUsing(fn ($state) => filled($state) ? $state : null)
|
|
->dehydrated(fn ($state) => filled($state)),
|
|
Forms\Components\TextInput::make('app_certificate_thumbprint')
|
|
->label('Certificate thumbprint')
|
|
->maxLength(255),
|
|
Forms\Components\Textarea::make('app_notes')
|
|
->label('Notes')
|
|
->rows(3),
|
|
]);
|
|
}
|
|
|
|
public static function table(Table $table): Table
|
|
{
|
|
return $table
|
|
->modifyQueryUsing(fn (\Illuminate\Database\Eloquent\Builder $query) => $query->withTrashed())
|
|
->columns([
|
|
Tables\Columns\TextColumn::make('name')
|
|
->searchable(),
|
|
Tables\Columns\TextColumn::make('tenant_id')
|
|
->label('Tenant ID')
|
|
->copyable()
|
|
->searchable(),
|
|
Tables\Columns\TextColumn::make('domain')
|
|
->copyable()
|
|
->toggleable(),
|
|
Tables\Columns\IconColumn::make('is_current')
|
|
->label('Current')
|
|
->boolean(),
|
|
Tables\Columns\TextColumn::make('status')
|
|
->badge()
|
|
->sortable(),
|
|
Tables\Columns\TextColumn::make('app_status')
|
|
->badge(),
|
|
Tables\Columns\TextColumn::make('created_at')
|
|
->dateTime()
|
|
->since(),
|
|
])
|
|
->filters([
|
|
Tables\Filters\TrashedFilter::make()
|
|
->label('Archive filter')
|
|
->placeholder('Active only')
|
|
->trueLabel('Active + archived')
|
|
->falseLabel('Archived only')
|
|
->default(true),
|
|
Tables\Filters\SelectFilter::make('app_status')
|
|
->options([
|
|
'ok' => 'OK',
|
|
'consent_required' => 'Consent required',
|
|
'error' => 'Error',
|
|
'unknown' => 'Unknown',
|
|
]),
|
|
])
|
|
->actions([
|
|
Actions\ViewAction::make(),
|
|
ActionGroup::make([
|
|
Actions\EditAction::make(),
|
|
Actions\RestoreAction::make()
|
|
->label('Restore')
|
|
->color('success')
|
|
->successNotificationTitle('Tenant reactivated')
|
|
->after(function (Tenant $record, AuditLogger $auditLogger) {
|
|
$auditLogger->log(
|
|
tenant: $record,
|
|
action: 'tenant.restored',
|
|
resourceType: 'tenant',
|
|
resourceId: (string) $record->id,
|
|
status: 'success',
|
|
context: ['metadata' => ['tenant_id' => $record->tenant_id]]
|
|
);
|
|
}),
|
|
Actions\Action::make('makeCurrent')
|
|
->label('Make current')
|
|
->color('success')
|
|
->icon('heroicon-o-check-circle')
|
|
->requiresConfirmation()
|
|
->visible(fn (Tenant $record) => $record->isActive() && ! $record->is_current)
|
|
->action(function (Tenant $record, AuditLogger $auditLogger) {
|
|
$record->makeCurrent();
|
|
|
|
$auditLogger->log(
|
|
tenant: $record,
|
|
action: 'tenant.current_set',
|
|
resourceType: 'tenant',
|
|
resourceId: (string) $record->id,
|
|
status: 'success',
|
|
context: ['metadata' => ['tenant_id' => $record->tenant_id]]
|
|
);
|
|
|
|
Notification::make()
|
|
->title('Current tenant updated')
|
|
->success()
|
|
->send();
|
|
}),
|
|
Actions\Action::make('admin_consent')
|
|
->label('Admin consent')
|
|
->icon('heroicon-o-clipboard-document')
|
|
->url(fn (Tenant $record) => static::adminConsentUrl($record))
|
|
->visible(fn (Tenant $record) => static::adminConsentUrl($record) !== null)
|
|
->openUrlInNewTab(),
|
|
Actions\Action::make('verify')
|
|
->label('Verify configuration')
|
|
->icon('heroicon-o-check-badge')
|
|
->color('primary')
|
|
->requiresConfirmation()
|
|
->action(function (
|
|
Tenant $record,
|
|
TenantConfigService $configService,
|
|
TenantPermissionService $permissionService,
|
|
AuditLogger $auditLogger
|
|
) {
|
|
static::verifyTenant($record, $configService, $permissionService, $auditLogger);
|
|
}),
|
|
Actions\Action::make('archive')
|
|
->label('Deactivate')
|
|
->color('danger')
|
|
->icon('heroicon-o-archive-box-x-mark')
|
|
->requiresConfirmation()
|
|
->visible(fn (Tenant $record) => ! $record->trashed())
|
|
->action(function (Tenant $record, AuditLogger $auditLogger) {
|
|
$record->delete();
|
|
|
|
$auditLogger->log(
|
|
tenant: $record,
|
|
action: 'tenant.archived',
|
|
resourceType: 'tenant',
|
|
resourceId: (string) $record->id,
|
|
status: 'success',
|
|
context: ['metadata' => ['tenant_id' => $record->tenant_id]]
|
|
);
|
|
|
|
Notification::make()
|
|
->title('Tenant deactivated')
|
|
->body('The tenant has been archived and hidden from lists.')
|
|
->success()
|
|
->send();
|
|
}),
|
|
Actions\Action::make('forceDelete')
|
|
->label('Force delete')
|
|
->color('danger')
|
|
->icon('heroicon-o-trash')
|
|
->requiresConfirmation()
|
|
->visible(fn (?Tenant $record) => $record?->trashed())
|
|
->action(function (?Tenant $record, AuditLogger $auditLogger) {
|
|
if ($record === null) {
|
|
return;
|
|
}
|
|
|
|
$tenant = Tenant::withTrashed()->find($record->id);
|
|
|
|
if (! $tenant?->trashed()) {
|
|
Notification::make()
|
|
->title('Tenant must be archived first')
|
|
->danger()
|
|
->send();
|
|
|
|
return;
|
|
}
|
|
|
|
$auditLogger->log(
|
|
tenant: $tenant,
|
|
action: 'tenant.force_deleted',
|
|
resourceType: 'tenant',
|
|
resourceId: (string) $tenant->id,
|
|
status: 'success',
|
|
context: ['metadata' => ['tenant_id' => $tenant->tenant_id]]
|
|
);
|
|
|
|
$tenant->forceDelete();
|
|
|
|
Notification::make()
|
|
->title('Tenant permanently deleted')
|
|
->success()
|
|
->send();
|
|
}),
|
|
])->icon('heroicon-o-ellipsis-vertical'),
|
|
])
|
|
->bulkActions([])
|
|
->headerActions([]);
|
|
}
|
|
|
|
public static function infolist(Schema $schema): Schema
|
|
{
|
|
return $schema
|
|
->schema([
|
|
Infolists\Components\TextEntry::make('name'),
|
|
Infolists\Components\TextEntry::make('tenant_id')->label('Tenant ID')->copyable(),
|
|
Infolists\Components\TextEntry::make('domain')->copyable(),
|
|
Infolists\Components\TextEntry::make('app_client_id')->label('App Client ID')->copyable(),
|
|
Infolists\Components\TextEntry::make('status')->badge(),
|
|
Infolists\Components\TextEntry::make('app_status')->badge(),
|
|
Infolists\Components\TextEntry::make('app_notes')->label('Notes'),
|
|
Infolists\Components\TextEntry::make('created_at')->dateTime(),
|
|
Infolists\Components\TextEntry::make('updated_at')->dateTime(),
|
|
Infolists\Components\TextEntry::make('admin_consent_url')
|
|
->label('Admin consent URL')
|
|
->state(fn (Tenant $record) => static::adminConsentUrl($record))
|
|
->visible(fn (?string $state) => filled($state))
|
|
->copyable(),
|
|
Infolists\Components\RepeatableEntry::make('permissions')
|
|
->label('Required permissions')
|
|
->state(fn (Tenant $record) => app(TenantPermissionService::class)->compare($record, persist: false)['permissions'])
|
|
->schema([
|
|
Infolists\Components\TextEntry::make('key')->label('Permission')->badge(),
|
|
Infolists\Components\TextEntry::make('type')->badge(),
|
|
Infolists\Components\TextEntry::make('features')
|
|
->label('Features')
|
|
->formatStateUsing(fn ($state) => is_array($state) ? implode(', ', $state) : (string) $state),
|
|
Infolists\Components\TextEntry::make('status')
|
|
->badge(),
|
|
])
|
|
->columnSpanFull(),
|
|
]);
|
|
}
|
|
|
|
public static function getPages(): array
|
|
{
|
|
return [
|
|
'index' => Pages\ListTenants::route('/'),
|
|
'create' => Pages\CreateTenant::route('/create'),
|
|
'view' => Pages\ViewTenant::route('/{record}'),
|
|
'edit' => Pages\EditTenant::route('/{record}/edit'),
|
|
];
|
|
}
|
|
|
|
public static function adminConsentUrl(Tenant $tenant): ?string
|
|
{
|
|
$tenantId = $tenant->graphTenantId();
|
|
$clientId = $tenant->app_client_id;
|
|
$redirectUri = route('admin.consent.callback');
|
|
$scope = config('graph.scope') ?: 'https://graph.microsoft.com/.default';
|
|
$state = sprintf('tenantpilot|%s', $tenant->id);
|
|
|
|
if (! $tenantId || ! $clientId || ! $redirectUri) {
|
|
return null;
|
|
}
|
|
|
|
$query = http_build_query([
|
|
'client_id' => $clientId,
|
|
'state' => $state,
|
|
'redirect_uri' => $redirectUri,
|
|
'scope' => $scope,
|
|
]);
|
|
|
|
return sprintf('https://login.microsoftonline.com/%s/v2.0/adminconsent?%s', $tenantId, $query);
|
|
}
|
|
|
|
public static function entraUrl(Tenant $tenant): ?string
|
|
{
|
|
if ($tenant->app_client_id) {
|
|
return sprintf(
|
|
'https://entra.microsoft.com/#view/Microsoft_AAD_RegisteredApps/ApplicationMenuBlade/~/Overview/appId/%s',
|
|
$tenant->app_client_id
|
|
);
|
|
}
|
|
|
|
if ($tenant->graphTenantId()) {
|
|
return sprintf(
|
|
'https://entra.microsoft.com/#view/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/~/Overview/tenantId/%s',
|
|
$tenant->graphTenantId()
|
|
);
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
public static function verifyTenant(
|
|
Tenant $tenant,
|
|
TenantConfigService $configService,
|
|
TenantPermissionService $permissionService,
|
|
AuditLogger $auditLogger
|
|
): void {
|
|
$configResult = $configService->testConnectivity($tenant);
|
|
|
|
$permissionStatuses = [];
|
|
foreach ($permissionService->getRequiredPermissions() as $permission) {
|
|
$permissionStatuses[$permission['key']] = [
|
|
'status' => $configResult['success'] ? 'ok' : 'error',
|
|
'details' => $configResult['success']
|
|
? null
|
|
: ['message' => $configResult['error_message']],
|
|
];
|
|
}
|
|
|
|
$permissions = $permissionService->compare($tenant, $permissionStatuses);
|
|
|
|
$appStatus = $configResult['success']
|
|
? 'ok'
|
|
: ($configResult['requires_consent'] ? 'consent_required' : 'error');
|
|
|
|
$tenant->update([
|
|
'app_status' => $appStatus,
|
|
'app_notes' => $configResult['error_message'],
|
|
]);
|
|
|
|
$user = auth()->user();
|
|
|
|
$auditLogger->log(
|
|
tenant: $tenant,
|
|
action: 'tenant.config.verified',
|
|
context: [
|
|
'metadata' => [
|
|
'app_status' => $appStatus,
|
|
'error' => $configResult['error_message'],
|
|
],
|
|
],
|
|
actorId: $user?->id,
|
|
actorEmail: $user?->email,
|
|
actorName: $user?->name,
|
|
status: $appStatus === 'ok' ? 'success' : 'error',
|
|
resourceType: 'tenant',
|
|
resourceId: (string) $tenant->id,
|
|
);
|
|
|
|
$auditLogger->log(
|
|
tenant: $tenant,
|
|
action: 'tenant.permissions.checked',
|
|
context: [
|
|
'metadata' => [
|
|
'overall_status' => $permissions['overall_status'],
|
|
],
|
|
],
|
|
actorId: $user?->id,
|
|
actorEmail: $user?->email,
|
|
actorName: $user?->name,
|
|
status: match ($permissions['overall_status']) {
|
|
'ok' => 'success',
|
|
'error' => 'error',
|
|
default => 'partial',
|
|
},
|
|
resourceType: 'tenant',
|
|
resourceId: (string) $tenant->id,
|
|
);
|
|
|
|
$notification = Notification::make()
|
|
->title($configResult['success'] ? 'Configuration verified' : 'Verification failed')
|
|
->body($configResult['success']
|
|
? 'Graph connectivity confirmed. Permission status: '.$permissions['overall_status']
|
|
: ($configResult['error_message'] ?? 'Graph connectivity failed'));
|
|
|
|
if ($configResult['success']) {
|
|
$notification->success();
|
|
} elseif ($configResult['requires_consent']) {
|
|
$notification->warning();
|
|
} else {
|
|
$notification->danger();
|
|
}
|
|
|
|
$notification->send();
|
|
}
|
|
}
|