diff --git a/app/Console/Commands/SyncActiveDirectory.php b/Modules/ActiveDirectory/Console/Commands/SyncActiveDirectory.php similarity index 82% rename from app/Console/Commands/SyncActiveDirectory.php rename to Modules/ActiveDirectory/Console/Commands/SyncActiveDirectory.php index f54f726..1f8207d 100644 --- a/app/Console/Commands/SyncActiveDirectory.php +++ b/Modules/ActiveDirectory/Console/Commands/SyncActiveDirectory.php @@ -1,19 +1,21 @@ (string) Str::uuid(), 'dry_run' => (bool) $this->option('dry-run'), 'deactivate_missing' => (bool) $this->option('deactivate-missing'), + 'email' => (bool) $this->option('email'), + 'create_missing' => (bool) $this->option('create-missing'), ]; $duration = fn (): int => (int) ((hrtime(true) - $started) / 1_000_000); @@ -45,7 +49,7 @@ class SyncActiveDirectory extends Command throw new DirectorySyncRejected('A directory sync is already running.'); } try { - $result = $sync->run($context['dry_run'], $context['deactivate_missing'], $review); + $result = $sync->run($context['dry_run'], $context['deactivate_missing'], $review, $context['email'], $context['create_missing']); } finally { $lock->release(); } diff --git a/Modules/ActiveDirectory/Constants/AccountControl.php b/Modules/ActiveDirectory/Constants/AccountControl.php new file mode 100644 index 0000000..b16ad00 --- /dev/null +++ b/Modules/ActiveDirectory/Constants/AccountControl.php @@ -0,0 +1,62 @@ +getConstants() as $name => $flag) { + if (($value & $flag) !== 0) { + $result[] = $name; + } + } + + return $result; + } +} diff --git a/app/Http/Controllers/DirectorySyncController.php b/Modules/ActiveDirectory/Http/Controllers/DirectorySyncController.php similarity index 95% rename from app/Http/Controllers/DirectorySyncController.php rename to Modules/ActiveDirectory/Http/Controllers/DirectorySyncController.php index 5706f0b..f726e18 100644 --- a/app/Http/Controllers/DirectorySyncController.php +++ b/Modules/ActiveDirectory/Http/Controllers/DirectorySyncController.php @@ -1,10 +1,9 @@ mergeConfigFrom(__DIR__.'/../config/config.php', 'ad-sync'); + } + + public function boot(): void + { + $this->loadMigrationsFrom(__DIR__.'/../database/migrations'); + Gate::define('manage-directory-sync', fn (User $user): bool => $user->ad_guid === null + && $user->id === config('ad-sync.admin-id')); + + if ($this->app->runningInConsole()) { + $this->commands([SyncActiveDirectory::class]); + } + } +} diff --git a/app/Services/ActiveDirectory.php b/Modules/ActiveDirectory/Services/ActiveDirectory.php similarity index 91% rename from app/Services/ActiveDirectory.php rename to Modules/ActiveDirectory/Services/ActiveDirectory.php index 469a737..3205d64 100644 --- a/app/Services/ActiveDirectory.php +++ b/Modules/ActiveDirectory/Services/ActiveDirectory.php @@ -1,9 +1,10 @@ $user->getConvertedGuid(), 'email' => (string) $user->getFirstAttribute('mail'), 'name' => (string) ($user->getFirstAttribute('displayname') ?: $user->getFirstAttribute('cn')), - 'enabled' => ($flags & 2) === 0, + 'enabled' => ($flags & AccountControl::ACCOUNTDISABLE) === 0, + 'account_control' => $flags, + 'account_flags' => AccountControl::flags($flags), ]; } } diff --git a/app/Services/DirectorySyncHistory.php b/Modules/ActiveDirectory/Services/DirectorySyncHistory.php similarity index 95% rename from app/Services/DirectorySyncHistory.php rename to Modules/ActiveDirectory/Services/DirectorySyncHistory.php index f3dbd68..a639736 100644 --- a/app/Services/DirectorySyncHistory.php +++ b/Modules/ActiveDirectory/Services/DirectorySyncHistory.php @@ -1,6 +1,6 @@ , reason: ?string}> * } */ - public function run(bool $dryRun, bool $deactivateMissing, ?string $reviewedMissing = null): array + public function run(bool $dryRun, bool $deactivateMissing, ?string $reviewedMissing = null, bool $matchEmail = false, bool $createMissing = false): array { $entries = $this->snapshot(); $source = $this->source(); - return DB::transaction(function () use ($entries, $source, $dryRun, $deactivateMissing, $reviewedMissing): array { + return DB::transaction(function () use ($entries, $source, $dryRun, $deactivateMissing, $reviewedMissing, $matchEmail, $createMissing): array { $counts = ['created' => 0, 'updated' => 0, 'unchanged' => 0, 'deactivated' => 0, 'reactivated' => 0]; $changes = []; $missingGuids = []; @@ -33,6 +33,22 @@ class SyncDirectoryUsers throw new DirectorySyncRejected('GUID belongs to another directory scope.'); } + // Email matching never claims an unrelated directory-managed identity. + if (! $user && $matchEmail) { + $candidate = User::whereRaw('LOWER(email) = ?', [$entry['email']])->lockForUpdate()->get(); + if ($candidate->count() > 1) { + throw new DirectorySyncRejected('Ambiguous local email match.'); + } + $user = $candidate->first(); + if ($user && ($user->ad_guid !== null || ($user->ad_source !== null && $user->ad_source !== $source))) { + throw new DirectorySyncRejected('Email belongs to another directory identity.'); + } + } + + if (! $user && ! $createMissing) { + continue; + } + $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.'); @@ -115,6 +131,8 @@ class SyncDirectoryUsers } $audit[] = [ + 'account_control' => $entries[$user->ad_guid]['account_control'] ?? null, + 'account_flags' => $entries[$user->ad_guid]['account_flags'] ?? [], 'action' => $action, 'user_id' => $user->exists ? $user->id : null, 'ad_guid' => $user->ad_guid, @@ -162,7 +180,10 @@ class SyncDirectoryUsers } $emails[$email] = true; - $entries[$guid] = ['email' => $email, 'name' => $name, 'enabled' => $entry['enabled']]; + $entries[$guid] = ['email' => $email, 'name' => $name, 'enabled' => $entry['enabled'], + 'account_control' => $entry['account_control'] ?? null, + 'account_flags' => $entry['account_flags'] ?? [], + ]; } if ($entries === []) { diff --git a/Modules/ActiveDirectory/changelog.yaml b/Modules/ActiveDirectory/changelog.yaml new file mode 100755 index 0000000..3a0d100 --- /dev/null +++ b/Modules/ActiveDirectory/changelog.yaml @@ -0,0 +1,6 @@ +latest: 1.1.0 +releases: + - version: 1.1.0 + date: 2026-11-12 + changes: + Initial Build diff --git a/Modules/ActiveDirectory/composer.json b/Modules/ActiveDirectory/composer.json new file mode 100644 index 0000000..db2fd69 --- /dev/null +++ b/Modules/ActiveDirectory/composer.json @@ -0,0 +1,13 @@ +{ + "name": "mpba/active-directory-module", + "type": "laravel-module", + "require": { + "php": "^8.3", + "illuminate/support": "^13.0" + }, + "autoload": { + "psr-4": { + "Modules\\ActiveDirectory\\": "" + } + } +} diff --git a/config/ad-sync.php b/Modules/ActiveDirectory/config/config.php similarity index 100% rename from config/ad-sync.php rename to Modules/ActiveDirectory/config/config.php diff --git a/database/migrations/2026_11_11_000000_add_active_directory_identity_to_users.php b/Modules/ActiveDirectory/database/migrations/2026_11_11_000000_add_active_directory_identity_to_users.php similarity index 100% rename from database/migrations/2026_11_11_000000_add_active_directory_identity_to_users.php rename to Modules/ActiveDirectory/database/migrations/2026_11_11_000000_add_active_directory_identity_to_users.php diff --git a/Modules/ActiveDirectory/module.json b/Modules/ActiveDirectory/module.json new file mode 100644 index 0000000..f8bc47b --- /dev/null +++ b/Modules/ActiveDirectory/module.json @@ -0,0 +1,13 @@ +{ + "name": "ActiveDirectory", + "alias": "active-directory", + "version": "1.0.0", + "description": "Microsoft and Samba AD synchronization", + "priority": 0, + "providers": [ + "Modules\\ActiveDirectory\\Providers\\ActiveDirectoryServiceProvider" + ], + "aliases": {}, + "files": [], + "requires": [] +} diff --git a/Modules/Stylist/README.md b/Modules/Stylist/README.md deleted file mode 100755 index 810bf53..0000000 --- a/Modules/Stylist/README.md +++ /dev/null @@ -1,183 +0,0 @@ -# Stylist Module - -Tenant-aware styling module for Laravel 13 / nwidart Laravel Modules. - -## Theme layout - -Each theme is self-contained: - -```text -resources/themes/{theme}/ -├── theme.json -├── css/theme.css -└── views/ - ├── layouts/app.blade.php - ├── components/page-hero.blade.php - └── livewire/theme-preview.blade.php -``` - -The active tenant/company resolves to a theme key such as `default`, `mpba`, or `abbott`. - -## Rendering themed views - -Use the helper from controllers, Blade components, and Livewire components: - -```php -return stylist_view('layouts.app'); -``` - -It checks views in this order: - -```text -stylist-theme-{active-theme}::{view} -stylist-theme-{default-theme}::{view} -stylist::{view} -``` - -## Livewire - -Keep the PHP component class shared and put the template in each theme: - -```text -Livewire/ThemePreview.php -resources/themes/default/views/livewire/theme-preview.blade.php -resources/themes/mpba/views/livewire/theme-preview.blade.php -``` - -The component renders with: - -```php -return stylist_view('livewire.theme-preview', ['stats' => $this->stats]); -``` - -## Tenant assignment - -Add or use these fields on `companies`: - -```text -theme_key -brand_primary -brand_secondary -brand_accent -logo_path -favicon_path -theme_settings -``` - -Then assign: - -```php -$company->update(['theme_key' => 'mpba']); -``` - -## Publishing - -```bash -php artisan vendor:publish --tag=stylist-config -# or -php artisan stylist:publish-assets - -Themes are not published from or stored inside the module. Install them directly under `resources/themes`. -``` - -## Blade helpers - -```blade - - @themeVariables - @themeStylesheet - -``` - -## Self-contained application themes - -Application themes live in `resources/themes/{theme}` and own their runtime assets: - -```text -resources/themes/example/ -├── theme.json -├── css/theme.css -├── js/app.js -└── views/home.blade.php -``` - -Use `@themeStylesheet('css/theme.css')`, `@themeScript('js/app.js')`, or `theme_asset('images/example.svg')`. Assets are served from the selected theme directory by the `stylist.theme.asset` route; they do not need to be copied into `public/themes` or added to the global Vite inputs. - - -## Appearance and colour variants - -Themes may declare `appearances` (`light`, `dark`, `auto`) and named `accents` in `theme.json`. Include `@themeVariables` in the document `` before the theme stylesheet to prevent a flash of the wrong appearance. Add `@themeSwitcher` anywhere in a Blade layout for a ready-made runtime selector. User choices are stored in localStorage and are applied without rebuilding assets or reloading the page. - -## Theme manifest compatibility - -Stylist accepts versioned manifests while remaining compatible with older themes. New manifests should declare: - -```json -{ - "manifest_version": 1, - "key": "design-gallery", - "name": "Design Gallery" -} -``` - -`manifest_version` defaults to `1` when omitted. Unknown manifest fields are preserved and ignored by Stylist unless the current version explicitly uses them, allowing Theme Builder to add future metadata without preventing theme discovery. - -Appearance and accent features are optional. Stylist derives the internal capability flags only when the corresponding definitions exist: - -```json -{ - "appearances": ["light", "dark", "system"], - "accents": ["blue", "neutral"], - "default_appearance": "system", - "default_accent": "neutral" -} -``` - -Legacy themes with none of these fields continue to load unchanged and do not receive appearance or accent controls. - -Additional boolean capabilities may be declared explicitly: - -```json -{ - "capabilities": { - "marketplace": true - } -} -``` - -## Validate a theme - -Validate an installed theme key, unpacked theme directory, or ZIP package: - -```bash -php artisan stylist:validate design-gallery -php artisan stylist:validate resources/themes/design-gallery -php artisan stylist:validate ~/Downloads/design-gallery.zip -``` - -The command checks the manifest, required entry view, stylesheet, script, declared assets, preview and accessibility issues. It exits with a failure status when errors are found. - -## Theme inheritance and diagnostics - -Shared application views belong to the `common` theme. Child themes declare inheritance without copying those views: - -```json -{ - "name": "Dashboard", - "slug": "admin", - "extends": "common" -} -``` - -Resolution order is the active theme, each declared parent, the configured fallback, the common theme, module defaults, then Laravel's normal views. - -Use these maintenance commands: - -```bash -php artisan stylist:inspect -php artisan stylist:duplicates -php artisan stylist:doctor -php artisan stylist:create-theme customer --parent=common --name="Customer Portal" -``` - -`stylist:duplicates` fails when the same relative Blade task path exists in more than one theme. Add a child view only when it is a deliberate replacement; this application enforces one authoritative view per task. diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 842364f..ccff36d 100755 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -2,11 +2,9 @@ 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; @@ -27,8 +25,6 @@ class AppServiceProvider extends ServiceProvider { $this->configureDefaults(); - Gate::define('manage-directory-sync', fn (User $user): bool => $user->ad_guid === null - && $user->id === config('ad-sync.admin-id')); } /** diff --git a/composer.json b/composer.json index cc493bf..a8683f1 100755 --- a/composer.json +++ b/composer.json @@ -48,7 +48,8 @@ }, "autoload-dev": { "psr-4": { - "Tests\\": "tests/" + "Tests\\": "tests/", + "Modules\\ActiveDirectory\\Tests\\": "Modules/ActiveDirectory/tests/" } }, "repositories": [ diff --git a/modules_statuses.json b/modules_statuses.json index 573ab01..56dbe57 100755 --- a/modules_statuses.json +++ b/modules_statuses.json @@ -1,5 +1,4 @@ { "Stylist": true, - "M3": true, - "OTM": true -} \ No newline at end of file + "ActiveDirectory": true +} diff --git a/routes/web.php b/routes/web.php index c1a61ea..7642fa3 100755 --- a/routes/web.php +++ b/routes/web.php @@ -1,7 +1,7 @@ name('home'); diff --git a/tests/Feature/ActiveDirectoryModuleTest.php b/tests/Feature/ActiveDirectoryModuleTest.php new file mode 100644 index 0000000..c3ad5ad --- /dev/null +++ b/tests/Feature/ActiveDirectoryModuleTest.php @@ -0,0 +1,35 @@ +mock(ActiveDirectory::class)->shouldReceive('users')->once()->andReturn([ + ['guid' => '00112233-4455-6677-8899-aabbccddeeff', 'email' => 'missing@example.test', 'name' => 'Missing', 'enabled' => true], + ]); + $this->artisan('ad:sync --email')->assertSuccessful(); + expect(User::count())->toBe(0); +}); + +it('matches an existing Laravel user by email without creating a new user', function () { + $user = User::factory()->create(['email' => 'existing@example.test']); + $this->mock(ActiveDirectory::class)->shouldReceive('users')->once()->andReturn([ + ['guid' => '00112233-4455-6677-8899-aabbccddeeff', 'email' => 'existing@example.test', 'name' => 'Existing', 'enabled' => false], + ]); + $this->artisan('ad:sync --email')->assertSuccessful(); + expect(User::count())->toBe(1) + ->and($user->refresh()->ad_guid)->toBe('00112233-4455-6677-8899-aabbccddeeff') + ->and($user->ad_disabled_at)->not->toBeNull(); +}); + +it('decodes Microsoft and Samba user account control bitmasks', function () { + $flags = AccountControl::flags(AccountControl::NORMAL_ACCOUNT | AccountControl::ACCOUNTDISABLE | AccountControl::DONT_EXPIRE_PASSWORD); + expect($flags)->toContain('NORMAL_ACCOUNT', 'ACCOUNTDISABLE', 'DONT_EXPIRE_PASSWORD') + ->not->toContain('LOCKOUT'); +}); + +it('exposes the ActiveDirectory module and its sync command', function () { + expect(file_exists(base_path('Modules/ActiveDirectory/module.json')))->toBeTrue(); + $this->artisan('list')->assertSuccessful(); +}); diff --git a/tests/Feature/DirectorySyncAdminTest.php b/tests/Feature/DirectorySyncAdminTest.php index 4d3d05f..a54535d 100644 --- a/tests/Feature/DirectorySyncAdminTest.php +++ b/tests/Feature/DirectorySyncAdminTest.php @@ -1,8 +1,8 @@ admin = User::factory()->create(); @@ -26,10 +26,10 @@ it('restricts the directory status and actions to the configured local administr it('displays live success, counts, and failures and flags stale success', function () { adminDirectorySnapshot(); - $this->artisan('ad:sync')->assertSuccessful(); + $this->artisan('ad:sync --create-missing')->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->artisan('ad:sync --create-missing')->assertFailed(); $this->actingAs($this->admin)->get(route('admin.directory-sync'))->assertOk() ->assertSee('Scheduled every 10 minutes') ->assertSee('Directory snapshot is empty.'); @@ -40,7 +40,7 @@ it('displays live success, counts, and failures and flags stale success', functi it('previews missing users and applies only the reviewed deactivations', function () { adminDirectorySnapshot(); - $this->artisan('ad:sync')->assertSuccessful(); + $this->artisan('ad:sync --create-missing')->assertSuccessful(); adminDirectorySnapshot(includeSecond: false); $this->actingAs($this->admin)->post(route('admin.directory-sync.preview'))->assertRedirect(route('admin.directory-sync')); @@ -59,7 +59,7 @@ it('previews missing users and applies only the reviewed deactivations', functio it('rejects a review when the directory membership changes before apply', function () { adminDirectorySnapshot(); - $this->artisan('ad:sync')->assertSuccessful(); + $this->artisan('ad:sync --create-missing')->assertSuccessful(); adminDirectorySnapshot(includeSecond: false); $this->actingAs($this->admin)->post(route('admin.directory-sync.preview'))->assertRedirect(); @@ -72,7 +72,7 @@ it('rejects a review when the directory membership changes before apply', functi it('keeps the current review when an old browser tab submits its token', function () { adminDirectorySnapshot(); - $this->artisan('ad:sync')->assertSuccessful(); + $this->artisan('ad:sync --create-missing')->assertSuccessful(); $this->actingAs($this->admin); adminDirectorySnapshot(includeSecond: false); @@ -91,7 +91,7 @@ it('keeps the current review when an old browser tab submits its token', functio it('expires reviews and leaves all users unchanged', function () { adminDirectorySnapshot(); - $this->artisan('ad:sync')->assertSuccessful(); + $this->artisan('ad:sync --create-missing')->assertSuccessful(); adminDirectorySnapshot(includeSecond: false); $this->actingAs($this->admin)->post(route('admin.directory-sync.preview'))->assertRedirect(); $token = session('directory-sync-review.token'); @@ -105,7 +105,7 @@ it('expires reviews and leaves all users unchanged', function () { it('reports an empty candidate list and ignores successful dry runs for health', function () { adminDirectorySnapshot(); - $this->artisan('ad:sync --dry-run')->assertSuccessful(); + $this->artisan('ad:sync --create-missing --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(); diff --git a/tests/Feature/DirectorySyncTest.php b/tests/Feature/DirectorySyncTest.php index 25f9a15..ab9bfc8 100644 --- a/tests/Feature/DirectorySyncTest.php +++ b/tests/Feature/DirectorySyncTest.php @@ -1,7 +1,7 @@ artisan('ad:sync')->assertSuccessful(); + $this->artisan('ad:sync --create-missing')->assertSuccessful(); $user = User::sole(); expect($user->ad_guid)->toBe(directoryEntry()['guid']) ->and($user->email_verified_at)->toBeNull(); directorySnapshot([directoryEntry('renamed@example.test')]); - $this->artisan('ad:sync')->assertSuccessful(); + $this->artisan('ad:sync --create-missing')->assertSuccessful(); directorySnapshot([directoryEntry('renamed@example.test')]); - $this->artisan('ad:sync')->expectsOutputToContain('unchanged=1')->assertSuccessful(); + $this->artisan('ad:sync --create-missing')->expectsOutputToContain('unchanged=1')->assertSuccessful(); expect(User::sole()->id)->toBe($user->id) ->and($user->refresh()->email)->toBe('renamed@example.test'); @@ -42,14 +43,14 @@ it('imports by canonical GUID and retains the account when its email changes', f it('refuses to claim a local account by case-insensitive email and applies no partial changes', function () { $local = User::factory()->create(['email' => 'ADA@example.test']); directorySnapshot([directoryEntry('other@example.test', '11111111-1111-1111-1111-111111111111'), directoryEntry()]); - $this->artisan('ad:sync')->expectsOutputToContain('email collision')->assertFailed(); + $this->artisan('ad:sync --create-missing')->expectsOutputToContain('email collision')->assertFailed(); expect(User::sole()->id)->toBe($local->id) ->and($local->refresh()->ad_guid)->toBeNull(); }); it('rejects unsafe snapshots before writing', function (array $entries) { directorySnapshot($entries); - $this->artisan('ad:sync --deactivate-missing')->assertFailed(); + $this->artisan('ad:sync --create-missing --deactivate-missing')->assertFailed(); expect(User::count())->toBe(0); })->with([ 'empty' => fn () => [[]], @@ -60,27 +61,27 @@ it('rejects unsafe snapshots before writing', function (array $entries) { it('keeps dry runs read-only and blocks access for an explicitly disabled directory user', function () { directorySnapshot([directoryEntry()]); - $this->artisan('ad:sync --dry-run')->expectsOutputToContain('created=1')->assertSuccessful(); + $this->artisan('ad:sync --create-missing --dry-run')->expectsOutputToContain('created=1')->assertSuccessful(); expect(User::count())->toBe(0); directorySnapshot([directoryEntry()]); - $this->artisan('ad:sync')->assertSuccessful(); + $this->artisan('ad:sync --create-missing')->assertSuccessful(); $user = User::sole(); $user->update(['password' => 'example-password']); directorySnapshot([directoryEntry(enabled: false)]); - $this->artisan('ad:sync --dry-run')->expectsOutputToContain('deactivated=1')->assertSuccessful(); + $this->artisan('ad:sync --create-missing --dry-run')->expectsOutputToContain('deactivated=1')->assertSuccessful(); expect($user->refresh()->ad_disabled_at)->toBeNull() ->and($user->deleted_at)->toBeNull(); directorySnapshot([directoryEntry(enabled: false)]); - $this->artisan('ad:sync')->assertSuccessful(); + $this->artisan('ad:sync --create-missing')->assertSuccessful(); expect($user->refresh()->ad_disabled_at)->not->toBeNull() ->and($user->deleted_at)->toEqual($user->ad_disabled_at); $this->post(route('login.store'), ['email' => $user->email, 'password' => 'example-password']); $this->assertGuest(); directorySnapshot([directoryEntry()]); - $this->artisan('ad:sync')->assertSuccessful(); + $this->artisan('ad:sync --create-missing')->assertSuccessful(); expect($user->refresh()->ad_disabled_at)->toBeNull() ->and($user->deleted_at)->toBeNull(); }); @@ -90,18 +91,18 @@ it('requires explicit bounded missing-user deactivation and preserves local acco $third = directoryEntry('third@example.test', '22222222-2222-2222-2222-222222222222'); $local = User::factory()->create(); directorySnapshot([directoryEntry(), $second, $third]); - $this->artisan('ad:sync')->assertSuccessful(); + $this->artisan('ad:sync --create-missing')->assertSuccessful(); directorySnapshot([directoryEntry()]); - $this->artisan('ad:sync')->assertSuccessful(); + $this->artisan('ad:sync --create-missing')->assertSuccessful(); expect(User::whereNotNull('ad_disabled_at')->count())->toBe(0); config(['ad-sync.max-deactivations' => 1]); directorySnapshot([directoryEntry()]); - $this->artisan('ad:sync --deactivate-missing')->assertFailed(); + $this->artisan('ad:sync --create-missing --deactivate-missing')->assertFailed(); expect(User::whereNotNull('ad_disabled_at')->count())->toBe(0); directorySnapshot([directoryEntry(), $second]); - $this->artisan('ad:sync --deactivate-missing')->assertSuccessful(); + $this->artisan('ad:sync --create-missing --deactivate-missing')->assertSuccessful(); expect(User::whereNotNull('ad_disabled_at')->sole()->email)->toBe($third['email']) ->and(User::whereNotNull('deleted_at')->sole()->email)->toBe($third['email']) ->and($local->refresh()->ad_disabled_at)->toBeNull() @@ -110,7 +111,7 @@ it('requires explicit bounded missing-user deactivation and preserves local acco it('reports directory failures without changing users', function () { $this->mock(ActiveDirectory::class)->shouldReceive('users')->once()->andThrow(new RuntimeException('sensitive bind detail')); - $this->artisan('ad:sync --deactivate-missing')->expectsOutputToContain('directory or database error')->assertFailed(); + $this->artisan('ad:sync --create-missing --deactivate-missing')->expectsOutputToContain('directory or database error')->assertFailed(); expect(User::count())->toBe(0); }); @@ -119,7 +120,7 @@ it('rejects overlapping runs before reading the directory', function () { expect($lock->get())->toBeTrue(); try { $this->mock(ActiveDirectory::class)->shouldNotReceive('users'); - $this->artisan('ad:sync')->expectsOutputToContain('already running')->assertFailed(); + $this->artisan('ad:sync --create-missing')->expectsOutputToContain('already running')->assertFailed(); } finally { $lock->release(); } @@ -147,7 +148,12 @@ it('converts binary AD GUIDs and reads the account-disabled flag across pages', $ldap->shouldReceive('freeResult')->twice()->andReturnTrue(); useDirectoryConnection($ldap); - expect((new ActiveDirectory)->users())->toBe([directoryEntry(enabled: false)]); + expect((new ActiveDirectory)->users())->toBe([ + directoryEntry(enabled: false) + [ + 'account_control' => 514, + 'account_flags' => ['ACCOUNTDISABLE', 'NORMAL_ACCOUNT'], + ], + ]); }); it('discards the entire snapshot when the server returns a partial LDAP result', function () { @@ -158,7 +164,7 @@ it('discards the entire snapshot when the server returns a partial LDAP result', $ldap->shouldReceive('freeResult')->with('partial')->once()->andReturnTrue(); useDirectoryConnection($ldap); - $this->artisan('ad:sync --deactivate-missing')->expectsOutputToContain('directory or database error')->assertFailed(); + $this->artisan('ad:sync --create-missing --deactivate-missing')->expectsOutputToContain('directory or database error')->assertFailed(); expect(User::count())->toBe(0); }); @@ -176,13 +182,13 @@ function useDirectoryConnection(LdapInterface $ldap): void it('denies existing sessions and passkey logins while a managed user is disabled', function () { $this->withoutVite(); directorySnapshot([directoryEntry()]); - $this->artisan('ad:sync')->assertSuccessful(); + $this->artisan('ad:sync --create-missing')->assertSuccessful(); $user = User::sole(); $key = auth()->guard()->getName(); $this->withSession([$key => $user->id])->get(route('dashboard'))->assertOk(); directorySnapshot([directoryEntry(enabled: false)]); - $this->artisan('ad:sync')->assertSuccessful(); + $this->artisan('ad:sync --create-missing')->assertSuccessful(); Auth::forgetGuards(); $this->withSession([$key => $user->id])->get(route('dashboard'))->assertRedirect(route('login')); @@ -197,12 +203,14 @@ it('correlates run summaries and planned or committed changes without logging fi $events[$message] = $context; }); directorySnapshot([directoryEntry()]); - $this->artisan($dryRun ? 'ad:sync --dry-run' : 'ad:sync')->assertSuccessful(); + $this->artisan($dryRun ? 'ad:sync --create-missing --dry-run' : 'ad:sync --create-missing')->assertSuccessful(); $start = $events['Active Directory sync started.']; expect(Str::isUuid($start['run_id']))->toBeTrue() ->and($start['dry_run'])->toBe($dryRun) ->and($events['Active Directory sync user change.'])->toBe($start + [ + 'account_control' => null, + 'account_flags' => [], 'action' => 'created', 'user_id' => $dryRun ? null : User::sole()->id, 'ad_guid' => directoryEntry()['guid'], @@ -217,7 +225,7 @@ it('correlates run summaries and planned or committed changes without logging fi 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->artisan('ad:sync')->assertFailed(); + $this->artisan('ad:sync --create-missing')->assertFailed(); $log->shouldHaveReceived('error')->once()->withArgs(fn ($message, $context) => $message === 'Active Directory sync failed.' && $context['exception_type'] === RuntimeException::class && $context['exception_code'] === 0 @@ -225,7 +233,7 @@ it('logs sanitized failures and emits no user changes for a rejected run', funct ); directorySnapshot([]); - $this->artisan('ad:sync')->assertFailed(); + $this->artisan('ad:sync --create-missing')->assertFailed(); $log->shouldHaveReceived('warning')->once()->withArgs(fn ($message, $context) => $message === 'Active Directory sync rejected.' && $context['reason'] === 'Directory snapshot is empty.' && $context['duration_ms'] >= 0 @@ -235,14 +243,14 @@ it('logs sanitized failures and emits no user changes for a rejected run', funct it('will neither claim an existing GUID nor deactivate missing users from another directory scope', function () { directorySnapshot([directoryEntry()]); - $this->artisan('ad:sync')->assertSuccessful(); + $this->artisan('ad:sync --create-missing')->assertSuccessful(); $existing = User::sole(); config(['ad-sync.base-dn' => 'OU=Other,DC=ad,DC=test']); directorySnapshot([directoryEntry()]); - $this->artisan('ad:sync')->expectsOutputToContain('another directory scope')->assertFailed(); + $this->artisan('ad:sync --create-missing')->expectsOutputToContain('another directory scope')->assertFailed(); directorySnapshot([directoryEntry('other@example.test', '11111111-1111-1111-1111-111111111111')]); - $this->artisan('ad:sync --deactivate-missing')->assertSuccessful(); + $this->artisan('ad:sync --create-missing --deactivate-missing')->assertSuccessful(); expect($existing->refresh()->deleted_at)->toBeNull(); }); @@ -252,11 +260,11 @@ it('registers an overlap-protected ten-minute job only when scheduling is enable Illuminate\Support\Facades\Schedule::swap($schedule); require base_path('routes/console.php'); - $events = collect($schedule->events())->filter(fn ($event) => str_contains($event->command, 'ad:sync')); + $events = collect($schedule->events())->filter(fn ($event) => preg_match('/\\bad:sync(?:\\s|$)/', $event->command) === 1); expect($events)->toHaveCount($enabled ? 1 : 0); if ($enabled) { expect($events->sole()->expression)->toBe('*/10 * * * *') ->and($events->sole()->withoutOverlapping)->toBeTrue() - ->and($events->sole()->command)->not->toContain('--deactivate-missing'); + ->and($events->sole()->command)->toBe(Artisan::formatCommandString('ad:sync')); } })->with(['enabled' => [true], 'disabled' => [false]]);