Loheide-eu-mitarbeiterplatt.../tests/Feature/Identity/EntraAttributeMappingTest.php
Friederich Loheide 2b5fe55f8e
All checks were successful
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 2m40s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 2m23s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 2m53s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 2m47s
CI / PHP 8.3 / mysql:8.0 (pull_request) Successful in 3m2s
CI / PHP 8.4 / mysql:8.0 (pull_request) Successful in 3m5s
CI / PHP 8.3 / mysql:8.4 (pull_request) Successful in 2m50s
CI / PHP 8.4 / mysql:8.4 (pull_request) Successful in 2m41s
CI / Build-Artefakte aktuell (pull_request) Successful in 1m6s
MySQL: JSON-Schlüsselreihenfolge darf keine Rolle spielen
MySQL speichert Schlüssel in JSON-Spalten sortiert, MariaDB unverändert.
- Seiten: „Stand unverändert → kein Entwurf“ vergleicht jetzt unabhängig von der
  Schlüsselreihenfolge (auf MySQL entstand sonst bei jedem Speichern ein Entwurf)
- Formulare: Antworten in Ergebnisansicht und E-Mail in der Reihenfolge des Formulars
- Tests vergleichen assoziative Arrays ohne Reihenfolge; neue Tests dafür

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-26 11:22:46 +00:00

250 lines
12 KiB
PHP

