Anmeldung mit Microsoft Entra ID
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

- 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>
This commit is contained in:
Friederich Loheide 2026-09-26 07:52:22 +00:00
parent 9ddc35a62c
commit 51c94cd0cf
111 changed files with 5721 additions and 244 deletions

View file

@ -0,0 +1,214 @@
<?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']);
}
}

View file

@ -0,0 +1,335 @@
<?php
namespace Tests\Feature\Identity;
use App\Models\IdentityProvider;
use App\Models\IdpGroupMapping;
use App\Models\Role;
use App\Models\User;
use App\Models\UserIdentity;
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 Inertia\Testing\AssertableInertia as Assert;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\Support\FakeEntra;
use Tests\TestCase;
class EntraLoginTest extends TestCase
{
use FakeEntra;
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
Storage::fake('uploads');
Cache::flush();
}
public function test_login_page_offers_microsoft_sign_in(): void
{
$this->entraProvider(['button_label' => 'Mit dem Firmenkonto anmelden']);
IdentityProvider::query()->create(['type' => 'entra', 'name' => 'Alt', 'slug' => 'alt', 'enabled' => false, 'config' => []]);
$this->get('/login')->assertInertia(fn (Assert $page) => $page
->has('providers', 1)
->where('providers.0.slug', 'entra')
->where('providers.0.label', 'Mit dem Firmenkonto anmelden'));
}
public function test_redirect_uses_pkce_state_and_nonce(): void
{
$provider = $this->entraProvider();
$response = $this->get('/auth/entra/redirect');
$location = $response->headers->get('Location');
parse_str((string) parse_url($location, PHP_URL_QUERY), $query);
$this->assertStringStartsWith('https://login.microsoftonline.com/'.$this->tenantId.'/oauth2/v2.0/authorize', $location);
$this->assertSame($this->clientId, $query['client_id']);
$this->assertSame('S256', $query['code_challenge_method']);
$this->assertSame(session('identity_login.state'), $query['state']);
$this->assertSame(session('identity_login.nonce'), $query['nonce']);
$this->assertSame(
rtrim(strtr(base64_encode(hash('sha256', session('identity_login.verifier'), true)), '+/', '-_'), '='),
$query['code_challenge'],
);
$this->assertSame(url('/auth/entra/callback'), $query['redirect_uri']);
$this->assertStringContainsString('GroupMember.Read.All', $query['scope']);
}
public function test_first_login_creates_account_with_profile_photo_roles_and_manager(): void
{
$mav = Role::query()->create(['name' => 'MAV']);
$staff = Role::query()->create(['name' => 'Mitarbeitende']);
$provider = $this->entraProvider(['default_role_id' => $staff->id]);
$provider->mappings()->create(['kind' => IdpGroupMapping::GROUP, 'external_id' => 'GRUPPE-MAV', 'external_name' => 'GG-MAV', 'role_id' => $mav->id]);
$boss = User::factory()->create(['email' => 'chefin@firma.de']);
UserIdentity::query()->create(['user_id' => $boss->id, 'identity_provider_id' => $provider->id, 'subject' => 'oid-chefin']);
$this->entraClaims = ['groups' => ['gruppe-mav', 'andere-gruppe']];
$this->graph = ['/me/manager' => ['id' => 'oid-chefin'], '/me/photo/$value' => $this->jpeg()];
$this->fakeEntra();
$this->loginWithEntra($provider)->assertRedirect('/');
$user = User::query()->where('email', 'anna.schmidt@firma.de')->sole();
$this->assertAuthenticatedAs($user);
$this->assertNull($user->password);
$this->assertSame('Anna Schmidt', $user->name);
$this->assertSame('Pflegedienstleitung', $user->job_title);
$this->assertSame('Pflege', $user->department);
$this->assertSame('Hamburg', $user->location);
$this->assertSame('+49 40 123', $user->phone);
$this->assertSame($boss->id, $user->manager_id);
$this->assertNotNull($user->avatar_path);
Storage::disk('uploads')->assertExists($user->avatar_path.'-96.webp');
$this->assertTrue($user->hasRole('mav'), 'Gruppen-ID wird ohne Rücksicht auf Groß-/Kleinschreibung verglichen.');
$this->assertTrue($user->hasRole('mitarbeitende'));
$this->assertSame(['idp'], $user->roles()->pluck('role_user.source')->unique()->values()->all());
Http::assertSent(fn (Request $r) => str_contains($r->url(), '/oauth2/v2.0/token')
&& $r['code'] === 'auth-code' && $r['client_secret'] === 'geheim' && strlen($r['code_verifier']) === 64);
}
public function test_group_removal_removes_the_role_but_keeps_manual_roles(): void
{
$mav = Role::query()->create(['name' => 'MAV']);
$manual = Role::query()->create(['name' => 'Redaktion']);
$provider = $this->entraProvider();
$provider->mappings()->create(['kind' => IdpGroupMapping::GROUP, 'external_id' => 'gruppe-mav', 'role_id' => $mav->id]);
$this->entraClaims = ['groups' => ['gruppe-mav']];
$this->fakeEntra();
$this->loginWithEntra($provider);
$user = User::query()->where('email', 'anna.schmidt@firma.de')->sole();
$user->syncManualRoles([$manual->id, $mav->id]);
$this->assertTrue($user->can('feedback.send') === false);
auth()->logout();
$this->entraClaims = ['groups' => []];
$this->graph = ['/me/transitiveMemberOf' => ['value' => []]];
$this->loginWithEntra($provider);
$user->refresh();
$this->assertTrue($user->hasRole('redaktion'));
$this->assertTrue($user->hasRole('mav'), 'Manuell zugewiesen – bleibt trotz Gruppen-Austritt.');
$this->assertSame(0, $user->roles()->wherePivot('source', 'idp')->count());
}
public function test_group_overage_is_resolved_via_graph(): void
{
$role = Role::query()->create(['name' => 'Verschachtelt']);
$provider = $this->entraProvider();
$provider->mappings()->create(['kind' => IdpGroupMapping::GROUP, 'external_id' => 'tief-verschachtelt', 'role_id' => $role->id]);
$this->entraClaims = ['hasgroups' => true, '_claim_names' => ['groups' => 'src1']];
$this->graph = ['/me/transitiveMemberOf/microsoft.graph.group' => function () {
static $page = 0;
return ++$page === 1
? Http::response(['value' => [['id' => 'a']], '@odata.nextLink' => 'https://graph.microsoft.com/v1.0/me/transitiveMemberOf/microsoft.graph.group?$skiptoken=2'])
: Http::response(['value' => [['id' => 'tief-verschachtelt']]]);
}];
$this->fakeEntra();
$this->loginWithEntra($provider)->assertRedirect('/');
$this->assertTrue(User::query()->where('email', 'anna.schmidt@firma.de')->sole()->hasRole('verschachtelt'));
}
public function test_app_roles_are_mapped(): void
{
$role = Role::query()->create(['name' => 'Chefredaktion']);
$provider = $this->entraProvider();
$provider->mappings()->create(['kind' => IdpGroupMapping::APP_ROLE, 'external_id' => 'Portal.Chefredaktion', 'role_id' => $role->id]);
$this->entraClaims = ['groups' => ['x'], 'roles' => ['Portal.Chefredaktion']];
$this->fakeEntra();
$this->loginWithEntra($provider);
$this->assertTrue(User::query()->where('email', 'anna.schmidt@firma.de')->sole()->hasRole('chefredaktion'));
}
public function test_existing_account_is_linked_by_email_and_keeps_its_password(): void
{
$provider = $this->entraProvider();
$existing = User::factory()->create(['email' => 'anna.schmidt@firma.de']);
$this->entraClaims = ['groups' => ['x']];
$this->fakeEntra();
$this->loginWithEntra($provider)->assertRedirect('/');
$this->assertAuthenticatedAs($existing);
$this->assertNotNull($existing->fresh()->password);
$this->assertSame('oid-anna', $existing->identities()->sole()->subject);
$this->assertSame(1, User::query()->count());
}
/**
* @return array<string, array{0: array<string, mixed>, 1: string}>
*/
public static function invalidTokens(): array
{
return [
'fremder Mandant' => [['iss' => 'https://login.microsoftonline.com/99999999-9999-9999-9999-999999999999/v2.0'], 'nicht aus dem erwarteten Microsoft-Mandanten'],
'andere App' => [['aud' => 'andere-app'], 'für eine andere Anwendung bestimmt'],
'falsche Nonce' => [['nonce' => 'manipuliert'], 'nicht zugeordnet werden'],
'abgelaufen' => [['exp' => time() - 3600, 'iat' => time() - 7200, 'nbf' => time() - 7200], 'nicht bestätigt'],
'ohne Objekt-ID' => [['oid' => ''], 'keine Benutzerkennung'],
];
}
/**
* @dataProvider invalidTokens
*/
#[DataProvider('invalidTokens')]
public function test_invalid_id_tokens_are_rejected(array $claims, string $message): void
{
$provider = $this->entraProvider();
$this->entraClaims = $claims;
$this->fakeEntra();
$this->loginWithEntra($provider)->assertRedirect('/login')->assertSessionHas('identity_error', fn ($m) => str_contains($m, $message));
$this->assertGuest();
$this->assertSame(0, User::query()->count());
}
public function test_token_signed_with_foreign_key_is_rejected(): void
{
$provider = $this->entraProvider();
$foreignKey = openssl_pkey_new(['private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA]);
$this->fakeEntra(fn () => Http::response(['id_token' => $this->entraIdToken((string) $this->lastNonce, [], $foreignKey), 'access_token' => 'x']));
$this->loginWithEntra($provider)->assertSessionHas('identity_error', fn ($m) => str_contains($m, 'nicht bestätigt'));
$this->assertGuest();
}
public function test_key_rotation_reloads_the_keys_once(): void
{
$provider = $this->entraProvider();
$newKey = openssl_pkey_new(['private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA]);
Cache::put('entra.jwks.'.$this->tenantId, $this->entraJwks(), 3600); // alter Schlüssel im Cache
$this->fakeEntra(
fn () => Http::response(['id_token' => $this->entraIdToken((string) $this->lastNonce, ['groups' => ['x']], $newKey, 'neuer-schluessel'), 'access_token' => 'x']),
jwks: $this->entraJwks($newKey, 'neuer-schluessel'),
);
$this->loginWithEntra($provider)->assertRedirect('/');
$this->assertAuthenticated();
}
public function test_invalid_state_is_rejected(): void
{
$provider = $this->entraProvider();
$this->fakeEntra();
$this->loginWithEntra($provider, ['state' => 'gefälscht'])->assertSessionHas('identity_error', 'Die Anmeldung ist abgelaufen. Bitte erneut versuchen.');
$this->assertGuest();
Http::assertNotSent(fn (Request $r) => str_contains($r->url(), '/token'));
}
public function test_cancelled_login_shows_a_message(): void
{
$provider = $this->entraProvider();
$this->loginWithEntra($provider, ['error' => 'access_denied', 'error_description' => 'User cancelled'])
->assertRedirect('/login')
->assertSessionHas('identity_error', 'Die Anmeldung wurde abgebrochen.');
}
public function test_unknown_people_are_rejected_without_auto_provisioning(): void
{
$provider = $this->entraProvider(['auto_provision' => false]);
$this->entraClaims = ['groups' => ['x']];
$this->fakeEntra();
$this->loginWithEntra($provider)->assertSessionHas('identity_error', fn ($m) => str_contains($m, 'kein Konto'));
$this->assertSame(0, User::query()->count());
}
public function test_email_domain_restriction(): void
{
$provider = $this->entraProvider(['allowed_domains' => ['andere-firma.de']]);
$this->entraClaims = ['groups' => ['x']];
$this->fakeEntra();
$this->loginWithEntra($provider)->assertSessionHas('identity_error', fn ($m) => str_contains($m, 'E-Mail-Domain'));
$this->assertGuest();
}
public function test_deactivated_accounts_cannot_sign_in(): void
{
$provider = $this->entraProvider();
User::factory()->inactive()->create(['email' => 'anna.schmidt@firma.de']);
$this->entraClaims = ['groups' => ['x']];
$this->fakeEntra();
$this->loginWithEntra($provider)->assertSessionHas('identity_error', fn ($m) => str_contains($m, 'deaktiviert'));
$this->assertGuest();
}
public function test_graph_outage_falls_back_to_token_claims(): void
{
$provider = $this->entraProvider();
$this->entraClaims = ['groups' => ['x'], 'given_name' => 'Anna', 'family_name' => 'Aus-Token'];
$this->graph = ['/me' => 503];
$this->fakeEntra();
$this->loginWithEntra($provider)->assertRedirect('/');
$this->assertSame('Anna Aus-Token', User::query()->sole()->name);
}
public function test_disabled_provider_cannot_be_used(): void
{
$this->entraProvider([], enabled: false);
$this->get('/auth/entra/redirect')->assertNotFound();
$this->get('/auth/entra/callback?code=x&state=y')->assertNotFound();
}
public function test_entra_managed_profile_fields_are_read_only_in_the_portal(): void
{
$provider = $this->entraProvider(['synced_fields' => ['job_title', 'department']]);
$this->entraClaims = ['groups' => ['x']];
$this->fakeEntra();
$this->loginWithEntra($provider);
$user = User::query()->sole();
$this->get('/profil/bearbeiten')->assertInertia(fn (Assert $page) => $page->where('managed', ['job_title', 'department']));
$this->put('/profil', [
'first_name' => 'Anna', 'last_name' => 'Schmidt', 'email' => 'anna.schmidt@firma.de',
'job_title' => 'Selbst geändert', 'department' => 'Selbst geändert', 'about' => 'Hallo',
])->assertSessionHasNoErrors();
$user->refresh();
$this->assertSame('Pflegedienstleitung', $user->job_title);
$this->assertSame('Pflege', $user->department);
$this->assertSame('Hallo', $user->about);
}
public function test_unchanged_photo_is_not_processed_again(): void
{
$provider = $this->entraProvider();
$this->entraClaims = ['groups' => ['x']];
$this->graph = ['/me/photo/$value' => $this->jpeg()];
$this->fakeEntra();
$this->loginWithEntra($provider);
$first = User::query()->sole()->avatar_path;
auth()->logout();
$this->loginWithEntra($provider);
$this->assertSame($first, User::query()->sole()->avatar_path);
}
}

View file

@ -0,0 +1,114 @@
<?php
namespace Tests\Feature\Identity;
use App\Filament\Resources\IdentityProviders\Pages\CreateIdentityProvider;
use App\Filament\Resources\IdentityProviders\Pages\EditIdentityProvider;
use App\Filament\Resources\IdentityProviders\Pages\TestMapping;
use App\Models\IdentityProvider;
use App\Models\IdpGroupMapping;
use App\Models\Role;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Livewire\Livewire;
use Tests\Support\FakeEntra;
use Tests\TestCase;
class IdentityAdminTest extends TestCase
{
use FakeEntra;
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
Cache::flush();
$this->actingAs(User::factory()->admin()->create());
}
public function test_admin_can_connect_entra(): void
{
Livewire::test(CreateIdentityProvider::class)
->fillForm([
'name' => 'Microsoft Entra ID',
'enabled' => true,
'config' => [
'tenant_id' => $this->tenantId,
'client_id' => $this->clientId,
'client_secret' => 'sehr-geheim',
],
])
->call('create')
->assertHasNoFormErrors();
$provider = IdentityProvider::query()->sole();
$this->assertSame('entra', $provider->type);
$this->assertSame('sehr-geheim', $provider->setting('client_secret'));
$this->assertStringNotContainsString('sehr-geheim', (string) \DB::table('identity_providers')->value('config'), 'Konfiguration liegt verschlüsselt in der Datenbank.');
}
public function test_tenant_must_be_a_guid(): void
{
Livewire::test(CreateIdentityProvider::class)
->fillForm(['name' => 'Entra', 'config' => ['tenant_id' => 'firma.onmicrosoft.com', 'client_id' => $this->clientId, 'client_secret' => 'x']])
->call('create')
->assertHasFormErrors(['config.tenant_id']);
}
public function test_secret_is_never_sent_to_the_browser_and_kept_when_left_empty(): void
{
$provider = $this->entraProvider(['client_secret' => 'bleibt-geheim']);
$role = Role::query()->create(['name' => 'MAV']);
$this->get('/admin/anmeldung/'.$provider->id.'/bearbeiten')->assertOk()->assertDontSee('bleibt-geheim')->assertSee('/auth/entra/callback');
Livewire::test(EditIdentityProvider::class, ['record' => $provider->getRouteKey()])
->fillForm([
'name' => 'Firmenkonto',
'mappings' => [['kind' => IdpGroupMapping::GROUP, 'external_id' => 'gruppe-mav', 'external_name' => 'GG-MAV', 'role_id' => $role->id]],
])
->call('save')
->assertHasNoFormErrors();
$provider->refresh();
$this->assertSame('bleibt-geheim', $provider->setting('client_secret'));
$this->assertSame('Firmenkonto', $provider->name);
$this->assertSame('gruppe-mav', $provider->mappings()->sole()->external_id);
}
public function test_mapping_tester_shows_groups_and_resulting_roles(): void
{
$provider = $this->entraProvider();
$mav = Role::query()->create(['name' => 'MAV']);
$provider->mappings()->create(['kind' => IdpGroupMapping::GROUP, 'external_id' => 'gruppe-mav', 'role_id' => $mav->id]);
$this->graph = [
'/users/anna.schmidt@firma.de' => ['id' => 'oid-anna', 'displayName' => 'Anna Schmidt', 'mail' => 'anna.schmidt@firma.de', 'accountEnabled' => true],
'/users/oid-anna/transitiveMemberOf' => ['value' => [['id' => 'gruppe-mav', 'displayName' => 'GG-MAV'], ['id' => 'x', 'displayName' => 'Alle']]],
"/servicePrincipals(appId='{$this->clientId}')" => ['id' => 'sp-1', 'appRoles' => []],
'/users/oid-anna/appRoleAssignments' => ['value' => []],
'/servicePrincipals/sp-1/appRoleAssignedTo' => ['value' => []],
];
$this->fakeEntra();
Livewire::test(TestMapping::class, ['record' => $provider->getRouteKey()])
->set('person', 'anna.schmidt@firma.de')
->call('test')
->assertSet('error', null)
->assertSee('GG-MAV')
->assertSee('MAV');
}
public function test_identity_pages_require_the_right(): void
{
$provider = $this->entraProvider();
$role = Role::query()->create(['name' => 'Gestaltung']);
$role->grants()->create(['ability' => 'appearance.manage']);
$this->actingAs(User::factory()->withRoles([$role])->create());
$this->get('/admin/anmeldung')->assertForbidden();
$this->get('/admin/anmeldung/'.$provider->id.'/testen')->assertForbidden();
}
}

View file

@ -33,14 +33,14 @@ class UpdateStateTest extends TestCase
$version = new InstalledVersion($this->dir.'/.version');
$this->assertNull($version->current());
$this->assertSame('0.3.0', $version->release());
$this->assertSame('0.3.0', $version->full());
$this->assertSame('0.4.0', $version->release());
$this->assertSame('0.4.0', $version->full());
$version->save('A1B2C3D4E5F60718293a4b5c6d7e8f9012345678');
$this->assertSame('a1b2c3d4e5f60718293a4b5c6d7e8f9012345678', $version->current());
$this->assertSame('a1b2c3d', $version->short());
$this->assertSame('0.3.0 (a1b2c3d)', $version->full());
$this->assertSame('0.4.0 (a1b2c3d)', $version->full());
}
public function test_invalid_sha_is_rejected(): void

187
tests/Support/FakeEntra.php Normal file
View file

@ -0,0 +1,187 @@
<?php
namespace Tests\Support;
use App\Models\IdentityProvider;
use Firebase\JWT\JWT;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Testing\TestResponse;
/**
* Simulierter Microsoft-Entra-Mandant für Tests: signiert echte ID-Token (RS256)
* und beantwortet Token-, Schlüssel- und Graph-Anfragen.
*/
trait FakeEntra
{
protected string $tenantId = '11111111-2222-3333-4444-555555555555';
protected string $clientId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee';
protected string $entraKid = 'test-key-1';
/** @var \OpenSSLAsymmetricKey|null */
protected $entraKey = null;
/** Claims für das nächste ID-Token (werden mit Standardwerten zusammengeführt). */
protected array $entraClaims = [];
/** Graph-Antworten: Pfad-Muster => Antwort (array = JSON, string = Binärdaten, int = Statuscode). */
protected array $graph = [];
protected array $graphUser = [
'id' => 'oid-anna',
'displayName' => 'Anna Schmidt',
'givenName' => 'Anna',
'surname' => 'Schmidt',
'mail' => 'anna.schmidt@firma.de',
'userPrincipalName' => 'anna.schmidt@firma.de',
'jobTitle' => 'Pflegedienstleitung',
'department' => 'Pflege',
'officeLocation' => 'Hamburg',
'businessPhones' => ['+49 40 123'],
'mobilePhone' => null,
'accountEnabled' => true,
'userType' => 'Member',
];
protected function entraProvider(array $config = [], bool $enabled = true): IdentityProvider
{
return IdentityProvider::query()->create([
'type' => IdentityProvider::ENTRA,
'name' => 'Microsoft Entra ID',
'slug' => 'entra',
'enabled' => $enabled,
'config' => array_merge([
'tenant_id' => $this->tenantId,
'client_id' => $this->clientId,
'client_secret' => 'geheim',
'auto_provision' => true,
'link_by_email' => true,
'synced_fields' => array_keys(IdentityProvider::SYNCABLE_FIELDS),
'sync_photo' => true,
'directory_sync' => false,
], $config),
]);
}
protected function entraKey()
{
return $this->entraKey ??= openssl_pkey_new(['private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA]);
}
/**
* @return array{keys: list<array<string, string>>}
*/
protected function entraJwks($key = null, ?string $kid = null): array
{
$details = openssl_pkey_get_details($key ?? $this->entraKey());
$b64 = fn (string $v) => rtrim(strtr(base64_encode($v), '+/', '-_'), '=');
return ['keys' => [[
'kty' => 'RSA', 'use' => 'sig', 'alg' => 'RS256', 'kid' => $kid ?? $this->entraKid,
'n' => $b64($details['rsa']['n']), 'e' => $b64($details['rsa']['e']),
]]];
}
protected function entraIdToken(string $nonce, array $claims = [], $key = null, ?string $kid = null): string
{
$payload = array_merge([
'iss' => 'https://login.microsoftonline.com/'.$this->tenantId.'/v2.0',
'aud' => $this->clientId,
'tid' => $this->tenantId,
'oid' => 'oid-anna',
'name' => 'Anna Schmidt',
'given_name' => 'Anna',
'family_name' => 'Schmidt',
'preferred_username' => 'anna.schmidt@firma.de',
'email' => 'anna.schmidt@firma.de',
'nonce' => $nonce,
'iat' => time(),
'nbf' => time(),
'exp' => time() + 3600,
], $claims);
openssl_pkey_export($key ?? $this->entraKey(), $pem);
return JWT::encode($payload, $pem, 'RS256', $kid ?? $this->entraKid);
}
/**
* Http::fake für den simulierten Mandanten. Das ID-Token trägt die Nonce aus der Sitzung.
*/
protected function fakeEntra(?callable $tokenOverride = null, ?array $jwks = null): void
{
Http::fake(function (Request $request) use ($tokenOverride, $jwks) {
$url = $request->url();
if (str_contains($url, '/oauth2/v2.0/token')) {
if ($request['grant_type'] === 'client_credentials') {
return Http::response(['access_token' => 'app-token', 'expires_in' => 3600]);
}
if ($tokenOverride) {
return $tokenOverride($request);
}
$nonce = session('identity_login.nonce') ?? $this->lastNonce ?? '';
return Http::response(['id_token' => $this->entraIdToken($nonce, $this->entraClaims), 'access_token' => 'user-token']);
}
if (str_contains($url, '/discovery/v2.0/keys')) {
return Http::response($jwks ?? $this->entraJwks());
}
if (str_starts_with($url, 'https://graph.microsoft.com/v1.0')) {
$path = substr($url, strlen('https://graph.microsoft.com/v1.0'));
foreach ($this->graph as $pattern => $response) {
if (str_starts_with(urldecode($path), $pattern)) {
return match (true) {
is_int($response) => Http::response(['error' => ['code' => 'x']], $response),
is_string($response) => Http::response($response, 200, ['Content-Type' => 'image/jpeg']),
is_callable($response) => $response($request),
default => Http::response($response),
};
}
}
if (str_starts_with($path, '/me?') || $path === '/me') {
return Http::response($this->graphUser);
}
return Http::response(['error' => ['code' => 'Request_ResourceNotFound']], 404);
}
return Http::response('unerwartete Anfrage: '.$url, 500);
});
}
protected ?string $lastNonce = null;
/**
* Kompletter Anmeldeablauf: Weiterleitung, dann Rückkehr mit Code.
*/
protected function loginWithEntra(IdentityProvider $provider, array $callbackOverrides = []): TestResponse
{
$this->get('/auth/'.$provider->slug.'/redirect');
$session = session('identity_login');
$this->lastNonce = $session['nonce'] ?? null;
return $this->get('/auth/'.$provider->slug.'/callback?'.http_build_query(array_merge([
'code' => 'auth-code',
'state' => $session['state'] ?? '',
], $callbackOverrides)));
}
protected function jpeg(string $color = 'red'): string
{
$image = imagecreatetruecolor(300, 300);
imagefill($image, 0, 0, $color === 'red' ? imagecolorallocate($image, 200, 0, 0) : imagecolorallocate($image, 0, 0, 200));
ob_start();
imagejpeg($image);
return (string) ob_get_clean();
}
}