Loheide-eu-mitarbeiterplatt.../tests/Feature/Identity/EntraDirectorySyncTest.php
Friederich Loheide 51c94cd0cf
Some checks failed
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 1m37s
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 1m41s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 1m40s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 1m42s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 2m10s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 2m6s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 1m55s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 2m2s
CI / Build-Artefakte aktuell (pull_request) Successful in 52s
Anmeldung mit Microsoft Entra ID
- OpenID Connect mit PKCE, State und Nonce; ID-Token-Prüfung gegen die
  Microsoft-Schlüssel (Signatur, Mandant, App, Gültigkeit, Nonce) inkl.
  Neuladen bei Schlüsselwechsel
- Konto bei erster Anmeldung anlegen oder per E-Mail verknüpfen, optionale
  Domain-Beschränkung, deaktivierte Konten bleiben gesperrt
- Gruppen (inkl. Overage über Graph, transitiv) und App-Rollen → Rollen,
  additiv; nur Zuweisungen aus Entra werden abgeglichen, manuelle bleiben
- Profilfelder, Vorgesetzte*r und Profilfoto aus Graph, je Feld wählbar und
  im Portal schreibgeschützt; Fallback auf Token-Angaben, wenn Graph ausfällt
- Hintergrund-Abgleich mit Delta-Abfragen (Zeitbudget, Fortsetzung über
  nextLink/deltaLink), Offboarding deaktivierter/gelöschter Konten, optionale
  Vorab-Anlage, Fotos/Vorgesetzte rollierend, Gruppen und App-Rollen stündlich
- Admin „Anmeldung“: Einrichtung mit Umleitungs-URI und Berechtigungen,
  verschlüsseltes Geheimnis (nie im Browser), Gruppensuche, Status, „Mapping testen“
- Fix: @odata.nextLink/@odata.deltaLink wurden als Pfad gelesen – Folgeseiten fehlten
- Profilseite mit Vorgesetzter/m und Mitarbeitenden; Version 0.4.0

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-26 07:52:22 +00:00

214 lines
9.4 KiB
PHP

