updates for active directory
tests / ci (push) Canceled after 0s

This commit is contained in:
Mark Gregory
2026-11-11 16:19:50 +00:00
parent 65d58f19dc
commit c15221c98f
14 changed files with 592 additions and 2 deletions
@@ -0,0 +1,57 @@
<?php
namespace App\Console\Commands;
use App\Services\DirectorySyncRejected;
use App\Services\SyncDirectoryUsers;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Throwable;
class SyncActiveDirectory extends Command
{
protected $signature = 'ad:sync {--dry-run : Preview changes without saving users}
{--deactivate-missing : Disable managed users absent from the snapshot}';
protected $description = 'Synchronize local user records from Active Directory';
public function handle(SyncDirectoryUsers $sync): int
{
$context = [
'dry_run' => (bool) $this->option('dry-run'),
'deactivate_missing' => (bool) $this->option('deactivate-missing'),
];
try {
$lock = Cache::lock('ad:sync', 3600);
if (! $lock->get()) {
throw new DirectorySyncRejected('A directory sync is already running.');
}
try {
$counts = $sync->run($context['dry_run'], $context['deactivate_missing']);
} finally {
$lock->release();
}
} catch (DirectorySyncRejected $exception) {
Log::warning('Active Directory sync rejected.', $context + ['reason' => $exception->getMessage()]);
$this->error($exception->getMessage());
return self::FAILURE;
} catch (Throwable $exception) {
Log::error('Active Directory sync failed.', $context + ['exception_type' => $exception::class]);
$this->error('Sync stopped due to a directory or database error.');
return self::FAILURE;
}
Log::info('Active Directory sync completed.', $context + $counts);
$summary = [];
foreach ($counts as $key => $value) {
$summary[] = "$key=$value";
}
$this->info(($context['dry_run'] ? 'Dry run: ' : '').implode(' ', $summary));
return self::SUCCESS;
}
}
+5
View File
@@ -3,6 +3,7 @@
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Carbon\CarbonImmutable;
use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
@@ -16,6 +17,9 @@ use Laravel\Fortify\PasskeyAuthenticatable;
use Laravel\Fortify\TwoFactorAuthenticatable;
/**
* @property string|null $ad_guid
* @property string|null $ad_source
* @property CarbonImmutable|null $ad_disabled_at
* @property int $id
* @property string $name
* @property string $email
@@ -44,6 +48,7 @@ class User extends Authenticatable implements PasskeyUser
{
return [
'email_verified_at' => 'datetime',
'ad_disabled_at' => 'datetime',
'password' => 'hashed',
];
}
+20 -1
View File
@@ -4,12 +4,19 @@ namespace App\Providers;
use App\Actions\Fortify\CreateNewUser;
use App\Actions\Fortify\ResetUserPassword;
use App\Models\User;
use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Contracts\Hashing\Hasher;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
use Laravel\Fortify\Fortify;
use Laravel\Passkeys\Contracts\PasskeyUser;
use Laravel\Passkeys\Passkeys;
class FortifyServiceProvider extends ServiceProvider
{
@@ -18,7 +25,15 @@ class FortifyServiceProvider extends ServiceProvider
*/
public function register(): void
{
//
Auth::provider('active-users', function ($app, array $config): EloquentUserProvider {
$provider = new EloquentUserProvider($app->make(Hasher::class), $config['model']);
if (is_a($config['model'], User::class, true)) {
$provider->withQuery(fn (Builder $query) => $query->whereNull('ad_disabled_at'));
}
return $provider;
});
}
/**
@@ -26,6 +41,10 @@ class FortifyServiceProvider extends ServiceProvider
*/
public function boot(): void
{
Passkeys::authorizeLoginUsing(
fn (Request $request, PasskeyUser $user): bool => ! ($user instanceof User) || $user->ad_disabled_at === null,
);
$this->configureActions();
$this->configureViews();
$this->configureRateLimiting();
+83
View File
@@ -0,0 +1,83 @@
<?php
namespace App\Services;
use LdapRecord\LdapInterface;
use LdapRecord\Models\ActiveDirectory\User;
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 & 2) === 0,
];
}
}
+7
View File
@@ -0,0 +1,7 @@
<?php
namespace App\Services;
use RuntimeException;
class DirectorySyncRejected extends RuntimeException {}
+131
View File
@@ -0,0 +1,131 @@
<?php
namespace App\Services;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class SyncDirectoryUsers
{
public function __construct(private ActiveDirectory $directory) {}
/** @return array{created: int, updated: int, unchanged: int, deactivated: int, reactivated: int} */
public function run(bool $dryRun, bool $deactivateMissing): array
{
$entries = $this->snapshot();
$source = $this->source();
return DB::transaction(function () use ($entries, $source, $dryRun, $deactivateMissing): array {
$counts = ['created' => 0, 'updated' => 0, 'unchanged' => 0, 'deactivated' => 0, 'reactivated' => 0];
$changes = [];
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.');
}
$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) {
$counts['created']++;
$user->ad_disabled_at = $entry['enabled'] ? null : now();
} elseif (! $entry['enabled'] && $user->ad_disabled_at === null) {
$counts['deactivated']++;
$this->disable($user);
} elseif ($entry['enabled'] && $user->ad_disabled_at !== null) {
$counts['reactivated']++;
$user->ad_disabled_at = null;
} elseif ($user->isDirty()) {
$counts['updated']++;
} else {
$counts['unchanged']++;
}
if ($user->isDirty()) {
$changes[] = $user;
}
}
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);
$changes[] = $user;
}
}
}
if ($counts['deactivated'] > config('ad-sync.max-deactivations')) {
throw new DirectorySyncRejected('Deactivation limit exceeded.');
}
if (! $dryRun) {
foreach ($changes as $user) {
if (! $user->exists) {
$user->password = Str::random(64);
}
$user->save();
}
}
return $counts;
}, attempts: 3);
}
private function disable(User $user): void
{
$user->forceFill(['ad_disabled_at' => now(), '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']];
}
if ($entries === []) {
throw new DirectorySyncRejected('Directory snapshot is empty.');
}
return $entries;
}
}