updates for active directory now with docs

This commit is contained in:
Mark Gregory
2026-11-12 08:28:46 +00:00
parent 7166dd33f9
commit 1c57e92780
6 changed files with 225 additions and 9 deletions
@@ -6,9 +6,11 @@ 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
@@ -16,6 +18,8 @@ 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}';
@@ -38,6 +42,7 @@ class SyncActiveDirectory extends Command
$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'])) {
@@ -49,7 +54,15 @@ class SyncActiveDirectory extends Command
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']);
$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();
}
@@ -67,17 +80,31 @@ class SyncActiveDirectory extends Command
]);
$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";
@@ -86,4 +113,29 @@ class SyncActiveDirectory extends Command
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);
}
}
}
@@ -11,6 +11,11 @@ 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');
@@ -19,19 +24,20 @@ class ActiveDirectory
}
/** @return list<array{guid: ?string, email: string, name: string, enabled: bool}> */
public function users(): array
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): array {
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))', self::ATTRIBUTES, controls: [[
$result = $ldap->search($baseDn, '(&(objectCategory=person)(objectClass=user))', $attributes, controls: [[
'oid' => LDAP_CONTROL_PAGEDRESULTS,
'iscritical' => true,
'value' => ['size' => 500, 'cookie' => $cookie],
@@ -51,7 +57,18 @@ class ActiveDirectory
}
for ($index = 0; $index < $count; $index++) {
$entries[] = $this->entry((new User)->setRawAttributes($page[$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;
@@ -3,6 +3,7 @@
namespace Modules\ActiveDirectory\Services;
use App\Models\User;
use Closure;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
@@ -17,9 +18,11 @@ class SyncDirectoryUsers
* 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
public function run(bool $dryRun, bool $deactivateMissing, ?string $reviewedMissing = null, bool $matchEmail = false, bool $createMissing = false, ?Closure $inspectDirectory = null, bool $includeProperties = false): array
{
$entries = $this->snapshot();
$directoryUsers = $includeProperties ? $this->directory->users(true) : $this->directory->users();
$inspectDirectory?->__invoke($directoryUsers);
$entries = $this->snapshot($directoryUsers);
$source = $this->source();
return DB::transaction(function () use ($entries, $source, $dryRun, $deactivateMissing, $reviewedMissing, $matchEmail, $createMissing): array {
@@ -161,11 +164,11 @@ class SyncDirectoryUsers
}
/** @return array<string, array{email: string, name: string, enabled: bool}> */
private function snapshot(): array
private function snapshot(array $directoryUsers): array
{
$entries = [];
$emails = [];
foreach ($this->directory->users() as $entry) {
foreach ($directoryUsers as $entry) {
$guid = strtolower((string) $entry['guid']);
$email = strtolower(trim($entry['email']));
$name = trim($entry['name']);
+57
View File
@@ -0,0 +1,57 @@
# Microsoft Active Directory Domain Services
Use a Windows Server AD DS domain controller and a dedicated LDAP read account. The sync uses standard AD DS LDAP attributes and paged searches. This guide uses `corp.example.net` as an example domain.
## Configure LDAP over TLS
Use a domain controller hostname that matches its certificate. The Laravel host needs DNS resolution, TCP access to port 636, the PHP LDAP extension, and trust in the issuing CA. If the CA is private, place the public CA chain in a readable PEM file and point `LDAP_TLS_CA_CERT` to it. Keep the bind password in the deployment secret store or the local environment.
```dotenv
LDAP_CONNECTION=default
LDAP_HOST=dc01.corp.example.net
LDAP_PORT=636
LDAP_TLS=true
LDAP_STARTTLS=false
LDAP_SASL=false
LDAP_USERNAME="svc-laravel-sync@corp.example.net"
LDAP_PASSWORD="<bind password>"
LDAP_TLS_CA_CERT="/absolute/path/to/ad-ca-chain.pem"
LDAP_BASE_DN="DC=corp,DC=example,DC=net"
AD_SYNC_BASE_DN="OU=LaravelSync,DC=corp,DC=example,DC=net"
AD_SYNC_SCHEDULED=false
```
This example uses a simple bind inside TLS. Confirm the bind works under your organisation's LDAP policy before enabling scheduled sync. Reload Laravel's configuration cache using your normal deployment process after changing settings. Use `ldp.exe` to independently verify the LDAPS endpoint if needed. [Microsoft LDAPS certificate setup](https://learn.microsoft.com/windows-server/identity/ad-ds/configure-ldap-signing-certificates) · [LDAP signing](https://learn.microsoft.com/windows-server/identity/ad-ds/ldap-signing)
## Prepare the sync OU
Put test users in the configured OU. Give the bind account permission to read those users and their required attributes. Every returned user needs a unique, valid `mail` address and a usable `displayName` or `cn`. A missing or duplicate address rejects the whole snapshot. Laravel matches by `objectGUID` first. With `--email`, an existing eligible Laravel user can be linked by `mail`.
The LDAP filter combines `objectCategory=person` with `objectClass=user`. AD DS supplies the paged-results control used by the sync. The disabled state comes from the `ACCOUNTDISABLE` bit (`0x0002`) in `userAccountControl`. Use a dedicated OU on one domain controller's domain for the first run. The sync rejects incomplete pages and referrals. [User search filter](https://learn.microsoft.com/windows/win32/ad/querying-for-users) · [AD DS LDAP controls](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/3c5e87db-4728-4f29-b164-01dd7d7391ea) · [Account control flags](https://learn.microsoft.com/troubleshoot/windows-server/active-directory/useraccountcontrol-manipulate-account-properties)
## Verify against Windows AD
On a Windows admin workstation with the Active Directory PowerShell module, inspect the test account and its OU:
```powershell
Get-ADUser -Identity 'sync-test' -Server 'dc01.corp.example.net' -Properties mail,userAccountControl |
Select-Object DistinguishedName,ObjectGUID,mail,Enabled,userAccountControl
```
On the Laravel host, preview the same account:
```sh
php artisan ad:sync --email --dry-run -dd
php artisan ad:sync --email --dry-run -vvv --debug
```
Compare the GUID, mail, distinguished name, and account control with PowerShell. `-dd` (also `--dump-ad`) prints selected AD properties as returned by LDAP, with the binary GUID rendered as text. Optional fields appear only when returned by the server. `--debug` prints the account data Laravel uses for the sync.
For the live test, use a dedicated Laravel database and a dedicated AD test account:
1. Create a Laravel user with the same email and run `php artisan ad:sync --email`. Confirm the existing row gains the AD GUID. To test importing instead, use `--create-missing` explicitly after reviewing a dry run.
2. Disable the test account with `Disable-ADAccount -Identity 'sync-test' -Server 'dc01.corp.example.net'`. Run the email sync again. Confirm Laravel records `directory_disabled` and blocks login.
3. Run `Enable-ADAccount -Identity 'sync-test' -Server 'dc01.corp.example.net'`, then sync again. Confirm one reactivation and verify the Laravel login check.
4. For a scope larger than 500 users, compare the `-dd` dry-run result count with an AD query over the same OU to verify paging under the target controller's policies.
The application tests cover the sync logic and LDAP paging with fixtures. The live integration in this project was exercised against Samba AD. Run the steps above on the target Windows domain controller to confirm its certificate, bind policy, permissions, and directory data.
+61
View File
@@ -0,0 +1,61 @@
# Samba Active Directory and Laravel sync
The local Samba AD domain is `ad.test`. Docker runs it in the `samba-ad` container. Laravel connects to LDAPS at `127.0.0.1:1636` and searches `OU=LaravelSync,DC=ad,DC=test`.
Check that the container is running and confirm its published ports:
```sh
docker ps --filter name=samba-ad
docker port samba-ad
```
## Directory accounts
Set the AD `mail` attribute to the email address used in Laravel. Create a new test account directly in the sync OU with:
```sh
docker exec -it samba-ad samba-tool user create mark.gregory \
--given-name=Mark --surname=Gregory \
--mail-address=mark.gregory@absdev.net --userou='OU=LaravelSync'
```
For an existing account in the default Users container, move it into scope:
```sh
docker exec samba-ad samba-tool user move mark.gregory 'OU=LaravelSync,DC=ad,DC=test'
```
Check the account and toggle its enabled state:
```sh
docker exec samba-ad samba-tool user show mark.gregory --attributes=mail,userAccountControl
docker exec samba-ad samba-tool user disable mark.gregory
docker exec samba-ad samba-tool user enable mark.gregory
```
## Sync and diagnostics
Run these commands from the Laravel project directory:
```sh
php artisan ad:sync --email --dry-run -dd
php artisan ad:sync --email --dry-run -vvv --debug
php artisan ad:sync --email
```
- `-dd` and `--dump-ad` print AD properties for each returned account, including distinguished name, sign-in names, group memberships, account control, and timestamps when present.
- `--debug` prints each returned AD account, including names, email addresses, GUIDs, and account flags. Treat that output as directory data.
- `-v`, `-vv`, and `-vvv` increase sync detail.
- `--email` matches existing Laravel users by email. Add `--create-missing` explicitly to import absent users.
- `--dry-run` previews changes to user records. The sync still records audit history.
## Missing LDAPS CA certificate
If the configured CA file is missing, restore the public certificate from Samba and retry:
```sh
docker cp samba-ad:/var/lib/samba/private/tls/ca.pem storage/app/private/ldap-samba-ca.pem
php artisan ad:sync --email --dry-run -dd
```
The `LDAP_TLS_CA_CERT` setting must point to that local file.
+26
View File
@@ -268,3 +268,29 @@ it('registers an overlap-protected ten-minute job only when scheduling is enable
->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']);