Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 1m43s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 1m52s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 1m49s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 1m49s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 2m12s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 2m22s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 1m57s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 1m59s
CI / Build-Artefakte aktuell (pull_request) Successful in 57s
- Profilfelder frei definierbar (Typ, Sichtbarkeit, selbst pflegbar), Werte als JSON am Benutzer - Attribut-Zuordnung je Anbieter statt fester Feldliste: jedes Graph-Attribut inkl. verschachtelter Pfade, onPremisesExtensionAttributes und Verzeichniserweiterungen - Erweiterungsattribute per Knopf aus Entra laden - $select dynamisch aus der Zuordnung; Delta-Abgleich startet bei geänderter Zuordnung neu - Rückfall auf Grundattribute, wenn einzelne Attribute nicht lesbar sind - Ältere Konfiguration (synced_fields) wird weiter gelesen Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
280 lines
11 KiB
PHP
280 lines
11 KiB
PHP
<?php
|
||
|
||
namespace App\Identity\Entra;
|
||
|
||
use App\Identity\IdentityException;
|
||
use App\Identity\IdentitySync;
|
||
use App\Models\IdentityProvider;
|
||
use App\Models\IdpGroupMapping;
|
||
use App\Models\UserIdentity;
|
||
use App\Support\Settings;
|
||
use Illuminate\Support\Facades\Log;
|
||
use Throwable;
|
||
|
||
/**
|
||
* Hintergrund-Abgleich mit Entra ID – ohne dass sich jemand anmelden muss.
|
||
*
|
||
* - Benutzer per Delta-Abfrage (/users/delta): nur Änderungen seit dem letzten
|
||
* Lauf; deaktivierte oder gelöschte Konten werden im Portal deaktiviert
|
||
* (Offboarding). Optional werden neue Konten vorab angelegt.
|
||
* - Fotos und Vorgesetzte rollierend in kleinen Portionen.
|
||
* - Gruppen- und App-Rollen-Zuordnungen stündlich für alle verknüpften Konten.
|
||
*
|
||
* Arbeitet mit Zeitbudget und setzt beim nächsten Lauf fort (Shared Hosting,
|
||
* Pseudo-Cron). Benötigt Anwendungsberechtigungen User.Read.All und
|
||
* GroupMember.Read.All (Administratorzustimmung).
|
||
*/
|
||
class EntraDirectorySync
|
||
{
|
||
public const PHOTOS_PER_RUN = 25;
|
||
|
||
public const GROUP_SYNC_INTERVAL = 3600;
|
||
|
||
public function __construct(
|
||
private readonly IdentitySync $sync,
|
||
private readonly Settings $settings,
|
||
) {}
|
||
|
||
public function runAll(int $budgetSeconds = 45): void
|
||
{
|
||
IdentityProvider::query()->where('enabled', true)->where('type', IdentityProvider::ENTRA)->get()
|
||
->filter(fn (IdentityProvider $p) => (bool) $p->setting('directory_sync', false))
|
||
->each(fn (IdentityProvider $p) => $this->run($p, $budgetSeconds));
|
||
}
|
||
|
||
public function run(IdentityProvider $provider, int $budgetSeconds = 45): void
|
||
{
|
||
$deadline = microtime(true) + $budgetSeconds;
|
||
$client = new EntraClient($provider);
|
||
|
||
try {
|
||
$token = $client->appToken();
|
||
$this->syncUsers($provider, $client, $token, $deadline);
|
||
$this->syncPhotosAndManagers($provider, $client, $token, $deadline);
|
||
|
||
if (now()->getTimestamp() - (int) $this->state($provider, 'groups_synced_at', 0) >= self::GROUP_SYNC_INTERVAL) {
|
||
$this->syncGroups($provider, $client, $token);
|
||
$this->saveState($provider, ['groups_synced_at' => now()->getTimestamp()]);
|
||
}
|
||
|
||
$this->saveState($provider, ['last_run_at' => now()->getTimestamp(), 'last_error' => null]);
|
||
} catch (Throwable $e) {
|
||
$client->forgetAppToken();
|
||
Log::error("Entra-Abgleich ({$provider->name}) fehlgeschlagen: ".$e->getMessage());
|
||
$this->saveState($provider, ['last_run_at' => now()->getTimestamp(), 'last_error' => $e->getMessage()]);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* @return array<string, mixed>
|
||
*/
|
||
public function status(IdentityProvider $provider): array
|
||
{
|
||
return (array) $this->settings->get('identity.'.$provider->id.'.sync', []);
|
||
}
|
||
|
||
private function syncUsers(IdentityProvider $provider, EntraClient $client, string $token, float $deadline): void
|
||
{
|
||
$select = EntraAttributes::select($provider);
|
||
|
||
// Neue Attribute zugeordnet: Der alte Delta-Link liefert sie nicht – einmal komplett abgleichen.
|
||
if ($this->state($provider, 'select') !== $select) {
|
||
$this->saveState($provider, ['delta_link' => null, 'next_link' => null, 'select' => $select]);
|
||
}
|
||
|
||
$url = $this->state($provider, 'next_link') ?: $this->state($provider, 'delta_link') ?: '/users/delta?$select='.$select;
|
||
|
||
while ($url && microtime(true) < $deadline) {
|
||
$response = $client->graph($token)->get($url);
|
||
|
||
// Abgelaufener Delta-Link: von vorn beginnen.
|
||
if ($response->status() === 410) {
|
||
$this->saveState($provider, ['delta_link' => null, 'next_link' => null]);
|
||
|
||
return;
|
||
}
|
||
|
||
$client->assertGraph($response);
|
||
|
||
foreach ((array) $response->json('value', []) as $graphUser) {
|
||
$this->applyUser($provider, (array) $graphUser);
|
||
}
|
||
|
||
if ($next = ($response->json() ?? [])['@odata.nextLink'] ?? null) {
|
||
$url = $next;
|
||
$this->saveState($provider, ['next_link' => $next]);
|
||
} else {
|
||
$this->saveState($provider, ['delta_link' => ($response->json() ?? [])['@odata.deltaLink'] ?? null, 'next_link' => null, 'users_synced_at' => now()->getTimestamp()]);
|
||
$url = null;
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* @param array<string, mixed> $graphUser
|
||
*/
|
||
private function applyUser(IdentityProvider $provider, array $graphUser): void
|
||
{
|
||
$subject = (string) ($graphUser['id'] ?? '');
|
||
|
||
if ($subject === '') {
|
||
return;
|
||
}
|
||
|
||
$identity = UserIdentity::query()->with('user')->where('identity_provider_id', $provider->id)->where('subject', $subject)->first();
|
||
|
||
if (isset($graphUser['@removed']) || ($graphUser['accountEnabled'] ?? true) === false) {
|
||
if ($identity?->user) {
|
||
$this->sync->deactivate($provider, $identity);
|
||
}
|
||
|
||
return;
|
||
}
|
||
|
||
if (! $identity) {
|
||
$createAllowed = $provider->setting('directory_create_users', false)
|
||
&& ($graphUser['userType'] ?? 'Member') === 'Member'
|
||
&& ! empty($graphUser['mail']);
|
||
|
||
// Ohne Vorab-Anlage: nur bestehende Konten per E-Mail verknüpfen.
|
||
try {
|
||
$user = $this->sync->resolveUser($provider, $subject, EntraProfile::fromGraph($provider, $graphUser), (bool) $createAllowed);
|
||
} catch (IdentityException) {
|
||
return; // z. B. nicht erlaubte E-Mail-Domain – dieses Konto überspringen
|
||
}
|
||
|
||
if (! $user) {
|
||
return;
|
||
}
|
||
|
||
$identity = UserIdentity::query()->with('user')->where('identity_provider_id', $provider->id)->where('subject', $subject)->first();
|
||
}
|
||
|
||
// Delta liefert nur geänderte Felder – fehlende Felder nicht leeren.
|
||
$profile = EntraProfile::fromGraph($provider, $graphUser, partial: true);
|
||
|
||
$this->sync->syncProfile($provider, $identity->user, $profile);
|
||
}
|
||
|
||
private function syncPhotosAndManagers(IdentityProvider $provider, EntraClient $client, string $token, float $deadline): void
|
||
{
|
||
$withPhoto = (bool) $provider->setting('sync_photo', true);
|
||
$withManager = $provider->syncsManager();
|
||
|
||
if (! $withPhoto && ! $withManager) {
|
||
return;
|
||
}
|
||
|
||
$identities = UserIdentity::query()->with('user')
|
||
->where('identity_provider_id', $provider->id)
|
||
->whereHas('user', fn ($q) => $q->where('is_active', true))
|
||
->orderByRaw('synced_at is not null')->orderBy('synced_at')
|
||
->limit(self::PHOTOS_PER_RUN)->get();
|
||
|
||
foreach ($identities as $identity) {
|
||
if (microtime(true) >= $deadline) {
|
||
return;
|
||
}
|
||
|
||
if ($withPhoto) {
|
||
$response = $client->graph($token)->accept('image/*')->get('/users/'.$identity->subject.'/photo/$value');
|
||
|
||
if ($response->successful() || $response->status() === 404) {
|
||
$this->sync->syncPhoto($identity, $response->successful() ? $response->body() : null);
|
||
}
|
||
}
|
||
|
||
if ($withManager) {
|
||
$manager = $client->graph($token)->get('/users/'.$identity->subject.'/manager', ['$select' => 'id']);
|
||
|
||
if ($manager->successful() || $manager->status() === 404) {
|
||
$this->sync->syncProfile($provider, $identity->user, ['manager_subject' => $manager->successful() ? $manager->json('id') : null]);
|
||
}
|
||
}
|
||
|
||
$identity->forceFill(['synced_at' => now()])->save();
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Gruppen- und App-Rollen-Zuordnungen für alle verknüpften Konten neu berechnen.
|
||
*/
|
||
private function syncGroups(IdentityProvider $provider, EntraClient $client, string $token): void
|
||
{
|
||
$mappings = $provider->mappings()->get();
|
||
$groupsBySubject = [];
|
||
$appRolesBySubject = [];
|
||
|
||
foreach ($mappings->where('kind', IdpGroupMapping::GROUP)->pluck('external_id')->unique() as $groupId) {
|
||
foreach ($this->transitiveUserIds($client, $token, $groupId) as $subject) {
|
||
$groupsBySubject[$subject][] = $groupId;
|
||
}
|
||
}
|
||
|
||
if ($mappings->where('kind', IdpGroupMapping::APP_ROLE)->isNotEmpty()) {
|
||
$appRolesBySubject = $this->appRoleAssignments($provider, $client, $token);
|
||
}
|
||
|
||
UserIdentity::query()->with('user')->where('identity_provider_id', $provider->id)
|
||
->whereHas('user', fn ($q) => $q->where('is_active', true))
|
||
->each(fn (UserIdentity $identity) => $this->sync->syncRoles(
|
||
$provider,
|
||
$identity->user,
|
||
$groupsBySubject[$identity->subject] ?? [],
|
||
array_values(array_unique($appRolesBySubject[$identity->subject] ?? [])),
|
||
));
|
||
}
|
||
|
||
/**
|
||
* @return list<string>
|
||
*/
|
||
private function transitiveUserIds(EntraClient $client, string $token, string $groupId): array
|
||
{
|
||
return array_column($client->graphAll($token, '/groups/'.$groupId.'/transitiveMembers/microsoft.graph.user?$select=id&$top=999'), 'id');
|
||
}
|
||
|
||
/**
|
||
* App-Rollen der App-Registrierung: direkt zugewiesene Personen und Gruppen (aufgelöst).
|
||
*
|
||
* @return array<string, list<string>> Objekt-ID => Rollen-Werte
|
||
*/
|
||
private function appRoleAssignments(IdentityProvider $provider, EntraClient $client, string $token): array
|
||
{
|
||
$servicePrincipal = $client->graph($token)->get("/servicePrincipals(appId='".$client->clientId()."')", ['$select' => 'id,appRoles']);
|
||
$client->assertGraph($servicePrincipal);
|
||
|
||
$values = collect((array) $servicePrincipal->json('appRoles', []))->pluck('value', 'id')->all();
|
||
$result = [];
|
||
|
||
foreach ($client->graphAll($token, '/servicePrincipals/'.$servicePrincipal->json('id').'/appRoleAssignedTo?$top=999') as $assignment) {
|
||
$value = $values[$assignment['appRoleId'] ?? ''] ?? null;
|
||
|
||
if (! $value) {
|
||
continue;
|
||
}
|
||
|
||
$subjects = ($assignment['principalType'] ?? '') === 'Group'
|
||
? $this->transitiveUserIds($client, $token, $assignment['principalId'])
|
||
: [$assignment['principalId']];
|
||
|
||
foreach ($subjects as $subject) {
|
||
$result[$subject][] = $value;
|
||
}
|
||
}
|
||
|
||
return $result;
|
||
}
|
||
|
||
private function state(IdentityProvider $provider, string $key, mixed $default = null): mixed
|
||
{
|
||
return $this->status($provider)[$key] ?? $default;
|
||
}
|
||
|
||
/**
|
||
* @param array<string, mixed> $values
|
||
*/
|
||
private function saveState(IdentityProvider $provider, array $values): void
|
||
{
|
||
$this->settings->set('identity.'.$provider->id.'.sync', array_merge($this->status($provider), $values));
|
||
}
|
||
}
|