feat: add LDAP authentication as per-tenant login method

Add LDAP as a third authentication option alongside local password and
Microsoft Entra ID SSO. Per-tenant configuration supports Active Directory,
OpenLDAP, and FreeIPA with configurable attribute mapping, search-then-bind
and direct-bind methods, encrypted bind credentials (AES-256-GCM),
profile sync on login, and user auto-provisioning via external identity
linking.

Includes admin UI for connection settings with test-connection button,
login page LDAP form, 25 new PHPUnit tests, and de/en translations.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-03-25 07:26:04 +01:00
parent a0d816caaa
commit d1eeac6692
22 changed files with 2325 additions and 18 deletions

View File

@@ -2,11 +2,13 @@
namespace MintyPHP\Service\Auth;
use MintyPHP\Repository\Tenant\TenantLdapAuthRepositoryInterface;
use MintyPHP\Repository\Tenant\TenantMicrosoftAuthRepositoryInterface;
class TenantSsoService
{
public const PROVIDER_MICROSOFT = 'microsoft';
public const PROVIDER_LDAP = 'ldap';
private const PROFILE_SYNC_FIELD_OPTIONS = [
'first_name' => 'Sync first name',
@@ -16,11 +18,24 @@ class TenantSsoService
'avatar' => 'Sync avatar image',
];
private const LDAP_PROFILE_SYNC_FIELD_OPTIONS = [
'first_name' => 'Sync first name',
'last_name' => 'Sync last name',
'phone' => 'Sync phone',
'mobile' => 'Sync mobile',
'email' => 'Sync email',
];
private const DEFAULT_PROFILE_SYNC_FIELDS = ['first_name', 'last_name'];
private const VALID_LDAP_ENCRYPTION_MODES = ['none', 'starttls', 'ldaps'];
private const VALID_LDAP_BIND_METHODS = ['search_then_bind', 'direct_bind'];
private const VALID_LDAP_SEARCH_SCOPES = ['sub', 'one'];
public function __construct(
private readonly AuthTenantGateway $tenantGateway,
private readonly TenantMicrosoftAuthRepositoryInterface $tenantMicrosoftAuthRepository,
private readonly TenantLdapAuthRepositoryInterface $tenantLdapAuthRepository,
private readonly AuthSettingsGateway $settingsGateway,
private readonly AuthCryptoGateway $cryptoGateway
) {
@@ -31,6 +46,11 @@ class TenantSsoService
return self::PROVIDER_MICROSOFT;
}
public function ldapProviderKey(): string
{
return self::PROVIDER_LDAP;
}
public function findTenantByLoginSlug(string $slug): ?array
{
$slug = trim(strtolower($slug));
@@ -121,12 +141,17 @@ class TenantSsoService
public function isLocalPasswordLoginAllowed(int $tenantId): bool
{
$auth = $this->getTenantMicrosoftAuth($tenantId);
if (!$auth['enabled']) {
return true;
$microsoftAuth = $this->getTenantMicrosoftAuth($tenantId);
if ($microsoftAuth['enabled'] && $microsoftAuth['enforce_microsoft_login']) {
return false;
}
return !$auth['enforce_microsoft_login'];
$ldapAuth = $this->getTenantLdapAuth($tenantId);
if ($ldapAuth['enabled'] && $ldapAuth['enforce_ldap_login']) {
return false;
}
return true;
}
public function resolveTenantLoginMethods(int $tenantId): array
@@ -137,17 +162,24 @@ class TenantSsoService
'local' => false,
'microsoft' => false,
'microsoft_reason' => 'tenant_not_found',
'ldap' => false,
'ldap_reason' => 'tenant_not_found',
];
}
$configResult = $this->getEffectiveMicrosoftProviderConfig($tenant);
$microsoftResult = $this->getEffectiveMicrosoftProviderConfig($tenant);
$ldapResult = $this->getEffectiveLdapProviderConfig($tenant);
return [
'local' => $this->isLocalPasswordLoginAllowed($tenantId),
'microsoft' => !empty($configResult['ok']),
'microsoft_reason' => $configResult['ok'] ?? false
'microsoft' => !empty($microsoftResult['ok']),
'microsoft_reason' => $microsoftResult['ok'] ?? false
? ''
: (string) ($configResult['error'] ?? 'sso_disabled'),
: (string) ($microsoftResult['error'] ?? 'sso_disabled'),
'ldap' => !empty($ldapResult['ok']),
'ldap_reason' => $ldapResult['ok'] ?? false
? ''
: (string) ($ldapResult['error'] ?? 'ldap_disabled'),
];
}
@@ -518,6 +550,357 @@ class TenantSsoService
};
}
// ── LDAP provider methods ─────────────────────────────────────────
public function getTenantLdapAuth(int $tenantId): array
{
$row = $this->tenantLdapAuthRepository->findByTenantId($tenantId) ?? [];
$syncProfileOnLogin = !empty($row['sync_profile_on_login']);
$syncFields = $this->normalizeLdapProfileSyncFields($row['sync_profile_fields'] ?? []);
if ($syncProfileOnLogin && !$syncFields) {
$syncFields = self::DEFAULT_PROFILE_SYNC_FIELDS;
}
return [
'enabled' => !empty($row['enabled']),
'enforce_ldap_login' => !empty($row['enforce_ldap_login']),
'host' => trim((string) ($row['host'] ?? '')),
'port' => (int) ($row['port'] ?? 389),
'encryption_mode' => $this->normalizeLdapEnum($row['encryption_mode'] ?? 'starttls', self::VALID_LDAP_ENCRYPTION_MODES, 'starttls'),
'verify_tls_certificate' => !array_key_exists('verify_tls_certificate', $row) || !empty($row['verify_tls_certificate']),
'base_dn' => trim((string) ($row['base_dn'] ?? '')),
'bind_dn_enc' => trim((string) ($row['bind_dn_enc'] ?? '')),
'bind_password_enc' => trim((string) ($row['bind_password_enc'] ?? '')),
'user_search_filter' => trim((string) ($row['user_search_filter'] ?? '(&(objectClass=user)(sAMAccountName=%s))')),
'user_search_scope' => $this->normalizeLdapEnum($row['user_search_scope'] ?? 'sub', self::VALID_LDAP_SEARCH_SCOPES, 'sub'),
'bind_method' => $this->normalizeLdapEnum($row['bind_method'] ?? 'search_then_bind', self::VALID_LDAP_BIND_METHODS, 'search_then_bind'),
'bind_username_format' => trim((string) ($row['bind_username_format'] ?? '')),
'unique_id_attribute' => trim((string) ($row['unique_id_attribute'] ?? 'objectGUID')),
'attribute_map' => $this->normalizeLdapAttributeMap($row['attribute_map'] ?? null),
'sync_profile_on_login' => $syncProfileOnLogin,
'sync_profile_fields' => $this->profileSyncFieldsCsv($syncFields),
'sync_profile_fields_list' => $syncFields,
'allowed_domains' => $this->normalizeDomains((string) ($row['allowed_domains'] ?? '')),
'auto_remember_mode' => array_key_exists('auto_remember_mode', $row) && $row['auto_remember_mode'] !== null
? (int) $row['auto_remember_mode']
: null,
'network_timeout' => (int) ($row['network_timeout'] ?? 5),
];
}
public function getEffectiveLdapProviderConfig(array $tenant): array
{
$tenantId = (int) ($tenant['id'] ?? 0);
if ($tenantId <= 0) {
return ['ok' => false, 'error' => 'tenant_not_found'];
}
$auth = $this->getTenantLdapAuth($tenantId);
if (!$auth['enabled']) {
return ['ok' => false, 'error' => 'ldap_disabled'];
}
if ($auth['host'] === '') {
return ['ok' => false, 'error' => 'ldap_host_missing'];
}
if ($auth['base_dn'] === '') {
return ['ok' => false, 'error' => 'ldap_base_dn_missing'];
}
$bindDn = '';
$bindPassword = '';
if ($auth['bind_dn_enc'] !== '') {
try {
$bindDn = $this->cryptoGateway->decryptString($auth['bind_dn_enc']);
} catch (\Throwable) {
return ['ok' => false, 'error' => 'ldap_bind_dn_decrypt_failed'];
}
}
if ($auth['bind_password_enc'] !== '') {
try {
$bindPassword = $this->cryptoGateway->decryptString($auth['bind_password_enc']);
} catch (\Throwable) {
return ['ok' => false, 'error' => 'ldap_bind_password_decrypt_failed'];
}
}
return [
'ok' => true,
'config' => [
'provider' => self::PROVIDER_LDAP,
'host' => $auth['host'],
'port' => $auth['port'],
'encryption_mode' => $auth['encryption_mode'],
'verify_tls_certificate' => $auth['verify_tls_certificate'],
'base_dn' => $auth['base_dn'],
'bind_dn' => $bindDn,
'bind_password' => $bindPassword,
'user_search_filter' => $auth['user_search_filter'],
'user_search_scope' => $auth['user_search_scope'],
'bind_method' => $auth['bind_method'],
'bind_username_format' => $auth['bind_username_format'],
'unique_id_attribute' => $auth['unique_id_attribute'],
'attribute_map' => $auth['attribute_map'],
'sync_profile_on_login' => $auth['sync_profile_on_login'],
'sync_profile_fields' => $auth['sync_profile_fields_list'],
'allowed_domains' => $auth['allowed_domains'],
'enforce_ldap_login' => $auth['enforce_ldap_login'],
'network_timeout' => $auth['network_timeout'],
],
];
}
public function buildLdapUiState(int $tenantId, array $input = []): array
{
$existing = $this->getTenantLdapAuth($tenantId);
$enabled = array_key_exists('ldap_enabled', $input)
? !empty($input['ldap_enabled'])
: $existing['enabled'];
$enforce = array_key_exists('enforce_ldap_login', $input)
? !empty($input['enforce_ldap_login'])
: $existing['enforce_ldap_login'];
$host = array_key_exists('ldap_host', $input)
? trim((string) ($input['ldap_host'] ?? ''))
: $existing['host'];
$baseDn = array_key_exists('ldap_base_dn', $input)
? trim((string) ($input['ldap_base_dn'] ?? ''))
: $existing['base_dn'];
$configComplete = !$enabled || ($host !== '' && $baseDn !== '');
$configErrorCode = '';
if ($enabled && $host === '') {
$configErrorCode = 'ldap_host_missing';
} elseif ($enabled && $baseDn === '') {
$configErrorCode = 'ldap_base_dn_missing';
}
return [
'enabled' => $enabled,
'config_complete' => $configComplete,
'config_error_code' => $configErrorCode,
'config_error_label' => $this->ldapConfigErrorLabel($configErrorCode),
'password_mode' => !$enabled
? 'local_only'
: ($enforce ? 'ldap_only' : 'local_and_ldap'),
];
}
public function saveTenantLdapAuth(int $tenantId, array $input): array
{
$tenant = $this->tenantGateway->findById($tenantId);
if (!$tenant) {
return ['ok' => false, 'errors' => [t('Tenant not found')]];
}
$enabled = !empty($input['ldap_enabled']);
$enforce = !empty($input['enforce_ldap_login']);
$host = trim((string) ($input['ldap_host'] ?? ''));
$port = (int) ($input['ldap_port'] ?? 389);
$encryptionMode = $this->normalizeLdapEnum($input['ldap_encryption_mode'] ?? 'starttls', self::VALID_LDAP_ENCRYPTION_MODES, 'starttls');
$verifyTlsCertificate = !empty($input['ldap_verify_tls_certificate']);
$baseDn = trim((string) ($input['ldap_base_dn'] ?? ''));
$bindDn = trim((string) ($input['ldap_bind_dn'] ?? ''));
$bindPassword = trim((string) ($input['ldap_bind_password'] ?? ''));
$clearBindPassword = !empty($input['clear_ldap_bind_password']);
$userSearchFilter = trim((string) ($input['ldap_user_search_filter'] ?? '(&(objectClass=user)(sAMAccountName=%s))'));
$userSearchScope = $this->normalizeLdapEnum($input['ldap_user_search_scope'] ?? 'sub', self::VALID_LDAP_SEARCH_SCOPES, 'sub');
$bindMethod = $this->normalizeLdapEnum($input['ldap_bind_method'] ?? 'search_then_bind', self::VALID_LDAP_BIND_METHODS, 'search_then_bind');
$bindUsernameFormat = trim((string) ($input['ldap_bind_username_format'] ?? ''));
$uniqueIdAttribute = trim((string) ($input['ldap_unique_id_attribute'] ?? 'objectGUID'));
$attributeMap = $this->normalizeLdapAttributeMap($input['ldap_attribute_map'] ?? null);
$syncProfileOnLogin = !empty($input['ldap_sync_profile_on_login']);
$syncProfileFields = $this->normalizeLdapProfileSyncFields($input['ldap_sync_profile_fields'] ?? []);
if ($syncProfileOnLogin && !$syncProfileFields) {
$syncProfileFields = self::DEFAULT_PROFILE_SYNC_FIELDS;
}
$syncProfileFieldsCsv = $this->profileSyncFieldsCsv($syncProfileFields);
$allowedDomains = $this->normalizeDomains((string) ($input['ldap_allowed_domains'] ?? ''));
$networkTimeout = max(1, min(30, (int) ($input['ldap_network_timeout'] ?? 5)));
$errors = [];
if ($enabled && $host === '') {
$errors[] = t('LDAP host is required');
}
if ($enabled && $baseDn === '') {
$errors[] = t('LDAP base DN is required');
}
if ($enabled && $port < 1 || $port > 65535) {
$errors[] = t('LDAP port must be between 1 and 65535');
}
if ($enabled && !str_contains($userSearchFilter, '%s')) {
$errors[] = t('Search filter must contain %s placeholder');
}
if ($enabled && $enforce && ($host === '' || $baseDn === '')) {
$errors[] = t('LDAP-only login requires a complete configuration');
}
if ($bindMethod === 'direct_bind' && $bindUsernameFormat === '') {
$errors[] = t('Direct bind method requires a username format');
}
$existing = $this->getTenantLdapAuth($tenantId);
$bindDnEnc = (string) ($existing['bind_dn_enc'] ?? '');
if ($bindDn !== '') {
if (!$this->cryptoGateway->isConfigured()) {
$errors[] = t('APP_CRYPTO_KEY is missing or invalid');
} else {
try {
$bindDnEnc = $this->cryptoGateway->encryptString($bindDn);
} catch (\Throwable) {
$errors[] = t('Bind DN could not be encrypted');
}
}
}
$bindPasswordEnc = (string) ($existing['bind_password_enc'] ?? '');
if ($clearBindPassword) {
$bindPasswordEnc = '';
} elseif ($bindPassword !== '') {
if (!$this->cryptoGateway->isConfigured()) {
$errors[] = t('APP_CRYPTO_KEY is missing or invalid');
} else {
try {
$bindPasswordEnc = $this->cryptoGateway->encryptString($bindPassword);
} catch (\Throwable) {
$errors[] = t('Bind password could not be encrypted');
}
}
}
if ($errors) {
return ['ok' => false, 'errors' => $errors];
}
$autoRememberMode = $this->normalizeAutoRememberMode($input['ldap_auto_remember_mode'] ?? null);
$attributeMapJson = json_encode($attributeMap, JSON_THROW_ON_ERROR);
$saved = $this->tenantLdapAuthRepository->upsertByTenantId($tenantId, [
'enabled' => $enabled,
'enforce_ldap_login' => $enabled ? $enforce : false,
'host' => $host,
'port' => $port,
'encryption_mode' => $encryptionMode,
'verify_tls_certificate' => $verifyTlsCertificate,
'base_dn' => $baseDn,
'bind_dn_enc' => $bindDnEnc !== '' ? $bindDnEnc : null,
'bind_password_enc' => $bindPasswordEnc !== '' ? $bindPasswordEnc : null,
'user_search_filter' => $userSearchFilter,
'user_search_scope' => $userSearchScope,
'bind_method' => $bindMethod,
'bind_username_format' => $bindUsernameFormat !== '' ? $bindUsernameFormat : null,
'unique_id_attribute' => $uniqueIdAttribute,
'attribute_map' => $attributeMapJson,
'sync_profile_on_login' => $enabled ? $syncProfileOnLogin : false,
'sync_profile_fields' => $syncProfileFieldsCsv !== '' ? $syncProfileFieldsCsv : null,
'allowed_domains' => $allowedDomains === '' ? null : $allowedDomains,
'auto_remember_mode' => $autoRememberMode,
'network_timeout' => $networkTimeout,
]);
if (!$saved) {
return ['ok' => false, 'errors' => [t('Tenant LDAP settings could not be saved')]];
}
return ['ok' => true];
}
public function shouldAutoRememberOnLdapLogin(int $tenantId): bool
{
$auth = $this->getTenantLdapAuth($tenantId);
$mode = $auth['auto_remember_mode'] ?? null;
if ($mode === 1) {
return true;
}
if ($mode === 0) {
return false;
}
return false;
}
public function ldapProfileSyncFieldOptions(): array
{
return self::LDAP_PROFILE_SYNC_FIELD_OPTIONS;
}
public function normalizeLdapProfileSyncFields($raw): array
{
if (is_string($raw)) {
$raw = preg_split('/[\s,;]+/', $raw) ?: [];
} elseif (!is_array($raw)) {
return [];
}
$allowed = array_fill_keys(array_keys(self::LDAP_PROFILE_SYNC_FIELD_OPTIONS), true);
$normalized = [];
foreach ($raw as $item) {
$key = strtolower(trim((string) $item));
if ($key === '' || !isset($allowed[$key])) {
continue;
}
$normalized[$key] = true;
}
return array_keys($normalized);
}
public function normalizeLdapAttributeMap(mixed $raw): array
{
$default = [
'first_name' => 'givenName',
'last_name' => 'sn',
'email' => 'mail',
'phone' => 'telephoneNumber',
'mobile' => 'mobile',
];
if ($raw === null || $raw === '') {
return $default;
}
if (is_string($raw)) {
$decoded = json_decode($raw, true);
if (!is_array($decoded)) {
return $default;
}
$raw = $decoded;
}
if (!is_array($raw)) {
return $default;
}
$result = [];
foreach ($raw as $key => $value) {
$key = trim((string) $key);
$value = trim((string) $value);
if ($key !== '' && $value !== '') {
$result[$key] = $value;
}
}
return $result ?: $default;
}
private function ldapConfigErrorLabel(string $errorCode): string
{
return match ($errorCode) {
'ldap_host_missing' => t('LDAP host is required'),
'ldap_base_dn_missing' => t('LDAP base DN is required'),
'ldap_bind_dn_decrypt_failed' => t('Bind DN could not be decrypted'),
'ldap_bind_password_decrypt_failed' => t('Bind password could not be decrypted'),
default => '',
};
}
private function normalizeLdapEnum(string $value, array $valid, string $default): string
{
$value = strtolower(trim($value));
return in_array($value, $valid, true) ? $value : $default;
}
private function slugify(string $value): string
{
$value = strtolower(trim($value));