Phase 6 (Teil 2): OpenID Connect, LDAP/AD und SAML 2
All checks were successful
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 2m41s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 2m48s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 3m15s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 3m17s
CI / PHP 8.3 / mysql:8.0 (pull_request) Successful in 3m48s
CI / PHP 8.4 / mysql:8.0 (pull_request) Successful in 3m41s
CI / PHP 8.3 / mysql:8.4 (pull_request) Successful in 3m33s
CI / Build-Artefakte aktuell (pull_request) Successful in 1m26s
CI / PHP 8.4 / mysql:8.4 (pull_request) Successful in 3m59s

- Gemeinsamer Treiber-Unterbau (App\Identity\IdentityDriver, IdentityDrivers,
  IdentityLogin, AttributeProfile); Entra ID nutzt ihn ebenfalls
- Plugins oidc, ldap und saml mit Profil- und Gruppen-Zuordnung
- Admin: Verfahren wählen, Formular je Verfahren, zuletzt empfangene Angaben
- onelogin/php-saml als neue Abhängigkeit

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-26 12:38:32 +00:00
parent 0ab0838050
commit 4fcc41ed30
172 changed files with 18940 additions and 293 deletions

View file

@ -0,0 +1,176 @@
<?php
namespace Tests\Feature\Identity;
use App\Filament\Resources\IdentityProviders\Pages\EditIdentityProvider;
use App\Models\IdentityProvider;
use App\Models\IdpGroupMapping;
use App\Models\Role;
use App\Models\User;
use Filament\Actions\Testing\TestAction;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\RateLimiter;
use Inertia\Testing\AssertableInertia as Assert;
use Inhaus\Plugins\Ldap\Connection\LdapConnector;
use Inhaus\Plugins\Ldap\LdapDirectory;
use Livewire\Livewire;
use Tests\Support\FakeLdap;
use Tests\TestCase;
class LdapLoginTest extends TestCase
{
use RefreshDatabase;
private FakeLdap $ldap;
private const ANNA = 'CN=Anna Schmidt,OU=Pflege,DC=firma,DC=local';
private const CHEF = 'CN=Clara Chefin,OU=Leitung,DC=firma,DC=local';
/** objectGUID 3f2504e0-4f89-11d3-9a0c-0305e82c3301 in AD-Byte-Reihenfolge */
private string $guid;
protected function setUp(): void
{
parent::setUp();
Cache::flush();
$this->ldap = new FakeLdap;
$this->app->instance(LdapConnector::class, $this->ldap);
$this->guid = hex2bin('e004253f894fd3119a0c0305e82c3301');
$this->ldap->add('CN=svc-portal,DC=firma,DC=local', 'dienst', []);
$this->ldap->add(self::ANNA, 'richtig', [
'objectGUID' => $this->guid,
'sAMAccountName' => 'aschmidt',
'userPrincipalName' => 'aschmidt@firma.local',
'givenName' => 'Anna', 'sn' => 'Schmidt', 'displayName' => 'Anna Schmidt',
'mail' => 'anna@firma.de', 'title' => 'Pflegedienstleitung', 'department' => 'Pflege',
'memberOf' => ['CN=GG-Pflege,OU=Gruppen,DC=firma,DC=local'],
'manager' => self::CHEF,
'thumbnailPhoto' => 'binär',
'userAccountControl' => '512',
]);
$this->ldap->add(self::CHEF, 'chef', ['objectGUID' => hex2bin('00112233445566778899aabbccddeeff'), 'sAMAccountName' => 'cchefin', 'mail' => 'clara@firma.de', 'givenName' => 'Clara', 'sn' => 'Chefin']);
$this->ldap->nestedGroups[self::ANNA] = ['CN=GG-Pflege,OU=Gruppen,DC=firma,DC=local', 'CN=Alle-Mitarbeitenden,OU=Gruppen,DC=firma,DC=local'];
}
private function provider(array $config = []): IdentityProvider
{
return IdentityProvider::query()->create([
'type' => 'ldap',
'name' => 'Active Directory',
'slug' => 'ad',
'enabled' => true,
'config' => array_merge([
'schema' => 'ad',
'hosts' => 'dc1.firma.local dc2.firma.local',
'encryption' => 'ldaps',
'base_dn' => 'DC=firma,DC=local',
'bind_dn' => 'CN=svc-portal,DC=firma,DC=local',
'bind_password' => 'dienst',
'group_search' => true,
'auto_provision' => true,
'sync_manager' => true,
'sync_photo' => false,
], $config),
]);
}
public function test_login_form_and_successful_login_with_profile_groups_and_manager(): void
{
$provider = $this->provider();
$role = Role::query()->create(['name' => 'Alle']);
$provider->mappings()->create(['kind' => IdpGroupMapping::GROUP, 'external_id' => 'cn=alle-mitarbeitenden,ou=gruppen,dc=firma,dc=local', 'role_id' => $role->id]);
// Vorgesetzte hat sich schon einmal angemeldet.
$this->post('/auth/ad/login', ['username' => 'cchefin', 'password' => 'chef']);
auth()->logout();
$this->get('/auth/ad/redirect')->assertOk()->assertInertia(fn (Assert $page) => $page
->component('Auth/DirectoryLogin')
->where('provider.label', 'Mit Firmenkonto anmelden'));
$this->post('/auth/ad/login', ['username' => 'aschmidt', 'password' => 'richtig'])->assertRedirect('/');
$user = User::query()->where('email', 'anna@firma.de')->sole();
$this->assertAuthenticatedAs($user);
$this->assertSame('Pflegedienstleitung', $user->job_title);
$this->assertSame('3f2504e0-4f89-11d3-9a0c-0305e82c3301', $user->identities()->value('subject'));
$this->assertSame(User::query()->where('email', 'clara@firma.de')->value('id'), $user->manager_id);
$this->assertTrue($user->roles()->whereKey($role->id)->exists(), 'Verschachtelte Gruppe, DN ohne Rücksicht auf Groß-/Kleinschreibung');
$this->assertSame(['dc1.firma.local', 'dc2.firma.local'], $this->ldap->lastOptions['hosts']);
}
public function test_wrong_password_and_empty_password_are_rejected(): void
{
$this->provider();
$this->from('/auth/ad/redirect')->post('/auth/ad/login', ['username' => 'aschmidt', 'password' => 'falsch'])
->assertRedirect('/auth/ad/redirect')->assertSessionHasErrors(['username' => 'Benutzername oder Passwort ist falsch.']);
$this->post('/auth/ad/login', ['username' => 'aschmidt', 'password' => ''])->assertSessionHasErrors('password');
$this->post('/auth/ad/login', ['username' => 'niemand', 'password' => 'x'])->assertSessionHasErrors(['username' => 'Benutzername oder Passwort ist falsch.']);
$this->assertGuest();
}
public function test_filter_injection_is_escaped(): void
{
$this->provider();
$this->post('/auth/ad/login', ['username' => '*)(sAMAccountName=*', 'password' => 'richtig'])->assertSessionHasErrors('username');
$this->assertGuest();
$this->assertStringContainsString('\2a\29\28sAMAccountName=\2a', $this->ldap->filters[0]);
}
public function test_disabled_directory_accounts_cannot_sign_in(): void
{
$this->provider();
$this->ldap->entries[self::ANNA]['attributes']['useraccountcontrol'] = ['514'];
$this->post('/auth/ad/login', ['username' => 'aschmidt', 'password' => 'richtig'])->assertSessionHasErrors('username');
$this->assertGuest();
}
public function test_attempts_are_rate_limited(): void
{
$this->provider();
RateLimiter::clear('x');
for ($i = 0; $i < 5; $i++) {
$this->post('/auth/ad/login', ['username' => 'aschmidt', 'password' => 'falsch']);
}
$this->post('/auth/ad/login', ['username' => 'aschmidt', 'password' => 'richtig'])
->assertSessionHasErrors(['username']);
$this->assertGuest();
}
public function test_openldap_preset_uses_entry_uuid_and_group_search(): void
{
$this->provider(['schema' => 'openldap']);
$this->ldap->add('uid=bernd,ou=people,dc=firma,dc=local', 'pw', ['uid' => 'bernd', 'entryUUID' => 'uuid-bernd', 'mail' => 'bernd@firma.de', 'givenName' => 'Bernd', 'sn' => 'Brot']);
$this->post('/auth/ad/login', ['username' => 'bernd', 'password' => 'pw'])->assertRedirect('/');
$this->assertSame('uuid-bernd', User::query()->where('email', 'bernd@firma.de')->sole()->identities()->value('subject'));
$this->assertStringContainsString('(memberUid=bernd)', end($this->ldap->filters));
}
public function test_admin_can_test_the_connection(): void
{
$provider = $this->provider();
$this->actingAs(User::factory()->admin()->create());
Livewire::test(EditIdentityProvider::class, ['record' => $provider->getRouteKey()])
->assertFormSet(['config.bind_password' => null])
->callAction(TestAction::make('testLdap')->schemaComponent('connection', 'form'), ['username' => 'aschmidt'])
->assertNotified();
}
public function test_guid_conversion(): void
{
$this->assertSame('3f2504e0-4f89-11d3-9a0c-0305e82c3301', LdapDirectory::guid($this->guid));
}
}