<?php
namespace Tests\Feature\Identity;
use App\Identity\Entra\EntraDirectorySync;
use App\Models\IdentityProvider;
use App\Models\IdpGroupMapping;
use App\Models\Role;
use App\Models\User;
use App\Models\UserIdentity;
use App\Support\Settings;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Tests\Support\FakeEntra;
use Tests\TestCase;
class EntraDirectorySyncTest extends TestCase
{
use FakeEntra;
use RefreshDatabase;
private IdentityProvider $provider;
protected function setUp(): void
{
parent::setUp();
Storage::fake('uploads');
Cache::flush();
$this->provider = $this->entraProvider(['directory_sync' => true, 'sync_photo' => false, 'synced_fields' => ['first_name', 'last_name', 'job_title', 'department']]);
}
private function linked(string $subject, array $attributes = []): User
{
$user = User::factory()->create($attributes);
UserIdentity::query()->create(['user_id' => $user->id, 'identity_provider_id' => $this->provider->id, 'subject' => $subject]);
return $user;
}
private function sync(): void
{
app(EntraDirectorySync::class)->run($this->provider->fresh());
}
public function test_delta_pages_are_followed_and_the_delta_link_is_stored(): void
{
$anna = $this->linked('oid-anna', ['job_title' => 'alt']);
$ben = $this->linked('oid-ben', ['department' => 'alt']);
$this->graph = ['/users/delta' => function (Request $request) {
return str_contains($request->url(), 'skiptoken')
? Http::response(['value' => [['id' => 'oid-ben', 'department' => 'IT']], '@odata.deltaLink' => 'https://graph.microsoft.com/v1.0/users/delta?$deltatoken=abc'])
: Http::response(['value' => [['id' => 'oid-anna', 'jobTitle' => 'Leitung']], '@odata.nextLink' => 'https://graph.microsoft.com/v1.0/users/delta?$skiptoken=2']);
}];
$this->fakeEntra();
$this->sync();
$this->assertSame('Leitung', $anna->fresh()->job_title);
$this->assertSame('IT', $ben->fresh()->department);
$this->assertSame('https://graph.microsoft.com/v1.0/users/delta?$deltatoken=abc', app(EntraDirectorySync::class)->status($this->provider)['delta_link']);
$this->assertNull(app(EntraDirectorySync::class)->status($this->provider)['last_error']);
// Zweiter Lauf beginnt beim Delta-Link.
Http::fake(['*oauth2*' => Http::response(['access_token' => 'x']), '*users/delta*' => Http::response(['value' => [], '@odata.deltaLink' => 'https://graph.microsoft.com/v1.0/users/delta?$deltatoken=def'])]);
$this->sync();
Http::assertSent(fn (Request $r) => str_contains(urldecode($r->url()), 'deltatoken=abc'));
}
public function test_delta_only_updates_fields_that_changed(): void
{
$anna = $this->linked('oid-anna', ['first_name' => 'Anna', 'last_name' => 'Schmidt', 'job_title' => 'bleibt', 'department' => 'bleibt']);
$this->graph = ['/users/delta' => ['value' => [['id' => 'oid-anna', 'surname' => 'Meyer']], '@odata.deltaLink' => 'x']];
$this->fakeEntra();
$this->sync();
$anna->refresh();
$this->assertSame('Anna Meyer', $anna->name);
$this->assertSame('bleibt', $anna->job_title);
$this->assertSame('bleibt', $anna->department);
}
public function test_disabled_or_deleted_accounts_are_deactivated_and_lose_their_group_roles(): void
{
$role = Role::query()->create(['name' => 'MAV']);
$manual = Role::query()->create(['name' => 'Manuell']);
$disabled = $this->linked('oid-weg');
$deleted = $this->linked('oid-geloescht');
$disabled->roles()->attach($role->id, ['source' => 'idp', 'source_ref' => $this->provider->id.':group:x', 'created_at' => now()]);
$disabled->syncManualRoles([$manual->id]);
$this->graph = ['/users/delta' => ['value' => [
['id' => 'oid-weg', 'accountEnabled' => false],
['id' => 'oid-geloescht', '@removed' => ['reason' => 'deleted']],
], '@odata.deltaLink' => 'x']];
$this->fakeEntra();
$this->sync();
$this->assertFalse($disabled->fresh()->is_active);
$this->assertFalse($deleted->fresh()->is_active);
$this->assertFalse($disabled->fresh()->hasRole('mav'));
$this->assertTrue($disabled->fresh()->hasRole('manuell'));
}
public function test_accounts_are_created_in_advance_only_when_enabled(): void
{
$delta = ['value' => [
['id' => 'oid-neu', 'givenName' => 'Neu', 'surname' => 'Person', 'mail' => 'neu@firma.de', 'accountEnabled' => true, 'userType' => 'Member'],
['id' => 'oid-gast', 'givenName' => 'Gast', 'mail' => 'gast@extern.de', 'accountEnabled' => true, 'userType' => 'Guest'],
], '@odata.deltaLink' => 'x'];
$this->graph = ['/users/delta' => $delta];
$this->fakeEntra();
$this->sync();
$this->assertSame(0, User::query()->count());
$this->provider->update(['config' => array_merge($this->provider->config, ['directory_create_users' => true])]);
app(Settings::class)->set('identity.'.$this->provider->id.'.sync', []);
$this->sync();
$this->assertSame(['neu@firma.de'], User::query()->pluck('email')->all(), 'Gäste werden nicht angelegt.');
$this->assertSame('Neu Person', User::query()->sole()->name);
}
public function test_existing_accounts_are_linked_by_email_during_sync(): void
{
$existing = User::factory()->create(['email' => 'anna.schmidt@firma.de']);
$this->graph = ['/users/delta' => ['value' => [['id' => 'oid-anna', 'mail' => 'anna.schmidt@firma.de', 'jobTitle' => 'Leitung']], '@odata.deltaLink' => 'x']];
$this->fakeEntra();
$this->sync();
$this->assertSame('oid-anna', $existing->identities()->sole()->subject);
$this->assertSame('Leitung', $existing->fresh()->job_title);
}
public function test_group_memberships_and_app_roles_are_synced_for_linked_accounts(): void
{
$mav = Role::query()->create(['name' => 'MAV']);
$chef = Role::query()->create(['name' => 'Chefredaktion']);
$this->provider->mappings()->create(['kind' => IdpGroupMapping::GROUP, 'external_id' => 'gruppe-mav', 'role_id' => $mav->id]);
$this->provider->mappings()->create(['kind' => IdpGroupMapping::APP_ROLE, 'external_id' => 'Portal.Chef', 'role_id' => $chef->id]);
$anna = $this->linked('oid-anna');
$ben = $this->linked('oid-ben');
$ben->roles()->attach($mav->id, ['source' => 'idp', 'source_ref' => $this->provider->id.':group:gruppe-mav', 'created_at' => now()]);
$this->graph = [
'/users/delta' => ['value' => [], '@odata.deltaLink' => 'x'],
'/groups/gruppe-mav/transitiveMembers' => ['value' => [['id' => 'oid-anna']]],
"/servicePrincipals(appId='{$this->clientId}')" => ['id' => 'sp-1', 'appRoles' => [['id' => 'role-guid', 'value' => 'Portal.Chef']]],
'/servicePrincipals/sp-1/appRoleAssignedTo' => ['value' => [['principalType' => 'Group', 'principalId' => 'chef-gruppe', 'appRoleId' => 'role-guid']]],
'/groups/chef-gruppe/transitiveMembers' => ['value' => [['id' => 'oid-ben']]],
];
$this->fakeEntra();
$this->sync();
$this->assertTrue($anna->fresh()->hasRole('mav'));
$this->assertFalse($anna->fresh()->hasRole('chefredaktion'));
$this->assertFalse($ben->fresh()->hasRole('mav'), 'Ben ist nicht mehr in der Gruppe.');
$this->assertTrue($ben->fresh()->hasRole('chefredaktion'), 'App-Rolle über Gruppe zugewiesen.');
}
public function test_photos_and_managers_are_synced_in_small_batches(): void
{
$this->provider->update(['config' => array_merge($this->provider->config, ['sync_photo' => true, 'synced_fields' => ['manager']])]);
$boss = $this->linked('oid-boss');
$anna = $this->linked('oid-anna');
$this->graph = [
'/users/delta' => ['value' => [], '@odata.deltaLink' => 'x'],
'/users/oid-anna/photo/$value' => $this->jpeg(),
'/users/oid-anna/manager' => ['id' => 'oid-boss'],
'/users/oid-boss/photo/$value' => 404,
'/users/oid-boss/manager' => 404,
];
$this->fakeEntra();
$this->sync();
$this->assertNotNull($anna->fresh()->avatar_path);
$this->assertSame($boss->id, $anna->fresh()->manager_id);
$this->assertNull($boss->fresh()->avatar_path);
$this->assertNotNull(UserIdentity::query()->where('subject', 'oid-anna')->value('synced_at'));
}
public function test_errors_are_recorded_and_do_not_throw(): void
{
$this->graph = ['/users/delta' => 403];
$this->fakeEntra();
$this->sync();
$this->assertStringContainsString('verweigert den Zugriff', app(EntraDirectorySync::class)->status($this->provider)['last_error']);
}
public function test_expired_delta_link_restarts_the_full_sync(): void
{
app(Settings::class)->set('identity.'.$this->provider->id.'.sync', ['delta_link' => 'https://graph.microsoft.com/v1.0/users/delta?$deltatoken=alt']);
$this->graph = ['/users/delta' => 410];
$this->fakeEntra();
$this->sync();
$this->assertNull(app(EntraDirectorySync::class)->status($this->provider)['delta_link']);
}
}