<?php
namespace Tests\Feature\Identity;
use App\Filament\Resources\IdentityProviders\Pages\EditIdentityProvider;
use App\Identity\Entra\EntraAttributes;
use App\Identity\Entra\EntraDirectorySync;
use App\Models\ProfileField;
use App\Models\User;
use App\Models\UserIdentity;
use Filament\Actions\Testing\TestAction;
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 Livewire\Livewire;
use Tests\Support\FakeEntra;
use Tests\TestCase;
class EntraAttributeMappingTest extends TestCase
{
use FakeEntra;
use RefreshDatabase;
private const EXT = 'extension_0a1b2c3d4e5f60718293a4b5c6d7e8f9_eintritt';
protected function setUp(): void
{
parent::setUp();
Storage::fake('uploads');
Cache::flush();
ProfileField::query()->create(['key' => 'personalnummer', 'label' => 'Personalnummer', 'visibility' => 'restricted', 'editable' => false]);
ProfileField::query()->create(['key' => 'kostenstelle', 'label' => 'Kostenstelle']);
ProfileField::query()->create(['key' => 'eintritt', 'label' => 'Eintrittsdatum', 'type' => 'date']);
ProfileField::query()->create(['key' => 'station', 'label' => 'Station']);
ProfileField::query()->create(['key' => 'sprachen', 'label' => 'Sprachen']);
$this->graphUser += [
'employeeId' => 'P-4711',
'employeeOrgData' => ['costCenter' => 'KST 300', 'division' => 'Pflege'],
'onPremisesExtensionAttributes' => ['extensionAttribute3' => 'Station 4B', 'extensionAttribute4' => null],
self::EXT => '2019-04-01T00:00:00Z',
'otherMails' => ['a@x.de', 'b@x.de'],
];
}
private function mappedProvider(array $config = [])
{
return $this->entraProvider(array_merge([
'attribute_map' => [
['target' => 'first_name', 'attribute' => 'givenName'],
['target' => 'last_name', 'attribute' => 'surname'],
['target' => 'email', 'attribute' => 'mail'],
['target' => 'job_title', 'attribute' => 'employeeOrgData.division'],
['target' => 'custom.personalnummer', 'attribute' => 'employeeId'],
['target' => 'custom.kostenstelle', 'attribute' => 'employeeOrgData.costCenter'],
['target' => 'custom.eintritt', 'attribute' => self::EXT],
['target' => 'custom.station', 'attribute' => 'onPremisesExtensionAttributes.extensionAttribute3'],
['target' => 'custom.sprachen', 'attribute' => 'otherMails'],
],
'sync_manager' => false,
], $config));
}
public function test_any_graph_attribute_can_be_mapped_on_login(): void
{
$provider = $this->mappedProvider();
$this->entraClaims = ['groups' => ['x']];
$this->fakeEntra();
$this->loginWithEntra($provider)->assertRedirect('/');
$user = User::query()->sole();
$this->assertSame('Pflege', $user->job_title, 'Kernfelder lassen sich auf andere Attribute umlegen.');
$this->assertNull($user->department, 'Nicht zugeordnete Kernfelder bleiben unberührt.');
$this->assertEquals([
'personalnummer' => 'P-4711',
'kostenstelle' => 'KST 300',
'eintritt' => '2019-04-01',
'station' => 'Station 4B',
'sprachen' => 'a@x.de, b@x.de',
], $user->custom_fields);
Http::assertSent(function (Request $r) {
if (! str_contains($r->url(), 'graph.microsoft.com/v1.0/me?')) {
return false;
}
parse_str((string) parse_url($r->url(), PHP_URL_QUERY), $query);
$select = explode(',', $query['$select']);
return in_array('employeeOrgData', $select, true)
&& in_array('onPremisesExtensionAttributes', $select, true)
&& in_array(self::EXT, $select, true)
&& ! in_array('department', $select, true);
});
}
public function test_missing_permission_for_an_attribute_falls_back_to_base_attributes(): void
{
$provider = $this->mappedProvider();
$this->entraClaims = ['groups' => ['x']];
$this->graph = ['/me?$select=id,displayName,givenName,surname,mail,userPrincipalName,accountEnabled,userType,' => 403];
$this->fakeEntra();
$this->loginWithEntra($provider)->assertRedirect('/');
$this->assertSame('anna.schmidt@firma.de', User::query()->sole()->email);
}
public function test_mapped_custom_fields_are_read_only_and_others_can_be_edited(): void
{
$provider = $this->mappedProvider(['attribute_map' => [['target' => 'custom.kostenstelle', 'attribute' => 'employeeOrgData.costCenter']]]);
$this->entraClaims = ['groups' => ['x']];
$this->fakeEntra();
$this->loginWithEntra($provider);
$this->get('/profil/bearbeiten')->assertInertia(fn (Assert $page) => $page
->where('managed', ['custom.kostenstelle'])
->where('customFields', fn ($fields) => collect($fields)->mapWithKeys(fn ($f) => [$f['key'] => [$f['readonly'], $f['managed']]])->all() === [
'eintritt' => [false, false],
'kostenstelle' => [true, true],
'personalnummer' => [true, false],
'sprachen' => [false, false],
'station' => [false, false],
]));
$this->put('/profil', [
'first_name' => 'Anna', 'last_name' => 'Schmidt', 'email' => 'anna.schmidt@firma.de',
'custom_fields' => ['personalnummer' => 'gefälscht', 'kostenstelle' => 'gefälscht', 'station' => '3A', 'eintritt' => '2020-01-15'],
])->assertSessionHasNoErrors();
$this->assertEquals(['kostenstelle' => 'KST 300', 'station' => '3A', 'eintritt' => '2020-01-15'], User::query()->sole()->custom_fields);
$this->put('/profil', [
'first_name' => 'Anna', 'last_name' => 'Schmidt', 'email' => 'anna.schmidt@firma.de',
'custom_fields' => ['eintritt' => 'kein Datum'],
])->assertSessionHasErrors('custom_fields.eintritt');
}
public function test_restricted_fields_are_only_visible_to_the_person_and_hr(): void
{
$anna = User::factory()->create(['custom_fields' => ['personalnummer' => 'P-4711', 'station' => '4B', 'eintritt' => '2019-04-01']]);
$this->actingAs(User::factory()->create())->get('/personen/'.$anna->id)->assertInertia(fn (Assert $page) => $page
->where('person.fields', [
['key' => 'eintritt', 'label' => 'Eintrittsdatum', 'type' => 'date', 'value' => '01.04.2019'],
['key' => 'station', 'label' => 'Station', 'type' => 'text', 'value' => '4B'],
]));
$this->actingAs($anna)->get('/personen/'.$anna->id)
->assertInertia(fn (Assert $page) => $page->where('person.fields.0.key', 'eintritt')->where('person.fields.1.key', 'personalnummer'));
$this->actingAs(User::factory()->admin()->create())->get('/personen/'.$anna->id)
->assertInertia(fn (Assert $page) => $page->has('person.fields', 3));
}
public function test_delta_sync_maps_attributes_and_keeps_absent_ones(): void
{
$provider = $this->mappedProvider(['directory_sync' => true, 'sync_photo' => false]);
$user = User::factory()->create(['job_title' => 'bleibt', 'custom_fields' => ['personalnummer' => 'P-1', 'station' => 'alt']]);
UserIdentity::query()->create(['user_id' => $user->id, 'identity_provider_id' => $provider->id, 'subject' => 'oid-anna']);
$this->graph = ['/users/delta' => ['value' => [[
'id' => 'oid-anna',
'onPremisesExtensionAttributes' => ['extensionAttribute3' => null],
'employeeId' => 'P-2',
]], '@odata.deltaLink' => 'https://graph.microsoft.com/v1.0/users/delta?$deltatoken=abc']];
$this->fakeEntra();
app(EntraDirectorySync::class)->run($provider->fresh());
$user->refresh();
$this->assertSame('bleibt', $user->job_title);
$this->assertSame(['personalnummer' => 'P-2'], $user->custom_fields, 'Geleerte Attribute entfernen den Wert.');
Http::assertSent(fn (Request $r) => str_contains(urldecode($r->url()), '/users/delta?$select=') && str_contains(urldecode($r->url()), self::EXT));
}
public function test_changing_the_mapping_restarts_the_delta_sync(): void
{
$provider = $this->mappedProvider(['directory_sync' => true, 'sync_photo' => false]);
$this->graph = ['/users/delta' => ['value' => [], '@odata.deltaLink' => 'https://graph.microsoft.com/v1.0/users/delta?$deltatoken=abc']];
$this->fakeEntra();
app(EntraDirectorySync::class)->run($provider->fresh());
$provider->update(['config' => array_merge($provider->config, ['attribute_map' => [['target' => 'custom.station', 'attribute' => 'city']]])]);
app(EntraDirectorySync::class)->run($provider->fresh());
Http::assertSent(fn (Request $r) => str_contains(urldecode($r->url()), '/users/delta?$select=') && str_contains($r->url(), 'city'));
}
public function test_legacy_field_list_still_works(): void
{
$provider = $this->entraProvider(['synced_fields' => ['job_title', 'phone', 'manager']]);
$this->assertSame(['job_title' => 'jobTitle', 'phone' => 'businessPhones.0'], $provider->attributeMap());
$this->assertTrue($provider->syncsManager());
$this->assertSame(['job_title', 'phone', 'manager'], $provider->syncedFields());
}
public function test_attribute_values_are_read_from_paths(): void
{
$user = ['a' => ['b' => ['c' => 'tief']], 'list' => ['x', '', 'y'], 'flag' => true, 'empty' => ' '];
$this->assertSame('tief', EntraAttributes::value($user, 'a.b.c'));
$this->assertSame('x, y', EntraAttributes::value($user, 'list'));
$this->assertSame('x', EntraAttributes::value($user, 'list.0'));
$this->assertSame('Ja', EntraAttributes::value($user, 'flag'));
$this->assertNull(EntraAttributes::value($user, 'empty'));
$this->assertNull(EntraAttributes::value($user, 'a.fehlt'));
}
public function test_admin_maps_attributes_and_loads_directory_extensions(): void
{
$this->actingAs(User::factory()->admin()->create());
$provider = $this->entraProvider(['synced_fields' => ['job_title']]);
$this->graph = ['/directoryObjects/getAvailableExtensionProperties' => ['value' => [
['name' => self::EXT, 'targetObjects' => ['User']],
['name' => 'extension_0a1b_gruppenfeld', 'targetObjects' => ['Group']],
]]];
$this->fakeEntra();
$page = Livewire::test(EditIdentityProvider::class, ['record' => $provider->getRouteKey()])
->assertFormSet(['config.sync_manager' => false])
->callAction(TestAction::make('loadExtensions')->schemaComponent('profile', schema: 'form'))
->assertNotified();
$this->assertSame([self::EXT], $provider->fresh()->setting('extension_properties'));
$page->fillForm(['config.attribute_map' => [
['target' => 'job_title', 'attribute' => 'jobTitle'],
['target' => 'custom.eintritt', 'attribute' => self::EXT],
]])->call('save')->assertHasNoFormErrors();
$provider->refresh();
$this->assertSame(['job_title' => 'jobTitle', 'custom.eintritt' => self::EXT], $provider->attributeMap());
$this->assertSame([self::EXT], $provider->setting('extension_properties'), 'Geladene Erweiterungen bleiben beim Speichern erhalten.');
$this->assertNull($provider->setting('synced_fields'));
Livewire::test(EditIdentityProvider::class, ['record' => $provider->getRouteKey()])
->fillForm(['config.attribute_map' => [['target' => 'job_title', 'attribute' => 'job title; drop']]])
->call('save')
->assertHasFormErrors();
}
}