diff --git a/app/Console/Commands/SyncActiveDirectory.php b/app/Console/Commands/SyncActiveDirectory.php index 11f1b03..80c19e1 100644 --- a/app/Console/Commands/SyncActiveDirectory.php +++ b/app/Console/Commands/SyncActiveDirectory.php @@ -7,6 +7,7 @@ use App\Services\SyncDirectoryUsers; use Illuminate\Console\Command; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Log; +use Illuminate\Support\Str; use Throwable; class SyncActiveDirectory extends Command @@ -18,34 +19,48 @@ class SyncActiveDirectory extends Command public function handle(SyncDirectoryUsers $sync): int { + $started = hrtime(true); $context = [ + 'run_id' => (string) Str::uuid(), 'dry_run' => (bool) $this->option('dry-run'), 'deactivate_missing' => (bool) $this->option('deactivate-missing'), ]; + $duration = fn (): int => (int) ((hrtime(true) - $started) / 1_000_000); + Log::info('Active Directory sync started.', $context); + try { $lock = Cache::lock('ad:sync', 3600); if (! $lock->get()) { throw new DirectorySyncRejected('A directory sync is already running.'); } try { - $counts = $sync->run($context['dry_run'], $context['deactivate_missing']); + $result = $sync->run($context['dry_run'], $context['deactivate_missing']); } finally { $lock->release(); } } catch (DirectorySyncRejected $exception) { - Log::warning('Active Directory sync rejected.', $context + ['reason' => $exception->getMessage()]); + Log::warning('Active Directory sync rejected.', $context + ['reason' => $exception->getMessage(), 'duration_ms' => $duration()]); $this->error($exception->getMessage()); return self::FAILURE; } catch (Throwable $exception) { - Log::error('Active Directory sync failed.', $context + ['exception_type' => $exception::class]); + Log::error('Active Directory sync failed.', $context + [ + 'exception_type' => $exception::class, + 'exception_code' => $exception->getCode(), + 'duration_ms' => $duration(), + ]); $this->error('Sync stopped due to a directory or database error.'); return self::FAILURE; } - Log::info('Active Directory sync completed.', $context + $counts); + foreach ($result['changes'] as $change) { + Log::info('Active Directory sync user change.', $context + $change); + } + + $counts = $result['counts']; + Log::info('Active Directory sync completed.', $context + $counts + ['duration_ms' => $duration()]); $summary = []; foreach ($counts as $key => $value) { $summary[] = "$key=$value"; diff --git a/app/Services/SyncDirectoryUsers.php b/app/Services/SyncDirectoryUsers.php index aa508e4..bd3d33c 100644 --- a/app/Services/SyncDirectoryUsers.php +++ b/app/Services/SyncDirectoryUsers.php @@ -10,7 +10,12 @@ class SyncDirectoryUsers { public function __construct(private ActiveDirectory $directory) {} - /** @return array{created: int, updated: int, unchanged: int, deactivated: int, reactivated: int} */ + /** + * @return array{ + * counts: array{created: int, updated: int, unchanged: int, deactivated: int, reactivated: int}, + * changes: list, reason: ?string}> + * } + */ public function run(bool $dryRun, bool $deactivateMissing): array { $entries = $this->snapshot(); @@ -38,22 +43,28 @@ class SyncDirectoryUsers } if (! $user->exists) { - $counts['created']++; + $action = 'created'; $user->ad_disabled_at = $entry['enabled'] ? null : now(); } elseif (! $entry['enabled'] && $user->ad_disabled_at === null) { - $counts['deactivated']++; + $action = 'deactivated'; $this->disable($user); } elseif ($entry['enabled'] && $user->ad_disabled_at !== null) { - $counts['reactivated']++; + $action = 'reactivated'; $user->ad_disabled_at = null; } elseif ($user->isDirty()) { - $counts['updated']++; + $action = 'updated'; } else { - $counts['unchanged']++; + $action = 'unchanged'; } - if ($user->isDirty()) { - $changes[] = $user; + $counts[$action]++; + if ($action !== 'unchanged') { + $reason = match (true) { + ! $entry['enabled'] && in_array($action, ['created', 'deactivated'], true) => 'directory_disabled', + $action === 'reactivated' => 'directory_enabled', + default => null, + }; + $changes[] = [$user, $action, $reason]; } } @@ -64,7 +75,7 @@ class SyncDirectoryUsers if (! isset($entries[$user->ad_guid])) { $counts['deactivated']++; $this->disable($user); - $changes[] = $user; + $changes[] = [$user, 'deactivated', 'missing_from_snapshot']; } } } @@ -73,16 +84,27 @@ class SyncDirectoryUsers throw new DirectorySyncRejected('Deactivation limit exceeded.'); } - if (! $dryRun) { - foreach ($changes as $user) { + $audit = []; + foreach ($changes as [$user, $action, $reason]) { + $fields = array_values(array_intersect(['name', 'email', 'email_verified_at', 'ad_disabled_at'], array_keys($user->getDirty()))); + if (! $dryRun) { if (! $user->exists) { $user->password = Str::random(64); } $user->save(); } + + $audit[] = [ + 'action' => $action, + 'user_id' => $user->exists ? $user->id : null, + 'ad_guid' => $user->ad_guid, + 'disabled' => $user->ad_disabled_at !== null, + 'changed_fields' => $fields, + 'reason' => $reason, + ]; } - return $counts; + return ['counts' => $counts, 'changes' => $audit]; }, attempts: 3); } diff --git a/tests/Feature/DirectorySyncTest.php b/tests/Feature/DirectorySyncTest.php index b408ddf..b679704 100644 --- a/tests/Feature/DirectorySyncTest.php +++ b/tests/Feature/DirectorySyncTest.php @@ -5,6 +5,7 @@ use App\Services\ActiveDirectory; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Log; +use Illuminate\Support\Str; use Laravel\Passkeys\Passkey; use Laravel\Passkeys\Passkeys; use LdapRecord\Connection; @@ -184,25 +185,56 @@ it('denies existing sessions and passkey logins while a managed user is disabled expect(Passkeys::allowsLogin(request(), $passkey))->toBeFalse(); }); -it('logs counts and failure reasons without directory email addresses or exception messages', function () { +it('correlates run summaries and planned or committed changes without logging field values', function (bool $dryRun) { $log = Log::spy(); directorySnapshot([directoryEntry()]); - $this->artisan('ad:sync --dry-run')->assertSuccessful(); - $log->shouldHaveReceived('info')->once()->with('Active Directory sync completed.', [ - 'dry_run' => true, - 'deactivate_missing' => false, - 'created' => 1, - 'updated' => 0, - 'unchanged' => 0, - 'deactivated' => 0, - 'reactivated' => 0, - ]); + $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, + 'action' => 'created', + 'user_id' => $id, + 'ad_guid' => directoryEntry()['guid'], + 'disabled' => false, + 'changed_fields' => ['name', 'email'], + '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(); +})->with(['dry run' => [true], 'live run' => [false]]); + +it('logs sanitized failures and emits no user changes for a rejected run', function () { + $log = Log::spy(); $this->mock(ActiveDirectory::class)->shouldReceive('users')->once()->andThrow(new RuntimeException('sensitive bind detail')); $this->artisan('ad:sync')->assertFailed(); - $log->shouldHaveReceived('error')->once()->with('Active Directory sync failed.', [ - 'dry_run' => false, - 'deactivate_missing' => false, - 'exception_type' => RuntimeException::class, - ]); + $log->shouldHaveReceived('error')->once()->withArgs(fn ($message, $context) => $message === 'Active Directory sync failed.' + && $context['exception_type'] === RuntimeException::class + && $context['exception_code'] === 0 + && ! str_contains(json_encode($context), 'sensitive bind detail') + ); + + directorySnapshot([]); + $this->artisan('ad:sync')->assertFailed(); + $log->shouldHaveReceived('warning')->once()->withArgs(fn ($message, $context) => $message === 'Active Directory sync rejected.' + && $context['reason'] === 'Directory snapshot is empty.' + && $context['duration_ms'] >= 0 + ); + $log->shouldNotHaveReceived('info', ['Active Directory sync user change.', Mockery::any()]); });