updates for active directory now with docs

This commit is contained in:
Mark Gregory
2026-11-12 08:01:31 +00:00
parent c0d6b821cb
commit 7166dd33f9
21 changed files with 252 additions and 246 deletions
@@ -1,85 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Services\DirectorySyncHistory;
use App\Services\DirectorySyncRejected;
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
{
protected $signature = 'ad:sync {--dry-run : Preview changes without saving users}
{--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, DirectorySyncHistory $history): 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);
$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'], $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;
} catch (Throwable $exception) {
Log::error('Active Directory sync failed.', $context + [
'exception_type' => $exception::class,
'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;
}
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()]);
$record($review === null ? 'completed' : 'review_applied', $counts);
$summary = [];
foreach ($counts as $key => $value) {
$summary[] = "$key=$value";
}
$this->info(($context['dry_run'] ? 'Dry run: ' : '').implode(' ', $summary));
return self::SUCCESS;
}
}
@@ -1,100 +0,0 @@
<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Services\DirectorySyncRejected;
use App\Services\SyncDirectoryUsers;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Illuminate\View\View;
use Throwable;
class DirectorySyncController extends Controller
{
public function index(Request $request): View
{
$liveRuns = DB::table('ad_sync_runs')->where('dry_run', false);
$success = (clone $liveRuns)->where('status', 'completed')->latest('finished_at')->first();
$failure = (clone $liveRuns)->whereIn('status', ['failed', 'rejected'])->latest('finished_at')->first();
$review = $request->session()->get('directory-sync-review');
if ($review && $review['expires_at'] <= now()->timestamp) {
$request->session()->forget('directory-sync-review');
$review = null;
}
return view('admin.directory-sync', [
'scheduled' => config('ad-sync.scheduled'),
'stale' => ! $success || Carbon::parse($success->finished_at)->lte(now()->subMinutes(30)),
'success' => $success,
'failure' => $failure,
'counts' => $success ? json_decode($success->counts, true, flags: JSON_THROW_ON_ERROR) : [],
'disabledUsers' => User::whereNotNull('ad_guid')->whereNotNull('ad_disabled_at')
->orderByDesc('ad_disabled_at')->orderBy('id')->paginate(25),
'review' => $review,
]);
}
public function preview(Request $request, SyncDirectoryUsers $sync): RedirectResponse
{
$request->session()->forget('directory-sync-review');
try {
$result = $sync->run(dryRun: true, deactivateMissing: true);
} catch (DirectorySyncRejected $exception) {
return to_route('admin.directory-sync')->with('sync_error', $exception->getMessage());
} catch (Throwable $exception) {
Log::warning('Active Directory missing-user preview failed.', ['exception_type' => $exception::class]);
return to_route('admin.directory-sync')->with('sync_error', 'The directory could not be checked.');
}
$missing = collect($result['changes'])->where('reason', 'missing_from_snapshot');
$users = User::whereIn('id', $missing->pluck('user_id'))->orderBy('name')->get(['id', 'name', 'email', 'ad_guid']);
$request->session()->put('directory-sync-review', [
'token' => (string) Str::uuid(),
'expires_at' => now()->addMinutes(10)->timestamp,
'fingerprint' => $result['missing_fingerprint'],
'users' => $users->map(fn (User $user): array => ['name' => $user->name, 'email' => $user->email])->all(),
]);
Log::info('Active Directory missing-user preview completed.', [
'reviewer_id' => $request->user()?->getAuthIdentifier(),
'candidate_count' => $missing->count(),
]);
return to_route('admin.directory-sync');
}
public function apply(Request $request): RedirectResponse
{
$review = $request->session()->get('directory-sync-review');
if ($review && $review['expires_at'] <= now()->timestamp) {
$request->session()->forget('directory-sync-review');
$review = null;
}
if (! $review || ! $review['users'] || $request->input('review_token') !== $review['token']) {
return to_route('admin.directory-sync')->with('sync_error', 'Run a fresh preview before applying changes.');
}
$request->session()->forget('directory-sync-review');
$status = Artisan::call('ad:sync', [
'--deactivate-missing' => true,
'--reviewed-missing' => $review['fingerprint'],
]);
Log::info('Active Directory missing-user review submitted.', [
'reviewer_id' => $request->user()?->getAuthIdentifier(),
'candidate_count' => count($review['users']),
'exit_code' => $status,
]);
return $status === 0
? to_route('admin.directory-sync')->with('sync_status', 'Reviewed accounts deactivated.')
: to_route('admin.directory-sync')->with('sync_error', 'The review could not be applied. Check the latest failure and run a new preview.');
}
}
-4
View File
@@ -2,11 +2,9 @@
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;
@@ -27,8 +25,6 @@ class AppServiceProvider extends ServiceProvider
{
$this->configureDefaults();
Gate::define('manage-directory-sync', fn (User $user): bool => $user->ad_guid === null
&& $user->id === config('ad-sync.admin-id'));
}
/**
-83
View File
@@ -1,83 +0,0 @@
<?php
namespace App\Services;
use LdapRecord\LdapInterface;
use LdapRecord\Models\ActiveDirectory\User;
use RuntimeException;
class ActiveDirectory
{
private const ATTRIBUTES = ['objectguid', 'mail', 'displayname', 'cn', 'useraccountcontrol'];
public static function baseDn(): string
{
$connection = config('ldap.default');
return trim((string) (config('ad-sync.base-dn') ?: config("ldap.connections.{$connection}.base_dn")));
}
/** @return list<array{guid: ?string, email: string, name: string, enabled: bool}> */
public function users(): array
{
$baseDn = self::baseDn();
if ($baseDn === '') {
throw new RuntimeException('An LDAP search base is required.');
}
return User::resolveConnection(config('ldap.default'))->run(function (LdapInterface $ldap) use ($baseDn): array {
$entries = [];
$cookie = '';
do {
$result = $ldap->search($baseDn, '(&(objectCategory=person)(objectClass=user))', self::ATTRIBUTES, controls: [[
'oid' => LDAP_CONTROL_PAGEDRESULTS,
'iscritical' => true,
'value' => ['size' => 500, 'cookie' => $cookie],
]]);
try {
$response = $ldap->parseResult($result);
$next = $response ? ($response->controls[LDAP_CONTROL_PAGEDRESULTS]['value']['cookie'] ?? null) : null;
if (! $response || $response->failed() || $response->referrals || ! is_string($next)) {
throw new RuntimeException('LDAP returned an incomplete page.');
}
$page = $ldap->getEntries($result);
$count = $page['count'] ?? null;
if (! is_int($count) || $count !== count($page) - 1 || ($count === 0 && $next !== '')) {
throw new RuntimeException('LDAP returned invalid page entries.');
}
for ($index = 0; $index < $count; $index++) {
$entries[] = $this->entry((new User)->setRawAttributes($page[$index]));
}
$cookie = $next;
} finally {
$ldap->freeResult($result);
}
} while ($cookie !== '');
return $entries;
});
}
/** @return array{guid: ?string, email: string, name: string, enabled: bool} */
private function entry(User $user): array
{
$flags = filter_var($user->getFirstAttribute('useraccountcontrol'), FILTER_VALIDATE_INT, [
'options' => ['min_range' => 0],
]);
if ($flags === false) {
throw new RuntimeException('Missing or invalid userAccountControl.');
}
return [
'guid' => $user->getConvertedGuid(),
'email' => (string) $user->getFirstAttribute('mail'),
'name' => (string) ($user->getFirstAttribute('displayname') ?: $user->getFirstAttribute('cn')),
'enabled' => ($flags & 2) === 0,
];
}
}
-32
View File
@@ -1,32 +0,0 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Throwable;
class DirectorySyncHistory
{
/** @param array<string, int>|null $counts */
public function record(string $id, string $status, bool $dryRun, bool $deactivateMissing, int $duration, ?array $counts = null, ?string $failure = null): void
{
try {
DB::table('ad_sync_runs')->insert([
'id' => $id,
'status' => $status,
'dry_run' => $dryRun,
'deactivate_missing' => $deactivateMissing,
'duration_ms' => $duration,
'counts' => $counts === null ? null : json_encode($counts, JSON_THROW_ON_ERROR),
'failure' => $failure,
'finished_at' => now(),
]);
} catch (Throwable $exception) {
Log::warning('Active Directory sync history could not be saved.', [
'run_id' => $id,
'exception_type' => $exception::class,
]);
}
}
}
-7
View File
@@ -1,7 +0,0 @@
<?php
namespace App\Services;
use RuntimeException;
class DirectorySyncRejected extends RuntimeException {}
-174
View File
@@ -1,174 +0,0 @@
<?php
namespace App\Services;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class SyncDirectoryUsers
{
public function __construct(private ActiveDirectory $directory) {}
/**
* @return array{
* missing_fingerprint: string,
* counts: array{created: int, updated: int, unchanged: int, deactivated: int, reactivated: int},
* changes: list<array{action: string, user_id: ?int, ad_guid: ?string, disabled: bool, changed_fields: list<string>, reason: ?string}>
* }
*/
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, $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();
if ($user && $user->ad_source !== $source) {
throw new DirectorySyncRejected('GUID belongs to another directory scope.');
}
$owners = User::whereRaw('LOWER(email) = ?', [$entry['email']])->lockForUpdate()->get(['id']);
if ($owners->contains(fn (User $owner): bool => $owner->id !== $user?->id)) {
throw new DirectorySyncRejected('Local email collision.');
}
$user ??= new User;
$user->forceFill(['ad_guid' => $guid, 'ad_source' => $source, 'name' => $entry['name']]);
if ($user->email !== $entry['email']) {
$user->forceFill(['email' => $entry['email'], 'email_verified_at' => null]);
}
if (! $user->exists) {
$action = 'created';
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->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 {
$action = 'unchanged';
}
$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];
}
}
if ($deactivateMissing) {
$missing = User::where('ad_source', $source)->whereNotNull('ad_guid')
->whereNull('ad_disabled_at')->lockForUpdate()->get();
foreach ($missing as $user) {
if (! isset($entries[$user->ad_guid])) {
$counts['deactivated']++;
$this->disable($user, 'missing_from_snapshot');
$missingGuids[] = $user->ad_guid;
$changes[] = [$user, 'deactivated', 'missing_from_snapshot'];
}
}
}
if ($counts['deactivated'] > config('ad-sync.max-deactivations')) {
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', 'deleted_at', 'ad_disabled_reason'], 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' => $counts, 'changes' => $audit, 'missing_fingerprint' => $fingerprint];
}, attempts: 3);
}
private function disable(User $user, string $reason = 'directory_disabled'): void
{
$disabledAt = now();
$user->forceFill(['ad_disabled_at' => $disabledAt, 'deleted_at' => $disabledAt, 'ad_disabled_reason' => $reason, 'remember_token' => null]);
}
private function source(): string
{
$connection = config('ldap.default');
$base = ActiveDirectory::baseDn();
return hash('sha256', strtolower("{$connection}:$base"));
}
/** @return array<string, array{email: string, name: string, enabled: bool}> */
private function snapshot(): array
{
$entries = [];
$emails = [];
foreach ($this->directory->users() as $entry) {
$guid = strtolower((string) $entry['guid']);
$email = strtolower(trim($entry['email']));
$name = trim($entry['name']);
if (! Str::isUuid($guid) || $guid === '00000000-0000-0000-0000-000000000000'
|| strlen($email) > 255 || ! filter_var($email, FILTER_VALIDATE_EMAIL)
|| $name === '' || mb_strlen($name) > 255) {
throw new DirectorySyncRejected('Invalid GUID, email or name in directory snapshot.');
}
if (isset($entries[$guid]) || isset($emails[$email])) {
throw new DirectorySyncRejected('Duplicate GUID or email in directory snapshot.');
}
$emails[$email] = true;
$entries[$guid] = ['email' => $email, 'name' => $name, 'enabled' => $entry['enabled']];
}
if ($entries === []) {
throw new DirectorySyncRejected('Directory snapshot is empty.');
}
return $entries;
}
}