key = openssl_pkey_new(['private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA]); } private function provider(array $config = []): IdentityProvider { return IdentityProvider::query()->create([ 'type' => 'oidc', 'name' => 'Keycloak', 'slug' => 'keycloak', 'enabled' => true, 'config' => array_merge([ 'issuer' => self::ISSUER, 'client_id' => 'portal', 'client_secret' => 'geheim', 'groups_claim' => 'groups', 'auto_provision' => true, 'link_by_email' => true, 'use_userinfo' => true, 'attribute_map' => [ ['target' => 'first_name', 'attribute' => 'given_name'], ['target' => 'last_name', 'attribute' => 'family_name'], ['target' => 'email', 'attribute' => 'email'], ['target' => 'department', 'attribute' => 'org.department'], ], ], $config), ]); } private function fakeIssuer(): void { $b64 = fn (string $v) => rtrim(strtr(base64_encode($v), '+/', '-_'), '='); $details = openssl_pkey_get_details($this->key); Http::fake(function (Request $request) use ($b64, $details) { return match (true) { str_ends_with($request->url(), '/.well-known/openid-configuration') => Http::response([ 'issuer' => self::ISSUER, 'authorization_endpoint' => self::ISSUER.'/protocol/openid-connect/auth', 'token_endpoint' => self::ISSUER.'/protocol/openid-connect/token', 'userinfo_endpoint' => self::ISSUER.'/protocol/openid-connect/userinfo', 'jwks_uri' => self::ISSUER.'/protocol/openid-connect/certs', ]), str_ends_with($request->url(), '/certs') => Http::response(['keys' => [[ 'kty' => 'RSA', 'use' => 'sig', 'kid' => 'k1', 'n' => $b64($details['rsa']['n']), 'e' => $b64($details['rsa']['e']), ]]]), str_ends_with($request->url(), '/token') => Http::response(['id_token' => $this->idToken(), 'access_token' => 'at', 'token_type' => 'Bearer']), str_ends_with($request->url(), '/userinfo') => Http::response($this->userinfo), default => Http::response([], 404), }; }); } private function idToken(): string { return JWT::encode(array_merge([ 'iss' => self::ISSUER, 'aud' => 'portal', 'sub' => 'kc-anna', 'nonce' => $this->nonce, 'iat' => time(), 'exp' => time() + 300, 'given_name' => 'Anna', 'family_name' => 'Schmidt', 'name' => 'Anna Schmidt', 'email' => 'anna@firma.de', 'email_verified' => true, 'groups' => ['/Pflege', '/MAV'], ], $this->claims), openssl_pkey_get_private($this->key), 'RS256', 'k1'); } private function login(IdentityProvider $provider) { $redirect = $this->get('/auth/'.$provider->slug.'/redirect'); $redirect->assertRedirect(); parse_str((string) parse_url($redirect->headers->get('Location'), PHP_URL_QUERY), $query); $this->nonce = $query['nonce']; return [$this->get('/auth/'.$provider->slug.'/callback?code=abc&state='.$query['state']), $query]; } public function test_login_creates_account_with_profile_and_roles_from_groups(): void { $this->fakeIssuer(); $provider = $this->provider(); $mav = Role::query()->create(['name' => 'MAV']); $provider->mappings()->create(['kind' => IdpGroupMapping::GROUP, 'external_id' => '/mav', 'role_id' => $mav->id]); $this->userinfo = ['sub' => 'kc-anna', 'org' => ['department' => 'Pflege']]; [$response, $query] = $this->login($provider); $response->assertRedirect('/')->assertSessionMissing('identity_error'); $this->assertSame('S256', $query['code_challenge_method']); $this->assertSame('openid profile email', $query['scope']); $user = User::query()->where('email', 'anna@firma.de')->sole(); $this->assertAuthenticatedAs($user); $this->assertSame('Pflege', $user->department, 'Verschachtelter Claim aus UserInfo'); $this->assertTrue($user->roles()->whereKey($mav->id)->exists(), 'Gruppe ohne Rücksicht auf Groß-/Kleinschreibung'); Http::assertSent(fn (Request $r) => str_ends_with($r->url(), '/token') && $r->hasHeader('Authorization', 'Basic '.base64_encode('portal:geheim'))); $seen = IdentityLogin::lastSeen($provider); $this->assertSame('kc-anna', $seen['subject']); $this->assertSame('Pflege', json_decode($seen['attributes']['org'], true)['department'] ?? null); } public function test_tokens_from_other_issuers_or_clients_are_rejected(): void { $this->fakeIssuer(); $provider = $this->provider(); foreach ([['iss' => 'https://boese.example'], ['aud' => 'andere-app'], ['nonce' => 'falsch']] as $claims) { $this->claims = $claims; [$response] = $this->login($provider); $response->assertRedirect('/login')->assertSessionHas('identity_error'); $this->assertGuest(); } } public function test_state_must_match(): void { $this->fakeIssuer(); $provider = $this->provider(); $this->get('/auth/keycloak/redirect'); $this->get('/auth/keycloak/callback?code=abc&state=manipuliert')->assertRedirect('/login') ->assertSessionHas('identity_error', 'Die Anmeldung ist abgelaufen. Bitte erneut versuchen.'); } public function test_unverified_email_never_links_existing_accounts(): void { $this->fakeIssuer(); $provider = $this->provider(['auto_provision' => false]); $admin = User::factory()->admin()->create(['email' => 'anna@firma.de']); $this->claims = ['email_verified' => false]; [$response] = $this->login($provider); $response->assertRedirect('/login'); $this->assertGuest(); $this->assertSame(0, $admin->identities()->count()); } public function test_login_page_lists_plugin_providers(): void { $this->provider(['button_label' => 'Mit Firmenkonto anmelden']); $this->get('/login')->assertInertia(fn (Assert $page) => $page ->where('providers.0.label', 'Mit Firmenkonto anmelden') ->where('providers.0.type', 'oidc')); } public function test_admin_connects_an_oidc_provider(): void { $this->actingAs(User::factory()->admin()->create()); Livewire::withQueryParams(['typ' => 'oidc'])->test(CreateIdentityProvider::class) ->fillForm([ 'name' => 'Keycloak', 'enabled' => true, 'config' => ['issuer' => self::ISSUER, 'client_id' => 'portal', 'client_secret' => 'sehr-geheim'], ]) ->call('create') ->assertHasNoFormErrors(); $provider = IdentityProvider::query()->sole(); $this->assertSame('oidc', $provider->type); $this->assertSame('given_name', $provider->attributeMap()['first_name']); // Geheimnis nie im Formular, leer lassen behält es. Livewire::test(EditIdentityProvider::class, ['record' => $provider->getRouteKey()]) ->assertFormSet(['config.client_secret' => null]) ->fillForm(['name' => 'Keycloak intern']) ->call('save') ->assertHasNoFormErrors(); $this->assertSame('sehr-geheim', $provider->fresh()->setting('client_secret')); $this->get('/admin/anmeldung')->assertOk()->assertSee('OpenID Connect'); $this->get('/admin/anmeldung/'.$provider->id.'/testen')->assertNotFound(); } public function test_unknown_types_cannot_be_created(): void { $this->actingAs(User::factory()->admin()->create()); $this->get('/admin/anmeldung/neu?typ=kerberos')->assertNotFound(); } }