This commit is contained in:
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Services\DirectorySyncHistory;
|
||||
use App\Services\DirectorySyncRejected;
|
||||
use App\Services\SyncDirectoryUsers;
|
||||
use Illuminate\Console\Command;
|
||||
@@ -13,11 +14,12 @@ 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}';
|
||||
{--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): int
|
||||
public function handle(SyncDirectoryUsers $sync, DirectorySyncHistory $history): int
|
||||
{
|
||||
$started = hrtime(true);
|
||||
$context = [
|
||||
@@ -27,20 +29,29 @@ class SyncActiveDirectory extends Command
|
||||
];
|
||||
|
||||
$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);
|
||||
|
||||
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']);
|
||||
$result = $sync->run($context['dry_run'], $context['deactivate_missing'], $review);
|
||||
} 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;
|
||||
@@ -50,6 +61,7 @@ class SyncActiveDirectory extends Command
|
||||
'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.');
|
||||
|
||||
return self::FAILURE;
|
||||
@@ -61,6 +73,7 @@ class SyncActiveDirectory extends Command
|
||||
|
||||
$counts = $result['counts'];
|
||||
Log::info('Active Directory sync completed.', $context + $counts + ['duration_ms' => $duration()]);
|
||||
$record($review === null ? 'completed' : 'review_applied', $counts);
|
||||
$summary = [];
|
||||
foreach ($counts as $key => $value) {
|
||||
$summary[] = "$key=$value";
|
||||
|
||||
@@ -19,7 +19,9 @@ use Laravel\Fortify\TwoFactorAuthenticatable;
|
||||
/**
|
||||
* @property string|null $ad_guid
|
||||
* @property string|null $ad_source
|
||||
* @property string|null $ad_disabled_reason
|
||||
* @property CarbonImmutable|null $ad_disabled_at
|
||||
* @property CarbonImmutable|null $deleted_at
|
||||
* @property int $id
|
||||
* @property string $name
|
||||
* @property string $email
|
||||
@@ -49,6 +51,7 @@ class User extends Authenticatable implements PasskeyUser
|
||||
return [
|
||||
'email_verified_at' => 'datetime',
|
||||
'ad_disabled_at' => 'datetime',
|
||||
'deleted_at' => 'datetime',
|
||||
'password' => 'hashed',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use App\Models\User;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Facades\Date;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Illuminate\Validation\Rules\Password;
|
||||
|
||||
@@ -24,6 +26,9 @@ class AppServiceProvider extends ServiceProvider
|
||||
public function boot(): void
|
||||
{
|
||||
$this->configureDefaults();
|
||||
|
||||
Gate::define('manage-directory-sync', fn (User $user): bool => $user->ad_guid === null
|
||||
&& $user->id === config('ad-sync.admin-id'));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -12,18 +12,20 @@ class SyncDirectoryUsers
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* missing_fingerprint: string,
|
||||
* 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, ?string $reviewedMissing = null): array
|
||||
{
|
||||
$entries = $this->snapshot();
|
||||
$source = $this->source();
|
||||
|
||||
return DB::transaction(function () use ($entries, $source, $dryRun, $deactivateMissing): array {
|
||||
return DB::transaction(function () use ($entries, $source, $dryRun, $deactivateMissing, $reviewedMissing): array {
|
||||
$counts = ['created' => 0, 'updated' => 0, 'unchanged' => 0, 'deactivated' => 0, 'reactivated' => 0];
|
||||
$changes = [];
|
||||
$missingGuids = [];
|
||||
|
||||
foreach ($entries as $guid => $entry) {
|
||||
$user = User::where('ad_guid', $guid)->lockForUpdate()->first();
|
||||
@@ -44,13 +46,18 @@ class SyncDirectoryUsers
|
||||
|
||||
if (! $user->exists) {
|
||||
$action = 'created';
|
||||
$user->ad_disabled_at = $entry['enabled'] ? null : now();
|
||||
if (! $entry['enabled']) {
|
||||
$this->disable($user);
|
||||
}
|
||||
} elseif (! $entry['enabled'] && $user->ad_disabled_at === null) {
|
||||
$action = 'deactivated';
|
||||
$this->disable($user);
|
||||
} elseif ($entry['enabled'] && $user->ad_disabled_at !== null) {
|
||||
$action = 'reactivated';
|
||||
$user->ad_disabled_at = null;
|
||||
$user->forceFill(['ad_disabled_at' => null, 'deleted_at' => null, 'ad_disabled_reason' => null]);
|
||||
} elseif (! $entry['enabled'] && $user->ad_disabled_reason !== 'directory_disabled') {
|
||||
$action = 'updated';
|
||||
$user->ad_disabled_reason = 'directory_disabled';
|
||||
} elseif ($user->isDirty()) {
|
||||
$action = 'updated';
|
||||
} else {
|
||||
@@ -74,7 +81,8 @@ class SyncDirectoryUsers
|
||||
foreach ($missing as $user) {
|
||||
if (! isset($entries[$user->ad_guid])) {
|
||||
$counts['deactivated']++;
|
||||
$this->disable($user);
|
||||
$this->disable($user, 'missing_from_snapshot');
|
||||
$missingGuids[] = $user->ad_guid;
|
||||
$changes[] = [$user, 'deactivated', 'missing_from_snapshot'];
|
||||
}
|
||||
}
|
||||
@@ -84,9 +92,21 @@ class SyncDirectoryUsers
|
||||
throw new DirectorySyncRejected('Deactivation limit exceeded.');
|
||||
}
|
||||
|
||||
sort($missingGuids);
|
||||
$fingerprint = hash('sha256', $source.':'.implode(',', $missingGuids));
|
||||
if ($reviewedMissing !== null) {
|
||||
if ($missingGuids === [] || ! hash_equals($fingerprint, $reviewedMissing)) {
|
||||
throw new DirectorySyncRejected('Missing users changed since the preview. Review the list again.');
|
||||
}
|
||||
|
||||
$changes = array_values(array_filter($changes, fn (array $change): bool => $change[2] === 'missing_from_snapshot'));
|
||||
$counts = array_fill_keys(array_keys($counts), 0);
|
||||
$counts['deactivated'] = count($changes);
|
||||
}
|
||||
|
||||
$audit = [];
|
||||
foreach ($changes as [$user, $action, $reason]) {
|
||||
$fields = array_values(array_intersect(['name', 'email', 'email_verified_at', 'ad_disabled_at'], array_keys($user->getDirty())));
|
||||
$fields = array_values(array_intersect(['name', 'email', 'email_verified_at', 'ad_disabled_at', 'deleted_at', 'ad_disabled_reason'], array_keys($user->getDirty())));
|
||||
if (! $dryRun) {
|
||||
if (! $user->exists) {
|
||||
$user->password = Str::random(64);
|
||||
@@ -104,13 +124,14 @@ class SyncDirectoryUsers
|
||||
];
|
||||
}
|
||||
|
||||
return ['counts' => $counts, 'changes' => $audit];
|
||||
return ['counts' => $counts, 'changes' => $audit, 'missing_fingerprint' => $fingerprint];
|
||||
}, attempts: 3);
|
||||
}
|
||||
|
||||
private function disable(User $user): void
|
||||
private function disable(User $user, string $reason = 'directory_disabled'): void
|
||||
{
|
||||
$user->forceFill(['ad_disabled_at' => now(), 'remember_token' => null]);
|
||||
$disabledAt = now();
|
||||
$user->forceFill(['ad_disabled_at' => $disabledAt, 'deleted_at' => $disabledAt, 'ad_disabled_reason' => $reason, 'remember_token' => null]);
|
||||
}
|
||||
|
||||
private function source(): string
|
||||
|
||||
Reference in New Issue
Block a user