@@ -63,3 +63,8 @@ AWS_BUCKET=
|
|||||||
AWS_USE_PATH_STYLE_ENDPOINT=false
|
AWS_USE_PATH_STYLE_ENDPOINT=false
|
||||||
|
|
||||||
VITE_APP_NAME="${APP_NAME}"
|
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
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use App\Services\DirectorySyncRejected;
|
||||||
|
use App\Services\SyncDirectoryUsers;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
use Illuminate\Support\Facades\Cache;
|
||||||
|
use Illuminate\Support\Facades\Log;
|
||||||
|
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}';
|
||||||
|
|
||||||
|
protected $description = 'Synchronize local user records from Active Directory';
|
||||||
|
|
||||||
|
public function handle(SyncDirectoryUsers $sync): int
|
||||||
|
{
|
||||||
|
$context = [
|
||||||
|
'dry_run' => (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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
namespace App\Models;
|
namespace App\Models;
|
||||||
|
|
||||||
// use Illuminate\Contracts\Auth\MustVerifyEmail;
|
// use Illuminate\Contracts\Auth\MustVerifyEmail;
|
||||||
|
use Carbon\CarbonImmutable;
|
||||||
use Database\Factories\UserFactory;
|
use Database\Factories\UserFactory;
|
||||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
use Illuminate\Database\Eloquent\Attributes\Hidden;
|
use Illuminate\Database\Eloquent\Attributes\Hidden;
|
||||||
@@ -16,6 +17,9 @@ use Laravel\Fortify\PasskeyAuthenticatable;
|
|||||||
use Laravel\Fortify\TwoFactorAuthenticatable;
|
use Laravel\Fortify\TwoFactorAuthenticatable;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
* @property string|null $ad_guid
|
||||||
|
* @property string|null $ad_source
|
||||||
|
* @property CarbonImmutable|null $ad_disabled_at
|
||||||
* @property int $id
|
* @property int $id
|
||||||
* @property string $name
|
* @property string $name
|
||||||
* @property string $email
|
* @property string $email
|
||||||
@@ -44,6 +48,7 @@ class User extends Authenticatable implements PasskeyUser
|
|||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'email_verified_at' => 'datetime',
|
'email_verified_at' => 'datetime',
|
||||||
|
'ad_disabled_at' => 'datetime',
|
||||||
'password' => 'hashed',
|
'password' => 'hashed',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,12 +4,19 @@ namespace App\Providers;
|
|||||||
|
|
||||||
use App\Actions\Fortify\CreateNewUser;
|
use App\Actions\Fortify\CreateNewUser;
|
||||||
use App\Actions\Fortify\ResetUserPassword;
|
use App\Actions\Fortify\ResetUserPassword;
|
||||||
|
use App\Models\User;
|
||||||
|
use Illuminate\Auth\EloquentUserProvider;
|
||||||
use Illuminate\Cache\RateLimiting\Limit;
|
use Illuminate\Cache\RateLimiting\Limit;
|
||||||
|
use Illuminate\Contracts\Hashing\Hasher;
|
||||||
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\Auth;
|
||||||
use Illuminate\Support\Facades\RateLimiter;
|
use Illuminate\Support\Facades\RateLimiter;
|
||||||
use Illuminate\Support\ServiceProvider;
|
use Illuminate\Support\ServiceProvider;
|
||||||
use Illuminate\Support\Str;
|
use Illuminate\Support\Str;
|
||||||
use Laravel\Fortify\Fortify;
|
use Laravel\Fortify\Fortify;
|
||||||
|
use Laravel\Passkeys\Contracts\PasskeyUser;
|
||||||
|
use Laravel\Passkeys\Passkeys;
|
||||||
|
|
||||||
class FortifyServiceProvider extends ServiceProvider
|
class FortifyServiceProvider extends ServiceProvider
|
||||||
{
|
{
|
||||||
@@ -18,7 +25,15 @@ class FortifyServiceProvider extends ServiceProvider
|
|||||||
*/
|
*/
|
||||||
public function register(): void
|
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
|
public function boot(): void
|
||||||
{
|
{
|
||||||
|
Passkeys::authorizeLoginUsing(
|
||||||
|
fn (Request $request, PasskeyUser $user): bool => ! ($user instanceof User) || $user->ad_disabled_at === null,
|
||||||
|
);
|
||||||
|
|
||||||
$this->configureActions();
|
$this->configureActions();
|
||||||
$this->configureViews();
|
$this->configureViews();
|
||||||
$this->configureRateLimiting();
|
$this->configureRateLimiting();
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services;
|
||||||
|
|
||||||
|
use LdapRecord\LdapInterface;
|
||||||
|
use LdapRecord\Models\ActiveDirectory\User;
|
||||||
|
use RuntimeException;
|
||||||
|
|
||||||
|
class ActiveDirectory
|
||||||
|
{
|
||||||
|
private const ATTRIBUTES = ['objectguid', 'mail', 'displayname', 'cn', 'useraccountcontrol'];
|
||||||
|
|
||||||
|
public static function baseDn(): string
|
||||||
|
{
|
||||||
|
$connection = config('ldap.default');
|
||||||
|
|
||||||
|
return trim((string) (config('ad-sync.base-dn') ?: config("ldap.connections.{$connection}.base_dn")));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return list<array{guid: ?string, email: string, name: string, enabled: bool}> */
|
||||||
|
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,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services;
|
||||||
|
|
||||||
|
use RuntimeException;
|
||||||
|
|
||||||
|
class DirectorySyncRejected extends RuntimeException {}
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services;
|
||||||
|
|
||||||
|
use App\Models\User;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
|
||||||
|
class SyncDirectoryUsers
|
||||||
|
{
|
||||||
|
public function __construct(private ActiveDirectory $directory) {}
|
||||||
|
|
||||||
|
/** @return array{created: int, updated: int, unchanged: int, deactivated: int, reactivated: int} */
|
||||||
|
public function run(bool $dryRun, bool $deactivateMissing): array
|
||||||
|
{
|
||||||
|
$entries = $this->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<string, array{email: string, name: string, enabled: bool}> */
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
return [
|
||||||
|
'base-dn' => env('AD_SYNC_BASE_DN'),
|
||||||
|
'scheduled' => env('AD_SYNC_SCHEDULED', false),
|
||||||
|
'max-deactivations' => (int) env('AD_SYNC_MAX_DEACTIVATIONS', 5),
|
||||||
|
];
|
||||||
+1
-1
@@ -63,7 +63,7 @@ return [
|
|||||||
|
|
||||||
'providers' => [
|
'providers' => [
|
||||||
'users' => [
|
'users' => [
|
||||||
'driver' => 'eloquent',
|
'driver' => 'active-users',
|
||||||
'model' => env('AUTH_MODEL', User::class),
|
'model' => env('AUTH_MODEL', User::class),
|
||||||
],
|
],
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::table('users', function (Blueprint $table): void {
|
||||||
|
$table->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']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -2,7 +2,12 @@
|
|||||||
|
|
||||||
use Illuminate\Foundation\Inspiring;
|
use Illuminate\Foundation\Inspiring;
|
||||||
use Illuminate\Support\Facades\Artisan;
|
use Illuminate\Support\Facades\Artisan;
|
||||||
|
use Illuminate\Support\Facades\Schedule;
|
||||||
|
|
||||||
Artisan::command('inspire', function () {
|
Artisan::command('inspire', function () {
|
||||||
$this->comment(Inspiring::quote());
|
$this->comment(Inspiring::quote());
|
||||||
})->purpose('Display an inspiring quote');
|
})->purpose('Display an inspiring quote');
|
||||||
|
|
||||||
|
if (config('ad-sync.scheduled')) {
|
||||||
|
Schedule::command('ad:sync')->dailyAt('02:00')->withoutOverlapping();
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,208 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\ActiveDirectory;
|
||||||
|
use Illuminate\Support\Facades\Auth;
|
||||||
|
use Illuminate\Support\Facades\Cache;
|
||||||
|
use Illuminate\Support\Facades\Log;
|
||||||
|
use Laravel\Passkeys\Passkey;
|
||||||
|
use Laravel\Passkeys\Passkeys;
|
||||||
|
use LdapRecord\Connection;
|
||||||
|
use LdapRecord\LdapInterface;
|
||||||
|
use LdapRecord\LdapResultResponse;
|
||||||
|
|
||||||
|
function directoryEntry(string $email = '[email protected]', string $guid = '00112233-4455-6677-8899-aabbccddeeff', bool $enabled = true): array
|
||||||
|
{
|
||||||
|
return ['guid' => $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('[email protected]')]);
|
||||||
|
$this->artisan('ad:sync')->assertSuccessful();
|
||||||
|
directorySnapshot([directoryEntry('[email protected]')]);
|
||||||
|
$this->artisan('ad:sync')->expectsOutputToContain('unchanged=1')->assertSuccessful();
|
||||||
|
|
||||||
|
expect(User::sole()->id)->toBe($user->id)
|
||||||
|
->and($user->refresh()->email)->toBe('[email protected]');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuses to claim a local account by case-insensitive email and applies no partial changes', function () {
|
||||||
|
$local = User::factory()->create(['email' => '[email protected]']);
|
||||||
|
directorySnapshot([directoryEntry('[email protected]', '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('[email protected]')]],
|
||||||
|
'duplicate email' => fn () => [[directoryEntry(), directoryEntry('[email protected]', '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('[email protected]', '11111111-1111-1111-1111-111111111111');
|
||||||
|
$third = directoryEntry('[email protected]', '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' => ['[email protected]'],
|
||||||
|
'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,
|
||||||
|
]);
|
||||||
|
});
|
||||||
@@ -1,8 +1,12 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use Illuminate\Filesystem\Filesystem;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Facades\Blade;
|
use Illuminate\Support\Facades\Blade;
|
||||||
use Illuminate\Support\Facades\View;
|
use Illuminate\Support\Facades\View;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Modules\Stylist\Providers\StylistServiceProvider;
|
||||||
|
|
||||||
it('resolves backend theme views', function () {
|
it('resolves backend theme views', function () {
|
||||||
expect(View::exists('dashboard'))->toBeTrue()
|
expect(View::exists('dashboard'))->toBeTrue()
|
||||||
@@ -30,3 +34,36 @@ it('renders the authenticated security settings', function () {
|
|||||||
->get(route('security.edit'))
|
->get(route('security.edit'))
|
||||||
->assertOk();
|
->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'],
|
||||||
|
]);
|
||||||
|
|||||||
Reference in New Issue
Block a user