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>
212 lines
11 KiB
PHP
212 lines
11 KiB
PHP
<?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();
|
|
}
|
|
}
|