From 90f8655595df3beca0c028f6a6f536d70838399b Mon Sep 17 00:00:00 2001 From: Mark Gregory Date: Wed, 11 Nov 2026 17:15:37 +0000 Subject: [PATCH] updates for active directory now with docs --- .../Controllers/DirectorySyncController.php | 95 ++++++++++++++ app/Services/DirectorySyncHistory.php | 32 +++++ ...6_11_11_000001_add_deleted_at_to_users.php | 26 ++++ ...00002_create_directory_sync_monitoring.php | 36 ++++++ docs/active-directory-sync.md | 32 +++++ .../views/admin/directory-sync.blade.php | 96 +++++++++++++++ tests/Feature/DirectorySyncAdminTest.php | 116 ++++++++++++++++++ 7 files changed, 433 insertions(+) create mode 100644 app/Http/Controllers/DirectorySyncController.php create mode 100644 app/Services/DirectorySyncHistory.php create mode 100644 database/migrations/2026_11_11_000001_add_deleted_at_to_users.php create mode 100644 database/migrations/2026_11_11_000002_create_directory_sync_monitoring.php create mode 100644 docs/active-directory-sync.md create mode 100644 resources/themes/backend/views/admin/directory-sync.blade.php create mode 100644 tests/Feature/DirectorySyncAdminTest.php diff --git a/app/Http/Controllers/DirectorySyncController.php b/app/Http/Controllers/DirectorySyncController.php new file mode 100644 index 0000000..592c761 --- /dev/null +++ b/app/Http/Controllers/DirectorySyncController.php @@ -0,0 +1,95 @@ +where('dry_run', false); + $success = (clone $liveRuns)->where('status', 'completed')->latest('finished_at')->first(); + $failure = (clone $liveRuns)->whereIn('status', ['failed', 'rejected'])->latest('finished_at')->first(); + $review = $request->session()->get('directory-sync-review'); + if ($review && $review['expires_at'] <= now()->timestamp) { + $request->session()->forget('directory-sync-review'); + $review = null; + } + + return view('admin.directory-sync', [ + 'scheduled' => config('ad-sync.scheduled'), + 'stale' => ! $success || Carbon::parse($success->finished_at)->lte(now()->subMinutes(30)), + 'success' => $success, + 'failure' => $failure, + 'counts' => $success ? json_decode($success->counts, true, flags: JSON_THROW_ON_ERROR) : [], + 'disabledUsers' => User::whereNotNull('ad_guid')->whereNotNull('ad_disabled_at') + ->orderByDesc('ad_disabled_at')->orderBy('id')->paginate(25), + 'review' => $review, + ]); + } + + public function preview(Request $request, SyncDirectoryUsers $sync): RedirectResponse + { + $request->session()->forget('directory-sync-review'); + + try { + $result = $sync->run(dryRun: true, deactivateMissing: true); + } catch (DirectorySyncRejected $exception) { + return to_route('admin.directory-sync')->with('sync_error', $exception->getMessage()); + } catch (Throwable $exception) { + Log::warning('Active Directory missing-user preview failed.', ['exception_type' => $exception::class]); + + return to_route('admin.directory-sync')->with('sync_error', 'The directory could not be checked.'); + } + + $missing = collect($result['changes'])->where('reason', 'missing_from_snapshot'); + $users = User::whereIn('id', $missing->pluck('user_id'))->orderBy('name')->get(['id', 'name', 'email', 'ad_guid']); + $request->session()->put('directory-sync-review', [ + 'token' => (string) Str::uuid(), + 'expires_at' => now()->addMinutes(10)->timestamp, + 'fingerprint' => $result['missing_fingerprint'], + 'users' => $users->map(fn (User $user): array => ['name' => $user->name, 'email' => $user->email])->all(), + ]); + Log::info('Active Directory missing-user preview completed.', [ + 'reviewer_id' => $request->user()?->getAuthIdentifier(), + 'candidate_count' => $missing->count(), + ]); + + return to_route('admin.directory-sync'); + } + + public function apply(Request $request): RedirectResponse + { + $review = $request->session()->pull('directory-sync-review'); + if (! $review || ! $review['users'] || $review['expires_at'] <= now()->timestamp + || $request->input('review_token') !== $review['token']) { + return to_route('admin.directory-sync')->with('sync_error', 'Run a fresh preview before applying changes.'); + } + + $status = Artisan::call('ad:sync', [ + '--deactivate-missing' => true, + '--reviewed-missing' => $review['fingerprint'], + ]); + Log::info('Active Directory missing-user review submitted.', [ + 'reviewer_id' => $request->user()?->getAuthIdentifier(), + 'candidate_count' => count($review['users']), + 'exit_code' => $status, + ]); + + return $status === 0 + ? to_route('admin.directory-sync')->with('sync_status', 'Reviewed accounts deactivated.') + : to_route('admin.directory-sync')->with('sync_error', 'The review could not be applied. Check the latest failure and run a new preview.'); + } +} diff --git a/app/Services/DirectorySyncHistory.php b/app/Services/DirectorySyncHistory.php new file mode 100644 index 0000000..f3dbd68 --- /dev/null +++ b/app/Services/DirectorySyncHistory.php @@ -0,0 +1,32 @@ +|null $counts */ + public function record(string $id, string $status, bool $dryRun, bool $deactivateMissing, int $duration, ?array $counts = null, ?string $failure = null): void + { + try { + DB::table('ad_sync_runs')->insert([ + 'id' => $id, + 'status' => $status, + 'dry_run' => $dryRun, + 'deactivate_missing' => $deactivateMissing, + 'duration_ms' => $duration, + 'counts' => $counts === null ? null : json_encode($counts, JSON_THROW_ON_ERROR), + 'failure' => $failure, + 'finished_at' => now(), + ]); + } catch (Throwable $exception) { + Log::warning('Active Directory sync history could not be saved.', [ + 'run_id' => $id, + 'exception_type' => $exception::class, + ]); + } + } +} diff --git a/database/migrations/2026_11_11_000001_add_deleted_at_to_users.php b/database/migrations/2026_11_11_000001_add_deleted_at_to_users.php new file mode 100644 index 0000000..4cfb538 --- /dev/null +++ b/database/migrations/2026_11_11_000001_add_deleted_at_to_users.php @@ -0,0 +1,26 @@ +softDeletes(); + }); + + DB::table('users')->whereNotNull('ad_guid')->whereNotNull('ad_disabled_at') + ->update(['deleted_at' => DB::raw('ad_disabled_at')]); + } + + public function down(): void + { + Schema::table('users', function (Blueprint $table): void { + $table->dropSoftDeletes(); + }); + } +}; diff --git a/database/migrations/2026_11_11_000002_create_directory_sync_monitoring.php b/database/migrations/2026_11_11_000002_create_directory_sync_monitoring.php new file mode 100644 index 0000000..a97002a --- /dev/null +++ b/database/migrations/2026_11_11_000002_create_directory_sync_monitoring.php @@ -0,0 +1,36 @@ +uuid('id')->primary(); + $table->string('status', 16); + $table->boolean('dry_run'); + $table->boolean('deactivate_missing'); + $table->json('counts')->nullable(); + $table->string('failure')->nullable(); + $table->unsignedInteger('duration_ms'); + $table->timestamp('finished_at')->index(); + $table->index(['dry_run', 'status', 'finished_at']); + }); + + Schema::table('users', function (Blueprint $table): void { + $table->string('ad_disabled_reason', 32)->nullable(); + }); + } + + public function down(): void + { + Schema::table('users', function (Blueprint $table): void { + $table->dropColumn('ad_disabled_reason'); + }); + + Schema::dropIfExists('ad_sync_runs'); + } +}; diff --git a/docs/active-directory-sync.md b/docs/active-directory-sync.md new file mode 100644 index 0000000..fd67c47 --- /dev/null +++ b/docs/active-directory-sync.md @@ -0,0 +1,32 @@ +# Active Directory sync + +Laravel reads Samba Active Directory over verified LDAPS and matches accounts by `objectGUID`. The search base is `OU=LaravelSync,DC=ad,DC=test`. Users in that OU need a valid, unique `mail` address. The local Docker container publishes LDAPS on `127.0.0.1:1636`; `LDAP_TLS_CA_CERT` points to the local Samba CA. Keep the bind credentials in `.env`. + +Run the migrations on the configured database before enabling the page. Set `AD_SYNC_ADMIN_ID` to the ID of an existing local Laravel account. The default value of zero grants nobody access. The authorised account sees **Directory sync** in the sidebar. The page displays the latest live success and failure, counts, and disabled users. It flags the sync as stale after 30 minutes without a successful full live run. + +With `AD_SYNC_SCHEDULED=true`, Laravel schedules `ad:sync` every ten minutes. The local macOS cron entry invokes `artisan schedule:run` every minute while the Mac is awake. Check the schedule with `php artisan schedule:list` and the audit trail in `storage/logs/laravel.log`. + +A disabled AD account sets both `ad_disabled_at` and `deleted_at`. Re-enabling it clears both on the next successful sync. For missing users, use **Preview missing users** on the admin page, review the list, then select **Deactivate reviewed users**. The preview expires after ten minutes. The app checks a fresh LDAP snapshot before applying and rejects the review if the candidate list changed. Scheduled runs only deactivate accounts explicitly disabled in AD. The deactivation cap still applies to reviewed changes. + +## Local walkthrough + +Run these commands from the Laravel project. Use a fresh username and mail address for each walkthrough. + +```bash +docker exec samba-ad samba-tool user create sync-demo --random-password \ + --userou='OU=LaravelSync' --mail-address=sync-demo@ad.test \ + --given-name=Sync --surname=Demo +php artisan ad:sync --dry-run +php artisan ad:sync + +docker exec samba-ad samba-tool user disable sync-demo +php artisan ad:sync +docker exec samba-ad samba-tool user enable sync-demo +php artisan ad:sync +``` + +Inspect the directory entry with `docker exec samba-ad samba-tool user show sync-demo`. To inspect its schema, run `docker exec samba-ad samba-tool schema objectclass show user` or `docker exec samba-ad samba-tool schema attribute show userAccountControl`. + +- [LDAP protocol (RFC 4511)](https://www.rfc-editor.org/info/rfc4511/) covers bind and search. +- [LDAP directory schema (RFC 4512)](https://www.rfc-editor.org/info/rfc4512/) and [LDAP filters (RFC 4515)](https://www.rfc-editor.org/info/rfc4515/) describe the underlying directory model and query syntax. +- [AD account-control flags](https://learn.microsoft.com/en-us/troubleshoot/windows-server/active-directory/useraccountcontrol-manipulate-account-properties) documents the disabled bit. [AD object GUID](https://learn.microsoft.com/en-us/windows/win32/adschema/a-objectguid) documents the sync identity. diff --git a/resources/themes/backend/views/admin/directory-sync.blade.php b/resources/themes/backend/views/admin/directory-sync.blade.php new file mode 100644 index 0000000..455d66d --- /dev/null +++ b/resources/themes/backend/views/admin/directory-sync.blade.php @@ -0,0 +1,96 @@ + +
+
+ Directory sync + + @if (! $scheduled) + Schedule disabled + @elseif ($stale) + Stale · No successful sync in the last 30 minutes + @else + Scheduled every 10 minutes + @endif + +
+ + @if (session('sync_error')) + + @endif + @if (session('sync_status')) +

