updates for active directory now with docs, noiw with microsoft AD sync

This commit is contained in:
Mark Gregory
2026-11-12 12:36:38 +00:00
parent 77b92027df
commit 9404c7a210
18 changed files with 884 additions and 3 deletions
@@ -0,0 +1,141 @@
<?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\ActiveDirectory;
use Modules\ActiveDirectory\Services\DirectorySyncHistory;
use Modules\ActiveDirectory\Services\DirectorySyncRejected;
use Modules\ActiveDirectory\Services\SyncDirectoryUsers;
use Symfony\Component\Console\Output\OutputInterface;
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}
{--debug : Print the LDAP account attributes returned by the sync search}
{--d|dump-ad : Print AD account properties returned by LDAP (-dd)}
{--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);
$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);
}
}
}
@@ -0,0 +1,144 @@
<?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\ActiveDirectory;
use Modules\ActiveDirectory\Services\DirectorySyncHistory;
use Modules\ActiveDirectory\Services\DirectorySyncRejected;
use Modules\ActiveDirectory\Services\SyncDirectoryUsers;
use Symfony\Component\Console\Output\OutputInterface;
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}
{--debug : Print the LDAP account attributes returned by the sync search}
{--d|dump-ad : Print AD account properties returned by LDAP (-dd)}
{--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);
$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);
}
}
}
@@ -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;
@@ -0,0 +1,103 @@
<?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'];
private const DIAGNOSTIC_ATTRIBUTES = [
'distinguishedname', 'samaccountname', 'userprincipalname', 'givenname', 'sn',
'objectclass', 'memberof', 'whencreated', 'whenchanged', 'pwdlastset', 'lastlogontimestamp',
];
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(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),
];
}
}
@@ -0,0 +1,109 @@
<?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'];
private const DIAGNOSTIC_ATTRIBUTES = [
'distinguishedname', 'samaccountname', 'userprincipalname', 'givenname', 'sn',
'objectclass', 'memberof', 'whencreated', 'whenchanged', 'pwdlastset', 'lastlogontimestamp',
];
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(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),
];
}
}
@@ -0,0 +1,111 @@
<?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'];
private const DIAGNOSTIC_ATTRIBUTES = [
'distinguishedname', 'samaccountname', 'userprincipalname', 'givenname', 'sn',
'objectclass', 'memberof', 'whencreated', 'whenchanged', 'pwdlastset', 'lastlogontimestamp',
];
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(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),
];
}
}
@@ -0,0 +1,111 @@
<?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'];
private const DIAGNOSTIC_ATTRIBUTES = [
'distinguishedname', 'samaccountname', 'userprincipalname', 'givenname', 'sn',
'objectclass', 'memberof', 'whencreated', 'whenchanged', 'pwdlastset', 'lastlogontimestamp',
];
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(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),
];
}
}
@@ -0,0 +1,35 @@
<?php
use App\Models\User;
use Modules\ActiveDirectory\Constants\AccountControl;
use Modules\ActiveDirectory\Services\ActiveDirectory;
it('does not import missing directory accounts by default', function () {
$this->mock(ActiveDirectory::class)->shouldReceive('users')->once()->andReturn([
['guid' => '00112233-4455-6677-8899-aabbccddeeff', 'email' => '[email protected]', 'name' => 'Missing', 'enabled' => true],
]);
$this->artisan('ad:sync --email')->assertSuccessful();
expect(User::count())->toBe(0);
});
it('matches an existing Laravel user by email without creating a new user', function () {
$user = User::factory()->create(['email' => '[email protected]']);
$this->mock(ActiveDirectory::class)->shouldReceive('users')->once()->andReturn([
['guid' => '00112233-4455-6677-8899-aabbccddeeff', 'email' => '[email protected]', 'name' => 'Existing', 'enabled' => false],
]);
$this->artisan('ad:sync --email')->assertSuccessful();
expect(User::count())->toBe(1)
->and($user->refresh()->ad_guid)->toBe('00112233-4455-6677-8899-aabbccddeeff')
->and($user->ad_disabled_at)->not->toBeNull();
});
it('decodes Microsoft and Samba user account control bitmasks', function () {
$flags = AccountControl::flags(AccountControl::NORMAL_ACCOUNT | AccountControl::ACCOUNTDISABLE | AccountControl::DONT_EXPIRE_PASSWORD);
expect($flags)->toContain('NORMAL_ACCOUNT', 'ACCOUNTDISABLE', 'DONT_EXPIRE_PASSWORD')
->not->toContain('LOCKOUT');
});
it('exposes the ActiveDirectory module and its sync command', function () {
expect(file_exists(base_path('Modules/ActiveDirectory/module.json')))->toBeTrue();
$this->artisan('list')->assertSuccessful();
});
@@ -0,0 +1,116 @@
<?php
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Modules\ActiveDirectory\Services\ActiveDirectory;
beforeEach(function () {
$this->admin = User::factory()->create();
config(['ad-sync.admin-id' => $this->admin->id, 'ad-sync.scheduled' => true]);
});
function adminDirectorySnapshot(bool $includeSecond = true, bool $renameFirst = false): void
{
$first = ['guid' => '00112233-4455-6677-8899-aabbccddeeff', 'email' => '[email protected]', 'name' => $renameFirst ? 'Renamed' : 'First', 'enabled' => true];
$second = ['guid' => '11111111-2222-3333-4444-555555555555', 'email' => '[email protected]', 'name' => 'Second', 'enabled' => true];
test()->mock(ActiveDirectory::class)->shouldReceive('users')->once()->andReturn($includeSecond ? [$first, $second] : [$first]);
}
it('restricts the directory status and actions to the configured local administrator', function () {
$this->get(route('admin.directory-sync'))->assertRedirect(route('login'));
$this->actingAs(User::factory()->create())->get(route('admin.directory-sync'))->assertForbidden();
$this->post(route('admin.directory-sync.preview'))->assertForbidden();
$this->post(route('admin.directory-sync.apply'))->assertForbidden();
$this->actingAs($this->admin)->get(route('admin.directory-sync'))->assertOk()->assertSee('Stale');
});
it('displays live success, counts, and failures and flags stale success', function () {
adminDirectorySnapshot();
$this->artisan('ad:sync --create-missing')->assertSuccessful();
$this->assertDatabaseHas('ad_sync_runs', ['status' => 'completed', 'dry_run' => false]);
$this->mock(ActiveDirectory::class)->shouldReceive('users')->once()->andReturn([]);
$this->artisan('ad:sync --create-missing')->assertFailed();
$this->actingAs($this->admin)->get(route('admin.directory-sync'))->assertOk()
->assertSee('Scheduled every 10 minutes')
->assertSee('Directory snapshot is empty.');
$this->travel(31)->minutes();
$this->get(route('admin.directory-sync'))->assertSee('Stale');
});
it('previews missing users and applies only the reviewed deactivations', function () {
adminDirectorySnapshot();
$this->artisan('ad:sync --create-missing')->assertSuccessful();
adminDirectorySnapshot(includeSecond: false);
$this->actingAs($this->admin)->post(route('admin.directory-sync.preview'))->assertRedirect(route('admin.directory-sync'));
$this->get(route('admin.directory-sync'))->assertSee('[email protected]');
$this->assertDatabaseHas('users', ['email' => '[email protected]', 'ad_disabled_at' => null]);
adminDirectorySnapshot(includeSecond: false, renameFirst: true);
$this->post(route('admin.directory-sync.apply'), ['review_token' => session('directory-sync-review.token')])
->assertSessionHas('sync_status');
$this->assertDatabaseHas('users', ['email' => '[email protected]', 'name' => 'First']);
$this->assertDatabaseHas('users', ['email' => '[email protected]', 'ad_disabled_reason' => 'missing_from_snapshot']);
expect(DB::table('users')->where('email', '[email protected]')->value('deleted_at'))->not->toBeNull();
$this->get(route('admin.directory-sync'))->assertSee('Missing from the directory');
$this->post(route('admin.directory-sync.apply'))->assertSessionHas('sync_error');
});
it('rejects a review when the directory membership changes before apply', function () {
adminDirectorySnapshot();
$this->artisan('ad:sync --create-missing')->assertSuccessful();
adminDirectorySnapshot(includeSecond: false);
$this->actingAs($this->admin)->post(route('admin.directory-sync.preview'))->assertRedirect();
adminDirectorySnapshot();
$this->post(route('admin.directory-sync.apply'), ['review_token' => session('directory-sync-review.token')])
->assertSessionHas('sync_error');
$this->assertDatabaseHas('users', ['email' => '[email protected]', 'deleted_at' => null]);
$this->assertDatabaseHas('ad_sync_runs', ['status' => 'rejected', 'failure' => 'Missing users changed since the preview. Review the list again.']);
});
it('keeps the current review when an old browser tab submits its token', function () {
adminDirectorySnapshot();
$this->artisan('ad:sync --create-missing')->assertSuccessful();
$this->actingAs($this->admin);
adminDirectorySnapshot(includeSecond: false);
$this->post(route('admin.directory-sync.preview'))->assertRedirect();
$oldToken = session('directory-sync-review.token');
adminDirectorySnapshot(includeSecond: false);
$this->post(route('admin.directory-sync.preview'))->assertRedirect();
$currentToken = session('directory-sync-review.token');
$this->post(route('admin.directory-sync.apply'), ['review_token' => $oldToken])
->assertSessionHas('sync_error')
->assertSessionHas('directory-sync-review.token', $currentToken);
$this->assertDatabaseHas('users', ['email' => '[email protected]', 'deleted_at' => null]);
});
it('expires reviews and leaves all users unchanged', function () {
adminDirectorySnapshot();
$this->artisan('ad:sync --create-missing')->assertSuccessful();
adminDirectorySnapshot(includeSecond: false);
$this->actingAs($this->admin)->post(route('admin.directory-sync.preview'))->assertRedirect();
$token = session('directory-sync-review.token');
$this->travel(10)->minutes();
$this->post(route('admin.directory-sync.apply'), ['review_token' => $token])
->assertSessionHas('sync_error')
->assertSessionMissing('directory-sync-review');
$this->assertDatabaseHas('users', ['email' => '[email protected]', 'deleted_at' => null]);
});
it('reports an empty candidate list and ignores successful dry runs for health', function () {
adminDirectorySnapshot();
$this->artisan('ad:sync --create-missing --dry-run')->assertSuccessful();
$this->assertDatabaseHas('ad_sync_runs', ['status' => 'completed', 'dry_run' => true]);
adminDirectorySnapshot();
$this->actingAs($this->admin)->post(route('admin.directory-sync.preview'))->assertRedirect();
$this->get(route('admin.directory-sync'))->assertSee('No missing users found.')->assertSee('Stale');
$this->post(route('admin.directory-sync.apply'), ['review_token' => session('directory-sync-review.token')])
->assertSessionHas('sync_error');
expect(User::count())->toBe(1);
});
@@ -0,0 +1,296 @@
<?php
use App\Models\User;
use Illuminate\Console\Application as Artisan;
use Illuminate\Console\Scheduling\Schedule;
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;
use LdapRecord\LdapInterface;
use LdapRecord\LdapResultResponse;
use Modules\ActiveDirectory\Services\ActiveDirectory;
function directoryEntry(string $email = '[email protected]', string $guid = '00112233-4455-6677-8899-aabbccddeeff', bool $enabled = true): array
{
return ['guid' => $guid, 'email' => $email, 'name' => 'Ada Lovelace', 'enabled' => $enabled];
}
function directorySnapshot(array $entries): void
{
test()->mock(ActiveDirectory::class)->shouldReceive('users')->once()->andReturn($entries);
}
it('imports by canonical GUID and retains the account when its email changes', function () {
directorySnapshot([directoryEntry(guid: strtoupper(directoryEntry()['guid']))]);
$this->artisan('ad:sync --create-missing')->assertSuccessful();
$user = User::sole();
expect($user->ad_guid)->toBe(directoryEntry()['guid'])
->and($user->email_verified_at)->toBeNull();
directorySnapshot([directoryEntry('[email protected]')]);
$this->artisan('ad:sync --create-missing')->assertSuccessful();
directorySnapshot([directoryEntry('[email protected]')]);
$this->artisan('ad:sync --create-missing')->expectsOutputToContain('unchanged=1')->assertSuccessful();
expect(User::sole()->id)->toBe($user->id)
->and($user->refresh()->email)->toBe('[email protected]');
});
it('refuses to claim a local account by case-insensitive email and applies no partial changes', function () {
$local = User::factory()->create(['email' => '[email protected]']);
directorySnapshot([directoryEntry('[email protected]', '11111111-1111-1111-1111-111111111111'), directoryEntry()]);
$this->artisan('ad:sync --create-missing')->expectsOutputToContain('email collision')->assertFailed();
expect(User::sole()->id)->toBe($local->id)
->and($local->refresh()->ad_guid)->toBeNull();
});
it('rejects unsafe snapshots before writing', function (array $entries) {
directorySnapshot($entries);
$this->artisan('ad:sync --create-missing --deactivate-missing')->assertFailed();
expect(User::count())->toBe(0);
})->with([
'empty' => fn () => [[]],
'bad GUID' => fn () => [[directoryEntry(guid: 'invalid')]],
'duplicate GUID' => fn () => [[directoryEntry(), directoryEntry('[email protected]')]],
'duplicate email' => fn () => [[directoryEntry(), directoryEntry('[email protected]', '11111111-1111-1111-1111-111111111111')]],
]);
it('keeps dry runs read-only and blocks access for an explicitly disabled directory user', function () {
directorySnapshot([directoryEntry()]);
$this->artisan('ad:sync --create-missing --dry-run')->expectsOutputToContain('created=1')->assertSuccessful();
expect(User::count())->toBe(0);
directorySnapshot([directoryEntry()]);
$this->artisan('ad:sync --create-missing')->assertSuccessful();
$user = User::sole();
$user->update(['password' => 'example-password']);
directorySnapshot([directoryEntry(enabled: false)]);
$this->artisan('ad:sync --create-missing --dry-run')->expectsOutputToContain('deactivated=1')->assertSuccessful();
expect($user->refresh()->ad_disabled_at)->toBeNull()
->and($user->deleted_at)->toBeNull();
directorySnapshot([directoryEntry(enabled: false)]);
$this->artisan('ad:sync --create-missing')->assertSuccessful();
expect($user->refresh()->ad_disabled_at)->not->toBeNull()
->and($user->deleted_at)->toEqual($user->ad_disabled_at);
$this->post(route('login.store'), ['email' => $user->email, 'password' => 'example-password']);
$this->assertGuest();
directorySnapshot([directoryEntry()]);
$this->artisan('ad:sync --create-missing')->assertSuccessful();
expect($user->refresh()->ad_disabled_at)->toBeNull()
->and($user->deleted_at)->toBeNull();
});
it('requires explicit bounded missing-user deactivation and preserves local accounts', function () {
$second = directoryEntry('[email protected]', '11111111-1111-1111-1111-111111111111');
$third = directoryEntry('[email protected]', '22222222-2222-2222-2222-222222222222');
$local = User::factory()->create();
directorySnapshot([directoryEntry(), $second, $third]);
$this->artisan('ad:sync --create-missing')->assertSuccessful();
directorySnapshot([directoryEntry()]);
$this->artisan('ad:sync --create-missing')->assertSuccessful();
expect(User::whereNotNull('ad_disabled_at')->count())->toBe(0);
config(['ad-sync.max-deactivations' => 1]);
directorySnapshot([directoryEntry()]);
$this->artisan('ad:sync --create-missing --deactivate-missing')->assertFailed();
expect(User::whereNotNull('ad_disabled_at')->count())->toBe(0);
directorySnapshot([directoryEntry(), $second]);
$this->artisan('ad:sync --create-missing --deactivate-missing')->assertSuccessful();
expect(User::whereNotNull('ad_disabled_at')->sole()->email)->toBe($third['email'])
->and(User::whereNotNull('deleted_at')->sole()->email)->toBe($third['email'])
->and($local->refresh()->ad_disabled_at)->toBeNull()
->and($local->deleted_at)->toBeNull();
});
it('reports directory failures without changing users', function () {
$this->mock(ActiveDirectory::class)->shouldReceive('users')->once()->andThrow(new RuntimeException('sensitive bind detail'));
$this->artisan('ad:sync --create-missing --deactivate-missing')->expectsOutputToContain('directory or database error')->assertFailed();
expect(User::count())->toBe(0);
});
it('rejects overlapping runs before reading the directory', function () {
$lock = Cache::lock('ad:sync', 60);
expect($lock->get())->toBeTrue();
try {
$this->mock(ActiveDirectory::class)->shouldNotReceive('users');
$this->artisan('ad:sync --create-missing')->expectsOutputToContain('already running')->assertFailed();
} finally {
$lock->release();
}
});
it('converts binary AD GUIDs and reads the account-disabled flag across pages', function () {
$binaryGuid = hex2bin('33221100554477668899aabbccddeeff');
$entry = [
'objectguid' => [$binaryGuid],
'mail' => ['[email protected]'],
'cn' => ['Ada Lovelace'],
'useraccountcontrol' => ['514'],
];
$ldap = Mockery::mock(LdapInterface::class);
$ldap->shouldReceive('search')->once()->withArgs(fn (...$args) => ($args[7][0]['value']['cookie'] ?? null) === '')->andReturn('first');
$ldap->shouldReceive('search')->once()->withArgs(fn (...$args) => ($args[7][0]['value']['cookie'] ?? null) === 'next')->andReturn('second');
$ldap->shouldReceive('parseResult')->with('first')->andReturn(new LdapResultResponse(controls: [
LDAP_CONTROL_PAGEDRESULTS => ['value' => ['cookie' => 'next']],
]));
$ldap->shouldReceive('parseResult')->with('second')->andReturn(new LdapResultResponse(controls: [
LDAP_CONTROL_PAGEDRESULTS => ['value' => ['cookie' => '']],
]));
$ldap->shouldReceive('getEntries')->with('first')->andReturn([0 => $entry, 'count' => 1]);
$ldap->shouldReceive('getEntries')->with('second')->andReturn(['count' => 0]);
$ldap->shouldReceive('freeResult')->twice()->andReturnTrue();
useDirectoryConnection($ldap);
expect((new ActiveDirectory)->users())->toBe([
directoryEntry(enabled: false) + [
'account_control' => 514,
'account_flags' => ['ACCOUNTDISABLE', 'NORMAL_ACCOUNT'],
],
]);
});
it('discards the entire snapshot when the server returns a partial LDAP result', function () {
$ldap = Mockery::mock(LdapInterface::class);
$ldap->shouldReceive('search')->once()->andReturn('partial');
$ldap->shouldReceive('parseResult')->with('partial')->andReturn(new LdapResultResponse(errorCode: 4));
$ldap->shouldReceive('getEntries')->never();
$ldap->shouldReceive('freeResult')->with('partial')->once()->andReturnTrue();
useDirectoryConnection($ldap);
$this->artisan('ad:sync --create-missing --deactivate-missing')->expectsOutputToContain('directory or database error')->assertFailed();
expect(User::count())->toBe(0);
});
function useDirectoryConnection(LdapInterface $ldap): void
{
$connection = Mockery::mock(Connection::class)->makePartial();
$connection->shouldReceive('run')->once()->andReturnUsing(fn (Closure $operation) => $operation($ldap));
$manager = LdapRecord\Models\ActiveDirectory\User::getConnectionContainer()->getConnectionManager();
$name = $manager->getDefaultConnectionName();
$previous = $manager->getConnection($name);
$manager->addConnection($connection, $name);
test()->beforeApplicationDestroyed(fn () => $manager->addConnection($previous, $name));
}
it('denies existing sessions and passkey logins while a managed user is disabled', function () {
$this->withoutVite();
directorySnapshot([directoryEntry()]);
$this->artisan('ad:sync --create-missing')->assertSuccessful();
$user = User::sole();
$key = auth()->guard()->getName();
$this->withSession([$key => $user->id])->get(route('dashboard'))->assertOk();
directorySnapshot([directoryEntry(enabled: false)]);
$this->artisan('ad:sync --create-missing')->assertSuccessful();
Auth::forgetGuards();
$this->withSession([$key => $user->id])->get(route('dashboard'))->assertRedirect(route('login'));
$passkey = new Passkey;
$passkey->setRelation('user', $user->refresh());
expect(Passkeys::allowsLogin(request(), $passkey))->toBeFalse();
});
it('correlates run summaries and planned or committed changes without logging field values', function (bool $dryRun) {
$events = [];
Log::shouldReceive('info')->times(3)->andReturnUsing(function ($message, $context) use (&$events): void {
$events[$message] = $context;
});
directorySnapshot([directoryEntry()]);
$this->artisan($dryRun ? 'ad:sync --create-missing --dry-run' : 'ad:sync --create-missing')->assertSuccessful();
$start = $events['Active Directory sync started.'];
expect(Str::isUuid($start['run_id']))->toBeTrue()
->and($start['dry_run'])->toBe($dryRun)
->and($events['Active Directory sync user change.'])->toBe($start + [
'account_control' => null,
'account_flags' => [],
'action' => 'created',
'user_id' => $dryRun ? null : User::sole()->id,
'ad_guid' => directoryEntry()['guid'],
'disabled' => false,
'changed_fields' => ['name', 'email', 'email_verified_at'],
'reason' => null,
])
->and($events['Active Directory sync completed.']['run_id'])->toBe($start['run_id'])
->and($events['Active Directory sync completed.']['created'])->toBe(1);
})->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 --create-missing')->assertFailed();
$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 --create-missing')->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()]);
});
it('will neither claim an existing GUID nor deactivate missing users from another directory scope', function () {
directorySnapshot([directoryEntry()]);
$this->artisan('ad:sync --create-missing')->assertSuccessful();
$existing = User::sole();
config(['ad-sync.base-dn' => 'OU=Other,DC=ad,DC=test']);
directorySnapshot([directoryEntry()]);
$this->artisan('ad:sync --create-missing')->expectsOutputToContain('another directory scope')->assertFailed();
directorySnapshot([directoryEntry('[email protected]', '11111111-1111-1111-1111-111111111111')]);
$this->artisan('ad:sync --create-missing --deactivate-missing')->assertSuccessful();
expect($existing->refresh()->deleted_at)->toBeNull();
});
it('registers an overlap-protected ten-minute job only when scheduling is enabled', function (bool $enabled) {
config(['ad-sync.scheduled' => $enabled]);
$schedule = new Schedule;
Illuminate\Support\Facades\Schedule::swap($schedule);
require base_path('routes/console.php');
$events = collect($schedule->events())->filter(fn ($event) => preg_match('/\\bad:sync(?:\\s|$)/', $event->command) === 1);
expect($events)->toHaveCount($enabled ? 1 : 0);
if ($enabled) {
expect($events->sole()->expression)->toBe('*/10 * * * *')
->and($events->sole()->withoutOverlapping)->toBeTrue()
->and($events->sole()->command)->toBe(Artisan::formatCommandString('ad:sync'));
}
})->with(['enabled' => [true], 'disabled' => [false]]);
it('prints directory details only with the debug option', function () {
$entry = directoryEntry() + ['account_control' => 512, 'account_flags' => ['NORMAL_ACCOUNT']];
directorySnapshot([$entry]);
$this->artisan('ad:sync --email --dry-run')
->doesntExpectOutputToContain('AD account')
->assertSuccessful();
directorySnapshot([$entry]);
$this->artisan('ad:sync --email --dry-run --debug')
->expectsOutput('AD account '.json_encode($entry, JSON_THROW_ON_ERROR))
->expectsOutputToContain('created=0')
->assertSuccessful();
expect(User::count())->toBe(0);
});
it('prints LDAP properties separately from normalized account details', function (string $flag) {
$properties = ['samaccountname' => ['ada'], 'userprincipalname' => ['[email protected]']];
$this->mock(ActiveDirectory::class)->shouldReceive('users')->with(true)->once()
->andReturn([directoryEntry() + ['ad_properties' => $properties]]);
$this->artisan('ad:sync --email --dry-run '.$flag)
->expectsOutput('AD properties '.json_encode($properties, JSON_THROW_ON_ERROR))
->doesntExpectOutputToContain('AD account')
->assertSuccessful();
})->with(['-dd', '--dump-ad']);