View file

@ -0,0 +1,227 @@
<?php
namespace Tests\Feature\Identity;
use App\Filament\Resources\IdentityProviders\Pages\CreateIdentityProvider;
use App\Filament\Resources\IdentityProviders\Pages\EditIdentityProvider;
use App\Identity\IdentityLogin;
use App\Models\IdentityProvider;
use App\Models\IdpGroupMapping;
use App\Models\Role;
use App\Models\User;
use Firebase\JWT\JWT;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Inertia\Testing\AssertableInertia as Assert;
use Livewire\Livewire;
use Tests\TestCase;
class OidcLoginTest extends TestCase
{
use RefreshDatabase;
private const ISSUER = 'https://login.firma.de/realms/portal';
private $key;
private array $claims = [];
private array $userinfo = [];
private string $nonce = '';
protected function setUp(): void
{
parent::setUp();
Cache::flush();
$this->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();
}
}

View file

@ -0,0 +1,212 @@
<?php
namespace Tests\Feature\Identity;
use App\Filament\Resources\IdentityProviders\Pages\CreateIdentityProvider;
use App\Models\IdentityProvider;
use App\Models\IdpGroupMapping;
use App\Models\Role;
use App\Models\User;
use DOMDocument;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Livewire\Livewire;
use RobRichards\XMLSecLibs\XMLSecurityDSig;
use RobRichards\XMLSecLibs\XMLSecurityKey;
use Tests\TestCase;
class SamlLoginTest extends TestCase
{
use RefreshDatabase;
private const IDP = 'https://adfs.firma.de/adfs/services/trust';
private string $keyPem = '';
private string $certPem = '';
protected function setUp(): void
{
parent::setUp();
Cache::flush();
$key = openssl_pkey_new(['private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA]);
$cert = openssl_csr_sign(openssl_csr_new(['commonName' => 'adfs.firma.de'], $key), null, $key, 30, ['digest_alg' => 'sha256']);
openssl_pkey_export($key, $this->keyPem);
openssl_x509_export($cert, $this->certPem);
}
private function provider(array $config = []): IdentityProvider
{
return IdentityProvider::query()->create([
'type' => 'saml',
'name' => 'ADFS',
'slug' => 'adfs',
'enabled' => true,
'config' => array_merge([
'idp_entity_id' => self::IDP,
'idp_sso_url' => 'https://adfs.firma.de/adfs/ls/',
'idp_certificates' => $this->certPem,
'groups_attribute' => 'http://schemas.microsoft.com/ws/2008/06/identity/claims/groups',
'auto_provision' => true,
'attribute_map' => [
['target' => 'first_name', 'attribute' => 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname'],
['target' => 'last_name', 'attribute' => 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname'],
['target' => 'email', 'attribute' => 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress'],
['target' => 'department', 'attribute' => 'urn:oid:2.5.4.11'],
],
], $config),
]);
}
/**
* Anmeldung starten; liefert die Kennung der AuthnRequest und den RelayState.
*
* @return array{0: string, 1: string}
*/
private function start(): array
{
$location = $this->get('/auth/adfs/redirect')->assertRedirect()->headers->get('Location');
$this->assertStringStartsWith('https://adfs.firma.de/adfs/ls/?SAMLRequest=', $location);
parse_str((string) parse_url($location, PHP_URL_QUERY), $query);
preg_match('/ID="([^"]+)"/', gzinflate(base64_decode($query['SAMLRequest'])), $m);
return [$m[1], $query['RelayState'] ?? ''];
}
private function response(string $inResponseTo, array $overrides = [], ?callable $tamper = null): string
{
$acs = url('/auth/adfs/callback');
$o = array_merge(['destination' => $acs, 'audience' => url('/auth/adfs/metadata'), 'issuer' => self::IDP, 'assertion_id' => '_a'.bin2hex(random_bytes(8))], $overrides);
$now = gmdate('Y-m-d\TH:i:s\Z');
$later = gmdate('Y-m-d\TH:i:s\Z', time() + 300);
$before = gmdate('Y-m-d\TH:i:s\Z', time() - 60);
$attr = fn (string $name, array $values) => '<saml:Attribute Name="'.$name.'">'.implode('', array_map(fn ($v) => '<saml:AttributeValue>'.htmlspecialchars($v).'</saml:AttributeValue>', $values)).'</saml:Attribute>';
$assertion = '<saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="'.$o['assertion_id'].'" Version="2.0" IssueInstant="'.$now.'">'
.'<saml:Issuer>'.$o['issuer'].'</saml:Issuer>'
.'<saml:Subject><saml:NameID Format="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent">anna-4711</saml:NameID>'
.'<saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer"><saml:SubjectConfirmationData InResponseTo="'.$inResponseTo.'" NotOnOrAfter="'.$later.'" Recipient="'.$o['destination'].'"/></saml:SubjectConfirmation></saml:Subject>'
.'<saml:Conditions NotBefore="'.$before.'" NotOnOrAfter="'.$later.'"><saml:AudienceRestriction><saml:Audience>'.$o['audience'].'</saml:Audience></saml:AudienceRestriction></saml:Conditions>'
.'<saml:AuthnStatement AuthnInstant="'.$now.'" SessionIndex="_s1"><saml:AuthnContext><saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</saml:AuthnContextClassRef></saml:AuthnContext></saml:AuthnStatement>'
.'<saml:AttributeStatement>'
.$attr('http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname', ['Anna'])
.$attr('http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname', ['Schmidt'])
.$attr('http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress', ['anna@firma.de'])
.$attr('urn:oid:2.5.4.11', ['Pflege'])
.$attr('http://schemas.microsoft.com/ws/2008/06/identity/claims/groups', ['GG-Pflege', 'GG-MAV'])
.'</saml:AttributeStatement></saml:Assertion>';
$doc = new DOMDocument;
$doc->loadXML($assertion);
$dsig = new XMLSecurityDSig;
$dsig->setCanonicalMethod(XMLSecurityDSig::EXC_C14N);
$dsig->addReference($doc->documentElement, XMLSecurityDSig::SHA256, ['http://www.w3.org/2000/09/xmldsig#enveloped-signature', XMLSecurityDSig::EXC_C14N], ['id_name' => 'ID', 'overwrite' => false]);
$key = new XMLSecurityKey(XMLSecurityKey::RSA_SHA256, ['type' => 'private']);
$key->loadKey($this->keyPem);
$dsig->sign($key);
$dsig->add509Cert($this->certPem);
$dsig->insertSignature($doc->documentElement, $doc->getElementsByTagName('Issuer')->item(0)->nextSibling);
$signed = $doc->saveXML($doc->documentElement);
if ($tamper) {
$signed = $tamper($signed);
}
$xml = '<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="_r'.bin2hex(random_bytes(8)).'" Version="2.0" IssueInstant="'.$now.'" Destination="'.$o['destination'].'" InResponseTo="'.$inResponseTo.'">'
.'<saml:Issuer>'.$o['issuer'].'</saml:Issuer>'
.'<samlp:Status><samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/></samlp:Status>'
.$signed.'</samlp:Response>';
return base64_encode($xml);
}
public function test_signed_response_signs_in_with_profile_groups_and_relay_state(): void
{
$provider = $this->provider();
$mav = Role::query()->create(['name' => 'MAV']);
$provider->mappings()->create(['kind' => IdpGroupMapping::GROUP, 'external_id' => 'GG-MAV', 'role_id' => $mav->id]);
$this->get('/neuigkeiten'); // gemerkte Seite
[$requestId, $relay] = $this->start();
$this->assertSame('/neuigkeiten', $relay);
// Cross-Site-POST: ohne Sitzungs-Cookie und ohne CSRF-Token.
$this->flushSession();
$this->post('/auth/adfs/callback', ['SAMLResponse' => $this->response($requestId), 'RelayState' => $relay])
->assertSessionMissing('identity_error')
->assertRedirect('/neuigkeiten');
$user = User::query()->where('email', 'anna@firma.de')->sole();
$this->assertAuthenticatedAs($user);
$this->assertSame('Pflege', $user->department);
$this->assertSame('anna-4711', $user->identities()->value('subject'));
$this->assertTrue($user->roles()->whereKey($mav->id)->exists());
}
public function test_responses_are_single_use_and_must_be_requested(): void
{
$this->provider();
[$requestId] = $this->start();
$response = $this->response($requestId);
$this->post('/auth/adfs/callback', ['SAMLResponse' => $response])->assertRedirect('/');
auth()->logout();
$this->post('/auth/adfs/callback', ['SAMLResponse' => $response])->assertRedirect('/login')->assertSessionHas('identity_error');
$this->post('/auth/adfs/callback', ['SAMLResponse' => $this->response('_nie-angefragt')])->assertRedirect('/login')->assertSessionHas('identity_error');
$this->assertGuest();
}
public function test_tampered_or_misdirected_responses_are_rejected(): void
{
$this->provider();
$cases = [
'manipuliert' => [[], fn (string $xml) => str_replace('>Pflege<', '>Geschäftsführung<', $xml)],
'fremdes Ziel' => [['destination' => 'https://anderes-portal.de/acs'], null],
'andere Zielgruppe' => [['audience' => 'https://anderes-portal.de'], null],
'fremder Aussteller' => [['issuer' => 'https://boese.example'], null],
];
foreach ($cases as $label => [$overrides, $tamper]) {
[$requestId] = $this->start();
$this->post('/auth/adfs/callback', ['SAMLResponse' => $this->response($requestId, $overrides, $tamper)])
->assertRedirect('/login')->assertSessionHas('identity_error');
$this->assertFalse(auth()->check(), $label);
}
}
public function test_foreign_relay_states_are_ignored(): void
{
$this->provider();
[$requestId] = $this->start();
$this->post('/auth/adfs/callback', ['SAMLResponse' => $this->response($requestId), 'RelayState' => '//boese.example/phish'])->assertRedirect('/');
}
public function test_metadata_describes_the_service_provider(): void
{
$this->provider();
$this->get('/auth/adfs/metadata')->assertOk()
->assertHeader('Content-Type', 'application/samlmetadata+xml')
->assertSee('entityID="'.url('/auth/adfs/metadata').'"', false)
->assertSee('Location="'.url('/auth/adfs/callback').'"', false)
->assertSee('WantAssertionsSigned="true"', false);
}
public function test_admin_rejects_unreadable_certificates(): void
{
$this->actingAs(User::factory()->admin()->create());
Livewire::withQueryParams(['typ' => 'saml'])->test(CreateIdentityProvider::class)
->fillForm(['name' => 'ADFS', 'config' => ['idp_entity_id' => self::IDP, 'idp_sso_url' => 'https://adfs.firma.de/adfs/ls/', 'idp_certificates' => "-----BEGIN CERTIFICATE-----\nkaputt\n-----END CERTIFICATE-----"]])
->call('create')
->assertHasFormErrors(['config.idp_certificates']);
Livewire::withQueryParams(['typ' => 'saml'])->test(CreateIdentityProvider::class)
->fillForm(['name' => 'ADFS', 'config' => ['idp_entity_id' => self::IDP, 'idp_sso_url' => 'https://adfs.firma.de/adfs/ls/', 'idp_certificates' => $this->certPem]])
->call('create')
->assertHasNoFormErrors();
}
}

View file

@ -0,0 +1,91 @@
<?php
namespace Tests\Support;
use Inhaus\Plugins\Ldap\Connection\LdapConnection;
use Inhaus\Plugins\Ldap\Connection\LdapConnector;
use Inhaus\Plugins\Ldap\LdapDirectory;
/**
* Simuliertes Verzeichnis: Einträge mit Passwörtern, Gruppen je Person.
* Die Suche wertet nur „(attribut=wert)“-Paare aus – genug, um Filter und
* Maskierung zu prüfen.
*/
class FakeLdap implements LdapConnection, LdapConnector
{
/** @var array<string, array{password: ?string, attributes: array<string, list<string>>}> DN => Eintrag */
public array $entries = [];
/** @var array<string, list<string>> Personen-DN => Gruppen-DNs (verschachtelte Suche) */
public array $nestedGroups = [];
/** @var list<string> */
public array $filters = [];
/** @var list<?string> */
public array $binds = [];
public array $lastOptions = [];
public function connect(array $options): LdapConnection
{
$this->lastOptions = $options;
return $this;
}
public function add(string $dn, ?string $password, array $attributes): void
{
$this->entries[$dn] = ['password' => $password, 'attributes' => array_change_key_case(array_map(fn ($v) => (array) $v, $attributes))];
}
public function bind(?string $dn, ?string $password): bool
{
$this->binds[] = $dn;
if ($dn === null) {
return true;
}
return isset($this->entries[$dn]) && $this->entries[$dn]['password'] !== null && $password !== '' && hash_equals($this->entries[$dn]['password'], (string) $password);
}
public function search(string $base, string $filter, array $attributes, int $limit = 0): array
{
$this->filters[] = $filter;
if (str_contains($filter, 'member:1.2.840.113556.1.4.1941:=')) {
foreach ($this->nestedGroups as $dn => $groups) {
if (str_contains($filter, '='.LdapDirectory::escape($dn).')')) {
return array_map(fn ($g) => ['dn' => $g, 'attributes' => []], $groups);
}
}
return [];
}
$found = [];
foreach ($this->entries as $dn => $entry) {
foreach (['samaccountname', 'userprincipalname', 'mail', 'uid'] as $attribute) {
foreach ($entry['attributes'][$attribute] ?? [] as $value) {
if (preg_match('/\('.$attribute.'='.preg_quote(LdapDirectory::escape($value), '/').'\)/i', $filter)) {
$found[$dn] = ['dn' => $dn, 'attributes' => $entry['attributes']];
}
}
}
}
return array_values($found);
}
public function read(string $dn, array $attributes): ?array
{
return isset($this->entries[$dn]) ? ['dn' => $dn, 'attributes' => $this->entries[$dn]['attributes']] : null;
}
public function lastError(): string
{
return '';
}
}