{{ session('sync_status') }}

+ @endif + +
+ Latest successful sync + {{ $success?->finished_at ?? 'No successful sync recorded yet' }} + @if ($success) +
+ @foreach (['created' => 'Created', 'updated' => 'Updated', 'unchanged' => 'Unchanged', 'deactivated' => 'Disabled', 'reactivated' => 'Re-enabled'] as $key => $label) +
+
{{ $label }}
+
{{ $counts[$key] }}
+
+ @endforeach +
+ @endif + @if ($failure) +
+ Latest failure + {{ $failure->finished_at }} · {{ $failure->failure }} +
+ @endif +
+ +
+ Review missing users + Check which active Laravel accounts are missing from the directory. The preview expires after 10 minutes. +
+ @csrf + Preview missing users +
+ @if ($review) + @if ($review['users']) +
    + @foreach ($review['users'] as $user) +
  • {{ $user['name'] }} · {{ $user['email'] }}
  • + @endforeach +
+
+ @csrf + + Deactivate reviewed users +
+ @else + No missing users found. + @endif + @endif +
+ +
+ Disabled directory users +
+ + + + + + @forelse ($disabledUsers as $user) + + + + + + @empty + + @endforelse + +
UserReasonDisabled at
{{ $user->name }}
{{ $user->email }}
{{ match ($user->ad_disabled_reason) { + 'directory_disabled' => 'Disabled in Active Directory', + 'missing_from_snapshot' => 'Missing from the directory', + default => 'Reason unavailable', + } }}{{ $user->ad_disabled_at }}
No disabled directory users.
+
+ {{ $disabledUsers->links() }} +
+
+
diff --git a/tests/Feature/DirectorySyncAdminTest.php b/tests/Feature/DirectorySyncAdminTest.php new file mode 100644 index 0000000..4d3d05f --- /dev/null +++ b/tests/Feature/DirectorySyncAdminTest.php @@ -0,0 +1,116 @@ +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' => 'first@example.test', 'name' => $renameFirst ? 'Renamed' : 'First', 'enabled' => true]; + $second = ['guid' => '11111111-2222-3333-4444-555555555555', 'email' => 'second@example.test', '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')->assertSuccessful(); + $this->assertDatabaseHas('ad_sync_runs', ['status' => 'completed', 'dry_run' => false]); + $this->mock(ActiveDirectory::class)->shouldReceive('users')->once()->andReturn([]); + $this->artisan('ad:sync')->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')->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('second@example.test'); + $this->assertDatabaseHas('users', ['email' => 'second@example.test', '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' => 'first@example.test', 'name' => 'First']); + $this->assertDatabaseHas('users', ['email' => 'second@example.test', 'ad_disabled_reason' => 'missing_from_snapshot']); + expect(DB::table('users')->where('email', 'second@example.test')->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')->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' => 'second@example.test', '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')->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' => 'second@example.test', 'deleted_at' => null]); +}); + +it('expires reviews and leaves all users unchanged', function () { + adminDirectorySnapshot(); + $this->artisan('ad:sync')->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' => 'second@example.test', 'deleted_at' => null]); +}); + +it('reports an empty candidate list and ignores successful dry runs for health', function () { + adminDirectorySnapshot(); + $this->artisan('ad:sync --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); +});