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)
176 lines
4.5 KiB
PHP
176 lines
4.5 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
|
use Illuminate\Database\Eloquent\SoftDeletes;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Str;
|
|
use RuntimeException;
|
|
|
|
class Tenant extends Model
|
|
{
|
|
use HasFactory;
|
|
use SoftDeletes;
|
|
|
|
protected $guarded = [];
|
|
|
|
protected $casts = [
|
|
'metadata' => 'array',
|
|
'app_client_secret' => 'encrypted',
|
|
'is_current' => 'boolean',
|
|
];
|
|
|
|
protected static function booted(): void
|
|
{
|
|
static::creating(function (Tenant $tenant) {
|
|
if (empty($tenant->external_id)) {
|
|
$tenant->external_id = $tenant->tenant_id ?? (string) Str::uuid();
|
|
}
|
|
|
|
if (empty($tenant->status)) {
|
|
$tenant->status = 'active';
|
|
}
|
|
});
|
|
|
|
static::saving(function (Tenant $tenant) {
|
|
if (! empty($tenant->tenant_id)) {
|
|
$tenant->external_id = $tenant->tenant_id;
|
|
}
|
|
});
|
|
|
|
static::deleting(function (Tenant $tenant) {
|
|
if ($tenant->isForceDeleting()) {
|
|
return;
|
|
}
|
|
|
|
$tenant->status = 'archived';
|
|
$tenant->saveQuietly();
|
|
});
|
|
|
|
static::restored(function (Tenant $tenant) {
|
|
$tenant->forceFill(['status' => 'active'])->saveQuietly();
|
|
});
|
|
}
|
|
|
|
public static function activeQuery(): Builder
|
|
{
|
|
return static::query()
|
|
->whereNull('deleted_at')
|
|
->where('status', 'active');
|
|
}
|
|
|
|
public function makeCurrent(): void
|
|
{
|
|
if ($this->trashed() || $this->status !== 'active') {
|
|
throw new RuntimeException('Only active tenants can be made current.');
|
|
}
|
|
|
|
DB::transaction(function () {
|
|
static::activeQuery()->update(['is_current' => false]);
|
|
|
|
$this->forceFill(['is_current' => true])->save();
|
|
});
|
|
}
|
|
|
|
public static function current(): self
|
|
{
|
|
$envTenantId = env('INTUNE_TENANT_ID') ?: null;
|
|
|
|
if ($envTenantId) {
|
|
$tenant = static::activeQuery()
|
|
->where(function (Builder $query) use ($envTenantId) {
|
|
$query->where('tenant_id', $envTenantId)
|
|
->orWhere('external_id', $envTenantId);
|
|
})
|
|
->first();
|
|
|
|
if (! $tenant) {
|
|
throw new RuntimeException('Configured INTUNE_TENANT_ID tenant is missing or inactive.');
|
|
}
|
|
|
|
return $tenant;
|
|
}
|
|
|
|
$tenant = static::activeQuery()
|
|
->where('is_current', true)
|
|
->first();
|
|
|
|
if (! $tenant) {
|
|
throw new RuntimeException('No current tenant selected.');
|
|
}
|
|
|
|
return $tenant;
|
|
}
|
|
|
|
public function policies(): HasMany
|
|
{
|
|
return $this->hasMany(Policy::class);
|
|
}
|
|
|
|
public function backupSets(): HasMany
|
|
{
|
|
return $this->hasMany(BackupSet::class);
|
|
}
|
|
|
|
public function policyVersions(): HasMany
|
|
{
|
|
return $this->hasMany(PolicyVersion::class);
|
|
}
|
|
|
|
public function restoreRuns(): HasMany
|
|
{
|
|
return $this->hasMany(RestoreRun::class);
|
|
}
|
|
|
|
public function auditLogs(): HasMany
|
|
{
|
|
return $this->hasMany(AuditLog::class);
|
|
}
|
|
|
|
public function permissions(): HasMany
|
|
{
|
|
return $this->hasMany(TenantPermission::class);
|
|
}
|
|
|
|
public function graphTenantId(): ?string
|
|
{
|
|
return $this->tenant_id ?? $this->external_id;
|
|
}
|
|
|
|
/**
|
|
* @return array{tenant:?string,client_id:?string,client_secret:?string}
|
|
*/
|
|
public function graphOptions(): array
|
|
{
|
|
return [
|
|
'tenant' => $this->graphTenantId(),
|
|
'client_id' => $this->app_client_id,
|
|
'client_secret' => $this->app_client_secret,
|
|
];
|
|
}
|
|
|
|
public function scopeForTenant(Builder $query, self|int|string $tenant): Builder
|
|
{
|
|
if ($tenant instanceof self) {
|
|
return $query->whereKey($tenant->getKey());
|
|
}
|
|
|
|
if (is_int($tenant) || ctype_digit((string) $tenant)) {
|
|
return $query->whereKey($tenant);
|
|
}
|
|
|
|
return $query
|
|
->where('tenant_id', $tenant)
|
|
->orWhere('external_id', $tenant);
|
|
}
|
|
|
|
public function isActive(): bool
|
|
{
|
|
return ! $this->trashed() && ($this->status ?? 'active') === 'active';
|
|
}
|
|
}
|