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
@@ -0,0 +1,89 @@
<?php
namespace Modules\ActiveDirectory\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Modules\ActiveDirectory\Services\DirectorySyncHistory;
use Modules\ActiveDirectory\Services\DirectorySyncRejected;
use Modules\ActiveDirectory\Services\SyncDirectoryUsers;
use Throwable;
class SyncActiveDirectory extends Command
{
protected $signature = 'ad:sync {--email : Match directory accounts against existing Laravel user emails}
{--create-missing : Explicitly create users absent from Laravel}
{--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'),
'email' => (bool) $this->option('email'),
'create_missing' => (bool) $this->option('create-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, $context['email'], $context['create_missing']);
} 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;
}
}
@@ -0,0 +1,62 @@
<?php
namespace Modules\ActiveDirectory\Constants;
final class AccountControl
{
public const SCRIPT = 0x0001;
public const ACCOUNTDISABLE = 0x0002;
public const HOMEDIR_REQUIRED = 0x0008;
public const LOCKOUT = 0x0010;
public const PASSWD_NOTREQD = 0x0020;
public const PASSWD_CANT_CHANGE = 0x0040;
public const ENCRYPTED_TEXT_PWD_ALLOWED = 0x0080;
public const TEMP_DUPLICATE_ACCOUNT = 0x0100;
public const NORMAL_ACCOUNT = 0x0200;
public const INTERDOMAIN_TRUST_ACCOUNT = 0x0800;
public const WORKSTATION_TRUST_ACCOUNT = 0x1000;
public const SERVER_TRUST_ACCOUNT = 0x2000;
public const DONT_EXPIRE_PASSWORD = 0x10000;
public const MNS_LOGON_ACCOUNT = 0x20000;
public const SMARTCARD_REQUIRED = 0x40000;
public const TRUSTED_FOR_DELEGATION = 0x80000;
public const NOT_DELEGATED = 0x100000;
public const USE_DES_KEY_ONLY = 0x200000;
public const DONT_REQ_PREAUTH = 0x400000;
public const PASSWORD_EXPIRED = 0x800000;
public const TRUSTED_TO_AUTH_FOR_DELEGATION = 0x1000000;
public const PARTIAL_SECRETS_ACCOUNT = 0x04000000;
public static function flags(int $value): array
{
$result = [];
foreach ((new \ReflectionClass(self::class))->getConstants() as $name => $flag) {
if (($value & $flag) !== 0) {
$result[] = $name;
}
}
return $result;
}
}
@@ -0,0 +1,101 @@
<?php
namespace Modules\ActiveDirectory\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\User;
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 Modules\ActiveDirectory\Services\DirectorySyncRejected;
use Modules\ActiveDirectory\Services\SyncDirectoryUsers;
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.');
}
}
@@ -0,0 +1,27 @@
<?php
namespace Modules\ActiveDirectory\Providers;
use App\Models\User;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
use Modules\ActiveDirectory\Console\Commands\SyncActiveDirectory;
class ActiveDirectoryServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->mergeConfigFrom(__DIR__.'/../config/config.php', 'ad-sync');
}
public function boot(): void
{
$this->loadMigrationsFrom(__DIR__.'/../database/migrations');
Gate::define('manage-directory-sync', fn (User $user): bool => $user->ad_guid === null
&& $user->id === config('ad-sync.admin-id'));
if ($this->app->runningInConsole()) {
$this->commands([SyncActiveDirectory::class]);
}
}
}
@@ -0,0 +1,86 @@
<?php
namespace Modules\ActiveDirectory\Services;
use LdapRecord\LdapInterface;
use LdapRecord\Models\ActiveDirectory\User;
use Modules\ActiveDirectory\Constants\AccountControl;
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 & AccountControl::ACCOUNTDISABLE) === 0,
'account_control' => $flags,
'account_flags' => AccountControl::flags($flags),
];
}
}
@@ -0,0 +1,32 @@
<?php
namespace Modules\ActiveDirectory\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,
]);
}
}
}
@@ -0,0 +1,7 @@
<?php
namespace Modules\ActiveDirectory\Services;
use RuntimeException;
class DirectorySyncRejected extends RuntimeException {}
@@ -0,0 +1,195 @@
<?php
namespace Modules\ActiveDirectory\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, bool $matchEmail = false, bool $createMissing = false): array
{
$entries = $this->snapshot();
$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
{
$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'],
'account_control' => $entry['account_control'] ?? null,
'account_flags' => $entry['account_flags'] ?? [],
];
}
if ($entries === []) {
throw new DirectorySyncRejected('Directory snapshot is empty.');
}
return $entries;
}
}
+6
View File
@@ -0,0 +1,6 @@
latest: 1.1.0
releases:
- version: 1.1.0
date: 2026-11-12
changes:
Initial Build
+13
View File
@@ -0,0 +1,13 @@
{
"name": "mpba/active-directory-module",
"type": "laravel-module",
"require": {
"php": "^8.3",
"illuminate/support": "^13.0"
},
"autoload": {
"psr-4": {
"Modules\\ActiveDirectory\\": ""
}
}
}
@@ -0,0 +1,8 @@
<?php
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),
];
@@ -0,0 +1,26 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('users', function (Blueprint $table): void {
$table->uuid('ad_guid')->nullable()->unique();
$table->string('ad_source', 64)->nullable()->index();
$table->timestamp('ad_disabled_at')->nullable();
});
}
public function down(): void
{
Schema::table('users', function (Blueprint $table): void {
$table->dropUnique(['ad_guid']);
$table->dropIndex(['ad_source']);
$table->dropColumn(['ad_guid', 'ad_source', 'ad_disabled_at']);
});
}
};
+13
View File
@@ -0,0 +1,13 @@
{
"name": "ActiveDirectory",
"alias": "active-directory",
"version": "1.0.0",
"description": "Microsoft and Samba AD synchronization",
"priority": 0,
"providers": [
"Modules\\ActiveDirectory\\Providers\\ActiveDirectoryServiceProvider"
],
"aliases": {},
"files": [],
"requires": []
}