diff --git a/.env.example b/.env.example index a1746f0..89a5bb8 100755 --- a/.env.example +++ b/.env.example @@ -68,3 +68,6 @@ VITE_APP_NAME="${APP_NAME}" # AD_SYNC_BASE_DN="OU=People,DC=ad,DC=test" AD_SYNC_SCHEDULED=false AD_SYNC_MAX_DEACTIVATIONS=5 + +# Local Laravel user ID allowed to manage the directory sync page. +AD_SYNC_ADMIN_ID=0 diff --git a/app/Console/Commands/SyncActiveDirectory.php b/app/Console/Commands/SyncActiveDirectory.php index 80c19e1..f54f726 100644 --- a/app/Console/Commands/SyncActiveDirectory.php +++ b/app/Console/Commands/SyncActiveDirectory.php @@ -2,6 +2,7 @@ namespace App\Console\Commands; +use App\Services\DirectorySyncHistory; use App\Services\DirectorySyncRejected; use App\Services\SyncDirectoryUsers; use Illuminate\Console\Command; @@ -13,11 +14,12 @@ use Throwable; class SyncActiveDirectory extends Command { protected $signature = 'ad:sync {--dry-run : Preview changes without saving users} - {--deactivate-missing : Disable managed users absent from the snapshot}'; + {--deactivate-missing : Disable managed users absent from the snapshot} + {--reviewed-missing= : Apply only the missing users from the reviewed preview}'; protected $description = 'Synchronize local user records from Active Directory'; - public function handle(SyncDirectoryUsers $sync): int + public function handle(SyncDirectoryUsers $sync, DirectorySyncHistory $history): int { $started = hrtime(true); $context = [ @@ -27,20 +29,29 @@ class SyncActiveDirectory extends Command ]; $duration = fn (): int => (int) ((hrtime(true) - $started) / 1_000_000); + $review = $this->option('reviewed-missing'); + $record = fn (string $status, ?array $counts = null, ?string $failure = null) => $history->record( + $context['run_id'], $status, $context['dry_run'], $context['deactivate_missing'], $duration(), $counts, $failure, + ); Log::info('Active Directory sync started.', $context); try { + if ($review !== null && (! $context['deactivate_missing'] || $context['dry_run'])) { + throw new DirectorySyncRejected('A reviewed apply requires a live missing-user run.'); + } + $lock = Cache::lock('ad:sync', 3600); if (! $lock->get()) { throw new DirectorySyncRejected('A directory sync is already running.'); } try { - $result = $sync->run($context['dry_run'], $context['deactivate_missing']); + $result = $sync->run($context['dry_run'], $context['deactivate_missing'], $review); } finally { $lock->release(); } } catch (DirectorySyncRejected $exception) { Log::warning('Active Directory sync rejected.', $context + ['reason' => $exception->getMessage(), 'duration_ms' => $duration()]); + $record('rejected', failure: $exception->getMessage()); $this->error($exception->getMessage()); return self::FAILURE; @@ -50,6 +61,7 @@ class SyncActiveDirectory extends Command 'exception_code' => $exception->getCode(), 'duration_ms' => $duration(), ]); + $record('failed', failure: 'Directory or database error'); $this->error('Sync stopped due to a directory or database error.'); return self::FAILURE; @@ -61,6 +73,7 @@ class SyncActiveDirectory extends Command $counts = $result['counts']; Log::info('Active Directory sync completed.', $context + $counts + ['duration_ms' => $duration()]); + $record($review === null ? 'completed' : 'review_applied', $counts); $summary = []; foreach ($counts as $key => $value) { $summary[] = "$key=$value"; diff --git a/app/Models/User.php b/app/Models/User.php index 393a649..1d15239 100755 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -19,7 +19,9 @@ use Laravel\Fortify\TwoFactorAuthenticatable; /** * @property string|null $ad_guid * @property string|null $ad_source + * @property string|null $ad_disabled_reason * @property CarbonImmutable|null $ad_disabled_at + * @property CarbonImmutable|null $deleted_at * @property int $id * @property string $name * @property string $email @@ -49,6 +51,7 @@ class User extends Authenticatable implements PasskeyUser return [ 'email_verified_at' => 'datetime', 'ad_disabled_at' => 'datetime', + 'deleted_at' => 'datetime', 'password' => 'hashed', ]; } diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index f1525e9..842364f 100755 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -2,9 +2,11 @@ namespace App\Providers; +use App\Models\User; use Carbon\CarbonImmutable; use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Gate; use Illuminate\Support\ServiceProvider; use Illuminate\Validation\Rules\Password; @@ -24,6 +26,9 @@ class AppServiceProvider extends ServiceProvider public function boot(): void { $this->configureDefaults(); + + Gate::define('manage-directory-sync', fn (User $user): bool => $user->ad_guid === null + && $user->id === config('ad-sync.admin-id')); } /** diff --git a/app/Services/SyncDirectoryUsers.php b/app/Services/SyncDirectoryUsers.php index bd3d33c..5944644 100644 --- a/app/Services/SyncDirectoryUsers.php +++ b/app/Services/SyncDirectoryUsers.php @@ -12,18 +12,20 @@ class SyncDirectoryUsers /** * @return array{ + * missing_fingerprint: string, * counts: array{created: int, updated: int, unchanged: int, deactivated: int, reactivated: int}, * changes: list, reason: ?string}> * } */ - public function run(bool $dryRun, bool $deactivateMissing): array + public function run(bool $dryRun, bool $deactivateMissing, ?string $reviewedMissing = null): array { $entries = $this->snapshot(); $source = $this->source(); - return DB::transaction(function () use ($entries, $source, $dryRun, $deactivateMissing): array { + return DB::transaction(function () use ($entries, $source, $dryRun, $deactivateMissing, $reviewedMissing): array { $counts = ['created' => 0, 'updated' => 0, 'unchanged' => 0, 'deactivated' => 0, 'reactivated' => 0]; $changes = []; + $missingGuids = []; foreach ($entries as $guid => $entry) { $user = User::where('ad_guid', $guid)->lockForUpdate()->first(); @@ -44,13 +46,18 @@ class SyncDirectoryUsers if (! $user->exists) { $action = 'created'; - $user->ad_disabled_at = $entry['enabled'] ? null : now(); + if (! $entry['enabled']) { + $this->disable($user); + } } elseif (! $entry['enabled'] && $user->ad_disabled_at === null) { $action = 'deactivated'; $this->disable($user); } elseif ($entry['enabled'] && $user->ad_disabled_at !== null) { $action = 'reactivated'; - $user->ad_disabled_at = null; + $user->forceFill(['ad_disabled_at' => null, 'deleted_at' => null, 'ad_disabled_reason' => null]); + } elseif (! $entry['enabled'] && $user->ad_disabled_reason !== 'directory_disabled') { + $action = 'updated'; + $user->ad_disabled_reason = 'directory_disabled'; } elseif ($user->isDirty()) { $action = 'updated'; } else { @@ -74,7 +81,8 @@ class SyncDirectoryUsers foreach ($missing as $user) { if (! isset($entries[$user->ad_guid])) { $counts['deactivated']++; - $this->disable($user); + $this->disable($user, 'missing_from_snapshot'); + $missingGuids[] = $user->ad_guid; $changes[] = [$user, 'deactivated', 'missing_from_snapshot']; } } @@ -84,9 +92,21 @@ class SyncDirectoryUsers throw new DirectorySyncRejected('Deactivation limit exceeded.'); } + sort($missingGuids); + $fingerprint = hash('sha256', $source.':'.implode(',', $missingGuids)); + if ($reviewedMissing !== null) { + if ($missingGuids === [] || ! hash_equals($fingerprint, $reviewedMissing)) { + throw new DirectorySyncRejected('Missing users changed since the preview. Review the list again.'); + } + + $changes = array_values(array_filter($changes, fn (array $change): bool => $change[2] === 'missing_from_snapshot')); + $counts = array_fill_keys(array_keys($counts), 0); + $counts['deactivated'] = count($changes); + } + $audit = []; foreach ($changes as [$user, $action, $reason]) { - $fields = array_values(array_intersect(['name', 'email', 'email_verified_at', 'ad_disabled_at'], array_keys($user->getDirty()))); + $fields = array_values(array_intersect(['name', 'email', 'email_verified_at', 'ad_disabled_at', 'deleted_at', 'ad_disabled_reason'], array_keys($user->getDirty()))); if (! $dryRun) { if (! $user->exists) { $user->password = Str::random(64); @@ -104,13 +124,14 @@ class SyncDirectoryUsers ]; } - return ['counts' => $counts, 'changes' => $audit]; + return ['counts' => $counts, 'changes' => $audit, 'missing_fingerprint' => $fingerprint]; }, attempts: 3); } - private function disable(User $user): void + private function disable(User $user, string $reason = 'directory_disabled'): void { - $user->forceFill(['ad_disabled_at' => now(), 'remember_token' => null]); + $disabledAt = now(); + $user->forceFill(['ad_disabled_at' => $disabledAt, 'deleted_at' => $disabledAt, 'ad_disabled_reason' => $reason, 'remember_token' => null]); } private function source(): string diff --git a/config/ad-sync.php b/config/ad-sync.php index a4c5a57..acf07fa 100644 --- a/config/ad-sync.php +++ b/config/ad-sync.php @@ -2,6 +2,7 @@ return [ 'base-dn' => env('AD_SYNC_BASE_DN'), + 'admin-id' => (int) env('AD_SYNC_ADMIN_ID', 0), 'scheduled' => env('AD_SYNC_SCHEDULED', false), 'max-deactivations' => (int) env('AD_SYNC_MAX_DEACTIVATIONS', 5), ]; diff --git a/resources/themes/backend/views/layouts/app/sidebar.blade.php b/resources/themes/backend/views/layouts/app/sidebar.blade.php index 6db2170..fc92b51 100755 --- a/resources/themes/backend/views/layouts/app/sidebar.blade.php +++ b/resources/themes/backend/views/layouts/app/sidebar.blade.php @@ -15,6 +15,11 @@ {{ __('Dashboard') }} + @can('manage-directory-sync') + + {{ __('Directory sync') }} + + @endcan diff --git a/routes/web.php b/routes/web.php index 12e932e..c1a61ea 100755 --- a/routes/web.php +++ b/routes/web.php @@ -1,5 +1,6 @@ name('home'); @@ -8,4 +9,11 @@ Route::middleware(['auth', 'verified'])->group(function () { Route::view('dashboard', 'dashboard')->name('dashboard'); }); +Route::middleware(['auth', 'can:manage-directory-sync']) + ->prefix('admin/directory-sync')->name('admin.directory-sync')->group(function () { + Route::get('/', [DirectorySyncController::class, 'index']); + Route::post('/preview', [DirectorySyncController::class, 'preview'])->name('.preview'); + Route::post('/apply', [DirectorySyncController::class, 'apply'])->name('.apply'); + }); + require __DIR__.'/settings.php'; diff --git a/tests/Feature/DirectorySyncTest.php b/tests/Feature/DirectorySyncTest.php index b679704..801c535 100644 --- a/tests/Feature/DirectorySyncTest.php +++ b/tests/Feature/DirectorySyncTest.php @@ -68,17 +68,20 @@ it('keeps dry runs read-only and blocks access for an explicitly disabled direct $user->update(['password' => 'example-password']); directorySnapshot([directoryEntry(enabled: false)]); $this->artisan('ad:sync --dry-run')->expectsOutputToContain('deactivated=1')->assertSuccessful(); - expect($user->refresh()->ad_disabled_at)->toBeNull(); + expect($user->refresh()->ad_disabled_at)->toBeNull() + ->and($user->deleted_at)->toBeNull(); directorySnapshot([directoryEntry(enabled: false)]); $this->artisan('ad:sync')->assertSuccessful(); - expect($user->refresh()->ad_disabled_at)->not->toBeNull(); + expect($user->refresh()->ad_disabled_at)->not->toBeNull() + ->and($user->deleted_at)->toEqual($user->ad_disabled_at); $this->post(route('login.store'), ['email' => $user->email, 'password' => 'example-password']); $this->assertGuest(); directorySnapshot([directoryEntry()]); $this->artisan('ad:sync')->assertSuccessful(); - expect($user->refresh()->ad_disabled_at)->toBeNull(); + expect($user->refresh()->ad_disabled_at)->toBeNull() + ->and($user->deleted_at)->toBeNull(); }); it('requires explicit bounded missing-user deactivation and preserves local accounts', function () { @@ -99,7 +102,9 @@ it('requires explicit bounded missing-user deactivation and preserves local acco directorySnapshot([directoryEntry(), $second]); $this->artisan('ad:sync --deactivate-missing')->assertSuccessful(); expect(User::whereNotNull('ad_disabled_at')->sole()->email)->toBe($third['email']) - ->and($local->refresh()->ad_disabled_at)->toBeNull(); + ->and(User::whereNotNull('deleted_at')->sole()->email)->toBe($third['email']) + ->and($local->refresh()->ad_disabled_at)->toBeNull() + ->and($local->deleted_at)->toBeNull(); }); it('reports directory failures without changing users', function () { @@ -186,38 +191,26 @@ it('denies existing sessions and passkey logins while a managed user is disabled }); it('correlates run summaries and planned or committed changes without logging field values', function (bool $dryRun) { - $log = Log::spy(); + $events = []; + Log::shouldReceive('info')->times(3)->andReturnUsing(function ($message, $context) use (&$events): void { + $events[$message] = $context; + }); directorySnapshot([directoryEntry()]); $this->artisan($dryRun ? 'ad:sync --dry-run' : 'ad:sync')->assertSuccessful(); - $id = $dryRun ? null : User::sole()->id; - $runId = null; - $log->shouldHaveReceived('info')->withArgs(function ($message, $context) use (&$runId, $dryRun) { - if ($message !== 'Active Directory sync started.') { - return false; - } - $runId = $context['run_id']; - - return $context['dry_run'] === $dryRun && Str::isUuid($runId); - })->once(); - $log->shouldHaveReceived('info')->withArgs(fn ($message, $context) => $message === 'Active Directory sync user change.' - && $context === [ - 'run_id' => $runId, - 'dry_run' => $dryRun, - 'deactivate_missing' => false, + $start = $events['Active Directory sync started.']; + expect(Str::isUuid($start['run_id']))->toBeTrue() + ->and($start['dry_run'])->toBe($dryRun) + ->and($events['Active Directory sync user change.'])->toBe($start + [ 'action' => 'created', - 'user_id' => $id, + 'user_id' => $dryRun ? null : User::sole()->id, 'ad_guid' => directoryEntry()['guid'], 'disabled' => false, - 'changed_fields' => ['name', 'email'], + 'changed_fields' => ['name', 'email', 'email_verified_at'], 'reason' => null, - ] - )->once(); - $log->shouldHaveReceived('info')->withArgs(fn ($message, $context) => $message === 'Active Directory sync completed.' - && $context['run_id'] === $runId - && $context['created'] === 1 - && $context['duration_ms'] >= 0 - )->once(); + ]) + ->and($events['Active Directory sync completed.']['run_id'])->toBe($start['run_id']) + ->and($events['Active Directory sync completed.']['created'])->toBe(1); })->with(['dry run' => [true], 'live run' => [false]]); it('logs sanitized failures and emits no user changes for a rejected run', function () { @@ -238,3 +231,31 @@ it('logs sanitized failures and emits no user changes for a rejected run', funct ); $log->shouldNotHaveReceived('info', ['Active Directory sync user change.', Mockery::any()]); }); + +it('will neither claim an existing GUID nor deactivate missing users from another directory scope', function () { + directorySnapshot([directoryEntry()]); + $this->artisan('ad:sync')->assertSuccessful(); + $existing = User::sole(); + config(['ad-sync.base-dn' => 'OU=Other,DC=ad,DC=test']); + directorySnapshot([directoryEntry()]); + $this->artisan('ad:sync')->expectsOutputToContain('another directory scope')->assertFailed(); + + directorySnapshot([directoryEntry('other@example.test', '11111111-1111-1111-1111-111111111111')]); + $this->artisan('ad:sync --deactivate-missing')->assertSuccessful(); + expect($existing->refresh()->deleted_at)->toBeNull(); +}); + +it('registers an overlap-protected ten-minute job only when scheduling is enabled', function (bool $enabled) { + config(['ad-sync.scheduled' => $enabled]); + $schedule = new Illuminate\Console\Scheduling\Schedule; + Illuminate\Support\Facades\Schedule::swap($schedule); + require base_path('routes/console.php'); + + $events = collect($schedule->events())->filter(fn ($event) => str_contains($event->command, 'ad:sync')); + expect($events)->toHaveCount($enabled ? 1 : 0); + if ($enabled) { + expect($events->sole()->expression)->toBe('*/10 * * * *') + ->and($events->sole()->withoutOverlapping)->toBeTrue() + ->and($events->sole()->command)->not->toContain('--deactivate-missing'); + } +})->with(['enabled' => [true], 'disabled' => [false]]);