@@ -7,6 +7,7 @@ use App\Services\SyncDirectoryUsers;
|
|||||||
use Illuminate\Console\Command;
|
use Illuminate\Console\Command;
|
||||||
use Illuminate\Support\Facades\Cache;
|
use Illuminate\Support\Facades\Cache;
|
||||||
use Illuminate\Support\Facades\Log;
|
use Illuminate\Support\Facades\Log;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
use Throwable;
|
use Throwable;
|
||||||
|
|
||||||
class SyncActiveDirectory extends Command
|
class SyncActiveDirectory extends Command
|
||||||
@@ -18,34 +19,48 @@ class SyncActiveDirectory extends Command
|
|||||||
|
|
||||||
public function handle(SyncDirectoryUsers $sync): int
|
public function handle(SyncDirectoryUsers $sync): int
|
||||||
{
|
{
|
||||||
|
$started = hrtime(true);
|
||||||
$context = [
|
$context = [
|
||||||
|
'run_id' => (string) Str::uuid(),
|
||||||
'dry_run' => (bool) $this->option('dry-run'),
|
'dry_run' => (bool) $this->option('dry-run'),
|
||||||
'deactivate_missing' => (bool) $this->option('deactivate-missing'),
|
'deactivate_missing' => (bool) $this->option('deactivate-missing'),
|
||||||
];
|
];
|
||||||
|
|
||||||
|
$duration = fn (): int => (int) ((hrtime(true) - $started) / 1_000_000);
|
||||||
|
Log::info('Active Directory sync started.', $context);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$lock = Cache::lock('ad:sync', 3600);
|
$lock = Cache::lock('ad:sync', 3600);
|
||||||
if (! $lock->get()) {
|
if (! $lock->get()) {
|
||||||
throw new DirectorySyncRejected('A directory sync is already running.');
|
throw new DirectorySyncRejected('A directory sync is already running.');
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
$counts = $sync->run($context['dry_run'], $context['deactivate_missing']);
|
$result = $sync->run($context['dry_run'], $context['deactivate_missing']);
|
||||||
} finally {
|
} finally {
|
||||||
$lock->release();
|
$lock->release();
|
||||||
}
|
}
|
||||||
} catch (DirectorySyncRejected $exception) {
|
} catch (DirectorySyncRejected $exception) {
|
||||||
Log::warning('Active Directory sync rejected.', $context + ['reason' => $exception->getMessage()]);
|
Log::warning('Active Directory sync rejected.', $context + ['reason' => $exception->getMessage(), 'duration_ms' => $duration()]);
|
||||||
$this->error($exception->getMessage());
|
$this->error($exception->getMessage());
|
||||||
|
|
||||||
return self::FAILURE;
|
return self::FAILURE;
|
||||||
} catch (Throwable $exception) {
|
} catch (Throwable $exception) {
|
||||||
Log::error('Active Directory sync failed.', $context + ['exception_type' => $exception::class]);
|
Log::error('Active Directory sync failed.', $context + [
|
||||||
|
'exception_type' => $exception::class,
|
||||||
|
'exception_code' => $exception->getCode(),
|
||||||
|
'duration_ms' => $duration(),
|
||||||
|
]);
|
||||||
$this->error('Sync stopped due to a directory or database error.');
|
$this->error('Sync stopped due to a directory or database error.');
|
||||||
|
|
||||||
return self::FAILURE;
|
return self::FAILURE;
|
||||||
}
|
}
|
||||||
|
|
||||||
Log::info('Active Directory sync completed.', $context + $counts);
|
foreach ($result['changes'] as $change) {
|
||||||
|
Log::info('Active Directory sync user change.', $context + $change);
|
||||||
|
}
|
||||||
|
|
||||||
|
$counts = $result['counts'];
|
||||||
|
Log::info('Active Directory sync completed.', $context + $counts + ['duration_ms' => $duration()]);
|
||||||
$summary = [];
|
$summary = [];
|
||||||
foreach ($counts as $key => $value) {
|
foreach ($counts as $key => $value) {
|
||||||
$summary[] = "$key=$value";
|
$summary[] = "$key=$value";
|
||||||
|
|||||||
@@ -10,7 +10,12 @@ class SyncDirectoryUsers
|
|||||||
{
|
{
|
||||||
public function __construct(private ActiveDirectory $directory) {}
|
public function __construct(private ActiveDirectory $directory) {}
|
||||||
|
|
||||||
/** @return array{created: int, updated: int, unchanged: int, deactivated: int, reactivated: int} */
|
/**
|
||||||
|
* @return array{
|
||||||
|
* counts: array{created: int, updated: int, unchanged: int, deactivated: int, reactivated: int},
|
||||||
|
* changes: list<array{action: string, user_id: ?int, ad_guid: ?string, disabled: bool, changed_fields: list<string>, reason: ?string}>
|
||||||
|
* }
|
||||||
|
*/
|
||||||
public function run(bool $dryRun, bool $deactivateMissing): array
|
public function run(bool $dryRun, bool $deactivateMissing): array
|
||||||
{
|
{
|
||||||
$entries = $this->snapshot();
|
$entries = $this->snapshot();
|
||||||
@@ -38,22 +43,28 @@ class SyncDirectoryUsers
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (! $user->exists) {
|
if (! $user->exists) {
|
||||||
$counts['created']++;
|
$action = 'created';
|
||||||
$user->ad_disabled_at = $entry['enabled'] ? null : now();
|
$user->ad_disabled_at = $entry['enabled'] ? null : now();
|
||||||
} elseif (! $entry['enabled'] && $user->ad_disabled_at === null) {
|
} elseif (! $entry['enabled'] && $user->ad_disabled_at === null) {
|
||||||
$counts['deactivated']++;
|
$action = 'deactivated';
|
||||||
$this->disable($user);
|
$this->disable($user);
|
||||||
} elseif ($entry['enabled'] && $user->ad_disabled_at !== null) {
|
} elseif ($entry['enabled'] && $user->ad_disabled_at !== null) {
|
||||||
$counts['reactivated']++;
|
$action = 'reactivated';
|
||||||
$user->ad_disabled_at = null;
|
$user->ad_disabled_at = null;
|
||||||
} elseif ($user->isDirty()) {
|
} elseif ($user->isDirty()) {
|
||||||
$counts['updated']++;
|
$action = 'updated';
|
||||||
} else {
|
} else {
|
||||||
$counts['unchanged']++;
|
$action = 'unchanged';
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($user->isDirty()) {
|
$counts[$action]++;
|
||||||
$changes[] = $user;
|
if ($action !== 'unchanged') {
|
||||||
|
$reason = match (true) {
|
||||||
|
! $entry['enabled'] && in_array($action, ['created', 'deactivated'], true) => 'directory_disabled',
|
||||||
|
$action === 'reactivated' => 'directory_enabled',
|
||||||
|
default => null,
|
||||||
|
};
|
||||||
|
$changes[] = [$user, $action, $reason];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -64,7 +75,7 @@ class SyncDirectoryUsers
|
|||||||
if (! isset($entries[$user->ad_guid])) {
|
if (! isset($entries[$user->ad_guid])) {
|
||||||
$counts['deactivated']++;
|
$counts['deactivated']++;
|
||||||
$this->disable($user);
|
$this->disable($user);
|
||||||
$changes[] = $user;
|
$changes[] = [$user, 'deactivated', 'missing_from_snapshot'];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -73,16 +84,27 @@ class SyncDirectoryUsers
|
|||||||
throw new DirectorySyncRejected('Deactivation limit exceeded.');
|
throw new DirectorySyncRejected('Deactivation limit exceeded.');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$audit = [];
|
||||||
|
foreach ($changes as [$user, $action, $reason]) {
|
||||||
|
$fields = array_values(array_intersect(['name', 'email', 'email_verified_at', 'ad_disabled_at'], array_keys($user->getDirty())));
|
||||||
if (! $dryRun) {
|
if (! $dryRun) {
|
||||||
foreach ($changes as $user) {
|
|
||||||
if (! $user->exists) {
|
if (! $user->exists) {
|
||||||
$user->password = Str::random(64);
|
$user->password = Str::random(64);
|
||||||
}
|
}
|
||||||
$user->save();
|
$user->save();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$audit[] = [
|
||||||
|
'action' => $action,
|
||||||
|
'user_id' => $user->exists ? $user->id : null,
|
||||||
|
'ad_guid' => $user->ad_guid,
|
||||||
|
'disabled' => $user->ad_disabled_at !== null,
|
||||||
|
'changed_fields' => $fields,
|
||||||
|
'reason' => $reason,
|
||||||
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
return $counts;
|
return ['counts' => $counts, 'changes' => $audit];
|
||||||
}, attempts: 3);
|
}, attempts: 3);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ use App\Services\ActiveDirectory;
|
|||||||
use Illuminate\Support\Facades\Auth;
|
use Illuminate\Support\Facades\Auth;
|
||||||
use Illuminate\Support\Facades\Cache;
|
use Illuminate\Support\Facades\Cache;
|
||||||
use Illuminate\Support\Facades\Log;
|
use Illuminate\Support\Facades\Log;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
use Laravel\Passkeys\Passkey;
|
use Laravel\Passkeys\Passkey;
|
||||||
use Laravel\Passkeys\Passkeys;
|
use Laravel\Passkeys\Passkeys;
|
||||||
use LdapRecord\Connection;
|
use LdapRecord\Connection;
|
||||||
@@ -184,25 +185,56 @@ it('denies existing sessions and passkey logins while a managed user is disabled
|
|||||||
expect(Passkeys::allowsLogin(request(), $passkey))->toBeFalse();
|
expect(Passkeys::allowsLogin(request(), $passkey))->toBeFalse();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('logs counts and failure reasons without directory email addresses or exception messages', function () {
|
it('correlates run summaries and planned or committed changes without logging field values', function (bool $dryRun) {
|
||||||
$log = Log::spy();
|
$log = Log::spy();
|
||||||
directorySnapshot([directoryEntry()]);
|
directorySnapshot([directoryEntry()]);
|
||||||
$this->artisan('ad:sync --dry-run')->assertSuccessful();
|
$this->artisan($dryRun ? 'ad:sync --dry-run' : 'ad:sync')->assertSuccessful();
|
||||||
$log->shouldHaveReceived('info')->once()->with('Active Directory sync completed.', [
|
$id = $dryRun ? null : User::sole()->id;
|
||||||
'dry_run' => true,
|
$runId = null;
|
||||||
'deactivate_missing' => false,
|
$log->shouldHaveReceived('info')->withArgs(function ($message, $context) use (&$runId, $dryRun) {
|
||||||
'created' => 1,
|
if ($message !== 'Active Directory sync started.') {
|
||||||
'updated' => 0,
|
return false;
|
||||||
'unchanged' => 0,
|
}
|
||||||
'deactivated' => 0,
|
|
||||||
'reactivated' => 0,
|
|
||||||
]);
|
|
||||||
|
|
||||||
|
$runId = $context['run_id'];
|
||||||
|
|
||||||
|
return $context['dry_run'] === $dryRun && Str::isUuid($runId);
|
||||||
|
})->once();
|
||||||
|
$log->shouldHaveReceived('info')->withArgs(fn ($message, $context) => $message === 'Active Directory sync user change.'
|
||||||
|
&& $context === [
|
||||||
|
'run_id' => $runId,
|
||||||
|
'dry_run' => $dryRun,
|
||||||
|
'deactivate_missing' => false,
|
||||||
|
'action' => 'created',
|
||||||
|
'user_id' => $id,
|
||||||
|
'ad_guid' => directoryEntry()['guid'],
|
||||||
|
'disabled' => false,
|
||||||
|
'changed_fields' => ['name', 'email'],
|
||||||
|
'reason' => null,
|
||||||
|
]
|
||||||
|
)->once();
|
||||||
|
$log->shouldHaveReceived('info')->withArgs(fn ($message, $context) => $message === 'Active Directory sync completed.'
|
||||||
|
&& $context['run_id'] === $runId
|
||||||
|
&& $context['created'] === 1
|
||||||
|
&& $context['duration_ms'] >= 0
|
||||||
|
)->once();
|
||||||
|
})->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->mock(ActiveDirectory::class)->shouldReceive('users')->once()->andThrow(new RuntimeException('sensitive bind detail'));
|
||||||
$this->artisan('ad:sync')->assertFailed();
|
$this->artisan('ad:sync')->assertFailed();
|
||||||
$log->shouldHaveReceived('error')->once()->with('Active Directory sync failed.', [
|
$log->shouldHaveReceived('error')->once()->withArgs(fn ($message, $context) => $message === 'Active Directory sync failed.'
|
||||||
'dry_run' => false,
|
&& $context['exception_type'] === RuntimeException::class
|
||||||
'deactivate_missing' => false,
|
&& $context['exception_code'] === 0
|
||||||
'exception_type' => RuntimeException::class,
|
&& ! str_contains(json_encode($context), 'sensitive bind detail')
|
||||||
]);
|
);
|
||||||
|
|
||||||
|
directorySnapshot([]);
|
||||||
|
$this->artisan('ad:sync')->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()]);
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user