Files
ad_testbed/Modules/ActiveDirectory/Services/SyncDirectoryUsers.php
T

199 lines
8.9 KiB
PHP

<?php
namespace Modules\ActiveDirectory\Services;
use App\Models\User;
use Closure;
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, bool $matchEmail = false, bool $createMissing = false, ?Closure $inspectDirectory = null, bool $includeProperties = false): array
{
$directoryUsers = $includeProperties ? $this->directory->users(true) : $this->directory->users();
$inspectDirectory?->__invoke($directoryUsers);
$entries = $this->snapshot($directoryUsers);
$source = $this->source();
return DB::transaction(function () use ($entries, $source, $dryRun, $deactivateMissing, $reviewedMissing, $matchEmail, $createMissing): 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.');
}
// Email matching never claims an unrelated directory-managed identity.
if (! $user && $matchEmail) {
$candidate = User::whereRaw('LOWER(email) = ?', [$entry['email']])->lockForUpdate()->get();
if ($candidate->count() > 1) {
throw new DirectorySyncRejected('Ambiguous local email match.');
}
$user = $candidate->first();
if ($user && ($user->ad_guid !== null || ($user->ad_source !== null && $user->ad_source !== $source))) {
throw new DirectorySyncRejected('Email belongs to another directory identity.');
}
}
if (! $user && ! $createMissing) {
continue;
}
$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[] = [
'account_control' => $entries[$user->ad_guid]['account_control'] ?? null,
'account_flags' => $entries[$user->ad_guid]['account_flags'] ?? [],
'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 $directoryUsers): array
{
$entries = [];
$emails = [];
foreach ($directoryUsers 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'],
'account_control' => $entry['account_control'] ?? null,
'account_flags' => $entry['account_flags'] ?? [],
];
}
if ($entries === []) {
throw new DirectorySyncRejected('Directory snapshot is empty.');
}
return $entries;
}
}