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>
335 lines
14 KiB
PHP
335 lines
14 KiB
PHP
<?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);
|
||
}
|
||
}
|