TenantAtlas/app/Models/Tenant.php
ahmido bc846d7c5c 051-entra-group-directory-cache (#57)
Summary

Adds a tenant-scoped Entra Groups “Directory Cache” to enable DB-only group name resolution across the app (no render-time Graph calls), plus sync runs + observability.

What’s included
	•	Entra Groups cache
	•	New entra_groups storage (tenant-scoped) for group metadata (no memberships).
	•	Retention semantics: groups become stale / retained per spec (no hard delete on first miss).
	•	Group Sync Runs
	•	New “Group Sync Runs” UI (list + detail) with tenant isolation (403 on cross-tenant access).
	•	Manual “Sync Groups” action: creates/reuses a run, dispatches job, DB notification with “View run” link.
	•	Scheduled dispatcher command wired in console.php.
	•	DB-only label resolution (US3)
	•	Shared EntraGroupLabelResolver with safe fallback Unresolved (…last8) and UUID guarding.
	•	Refactors to prefer cached names (no typeahead / no live Graph) in:
	•	Tenant RBAC group selects
	•	Policy version assignments widget
	•	Restore results + restore wizard group mapping labels

Safety / Guardrails
	•	No render-time Graph calls: fail-hard guard test verifies UI paths don’t call GraphClientInterface during page render.
	•	Tenant isolation & authorization: policies + scoped queries enforced (cross-tenant access returns 403, not 404).
	•	Data minimization: only group metadata is cached (no membership/owners).

Tests / Verification
	•	Added/updated tests under tests/Feature/DirectoryGroups and tests/Unit/DirectoryGroups:
	•	Start sync → run record + job dispatch + upserts
	•	Retention purge semantics
	•	Scheduled dispatch wiring
	•	Render-time Graph guard
	•	UI/resource access isolation
	•	Ran:
	•	./vendor/bin/pint --dirty
	•	./vendor/bin/sail artisan test tests/Feature/DirectoryGroups
	•	./vendor/bin/sail artisan test tests/Unit/DirectoryGroups

Notes / Follow-ups
	•	UI polish remains (picker/lookup UX, consistent progress widget/toasts across modules, navigation grouping).
	•	pr-gate checklist still has non-blocking open items (mostly UX/ops polish); requirements gate is green.

Co-authored-by: Ahmed Darrazi <ahmeddarrazi@adsmac.local>
Reviewed-on: #57
2026-01-11 23:24:12 +00:00

255 lines
6.5 KiB
PHP

<?php
namespace App\Models;
use Filament\Facades\Filament;
use Filament\Models\Contracts\HasName;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
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 implements HasName
{
use HasFactory;
use SoftDeletes;
protected $guarded = [];
protected $casts = [
'metadata' => 'array',
'app_client_secret' => 'encrypted',
'is_current' => 'boolean',
'rbac_last_checked_at' => 'datetime',
'rbac_last_setup_at' => 'datetime',
'rbac_canary_results' => 'array',
'rbac_last_warnings' => 'array',
];
public function getRbacCanaryResultsAttribute($value): array
{
if (is_string($value)) {
$decoded = json_decode($value, true);
return is_array($decoded) ? $decoded : [];
}
return $value ?? [];
}
public function getRbacLastWarningsAttribute($value): array
{
if (is_string($value)) {
$decoded = json_decode($value, true);
return is_array($decoded) ? $decoded : [];
}
$warnings = $value ?? [];
if ($this->rbac_scope_mode === 'scope_group' || filled($this->rbac_scope_id)) {
$warnings[] = 'scope_limited';
}
return $warnings;
}
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]);
static::query()
->whereKey($this->getKey())
->update(['is_current' => true]);
});
$this->forceFill(['is_current' => true]);
}
public static function current(): self
{
$filamentTenant = Filament::getTenant();
if ($filamentTenant instanceof self) {
return $filamentTenant;
}
$envTenantId = getenv('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 getFilamentName(): string
{
$environment = strtoupper((string) ($this->environment ?? 'other'));
return "{$this->name} ({$environment})";
}
public function users(): BelongsToMany
{
return $this->belongsToMany(User::class)
->withPivot('role')
->withTimestamps();
}
public function policies(): HasMany
{
return $this->hasMany(Policy::class);
}
public function backupSets(): HasMany
{
return $this->hasMany(BackupSet::class);
}
public function backupSchedules(): HasMany
{
return $this->hasMany(BackupSchedule::class);
}
public function backupScheduleRuns(): HasMany
{
return $this->hasMany(BackupScheduleRun::class);
}
public function policyVersions(): HasMany
{
return $this->hasMany(PolicyVersion::class);
}
public function restoreRuns(): HasMany
{
return $this->hasMany(RestoreRun::class);
}
public function entraGroups(): HasMany
{
return $this->hasMany(EntraGroup::class);
}
public function entraGroupSyncRuns(): HasMany
{
return $this->hasMany(EntraGroupSyncRun::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';
}
}