From 9404c7a2100d00bf546373d822a4412e33864e0c Mon Sep 17 00:00:00 2001 From: Mark Gregory Date: Thu, 12 Nov 2026 12:36:38 +0000 Subject: [PATCH] updates for active directory now with docs, noiw with microsoft AD sync --- .env.bak-20261112-122821 | 115 ++++++++++++++ ...yncActiveDirectory.php.bak-20261112-122322 | 141 +++++++++++++++++ ...yncActiveDirectory.php.bak-20261112-123130 | 144 ++++++++++++++++++ .../Services/ActiveDirectory.php | 10 +- .../ActiveDirectory.php.bak-20261112-122508 | 103 +++++++++++++ .../ActiveDirectory.php.bak-20261112-122621 | 109 +++++++++++++ .../ActiveDirectory.php.bak-20261112-122707 | 111 ++++++++++++++ .../ActiveDirectory.php.bak-20261112-122932 | 111 ++++++++++++++ .../Feature/ActiveDirectoryModuleTest.php | 0 .../Tests}/Feature/DirectorySyncAdminTest.php | 0 .../Tests}/Feature/DirectorySyncTest.php | 0 [ | 0 certs/dc01-ad-test.cer | Bin 0 -> 805 bytes certs/dc01-ad-test.pem | 19 +++ certs/dc01-ad-test.pem.bak.20261112-121643 | 19 +++ composer.json | 2 +- phpunit.xml | 1 + tests/Pest.php | 2 +- 18 files changed, 884 insertions(+), 3 deletions(-) create mode 100755 .env.bak-20261112-122821 create mode 100644 Modules/ActiveDirectory/Console/Commands/SyncActiveDirectory.php.bak-20261112-122322 create mode 100644 Modules/ActiveDirectory/Console/Commands/SyncActiveDirectory.php.bak-20261112-123130 create mode 100644 Modules/ActiveDirectory/Services/ActiveDirectory.php.bak-20261112-122508 create mode 100644 Modules/ActiveDirectory/Services/ActiveDirectory.php.bak-20261112-122621 create mode 100644 Modules/ActiveDirectory/Services/ActiveDirectory.php.bak-20261112-122707 create mode 100644 Modules/ActiveDirectory/Services/ActiveDirectory.php.bak-20261112-122932 rename {tests => Modules/ActiveDirectory/Tests}/Feature/ActiveDirectoryModuleTest.php (100%) rename {tests => Modules/ActiveDirectory/Tests}/Feature/DirectorySyncAdminTest.php (100%) rename {tests => Modules/ActiveDirectory/Tests}/Feature/DirectorySyncTest.php (100%) create mode 100644 [ create mode 100644 certs/dc01-ad-test.cer create mode 100644 certs/dc01-ad-test.pem create mode 100644 certs/dc01-ad-test.pem.bak.20261112-121643 diff --git a/.env.bak-20261112-122821 b/.env.bak-20261112-122821 new file mode 100755 index 0000000..a1fe434 --- /dev/null +++ b/.env.bak-20261112-122821 @@ -0,0 +1,115 @@ +APP_NAME=AD_Testrig +APP_ENV=local +APP_KEY=base64:2T9x1AAYIEjGQNr3Ihkj0UprtsSwv44phhKgLyIsRn8= +APP_DEBUG=true +APP_URL=https://adtest.vm + +APP_LOCALE=en +APP_FALLBACK_LOCALE=en +APP_FAKER_LOCALE=en_US + +APP_MAINTENANCE_DRIVER=file +# APP_MAINTENANCE_STORE=database +# PHP_CLI_SERVER_WORKERS=4 + +BCRYPT_ROUNDS=12 + +LOG_CHANNEL=stack +LOG_STACK=single +LOG_DEPRECATIONS_CHANNEL=null +LOG_LEVEL=debug + +DB_CONNECTION=mysql +DB_HOST=127.0.0.1 +DB_PORT=3306 +DB_DATABASE="ad_testing" +DB_USERNAME=root +DB_PASSWORD=987400Kmh + +AD_HOST=192.168.122.50 +AD_PORT=389 +AD_BASE_DN="DC=ad,DC=test" +AD_USERNAME="Administrator@ad.test" +AD_PASSWORD="987400Kmh" +AD_USE_SSL=false +AD_USE_TLS=false + +#Microsoft +#LDAP_HOST=192.168.122.50 +#LDAP_PORT=636 +LDAP_SSL=true +#LDAP_TLS=false +#LDAP_BASE_DN="DC=ad,DC=test" + +LDAP_LOGGING=true +#LDAP_CONNECTION=default +#LDAP_HOST=127.0.0.1 +#LDAP_PORT=1636 +#LDAP_BASE_DN="DC=ad,DC=test" +#LDAP_USERNAME="CN=svc-laravel-sync,CN=Users,DC=ad,DC=test" +#LDAP_PASSWORD="aB1!mfOJfB2VVwks2dTCSlgwlQz7c3yBDxhcpVu4YSzhoT2f" +LDAP_TIMEOUT=5 +#LDAP_SSL=false +#LDAP_TLS=true +#LDAP_TLS_CA_CERT="/Users/markgregory/Developer/Sites/Testing/AD_Testing/storage/app/private/ldap-samba-ca.pem" + +LDAP_USERNAME="svc-laravel-sync@ad.test" +LDAP_PASSWORD="987400Kmh" +LDAP_HOST=dc01.ad.test +LDAP_PORT=636 +LDAP_TLS=true +LDAP_STARTTLS=false + +LDAP_CONNECTION=default +#LDAP_HOST=dc01.ad.test +#LDAP_PORT=636 +LDAP_BASE_DN="DC=ad,DC=test" +#LDAP_USERNAME="svc-laravel-sync@ad.test" +#LDAP_TLS=true +#LDAP_STARTTLS=false +LDAP_SASL=false +LDAP_TLS_CA_CERT=certs/dc01-ad-test.pem +SESSION_DRIVER=redis +SESSION_LIFETIME=120 +SESSION_ENCRYPT=false +SESSION_PATH=/ +SESSION_DOMAIN=null + +BROADCAST_CONNECTION=log +FILESYSTEM_DISK=local +QUEUE_CONNECTION=database + +CACHE_STORE=redis +# CACHE_PREFIX= + +MEMCACHED_HOST=127.0.0.1 + +REDIS_CLIENT=predis +REDIS_HOST=127.0.0.1 +REDIS_PASSWORD=null +REDIS_PORT=6379 + +MAIL_MAILER=log +MAIL_SCHEME=null +MAIL_HOST=127.0.0.1 +MAIL_PORT=2525 +MAIL_USERNAME=null +MAIL_PASSWORD=null +MAIL_FROM_ADDRESS="hello@example.com" +MAIL_FROM_NAME="${APP_NAME}" + +AWS_ACCESS_KEY_ID= +AWS_SECRET_ACCESS_KEY= +AWS_DEFAULT_REGION=us-east-1 +AWS_BUCKET= +AWS_USE_PATH_STYLE_ENDPOINT=false + +VITE_APP_NAME="${APP_NAME}" + +STYLIST_DEFAULT_THEME=backend +STYLIST_BACKEND_THEME=backend +STYLIST_FRONTEND_THEME=frontend + +AD_SYNC_BASE_DN="OU=LaravelSync,DC=ad,DC=test" +AD_SYNC_SCHEDULED=true +AD_SYNC_ADMIN_ID=3 diff --git a/Modules/ActiveDirectory/Console/Commands/SyncActiveDirectory.php.bak-20261112-122322 b/Modules/ActiveDirectory/Console/Commands/SyncActiveDirectory.php.bak-20261112-122322 new file mode 100644 index 0000000..f7ad6a2 --- /dev/null +++ b/Modules/ActiveDirectory/Console/Commands/SyncActiveDirectory.php.bak-20261112-122322 @@ -0,0 +1,141 @@ + (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); + $this->writeDetails('Sync options', $context, OutputInterface::VERBOSITY_VERBOSE); + + 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'], + ($this->option('debug') || $this->option('dump-ad')) ? $this->dumpDirectory(...) : null, + includeProperties: (bool) $this->option('dump-ad'), + ); + } 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.'); + $this->writeDetails('Error', [ + 'type' => $exception::class, + 'code' => $exception->getCode(), + ], OutputInterface::VERBOSITY_DEBUG); + + return self::FAILURE; + } + + foreach ($result['changes'] as $change) { + Log::info('Active Directory sync user change.', $context + $change); + if ($this->output->isDebug()) { + $this->writeDetails('User change', $change, OutputInterface::VERBOSITY_DEBUG); + } else { + $this->writeDetails('User change', [ + 'action' => $change['action'], + 'ad_guid' => $change['ad_guid'], + 'changed_fields' => $change['changed_fields'], + ], OutputInterface::VERBOSITY_VERY_VERBOSE); + } + } + + $counts = $result['counts']; + Log::info('Active Directory sync completed.', $context + $counts + ['duration_ms' => $duration()]); + $record($review === null ? 'completed' : 'review_applied', $counts); + $this->writeDetails('Run duration', ['milliseconds' => $duration()], OutputInterface::VERBOSITY_VERBOSE); + $summary = []; + foreach ($counts as $key => $value) { + $summary[] = "$key=$value"; + } + $this->info(($context['dry_run'] ? 'Dry run: ' : '').implode(' ', $summary)); + + return self::SUCCESS; + } + + private function dumpDirectory(array $users): void + { + $debug = $this->option('debug'); + if ($debug) { + $this->writeDetails('AD snapshot', ['base_dn' => ActiveDirectory::baseDn(), 'accounts' => count($users)]); + } + + foreach ($users as $user) { + if ($this->option('dump-ad')) { + $this->writeDetails('AD properties', $user['ad_properties']); + } + if ($debug) { + unset($user['ad_properties']); + $this->writeDetails('AD account', $user); + } + } + } + + private function writeDetails(string $label, array $details, int $verbosity = OutputInterface::VERBOSITY_NORMAL): void + { + if ($this->output->getVerbosity() >= $verbosity) { + $this->output->writeln($label.' '.json_encode($details, JSON_INVALID_UTF8_SUBSTITUTE | JSON_PARTIAL_OUTPUT_ON_ERROR), OutputInterface::OUTPUT_RAW); + } + } +} diff --git a/Modules/ActiveDirectory/Console/Commands/SyncActiveDirectory.php.bak-20261112-123130 b/Modules/ActiveDirectory/Console/Commands/SyncActiveDirectory.php.bak-20261112-123130 new file mode 100644 index 0000000..df585dd --- /dev/null +++ b/Modules/ActiveDirectory/Console/Commands/SyncActiveDirectory.php.bak-20261112-123130 @@ -0,0 +1,144 @@ + (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); + $this->writeDetails('Sync options', $context, OutputInterface::VERBOSITY_VERBOSE); + + 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'], + ($this->option('debug') || $this->option('dump-ad')) ? $this->dumpDirectory(...) : null, + includeProperties: (bool) $this->option('dump-ad'), + ); + } 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(), + 'exception_message' => $exception->getMessage(), + 'exception_file' => $exception->getFile(), + 'exception_line' => $exception->getLine(), + 'duration_ms' => $duration(), + ]); + $record('failed', failure: 'Directory or database error'); + $this->error('Sync stopped due to a directory or database error.'); + $this->writeDetails('Error', [ + 'type' => $exception::class, + 'code' => $exception->getCode(), + ], OutputInterface::VERBOSITY_DEBUG); + + return self::FAILURE; + } + + foreach ($result['changes'] as $change) { + Log::info('Active Directory sync user change.', $context + $change); + if ($this->output->isDebug()) { + $this->writeDetails('User change', $change, OutputInterface::VERBOSITY_DEBUG); + } else { + $this->writeDetails('User change', [ + 'action' => $change['action'], + 'ad_guid' => $change['ad_guid'], + 'changed_fields' => $change['changed_fields'], + ], OutputInterface::VERBOSITY_VERY_VERBOSE); + } + } + + $counts = $result['counts']; + Log::info('Active Directory sync completed.', $context + $counts + ['duration_ms' => $duration()]); + $record($review === null ? 'completed' : 'review_applied', $counts); + $this->writeDetails('Run duration', ['milliseconds' => $duration()], OutputInterface::VERBOSITY_VERBOSE); + $summary = []; + foreach ($counts as $key => $value) { + $summary[] = "$key=$value"; + } + $this->info(($context['dry_run'] ? 'Dry run: ' : '').implode(' ', $summary)); + + return self::SUCCESS; + } + + private function dumpDirectory(array $users): void + { + $debug = $this->option('debug'); + if ($debug) { + $this->writeDetails('AD snapshot', ['base_dn' => ActiveDirectory::baseDn(), 'accounts' => count($users)]); + } + + foreach ($users as $user) { + if ($this->option('dump-ad')) { + $this->writeDetails('AD properties', $user['ad_properties']); + } + if ($debug) { + unset($user['ad_properties']); + $this->writeDetails('AD account', $user); + } + } + } + + private function writeDetails(string $label, array $details, int $verbosity = OutputInterface::VERBOSITY_NORMAL): void + { + if ($this->output->getVerbosity() >= $verbosity) { + $this->output->writeln($label.' '.json_encode($details, JSON_INVALID_UTF8_SUBSTITUTE | JSON_PARTIAL_OUTPUT_ON_ERROR), OutputInterface::OUTPUT_RAW); + } + } +} diff --git a/Modules/ActiveDirectory/Services/ActiveDirectory.php b/Modules/ActiveDirectory/Services/ActiveDirectory.php index 0328b01..de819c5 100644 --- a/Modules/ActiveDirectory/Services/ActiveDirectory.php +++ b/Modules/ActiveDirectory/Services/ActiveDirectory.php @@ -37,12 +37,20 @@ class ActiveDirectory $cookie = ''; do { - $result = $ldap->search($baseDn, '(&(objectCategory=person)(objectClass=user))', $attributes, controls: [[ + $result = $ldap->search($baseDn, '(&(objectCategory=person)(objectClass=user)(mail=*))', $attributes, controls: [[ 'oid' => LDAP_CONTROL_PAGEDRESULTS, 'iscritical' => true, 'value' => ['size' => 500, 'cookie' => $cookie], ]]); + if ($result === false) { + throw new RuntimeException(sprintf( + 'Active Directory LDAP paged search failed (LDAP error %s: %s).', + (string) $ldap->errNo(), + ldap_err2str((int) $ldap->errNo()) + )); + } + try { $response = $ldap->parseResult($result); $next = $response ? ($response->controls[LDAP_CONTROL_PAGEDRESULTS]['value']['cookie'] ?? null) : null; diff --git a/Modules/ActiveDirectory/Services/ActiveDirectory.php.bak-20261112-122508 b/Modules/ActiveDirectory/Services/ActiveDirectory.php.bak-20261112-122508 new file mode 100644 index 0000000..0328b01 --- /dev/null +++ b/Modules/ActiveDirectory/Services/ActiveDirectory.php.bak-20261112-122508 @@ -0,0 +1,103 @@ + */ + public function users(bool $includeProperties = false): 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, $includeProperties): array { + $attributes = $includeProperties ? [...self::ATTRIBUTES, ...self::DIAGNOSTIC_ATTRIBUTES] : self::ATTRIBUTES; + $entries = []; + $cookie = ''; + + do { + $result = $ldap->search($baseDn, '(&(objectCategory=person)(objectClass=user))', $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++) { + $user = (new User)->setRawAttributes($page[$index]); + $entry = $this->entry($user); + if ($includeProperties) { + $entry['ad_properties'] = ['objectguid' => $entry['guid']]; + foreach (array_diff($attributes, ['objectguid']) as $attribute) { + $values = $user->getAttribute($attribute); + if ($values !== null) { + $entry['ad_properties'][$attribute] = $values; + } + } + } + $entries[] = $entry; + } + + $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), + ]; + } +} diff --git a/Modules/ActiveDirectory/Services/ActiveDirectory.php.bak-20261112-122621 b/Modules/ActiveDirectory/Services/ActiveDirectory.php.bak-20261112-122621 new file mode 100644 index 0000000..1d6135a --- /dev/null +++ b/Modules/ActiveDirectory/Services/ActiveDirectory.php.bak-20261112-122621 @@ -0,0 +1,109 @@ + */ + public function users(bool $includeProperties = false): 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, $includeProperties): array { + $attributes = $includeProperties ? [...self::ATTRIBUTES, ...self::DIAGNOSTIC_ATTRIBUTES] : self::ATTRIBUTES; + $entries = []; + $cookie = ''; + + do { + $result = $ldap->search($baseDn, '(&(objectCategory=person)(objectClass=user))', $attributes, controls: [[ + 'oid' => LDAP_CONTROL_PAGEDRESULTS, + 'iscritical' => true, + 'value' => ['size' => 500, 'cookie' => $cookie], + ]]); + + if ($result === false) { + throw new RuntimeException( + 'Active Directory LDAP paged search failed before returning a result.' + ); + } + + 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++) { + $user = (new User)->setRawAttributes($page[$index]); + $entry = $this->entry($user); + if ($includeProperties) { + $entry['ad_properties'] = ['objectguid' => $entry['guid']]; + foreach (array_diff($attributes, ['objectguid']) as $attribute) { + $values = $user->getAttribute($attribute); + if ($values !== null) { + $entry['ad_properties'][$attribute] = $values; + } + } + } + $entries[] = $entry; + } + + $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), + ]; + } +} diff --git a/Modules/ActiveDirectory/Services/ActiveDirectory.php.bak-20261112-122707 b/Modules/ActiveDirectory/Services/ActiveDirectory.php.bak-20261112-122707 new file mode 100644 index 0000000..2a867e9 --- /dev/null +++ b/Modules/ActiveDirectory/Services/ActiveDirectory.php.bak-20261112-122707 @@ -0,0 +1,111 @@ + */ + public function users(bool $includeProperties = false): 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, $includeProperties): array { + $attributes = $includeProperties ? [...self::ATTRIBUTES, ...self::DIAGNOSTIC_ATTRIBUTES] : self::ATTRIBUTES; + $entries = []; + $cookie = ''; + + do { + $result = $ldap->search($baseDn, '(&(objectCategory=person)(objectClass=user))', $attributes, controls: [[ + 'oid' => LDAP_CONTROL_PAGEDRESULTS, + 'iscritical' => true, + 'value' => ['size' => 500, 'cookie' => $cookie], + ]]); + + if ($result === false) { + throw new RuntimeException(sprintf( + 'Active Directory LDAP paged search failed (LDAP error %s: %s).', + (string) $ldap->errNo(), + (string) $ldap->errMsg() + )); + } + + 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++) { + $user = (new User)->setRawAttributes($page[$index]); + $entry = $this->entry($user); + if ($includeProperties) { + $entry['ad_properties'] = ['objectguid' => $entry['guid']]; + foreach (array_diff($attributes, ['objectguid']) as $attribute) { + $values = $user->getAttribute($attribute); + if ($values !== null) { + $entry['ad_properties'][$attribute] = $values; + } + } + } + $entries[] = $entry; + } + + $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), + ]; + } +} diff --git a/Modules/ActiveDirectory/Services/ActiveDirectory.php.bak-20261112-122932 b/Modules/ActiveDirectory/Services/ActiveDirectory.php.bak-20261112-122932 new file mode 100644 index 0000000..6c873d2 --- /dev/null +++ b/Modules/ActiveDirectory/Services/ActiveDirectory.php.bak-20261112-122932 @@ -0,0 +1,111 @@ + */ + public function users(bool $includeProperties = false): 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, $includeProperties): array { + $attributes = $includeProperties ? [...self::ATTRIBUTES, ...self::DIAGNOSTIC_ATTRIBUTES] : self::ATTRIBUTES; + $entries = []; + $cookie = ''; + + do { + $result = $ldap->search($baseDn, '(&(objectCategory=person)(objectClass=user))', $attributes, controls: [[ + 'oid' => LDAP_CONTROL_PAGEDRESULTS, + 'iscritical' => true, + 'value' => ['size' => 500, 'cookie' => $cookie], + ]]); + + if ($result === false) { + throw new RuntimeException(sprintf( + 'Active Directory LDAP paged search failed (LDAP error %s: %s).', + (string) $ldap->errNo(), + ldap_err2str((int) $ldap->errNo()) + )); + } + + 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++) { + $user = (new User)->setRawAttributes($page[$index]); + $entry = $this->entry($user); + if ($includeProperties) { + $entry['ad_properties'] = ['objectguid' => $entry['guid']]; + foreach (array_diff($attributes, ['objectguid']) as $attribute) { + $values = $user->getAttribute($attribute); + if ($values !== null) { + $entry['ad_properties'][$attribute] = $values; + } + } + } + $entries[] = $entry; + } + + $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), + ]; + } +} diff --git a/tests/Feature/ActiveDirectoryModuleTest.php b/Modules/ActiveDirectory/Tests/Feature/ActiveDirectoryModuleTest.php similarity index 100% rename from tests/Feature/ActiveDirectoryModuleTest.php rename to Modules/ActiveDirectory/Tests/Feature/ActiveDirectoryModuleTest.php diff --git a/tests/Feature/DirectorySyncAdminTest.php b/Modules/ActiveDirectory/Tests/Feature/DirectorySyncAdminTest.php similarity index 100% rename from tests/Feature/DirectorySyncAdminTest.php rename to Modules/ActiveDirectory/Tests/Feature/DirectorySyncAdminTest.php diff --git a/tests/Feature/DirectorySyncTest.php b/Modules/ActiveDirectory/Tests/Feature/DirectorySyncTest.php similarity index 100% rename from tests/Feature/DirectorySyncTest.php rename to Modules/ActiveDirectory/Tests/Feature/DirectorySyncTest.php diff --git a/[ b/[ new file mode 100644 index 0000000..e69de29 diff --git a/certs/dc01-ad-test.cer b/certs/dc01-ad-test.cer new file mode 100644 index 0000000000000000000000000000000000000000..abf462422eb7af69e4dd584438e2a33d92551092 GIT binary patch literal 805 zcmXqLVpcS0V&YuD%*4pVBp_>f>_+o*0AF)}h-iYU3arJt{GOQ~Ju!UlgEi>QN6yPhPf%*i)s6bzo> zrEa#O(6d!obJY46c^ysPy3?I(xdYaJ*^ zv=Y$X7kKZ8$?pZXy`oOen7z8g;YptO^-Aw`)g>D|;!m?yzB_j3*`;aCHsOyq8n#a_ z+I&2I#_tpL56+#O#`kkSTaduf++~f&mhs1JK6QO_?TRM~6Mq|)e!t4LfC zUcJ>Nxcq|q-MN|^B^Jn$0gQ2AWH2(sD&~o9E1Yaz(Y&VEQS0NuZ}HlN^V4!me5;>U zob1myvC}N{&+g>{wddz;|B{rDS|Go3+idIe|G)EZKJaj72KWBtnbiwJNL%jS>2(QzT-sP?;j?|nXi_eUGcB(T-)09Q|}*8{><+XX7X+AMDIm& z`TTeNCmxgMS5V$7eT)J+L}$_}>1?gbVRO{-3>fXH{^^87RGf|2TQ#!H(NM zSL}K8X7z`a$D6+Qtb5VS+1T{eXPHIS0)}^;ug^^Uvik>{eq@<|fU4e}Ws;AalHbnB nJ(VZ1zG;E tests/Feature + Modules/ActiveDirectory/Tests/Feature diff --git a/tests/Pest.php b/tests/Pest.php index 941e024..27e58c6 100755 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -16,7 +16,7 @@ use Tests\TestCase; pest()->extend(TestCase::class) ->use(RefreshDatabase::class) - ->in('Feature'); + ->in('Feature', '../Modules/ActiveDirectory/Tests/Feature'); /* |--------------------------------------------------------------------------