From c15221c98fc4292dc8b34c2b7854ae56636a5a2f Mon Sep 17 00:00:00 2001 From: Mark Gregory Date: Wed, 11 Nov 2026 16:19:50 +0000 Subject: [PATCH] updates for active directory --- .env.example | 5 + ad_test | Bin 0 -> 135168 bytes app/Console/Commands/SyncActiveDirectory.php | 57 +++++ app/Models/User.php | 5 + app/Providers/FortifyServiceProvider.php | 21 +- app/Services/ActiveDirectory.php | 83 +++++++ app/Services/DirectorySyncRejected.php | 7 + app/Services/SyncDirectoryUsers.php | 131 +++++++++++ config/ad-sync.php | 7 + config/auth.php | 2 +- ...add_active_directory_identity_to_users.php | 26 +++ routes/console.php | 5 + tests/Feature/DirectorySyncTest.php | 208 ++++++++++++++++++ tests/Feature/StylistIntegrationTest.php | 37 ++++ 14 files changed, 592 insertions(+), 2 deletions(-) create mode 100644 ad_test create mode 100644 app/Console/Commands/SyncActiveDirectory.php create mode 100644 app/Services/ActiveDirectory.php create mode 100644 app/Services/DirectorySyncRejected.php create mode 100644 app/Services/SyncDirectoryUsers.php create mode 100644 config/ad-sync.php create mode 100644 database/migrations/2026_11_11_000000_add_active_directory_identity_to_users.php create mode 100644 tests/Feature/DirectorySyncTest.php diff --git a/.env.example b/.env.example index 40bb13b..a1746f0 100755 --- a/.env.example +++ b/.env.example @@ -63,3 +63,8 @@ AWS_BUCKET= AWS_USE_PATH_STYLE_ENDPOINT=false VITE_APP_NAME="${APP_NAME}" + +# Limit synchronization to an OU containing users with mail addresses. +# AD_SYNC_BASE_DN="OU=People,DC=ad,DC=test" +AD_SYNC_SCHEDULED=false +AD_SYNC_MAX_DEACTIVATIONS=5 diff --git a/ad_test b/ad_test new file mode 100644 index 0000000000000000000000000000000000000000..921612f03504faf7265afbf2a204bb6dd3c444e4 GIT binary patch literal 135168 zcmeI5%X1vZeaCkQUP)eBM3kwKDP%OJbLQ4`PK~f~Z2UM!@V7CDb zFgvrHnFX+nRVskuA&0nJ8A+~28cE|)t?->2w1e5v%% z8@{36QsTMOt zf5`v3Z#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E`f<10ZxM>dHl2j (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; + } +} diff --git a/app/Models/User.php b/app/Models/User.php index 047225e..393a649 100755 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -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', ]; } diff --git a/app/Providers/FortifyServiceProvider.php b/app/Providers/FortifyServiceProvider.php index 72f4195..3358275 100755 --- a/app/Providers/FortifyServiceProvider.php +++ b/app/Providers/FortifyServiceProvider.php @@ -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(); diff --git a/app/Services/ActiveDirectory.php b/app/Services/ActiveDirectory.php new file mode 100644 index 0000000..469a737 --- /dev/null +++ b/app/Services/ActiveDirectory.php @@ -0,0 +1,83 @@ + */ + 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, + ]; + } +} diff --git a/app/Services/DirectorySyncRejected.php b/app/Services/DirectorySyncRejected.php new file mode 100644 index 0000000..368e3bd --- /dev/null +++ b/app/Services/DirectorySyncRejected.php @@ -0,0 +1,7 @@ +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 */ + 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; + } +} diff --git a/config/ad-sync.php b/config/ad-sync.php new file mode 100644 index 0000000..a4c5a57 --- /dev/null +++ b/config/ad-sync.php @@ -0,0 +1,7 @@ + env('AD_SYNC_BASE_DN'), + 'scheduled' => env('AD_SYNC_SCHEDULED', false), + 'max-deactivations' => (int) env('AD_SYNC_MAX_DEACTIVATIONS', 5), +]; diff --git a/config/auth.php b/config/auth.php index d7568ff..6fd1b0f 100755 --- a/config/auth.php +++ b/config/auth.php @@ -63,7 +63,7 @@ return [ 'providers' => [ 'users' => [ - 'driver' => 'eloquent', + 'driver' => 'active-users', 'model' => env('AUTH_MODEL', User::class), ], diff --git a/database/migrations/2026_11_11_000000_add_active_directory_identity_to_users.php b/database/migrations/2026_11_11_000000_add_active_directory_identity_to_users.php new file mode 100644 index 0000000..9e78ca6 --- /dev/null +++ b/database/migrations/2026_11_11_000000_add_active_directory_identity_to_users.php @@ -0,0 +1,26 @@ +uuid('ad_guid')->nullable()->unique(); + $table->string('ad_source', 64)->nullable()->index(); + $table->timestamp('ad_disabled_at')->nullable(); + }); + } + + public function down(): void + { + Schema::table('users', function (Blueprint $table): void { + $table->dropUnique(['ad_guid']); + $table->dropIndex(['ad_source']); + $table->dropColumn(['ad_guid', 'ad_source', 'ad_disabled_at']); + }); + } +}; diff --git a/routes/console.php b/routes/console.php index 3c9adf1..a863ca0 100755 --- a/routes/console.php +++ b/routes/console.php @@ -2,7 +2,12 @@ use Illuminate\Foundation\Inspiring; use Illuminate\Support\Facades\Artisan; +use Illuminate\Support\Facades\Schedule; Artisan::command('inspire', function () { $this->comment(Inspiring::quote()); })->purpose('Display an inspiring quote'); + +if (config('ad-sync.scheduled')) { + Schedule::command('ad:sync')->dailyAt('02:00')->withoutOverlapping(); +} diff --git a/tests/Feature/DirectorySyncTest.php b/tests/Feature/DirectorySyncTest.php new file mode 100644 index 0000000..b408ddf --- /dev/null +++ b/tests/Feature/DirectorySyncTest.php @@ -0,0 +1,208 @@ + $guid, 'email' => $email, 'name' => 'Ada Lovelace', 'enabled' => $enabled]; +} + +function directorySnapshot(array $entries): void +{ + test()->mock(ActiveDirectory::class)->shouldReceive('users')->once()->andReturn($entries); +} + +it('imports by canonical GUID and retains the account when its email changes', function () { + directorySnapshot([directoryEntry(guid: strtoupper(directoryEntry()['guid']))]); + $this->artisan('ad:sync')->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(); + directorySnapshot([directoryEntry('renamed@example.test')]); + $this->artisan('ad:sync')->expectsOutputToContain('unchanged=1')->assertSuccessful(); + + expect(User::sole()->id)->toBe($user->id) + ->and($user->refresh()->email)->toBe('renamed@example.test'); +}); + +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(); + 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(); + expect(User::count())->toBe(0); +})->with([ + 'empty' => fn () => [[]], + 'bad GUID' => fn () => [[directoryEntry(guid: 'invalid')]], + 'duplicate GUID' => fn () => [[directoryEntry(), directoryEntry('other@example.test')]], + 'duplicate email' => fn () => [[directoryEntry(), directoryEntry('ADA@example.test', '11111111-1111-1111-1111-111111111111')]], +]); + +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(); + expect(User::count())->toBe(0); + + directorySnapshot([directoryEntry()]); + $this->artisan('ad:sync')->assertSuccessful(); + $user = User::sole(); + $user->update(['password' => 'example-password']); + directorySnapshot([directoryEntry(enabled: false)]); + $this->artisan('ad:sync --dry-run')->expectsOutputToContain('deactivated=1')->assertSuccessful(); + expect($user->refresh()->ad_disabled_at)->toBeNull(); + + directorySnapshot([directoryEntry(enabled: false)]); + $this->artisan('ad:sync')->assertSuccessful(); + expect($user->refresh()->ad_disabled_at)->not->toBeNull(); + $this->post(route('login.store'), ['email' => $user->email, 'password' => 'example-password']); + $this->assertGuest(); + + directorySnapshot([directoryEntry()]); + $this->artisan('ad:sync')->assertSuccessful(); + expect($user->refresh()->ad_disabled_at)->toBeNull(); +}); + +it('requires explicit bounded missing-user deactivation and preserves local accounts', function () { + $second = directoryEntry('second@example.test', '11111111-1111-1111-1111-111111111111'); + $third = directoryEntry('third@example.test', '22222222-2222-2222-2222-222222222222'); + $local = User::factory()->create(); + directorySnapshot([directoryEntry(), $second, $third]); + $this->artisan('ad:sync')->assertSuccessful(); + directorySnapshot([directoryEntry()]); + $this->artisan('ad:sync')->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(); + expect(User::whereNotNull('ad_disabled_at')->count())->toBe(0); + + directorySnapshot([directoryEntry(), $second]); + $this->artisan('ad:sync --deactivate-missing')->assertSuccessful(); + expect(User::whereNotNull('ad_disabled_at')->sole()->email)->toBe($third['email']) + ->and($local->refresh()->ad_disabled_at)->toBeNull(); +}); + +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(); + expect(User::count())->toBe(0); +}); + +it('rejects overlapping runs before reading the directory', function () { + $lock = Cache::lock('ad:sync', 60); + expect($lock->get())->toBeTrue(); + try { + $this->mock(ActiveDirectory::class)->shouldNotReceive('users'); + $this->artisan('ad:sync')->expectsOutputToContain('already running')->assertFailed(); + } finally { + $lock->release(); + } +}); + +it('converts binary AD GUIDs and reads the account-disabled flag across pages', function () { + $binaryGuid = hex2bin('33221100554477668899aabbccddeeff'); + $entry = [ + 'objectguid' => [$binaryGuid], + 'mail' => ['ada@example.test'], + 'cn' => ['Ada Lovelace'], + 'useraccountcontrol' => ['514'], + ]; + $ldap = Mockery::mock(LdapInterface::class); + $ldap->shouldReceive('search')->once()->withArgs(fn (...$args) => ($args[7][0]['value']['cookie'] ?? null) === '')->andReturn('first'); + $ldap->shouldReceive('search')->once()->withArgs(fn (...$args) => ($args[7][0]['value']['cookie'] ?? null) === 'next')->andReturn('second'); + $ldap->shouldReceive('parseResult')->with('first')->andReturn(new LdapResultResponse(controls: [ + LDAP_CONTROL_PAGEDRESULTS => ['value' => ['cookie' => 'next']], + ])); + $ldap->shouldReceive('parseResult')->with('second')->andReturn(new LdapResultResponse(controls: [ + LDAP_CONTROL_PAGEDRESULTS => ['value' => ['cookie' => '']], + ])); + $ldap->shouldReceive('getEntries')->with('first')->andReturn([0 => $entry, 'count' => 1]); + $ldap->shouldReceive('getEntries')->with('second')->andReturn(['count' => 0]); + $ldap->shouldReceive('freeResult')->twice()->andReturnTrue(); + useDirectoryConnection($ldap); + + expect((new ActiveDirectory)->users())->toBe([directoryEntry(enabled: false)]); +}); + +it('discards the entire snapshot when the server returns a partial LDAP result', function () { + $ldap = Mockery::mock(LdapInterface::class); + $ldap->shouldReceive('search')->once()->andReturn('partial'); + $ldap->shouldReceive('parseResult')->with('partial')->andReturn(new LdapResultResponse(errorCode: 4)); + $ldap->shouldReceive('getEntries')->never(); + $ldap->shouldReceive('freeResult')->with('partial')->once()->andReturnTrue(); + useDirectoryConnection($ldap); + + $this->artisan('ad:sync --deactivate-missing')->expectsOutputToContain('directory or database error')->assertFailed(); + expect(User::count())->toBe(0); +}); + +function useDirectoryConnection(LdapInterface $ldap): void +{ + $connection = Mockery::mock(Connection::class)->makePartial(); + $connection->shouldReceive('run')->once()->andReturnUsing(fn (Closure $operation) => $operation($ldap)); + $manager = LdapRecord\Models\ActiveDirectory\User::getConnectionContainer()->getConnectionManager(); + $name = $manager->getDefaultConnectionName(); + $previous = $manager->getConnection($name); + $manager->addConnection($connection, $name); + test()->beforeApplicationDestroyed(fn () => $manager->addConnection($previous, $name)); +} + +it('denies existing sessions and passkey logins while a managed user is disabled', function () { + $this->withoutVite(); + directorySnapshot([directoryEntry()]); + $this->artisan('ad:sync')->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(); + Auth::forgetGuards(); + $this->withSession([$key => $user->id])->get(route('dashboard'))->assertRedirect(route('login')); + + $passkey = new Passkey; + $passkey->setRelation('user', $user->refresh()); + expect(Passkeys::allowsLogin(request(), $passkey))->toBeFalse(); +}); + +it('logs counts and failure reasons without directory email addresses or exception messages', function () { + $log = Log::spy(); + directorySnapshot([directoryEntry()]); + $this->artisan('ad:sync --dry-run')->assertSuccessful(); + $log->shouldHaveReceived('info')->once()->with('Active Directory sync completed.', [ + 'dry_run' => true, + 'deactivate_missing' => false, + 'created' => 1, + 'updated' => 0, + 'unchanged' => 0, + 'deactivated' => 0, + 'reactivated' => 0, + ]); + + $this->mock(ActiveDirectory::class)->shouldReceive('users')->once()->andThrow(new RuntimeException('sensitive bind detail')); + $this->artisan('ad:sync')->assertFailed(); + $log->shouldHaveReceived('error')->once()->with('Active Directory sync failed.', [ + 'dry_run' => false, + 'deactivate_missing' => false, + 'exception_type' => RuntimeException::class, + ]); +}); diff --git a/tests/Feature/StylistIntegrationTest.php b/tests/Feature/StylistIntegrationTest.php index 0cc1f6f..3bad9f6 100644 --- a/tests/Feature/StylistIntegrationTest.php +++ b/tests/Feature/StylistIntegrationTest.php @@ -1,8 +1,12 @@ toBeTrue() @@ -30,3 +34,36 @@ it('renders the authenticated security settings', function () { ->get(route('security.edit')) ->assertOk(); }); + +it('resolves shared views using the request theme and preserves the backend layout namespace', function (string $uri, string $theme) { + $files = new Filesystem; + $root = sys_get_temp_dir().'/stylist-precedence-'.Str::uuid(); + $request = Request::create($uri); + app()->instance('request', $request); + $console = new ReflectionProperty(app(), 'isRunningInConsole'); + $console->setValue(app(), false); + + try { + foreach (['frontend', 'backend'] as $key) { + $files->makeDirectory("$root/$key/views/layouts", recursive: true); + $files->copy(resource_path("themes/$key/theme.json"), "$root/$key/theme.json"); + $files->put("$root/$key/views/layouts/app.blade.php", $key); + } + $files->put("$root/frontend/views/welcome.blade.php", 'welcome'); + $files->put("$root/backend/views/dashboard.blade.php", 'dashboard'); + config(['stylist.themes_path' => $root]); + app()->getProvider(StylistServiceProvider::class)->boot(); + + $finder = View::getFinder(); + expect($finder->find('layouts.app'))->toBe("$root/$theme/views/layouts/app.blade.php") + ->and($finder->find('layouts::app'))->toBe("$root/backend/views/layouts/app.blade.php") + ->and($finder->find('welcome'))->toBe("$root/frontend/views/welcome.blade.php") + ->and($finder->find('dashboard'))->toBe("$root/backend/views/dashboard.blade.php"); + } finally { + $console->setValue(app(), true); + $files->deleteDirectory($root); + } +})->with([ + 'frontend request' => ['/', 'frontend'], + 'backend request' => ['/dashboard', 'backend'], +]);