Loheide-eu-mitarbeiterplatt.../tests/Support/FakeEntra.php
Friederich Loheide 51c94cd0cf
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
Anmeldung mit Microsoft Entra ID
- 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>
2026-09-26 07:52:22 +00:00

187 lines
6.8 KiB
PHP

<?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();
}
}