From 824bd55eb1f201823f6b34f4bb41b7dd1eb2f770 Mon Sep 17 00:00:00 2001
From: maniaba <61078470+maniaba@users.noreply.github.com>
Date: Tue, 24 Nov 2026 12:31:43 +0100
Subject: [PATCH 1/2] feat: add opt-in LDAP and Active Directory authentication
(#1)
* feat: add verified LDAP transport and filter support
* feat: integrate optional LDAP login with Shield sessions
* docs: disable remembered sessions in LDAP-only setup
* refactor: align LDAP login and exceptions with Shield conventions
* refactor: standardize LDAP class and file names
* refactor: isolate LDAP from Shield login defaults
* test: cover LDAP authentication and transport edge cases
* fix: redact native LDAP passwords from exception traces
* docs: configure LDAP through Auth properties
* chore: trigger GitHub Actions for LDAP review
* docs: connect the LDAP guide and use a controller login action
* docs: document the public LDAP API
* test: resolve Psalm errors in LDAP tests
* fix: preload migrations config for Rector analysis
* fix: remove migrations config from Rector bootstrap
* refactor: configure LDAP connections through AuthLDAP properties
* docs: address LDAP guide review feedback
* chore: retrigger PR checks after LDAP guide review
* refactor: persist LDAP identities as UserIdentity entities
* test: run OpenLDAP integration checks in CI
* fix: restore Rector analysis for LDAP changes
---
.github/workflows/phpunit-ldap.yml | 57 +++
composer.json | 1 +
docs/addons/ldap.md | 462 ++++++++++++++++++
docs/customization/custom_authenticators.md | 2 +-
docs/getting_started/authenticators.md | 3 +
.../authentication/authentication.md | 10 +-
mkdocs.yml | 1 +
rector.php | 2 +
src/Authentication/Authenticators/LDAP.php | 267 ++++++++++
src/Authentication/LDAP/LDAPConnection.php | 132 +++++
.../LDAP/LDAPDirectoryInterface.php | 71 +++
src/Authentication/LDAP/LDAPFilter.php | 195 ++++++++
src/Authentication/LDAP/LDAPUserResolver.php | 306 ++++++++++++
.../LDAP/NativeLDAPDirectory.php | 369 ++++++++++++++
src/Config/AuthLDAP.php | 125 +++++
src/Config/Services.php | 14 +
src/Exceptions/LDAPException.php | 28 ++
src/Language/ar/Auth.php | 1 +
src/Language/bg/Auth.php | 1 +
src/Language/cs/Auth.php | 1 +
src/Language/de/Auth.php | 1 +
src/Language/en/Auth.php | 1 +
src/Language/es/Auth.php | 1 +
src/Language/fa/Auth.php | 1 +
src/Language/fr/Auth.php | 1 +
src/Language/id/Auth.php | 1 +
src/Language/it/Auth.php | 1 +
src/Language/ja/Auth.php | 1 +
src/Language/lt/Auth.php | 1 +
src/Language/nl/Auth.php | 1 +
src/Language/pl/Auth.php | 1 +
src/Language/pt-BR/Auth.php | 1 +
src/Language/pt/Auth.php | 1 +
src/Language/ru/Auth.php | 1 +
src/Language/sk/Auth.php | 1 +
src/Language/sr/Auth.php | 1 +
src/Language/sv-SE/Auth.php | 1 +
src/Language/tr/Auth.php | 1 +
src/Language/uk/Auth.php | 1 +
.../Authenticators/LDAPAuthenticatorTest.php | 210 ++++++++
.../LDAP/LDAPConnectionTest.php | 150 ++++++
tests/Authentication/LDAP/LDAPFilterTest.php | 86 ++++
.../LDAP/LDAPUserResolverTest.php | 368 ++++++++++++++
.../NativeLDAPDirectoryIntegrationTest.php | 220 +++++++++
.../LDAP/NativeLDAPDirectoryTest.php | 74 +++
.../LDAP/NativeLDAPTransportTest.php | 237 +++++++++
tests/Controllers/LDAPLoginTest.php | 286 +++++++++++
tests/Unit/AuthLDAPTest.php | 199 ++++++++
tests/Unit/LDAPServicesTest.php | 45 ++
tests/_support/LDAP/Dockerfile | 17 +
tests/_support/LDAP/LoginController.php | 42 ++
tests/_support/LDAP/NativeLDAPStub.php | 46 ++
tests/_support/LDAP/entries.ldif | 38 ++
tests/_support/LDAP/native_ldap_functions.inc | 149 ++++++
tests/_support/LDAP/run-integration-tests.sh | 56 +++
tests/_support/LDAP/slapd.conf | 24 +
56 files changed, 4309 insertions(+), 5 deletions(-)
create mode 100644 .github/workflows/phpunit-ldap.yml
create mode 100644 docs/addons/ldap.md
create mode 100644 src/Authentication/Authenticators/LDAP.php
create mode 100644 src/Authentication/LDAP/LDAPConnection.php
create mode 100644 src/Authentication/LDAP/LDAPDirectoryInterface.php
create mode 100644 src/Authentication/LDAP/LDAPFilter.php
create mode 100644 src/Authentication/LDAP/LDAPUserResolver.php
create mode 100644 src/Authentication/LDAP/NativeLDAPDirectory.php
create mode 100644 src/Config/AuthLDAP.php
create mode 100644 src/Exceptions/LDAPException.php
create mode 100644 tests/Authentication/Authenticators/LDAPAuthenticatorTest.php
create mode 100644 tests/Authentication/LDAP/LDAPConnectionTest.php
create mode 100644 tests/Authentication/LDAP/LDAPFilterTest.php
create mode 100644 tests/Authentication/LDAP/LDAPUserResolverTest.php
create mode 100644 tests/Authentication/LDAP/NativeLDAPDirectoryIntegrationTest.php
create mode 100644 tests/Authentication/LDAP/NativeLDAPDirectoryTest.php
create mode 100644 tests/Authentication/LDAP/NativeLDAPTransportTest.php
create mode 100644 tests/Controllers/LDAPLoginTest.php
create mode 100644 tests/Unit/AuthLDAPTest.php
create mode 100644 tests/Unit/LDAPServicesTest.php
create mode 100644 tests/_support/LDAP/Dockerfile
create mode 100644 tests/_support/LDAP/LoginController.php
create mode 100644 tests/_support/LDAP/NativeLDAPStub.php
create mode 100644 tests/_support/LDAP/entries.ldif
create mode 100644 tests/_support/LDAP/native_ldap_functions.inc
create mode 100644 tests/_support/LDAP/run-integration-tests.sh
create mode 100644 tests/_support/LDAP/slapd.conf
diff --git a/.github/workflows/phpunit-ldap.yml b/.github/workflows/phpunit-ldap.yml
new file mode 100644
index 000000000..8fdd265e8
--- /dev/null
+++ b/.github/workflows/phpunit-ldap.yml
@@ -0,0 +1,57 @@
+name: OpenLDAP Integration Tests
+
+on:
+ pull_request:
+ branches:
+ - develop
+ paths:
+ - 'src/Authentication/LDAP/**'
+ - 'src/Exceptions/LDAPException.php'
+ - 'src/Language/en/Auth.php'
+ - 'tests/Authentication/LDAP/**'
+ - 'tests/_support/LDAP/**'
+ - 'composer.json'
+ - 'composer.lock'
+ - 'phpunit.dist.xml'
+ - '.github/workflows/phpunit-ldap.yml'
+ push:
+ branches:
+ - develop
+ paths:
+ - 'src/Authentication/LDAP/**'
+ - 'src/Exceptions/LDAPException.php'
+ - 'src/Language/en/Auth.php'
+ - 'tests/Authentication/LDAP/**'
+ - 'tests/_support/LDAP/**'
+ - 'composer.json'
+ - 'composer.lock'
+ - 'phpunit.dist.xml'
+ - '.github/workflows/phpunit-ldap.yml'
+
+permissions:
+ contents: read
+
+jobs:
+ main:
+ name: OpenLDAP Integration Tests
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+
+ - name: Set up PHP
+ uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # v2.40.0
+ with:
+ php-version: '8.2'
+ extensions: ldap, intl, mbstring
+ coverage: none
+
+ - name: Install dependencies
+ run: composer install --no-interaction --prefer-dist --no-progress
+
+ - name: Test with OpenLDAP
+ run: bash tests/_support/LDAP/run-integration-tests.sh
diff --git a/composer.json b/composer.json
index 58505f399..12ce3cb2a 100644
--- a/composer.json
+++ b/composer.json
@@ -45,6 +45,7 @@
},
"suggest": {
"ext-curl": "Required to use the password validation rule via PwnedValidator class.",
+ "ext-ldap": "Required to use Shield's native LDAP transport.",
"ext-openssl": "Required to use the JWT Authenticator."
},
"minimum-stability": "dev",
diff --git a/docs/addons/ldap.md b/docs/addons/ldap.md
new file mode 100644
index 000000000..a9c2ba436
--- /dev/null
+++ b/docs/addons/ldap.md
@@ -0,0 +1,462 @@
+# LDAP and Active Directory Authentication
+
+The LDAP authenticator verifies web login credentials against an LDAPv3
+directory, such as Active Directory or OpenLDAP. It uses Shield's sessions
+and login actions. LDAP is opt-in and requires PHP's `ldap` extension.
+Follow the [Shield installation](../getting_started/install.md) before configuring LDAP.
+
+## Directory and TLS Prerequisites
+
+1. Create a read-only service account. Give it access to the configured search
+ base, login attributes, immutable identifier, and any attributes used by
+ eligibility rules or profile mappings.
+2. Install a current build of the PHP LDAP extension linked against OpenLDAP in
+ the PHP process that serves the application. Confirm it is loaded with
+ `php --ri ldap` in the CLI and in the web runtime.
+3. Configure the OpenLDAP client trust store before starting PHP. For example,
+ set the following in the client configuration file used by PHP (commonly
+ `/etc/ldap/ldap.conf`):
+
+ ```text
+ TLS_CACERT /etc/ssl/certs/corporate-ldap-ca.pem
+ TLS_REQCERT demand
+ TLS_REQSAN demand
+ ```
+
+ A service manager can also supply `LDAPTLS_CACERT` as a process environment
+ variable. Mount a trusted CA bundle in the runtime and restart PHP workers
+ after changing their trust configuration. The native transport uses one
+ process-wide trust policy. All endpoints must present a trusted chain and a
+ certificate valid for the configured hostname. [OpenLDAP TLS reference](https://www.openldap.org/doc/admin26/tls.html)
+
+Use LDAPS for an endpoint that negotiates TLS as soon as it accepts a connection
+(commonly port 636). Use StartTLS for an endpoint that upgrades LDAP to TLS before
+either bind (commonly port 389). Shield refuses plaintext simple binds and does
+not chase LDAP referrals.
+
+## Configure Active Directory
+
+Create **app/Config/AuthLDAP.php** and define the directory settings in
+`$connections`. The array key is the connection ID.
+
+```php
+ [
+ 'hosts' => ['dc01.example.com', 'dc02.example.com'],
+ 'baseDn' => 'DC=example,DC=com',
+ 'bindDn' => 'CN=shield-reader,OU=Service Accounts,DC=example,DC=com',
+ 'bindPassword' => '',
+ 'encryption' => 'ldaps',
+ 'port' => 636,
+ 'userBaseDn' => 'OU=Users,DC=example,DC=com',
+ 'loginFilter' => '(&(objectCategory=person)(objectClass=user)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))',
+ 'loginAttributes' => ['sAMAccountName', 'userPrincipalName'],
+ 'externalIdAttribute' => 'objectGUID',
+ 'profileAttributes' => ['username' => 'sAMAccountName'],
+ 'provisionUsers' => true,
+ ],
+ ];
+}
+```
+
+Enable LDAP and supply the service-account password in your local CodeIgniter
+`.env` file. Keep that file out of source control and limit the service account
+to reading the necessary entries and attributes.
+
+```ini
+authldap.enabled = true
+authldap.connections.corporate.bindPassword = 'replace-with-service-account-password'
+```
+
+For deployment through the PHP process environment, use
+`authldap_connections_corporate_bindPassword` if the environment requires
+underscores. CodeIgniter populates the existing `bindPassword` entry when it
+initializes `AuthLDAP`, using the same environment override as other settings.
+
+CodeIgniter can override existing connection settings with environment keys
+such as `authldap.connections.corporate.hosts.0` or
+`authldap.connections.corporate.port`. Declare connection IDs, option keys,
+and list entries in the PHP array before overriding their values.
+
+!!! warning
+
+ Shield redacts bind passwords in `var_dump()` output. Direct reads of
+ `$connections`, configuration exports, and CodeIgniter's configuration
+ cache can expose the password. To keep the password outside the cache,
+ retrieve it through an application-owned connection provider. See
+ [Administrative diagnostics](#administrative-diagnostics).
+
+List endpoints in preferred order within a connection. Each endpoint in that
+list must reach the same logical directory and enforce equivalent access rules.
+To route UPNs to different directory configurations, map their lower-case domain
+suffixes to connection IDs in `$loginDomains`. For example, `['research.example.org'
+=> 'research']` routes `alice@research.example.org` to the `research` connection.
+The default connection handles unqualified logins and unmapped suffixes. The
+submitted value remains the lookup value, including any suffix.
+
+## Configure OpenLDAP
+
+In the configuration above, set `$defaultConnection` to `'openldap'` and use
+the following `$connections` property. The server must support StartTLS on
+the configured port.
+
+```php
+public array $connections = [
+ 'openldap' => [
+ 'hosts' => ['ldap.example.org'],
+ 'baseDn' => 'dc=example,dc=org',
+ 'bindDn' => 'cn=shield-reader,ou=services,dc=example,dc=org',
+ 'bindPassword' => '',
+ 'encryption' => 'starttls',
+ 'port' => 389,
+ 'userBaseDn' => 'ou=people,dc=example,dc=org',
+ 'loginFilter' => '(objectClass=inetOrgPerson)',
+ 'loginAttributes' => ['uid'],
+ 'externalIdAttribute' => 'entryUUID',
+ 'profileAttributes' => ['username' => 'uid'],
+ 'provisionUsers' => true,
+ ],
+];
+```
+
+Enable LDAP and provide the password for this connection ID in `.env`.
+
+```ini
+authldap.enabled = true
+authldap.connections.openldap.bindPassword = 'replace-with-service-account-password'
+```
+
+The process environment can supply the same value through
+`authldap_connections_openldap_bindPassword`.
+
+For another LDAPv3 directory, configure the login attributes, entry filter, and
+immutable identifier according to its schema. The configured identifier must
+be unique, readable, and stable across user renames and moves.
+
+## Enable Shield Web Login
+
+In **app/Config/Auth.php**, add the `ldap` entry to the existing
+`$authenticators` array. Shield's session filter and login actions use the
+`session` alias to read the session created by LDAP. Keep
+`$defaultAuthenticator` set to `'session'`. Add the LDAP entry alongside
+the default authenticators.
+
+```php
+public array $authenticators = [
+ 'tokens' => \CodeIgniter\Shield\Authentication\Authenticators\AccessTokens::class,
+ 'session' => \CodeIgniter\Shield\Authentication\Authenticators\Session::class,
+ 'hmac' => \CodeIgniter\Shield\Authentication\Authenticators\HmacSha256::class,
+ 'ldap' => \CodeIgniter\Shield\Authentication\Authenticators\LDAP::class,
+];
+```
+
+Set the `login` entry in the existing `$views` array to
+`'\App\Views\auth\ldap_login'`. For the routes shown below, set
+`allowRemembering` to `false` in the existing `$sessionConfig` array. Set
+the following properties so the login form displays only links for routes
+registered in the example.
+
+```php
+public bool $allowRegistration = false;
+public bool $allowMagicLinkLogins = false;
+```
+
+Copy **vendor/codeigniter4/shield/src/Views/login.php** to
+**app/Views/auth/ldap_login.php**. Replace the email field and its label with
+a text field named `username` so users can enter a simple login name or a UPN.
+Keep the password field and the CSRF field.
+
+```html
+
+
+```
+
+Add a login action to your application's controller. The following example
+uses **app/Controllers/Login.php**. After a successful LDAP sign-in, the action
+redirects to Shield's login action if one is pending, or to the configured
+login destination.
+
+```php
+getAuthenticator();
+ $result = $ldap->attempt($this->request->getPost(['username', 'password']));
+
+ if (! $result->isOK()) {
+ return redirect()->route('login')->with('error', $result->reason());
+ }
+
+ return $ldap->hasAction()
+ ? redirect()->route('auth-action-show')->withCookies()
+ : redirect()->to(config('Auth')->loginRedirect())->withCookies();
+ }
+}
+```
+
+In **app/Config/Routes.php**, use Shield's controller for the login form and
+register the application controller method for the POST route. This keeps the
+route definitions compatible with route caching.
+
+```php
+service('auth')->routes($routes, ['except' => ['login', 'register', 'magic-link']]);
+$routes->get('login', '\CodeIgniter\Shield\Controllers\LoginController::loginView', ['as' => 'login']);
+$routes->post('login', '\App\Controllers\Login::loginAction', ['filter' => 'auth-rates']);
+```
+
+Enable the `csrf` filter for the POST route and set `$csrfProtection` to
+`'session'` in **app/Config/Security.php**. Apply Shield's `auth-rates`
+filter to the authentication action routes as well. [Shield controller filters](../references/controller_filters.md#rate-limiting)
+
+The failure redirect flashes the error message. CodeIgniter's `withInput()`
+would copy the submitted password to session flash data. Set
+`zend.exception_ignore_args=On` in production PHP settings to keep submitted
+credentials out of exception traces in application code.
+
+## Login Eligibility
+
+The directory evaluates an administrator-defined login filter together with
+equality tests for the configured login attributes. For Active Directory, use
+`sAMAccountName` or `userPrincipalName`. For OpenLDAP, use an attribute such as
+`uid`. Case matching follows the directory attribute's equality rule. Shield
+requires one eligible match and escapes the submitted value as an LDAP filter
+assertion. Keep raw filter syntax restricted to trusted configuration.
+
+This Active Directory filter excludes disabled accounts and requires transitive
+membership in `Shield Users`. It can be configured as the `eligibilityFilter`
+and is checked on the matched user after a successful user bind:
+
+```ldap
+(&(objectCategory=person)(objectClass=user)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(memberOf:1.2.840.113556.1.4.1941:=CN=Shield Users,OU=Groups,DC=example,DC=com))
+```
+
+Confirm that `Shield Users` is the intended security group, and test nested and
+primary group membership behavior in your directory. Active Directory's
+`memberOf` matching follows its directory links. For OpenLDAP with a `memberOf`
+overlay, a direct eligibility filter can use
+`(&(objectClass=inetOrgPerson)(memberOf=cn=shield-users,ou=groups,dc=example,dc=org))`.
+Any OpenLDAP nested membership rule depends on the installed directory schema
+and overlays. [Active Directory matching rules](https://learn.microsoft.com/en-us/windows/win32/adsi/search-filter-syntax)
+
+Grouping operators `&`, `|`, and `!` can be nested. LDAP filter values use
+[RFC 4515](https://www.rfc-editor.org/rfc/rfc4515) escaping. If a filter compares
+a distinguished name, first encode the distinguished name according to
+[RFC 4514](https://www.rfc-editor.org/rfc/rfc4514), then encode that string as a
+filter assertion. An escaped comma in a DN, for example `CN=Family\, Given`, is
+written as `CN=Family\5c, Given` in a filter assertion.
+
+## Provisioning and Migration from Local Accounts
+
+The link between a directory account and a Shield user is scoped to a connection
+ID and an immutable directory identifier. Use `objectGUID` for Active Directory
+or `entryUUID` for OpenLDAP. Keep connection IDs stable. Replicas for a single
+directory belong to the same connection. Give independent directories separate
+connection IDs, even when their users have similar login attributes.
+
+For a new application, enable just-in-time provisioning to create a Shield user
+after the directory verifies the password. Map the local `username` field to a
+single-valued directory attribute that produces valid, unique Shield usernames
+of at most 30 characters. To map additional attributes, create columns and
+permit them in your [custom user provider](../customization/user_provider.md).
+For example, map `directory_email` to `mail` and `first_name` to `givenName`.
+Unconfigured fields stay under application control. Profile attributes used by
+application security decisions should be writable by trusted directory
+administrators only. Set `'updateProfile' => false` on the connection to use the
+configured attributes at provisioning only.
+
+For a migration, start with provisioning disabled. From a trusted operator
+workflow, verify the account in the directory and confirm which Shield user
+should own it. Then explicitly link the two identities:
+
+```php
+use CodeIgniter\Shield\Authentication\LDAP\LDAPUserResolver;
+
+$resolver = new LDAPUserResolver(auth()->getProvider());
+$resolver->link('corporate', '00112233-4455-6677-8899-aabbccddeeff', 42);
+```
+
+The example uses a canonical AD GUID and Shield user ID `42`. Convert the
+16-byte LDAP `objectGUID` value with `LDAPUserResolver::normalizeObjectGuid()`
+when reading it directly from LDAP. Use the `entryUUID` string as returned by
+OpenLDAP. A link conflicts if the same directory identity is already linked
+to another Shield user. Renaming an account or moving it to a new DN preserves
+the link as long as the updated account still meets the directory search and
+eligibility configuration. A conflicting username during attribute updates
+blocks the login until the conflict is resolved. The resolver owns a database
+transaction for each write operation. Call it outside other transactions on
+the Shield database connection.
+
+Shield never saves the submitted LDAP password or overwrites an existing local
+password. Directory email belongs in an application profile attribute if you
+need it. Use an independently verified contact method for Shield's email-based
+login action, or choose an action that supports directory-only users without an
+email identity. Review [Shield authentication actions](../references/authentication/auth_actions.md)
+before enabling just-in-time provisioning. If registration activation is
+configured, a newly provisioned account remains blocked until the application
+activates it through its trusted activation workflow.
+
+Users without a Shield password reset their password through the directory's
+account recovery process. Before enabling the `force-reset` filter on routes
+used by LDAP accounts, include Shield's fix for users without an email/password
+identity. [Force-reset fix](https://github.com/codeigniter4/shield/pull/1411)
+
+## Local-Only, LDAP-Only, and Hybrid Login
+
+For local-only login, keep the ordinary `Session` authenticator under the
+`session` alias. For LDAP-only login, configure `LDAP` as described above and
+leave `$localAccounts` empty. An application can enable hybrid login by listing
+the identifiers and corresponding Shield user IDs assigned to local
+password login in **app/Config/AuthLDAP.php**:
+
+```php
+public array $localAccounts = ['local-operator' => 10];
+```
+
+Reserve these identifiers for local users. Matching is case-insensitive, and
+configuration rejects duplicate identifiers that differ only in case. Shield
+verifies the local password for the specified user ID and requires a pending
+application login action before the operator can sign in. Configure an MFA
+action that applies to each operator and can be completed during a directory
+outage. Every other identifier goes to its selected LDAP connection. Directory
+credential failures and outages both deny a new LDAP login.
+
+## Availability and Session Revocation
+
+LDAP password login verifies the submitted credentials with the directory.
+The authenticator disables remember-me token issuance on password login. Keep
+`allowRemembering` disabled if previous installations issued remember-me cookies
+and users must prove their directory credentials on the next sign-in. Revoke
+pre-migration remember-me tokens before re-enabling the feature.
+
+Directory eligibility is checked during password login. Existing Shield
+sessions and issued API tokens follow their existing lifetime and revocation
+policies. When disabling a directory account, also revoke affected application
+sessions and tokens using the application's established procedures. If LDAP is
+the sole permitted web sign-in method, disable public registration and magic
+link routes in Shield, and review any custom password reset, login, or token
+issuance routes that could provide another sign-in path.
+
+## Administrative Diagnostics
+
+Application services can use the directory transport to test configured
+connections and preview a bounded search without provisioning users or changing
+authorization. Restrict administrative endpoints with application authorization,
+CSRF protection, and rate limits. Request only the attributes an operator needs,
+and keep raw results out of ordinary application logs.
+
+```php
+use CodeIgniter\Shield\Authentication\LDAP\LDAPFilter;
+use CodeIgniter\Shield\Exceptions\LDAPException;
+
+$config = config('AuthLDAP');
+$connectionIds = $config->connectionIds();
+$directory = service('ldapDirectory');
+
+try {
+ $connection = $config->getConnection('corporate');
+ $directory->testConnection($connection);
+ $directory->testBind($connection);
+
+ $entries = $directory->preview(
+ $connection,
+ $connection->userBaseDn ?? $connection->baseDn,
+ LDAPFilter::all($connection->loginFilter, $connection->eligibilityFilter),
+ ['sAMAccountName', 'displayName'],
+ 20,
+ );
+} catch (LDAPException $exception) {
+ log_message('warning', 'LDAP diagnostic failed ({reason}).', ['reason' => $exception->reason]);
+}
+```
+
+To inspect groups, pass the group base DN and a trusted group filter to
+`preview()`. The search limit is 1 to 100 entries. LDAP attribute names in
+returned entries are lowercase and values may be binary.
+
+To check a user's credentials without provisioning a Shield user, combine the
+connection's login filter and `LDAPFilter::equal($attribute, $identifier)`
+with `LDAPFilter::all()`. Pass the resulting filter, the submitted password,
+and the connection's eligibility filter to the directory's `authenticate()`
+method. Discard the password after the operation. Use `auth('ldap')->attempt()`
+for application sign-in and let Shield complete any configured login actions.
+
+To fetch connection settings from a database or another application source,
+override `AuthLDAP::getConnection()` and `AuthLDAP::connectionIds()`. In
+`getConnection()`, read the credential from your secret store and pass its
+string value as `bindPassword` to the `LDAPConnection` constructor. Present
+only connection IDs and the operational metadata your administrators need.
+
+### Troubleshooting
+
+- For connection or TLS errors, confirm DNS, port, certificate chain, hostname,
+ and the CA bundle loaded by the web runtime. The following command prompts
+ for the service password.
+
+ ```console
+ ldapsearch -H ldaps://dc01.example.com:636 -x -D '{bind DN}' -W \
+ -b 'DC=example,DC=com' -s base '(objectClass=*)' dn
+ ```
+
+ For StartTLS, use an `ldap://` URI and `-ZZ` to require the upgrade.
+
+- For a service bind failure, verify the service DN, secret, and directory policy.
+ For a missing or incomplete result, verify the search base, access controls,
+ filters, and timeout settings. Keep searches within the correct naming context
+ since referrals are rejected.
+- If a credential check succeeds but Shield login still fails, check for a
+ missing link, a disabled provisioning policy, a conflicting username, or a
+ local account ban or activation requirement. LDAP-specific logs use reason
+ codes, and the browser receives Shield's generic login error message.
+
+## Authorization
+
+Directory group filters control eligibility during LDAP sign-in. Manage
+application group assignments, permissions, and revocation through the
+[Shield authorization APIs](../references/authorization.md).
+
+## Testing Against OpenLDAP
+
+The **OpenLDAP Integration Tests** workflow runs
+`NativeLDAPDirectoryIntegrationTest` against the Docker fixture in
+`tests/_support/LDAP`. It uses test certificates and waits for the fixture to
+accept service-account binds over both LDAPS and StartTLS. The integration
+test run fails if any test is skipped.
+
+To run the same checks locally, install the test dependencies and make sure
+Docker, OpenSSL, and PHP's `ldap` extension are available. Run the following
+command from the Shield checkout.
+
+```bash
+bash tests/_support/LDAP/run-integration-tests.sh
+```
+
+The script publishes the fixture's ports on loopback and stops the container
+when the run finishes. The regular PHPUnit suite can run without the fixture.
+Test AD-specific GUIDs, account filters, and transitive group membership
+separately against a disposable AD DS or Samba AD test domain.
diff --git a/docs/customization/custom_authenticators.md b/docs/customization/custom_authenticators.md
index ddb1ed08b..e6d41f3f6 100644
--- a/docs/customization/custom_authenticators.md
+++ b/docs/customization/custom_authenticators.md
@@ -11,7 +11,7 @@ Custom Authenticators enable project-specific authentication strategies such as:
## Why Custom Authenticators
-While Shield provides built-in authenticators such as **Session**, **AccessTokens**, **HmacSha256**, and **JWT**, custom authenticators allow you to:
+While Shield provides built-in authenticators such as **Session**, **AccessTokens**, **HmacSha256**, **JWT**, and [**LDAP and Active Directory**](../addons/ldap.md), custom authenticators allow you to:
- Enforce project-specific login logic
- Integrate new or external authentication mechanisms
diff --git a/docs/getting_started/authenticators.md b/docs/getting_started/authenticators.md
index a1bed07c2..5fc7aff4b 100644
--- a/docs/getting_started/authenticators.md
+++ b/docs/getting_started/authenticators.md
@@ -17,5 +17,8 @@ Shield provides the following Authenticators:
[HMAC SHA256 Token Authenticator](../references/authentication/hmac.md) for usage.
- **JWT** authenticator provides stateless authentication using JSON Web Token. To use this,
you need additional setup. See [JWT Authentication](../addons/jwt.md).
+- **LDAP** authenticator verifies LDAPv3 directory credentials and uses Shield's
+ sessions and login actions. It requires additional setup. See
+ [LDAP and Active Directory Authentication](../addons/ldap.md).
In addition to the default authenticators listed above, CodeIgniter Shield allows you to build and register Custom Authenticators by implementing the `AuthenticatorInterface`, enabling completely project-specific authentication strategies (external providers, hardware or device challenges, or any other custom logic), while remaining fully compatible with Shield’s authentication lifecycle and its login/logout event system. For full implementation steps, see [Custom Authenticator](../customization/custom_authenticators.md).
\ No newline at end of file
diff --git a/docs/references/authentication/authentication.md b/docs/references/authentication/authentication.md
index 6ff162fee..13b9a19ce 100644
--- a/docs/references/authentication/authentication.md
+++ b/docs/references/authentication/authentication.md
@@ -6,18 +6,20 @@ web apps and APIs.
## Available Authenticators
-Shield ships with 4 authenticators that will serve several typical situations within web app development.
-You can see the [Authenticator List](../../getting_started/authenticators.md).
+Shield ships with five authenticators. The default configuration registers Session,
+AccessTokens, and HmacSha256. See the [Authenticator List](../../getting_started/authenticators.md).
-The available authenticators are defined in `Config\Auth`:
+[JWT](../../addons/jwt.md) and [LDAP](../../addons/ldap.md) require additional setup.
+Register them in `Config\Auth` when you enable them.
```php
public array $authenticators = [
// alias => classname
- 'session' => Session::class,
'tokens' => AccessTokens::class,
+ 'session' => Session::class,
'hmac' => HmacSha256::class,
// 'jwt' => JWT::class,
+ // 'ldap' => LDAP::class,
];
```
diff --git a/mkdocs.yml b/mkdocs.yml
index 73d4466ee..94df7699f 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -148,3 +148,4 @@ nav:
- references/testing.md
- Addons:
- JWT Authentication: addons/jwt.md
+ - LDAP Authentication: addons/ldap.md
diff --git a/rector.php b/rector.php
index ca31f2cde..bf4e96fa6 100644
--- a/rector.php
+++ b/rector.php
@@ -49,6 +49,8 @@
])
->withBootstrapFiles([
realpath(getcwd()) . '/vendor/codeigniter4/framework/system/Test/bootstrap.php',
+ // Load Config\Migrations before PHPStan's reflection can intercept its autoload.
+ realpath(getcwd()) . '/vendor/codeigniter4/framework/app/Config/Migrations.php',
])
->withPHPStanConfigs([
__DIR__ . '/phpstan.dist.neon',
diff --git a/src/Authentication/Authenticators/LDAP.php b/src/Authentication/Authenticators/LDAP.php
new file mode 100644
index 000000000..5c708b7d1
--- /dev/null
+++ b/src/Authentication/Authenticators/LDAP.php
@@ -0,0 +1,267 @@
+
+ *
+ * For the full copyright and license information, please view
+ * the LICENSE file that was distributed with this source code.
+ */
+
+namespace CodeIgniter\Shield\Authentication\Authenticators;
+
+use CodeIgniter\Events\Events;
+use CodeIgniter\HTTP\IncomingRequest;
+use CodeIgniter\Shield\Authentication\LDAP\LDAPDirectoryInterface;
+use CodeIgniter\Shield\Authentication\LDAP\LDAPFilter;
+use CodeIgniter\Shield\Authentication\LDAP\LDAPUserResolver;
+use CodeIgniter\Shield\Authentication\Passwords;
+use CodeIgniter\Shield\Config\AuthLDAP;
+use CodeIgniter\Shield\Entities\User;
+use CodeIgniter\Shield\Exceptions\LDAPException;
+use CodeIgniter\Shield\Models\UserModel;
+use CodeIgniter\Shield\Result;
+
+/**
+ * Uses verified LDAP identities with Shield's session and login action lifecycle.
+ */
+class LDAP extends Session
+{
+ private readonly AuthLDAP $ldapConfig;
+ private readonly LDAPDirectoryInterface $directory;
+ private readonly LDAPUserResolver $resolver;
+
+ /**
+ * @var array
+ */
+ private readonly array $localAccounts;
+
+ /**
+ * Uses the application configuration and directory service unless equivalents are supplied.
+ *
+ * @throws LDAPException If reserved local identifiers collide after case normalization.
+ */
+ public function __construct(
+ UserModel $provider,
+ ?AuthLDAP $config = null,
+ ?LDAPDirectoryInterface $directory = null,
+ ?LDAPUserResolver $resolver = null,
+ ) {
+ parent::__construct($provider);
+
+ $this->ldapConfig = $config ?? config('AuthLDAP');
+ $this->directory = $directory ?? service('ldapDirectory');
+ $this->resolver = $resolver ?? new LDAPUserResolver($provider);
+ $this->localAccounts = array_change_key_case($this->ldapConfig->localAccounts);
+
+ if (count($this->localAccounts) !== count($this->ldapConfig->localAccounts)) {
+ throw new LDAPException('invalid_configuration');
+ }
+ }
+
+ /**
+ * Verify credentials and begin a Shield session, subject to configured login actions.
+ *
+ * @param array $credentials
+ */
+ public function attempt(array $credentials): Result
+ {
+ $identifier = $credentials['username'] ?? '';
+
+ if (! $this->validIdentifier($identifier) || $this->getSessionUserKey('id') !== null) {
+ return $this->failedResult();
+ }
+
+ $result = $this->check($credentials);
+ $user = $result->extraInfo();
+
+ if (! $result->isOK() || ! $user instanceof User) {
+ return $this->rejectLogin($identifier);
+ }
+
+ $this->user = $user;
+ $started = $this->startUpAction('login', $user);
+ $local = isset($this->localAccounts[strtolower($identifier)]);
+
+ if ($local && ! $started) {
+ return $this->rejectLogin($identifier);
+ }
+
+ // Resolve pending actions before the session receives a user ID.
+ $pending = $this->hasAction();
+ if ($started && ! $pending) {
+ return $this->rejectLogin($identifier);
+ }
+
+ $this->recordAttempt($identifier, $user);
+ $this->startLogin($user);
+
+ if ($local && ($identity = $user->getEmailIdentity()) !== null) {
+ $user->touchIdentity($identity);
+ }
+
+ if (! $pending) {
+ $this->completeLogin($user);
+ }
+
+ return $result;
+ }
+
+ /**
+ * Verify credentials and resolve the user for a subsequent session login.
+ *
+ * A successful directory check may provision or update the local user.
+ *
+ * @param array $credentials
+ */
+ public function check(array $credentials): Result
+ {
+ $identifier = $credentials['username'] ?? '';
+ $password = $credentials['password'] ?? '';
+
+ if (! $this->ldapConfig->enabled || ! $this->validIdentifier($identifier)
+ || ! is_string($password) || $password === '' || strlen($password) > 4096 || str_contains($password, "\0")
+ ) {
+ return $this->failedResult();
+ }
+
+ $localId = $this->localAccounts[strtolower($identifier)] ?? null;
+ if ($localId !== null) {
+ return $this->checkLocalAccount($identifier, $password, $localId);
+ }
+
+ try {
+ $user = $this->resolveUser($identifier, $password);
+
+ if ($user->isBanned() || ! $user->isActivated()) {
+ return $this->failedResult();
+ }
+
+ return new Result(['success' => true, 'extraInfo' => $user]);
+ } catch (LDAPException $exception) {
+ log_message('debug', 'Shield LDAP login rejected ({reason}).', ['reason' => $exception->reason]);
+
+ return $this->failedResult();
+ }
+ }
+
+ private function rejectLogin(string $identifier): Result
+ {
+ $this->user = null;
+ $this->recordAttempt($identifier, null);
+ Events::trigger('failedLogin', ['username' => $identifier]);
+
+ return $this->failedResult();
+ }
+
+ private function recordAttempt(string $identifier, ?User $user): void
+ {
+ /** @var IncomingRequest $request */
+ $request = service('request');
+ $this->loginModel->recordLoginAttempt(
+ self::ID_TYPE_USERNAME,
+ $identifier,
+ $user !== null,
+ $request->getIPAddress(),
+ (string) $request->getUserAgent(),
+ $user?->id,
+ );
+ }
+
+ private function resolveUser(string $identifier, string $password): User
+ {
+ $separator = strrpos($identifier, '@');
+ $domain = $separator === false ? '' : strtolower(substr($identifier, $separator + 1));
+ $connectionId = $this->ldapConfig->loginDomains[$domain] ?? $this->ldapConfig->defaultConnection;
+ $connection = $this->ldapConfig->getConnection($connectionId);
+
+ if ($connection->id !== $connectionId) {
+ throw new LDAPException('invalid_configuration');
+ }
+
+ $predicates = [];
+
+ foreach ($connection->loginAttributes as $attribute) {
+ $predicates[] = LDAPFilter::equal($attribute, $identifier);
+ }
+
+ $filter = LDAPFilter::all($connection->loginFilter, LDAPFilter::any(...$predicates));
+ $entry = $this->directory->authenticate(
+ $connection,
+ $connection->userBaseDn ?? $connection->baseDn,
+ $filter,
+ array_values(array_unique([$connection->externalIdAttribute, ...array_values($connection->profileAttributes)])),
+ $password,
+ $connection->eligibilityFilter,
+ );
+
+ $ids = $entry['attributes'][strtolower($connection->externalIdAttribute)] ?? [];
+
+ if (count($ids) !== 1 || $ids[0] === '') {
+ throw new LDAPException('invalid_identity');
+ }
+
+ $externalId = strcasecmp($connection->externalIdAttribute, 'objectGUID') === 0
+ ? LDAPUserResolver::normalizeObjectGuid($ids[0])
+ : $ids[0];
+ $profile = [];
+
+ foreach ($connection->profileAttributes as $field => $attribute) {
+ $values = $entry['attributes'][strtolower($attribute)] ?? [];
+
+ if (count($values) === 1) {
+ $profile[$field] = $values[0];
+ } elseif ($values !== []) {
+ throw new LDAPException('invalid_profile');
+ }
+ }
+
+ return $this->resolver->resolve(
+ $connection->id,
+ $externalId,
+ $profile,
+ $connection->provisionUsers,
+ $connection->updateProfile,
+ );
+ }
+
+ private function checkLocalAccount(string $identifier, string $password, int|string $expectedId): Result
+ {
+ $user = $this->provider->findByCredentials(['username' => $identifier]);
+ $hash = $user?->password_hash;
+
+ /** @var Passwords $passwords */
+ $passwords = service('passwords');
+
+ if ($user === null || (string) $user->id !== (string) $expectedId || $hash === null || $hash === '') {
+ $passwords->verify($password, config('Auth')->dummyPasswordHash);
+
+ return $this->failedResult();
+ }
+
+ if (! $passwords->verify($password, $hash) || $user->isBanned() || ! $user->isActivated()) {
+ return $this->failedResult();
+ }
+
+ if ($passwords->needsRehash($hash)) {
+ $user->password_hash = $passwords->hash($password);
+ $this->provider->save($user);
+ }
+
+ return new Result(['success' => true, 'extraInfo' => $user]);
+ }
+
+ private function validIdentifier(mixed $identifier): bool
+ {
+ return is_string($identifier) && $identifier !== '' && strlen($identifier) <= 255
+ && preg_match('/^[^\p{Cc}]+$/uD', $identifier) === 1;
+ }
+
+ private function failedResult(): Result
+ {
+ return new Result(['success' => false, 'reason' => lang('Auth.badAttempt')]);
+ }
+}
diff --git a/src/Authentication/LDAP/LDAPConnection.php b/src/Authentication/LDAP/LDAPConnection.php
new file mode 100644
index 000000000..e1664b540
--- /dev/null
+++ b/src/Authentication/LDAP/LDAPConnection.php
@@ -0,0 +1,132 @@
+
+ *
+ * For the full copyright and license information, please view
+ * the LICENSE file that was distributed with this source code.
+ */
+
+namespace CodeIgniter\Shield\Authentication\LDAP;
+
+use Closure;
+use CodeIgniter\Shield\Exceptions\LDAPException;
+
+/**
+ * Immutable settings and a bind credential for an LDAP directory.
+ */
+final readonly class LDAPConnection
+{
+ /**
+ * @var Closure(): string
+ */
+ private Closure $readBindPassword;
+
+ /**
+ * Validate the directory settings and bind credential.
+ *
+ * @param array $hosts
+ * @param array $loginAttributes
+ * @param array $profileAttributes Local user field to LDAP attribute
+ *
+ * @throws LDAPException If the connection settings are invalid.
+ */
+ public function __construct(
+ public string $id,
+ public array $hosts,
+ public string $baseDn,
+ public string $bindDn,
+ string $bindPassword,
+ public string $encryption = 'ldaps',
+ public ?int $port = null,
+ public int $connectTimeout = 5,
+ public int $searchTimeout = 5,
+ public ?string $userBaseDn = null,
+ public string $loginFilter = '(objectClass=person)',
+ public array $loginAttributes = ['uid'],
+ public string $externalIdAttribute = 'entryUUID',
+ public array $profileAttributes = [],
+ public bool $provisionUsers = false,
+ public string $eligibilityFilter = '(objectClass=*)',
+ public bool $updateProfile = true,
+ ) {
+ if (preg_match('/\A[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}\z/', $id) !== 1
+ || $hosts === [] || count($hosts) > 10 || ! array_is_list($hosts)
+ || ! in_array($encryption, ['ldaps', 'starttls'], true)
+ || ($port !== null && ($port < 1 || $port > 65535))
+ || $connectTimeout < 1 || $connectTimeout > 60
+ || $searchTimeout < 1 || $searchTimeout > 60
+ || $loginAttributes === [] || count($loginAttributes) > 10 || ! array_is_list($loginAttributes)
+ || array_filter($hosts, is_string(...)) !== $hosts
+ || array_filter($loginAttributes, is_string(...)) !== $loginAttributes
+ || array_filter($profileAttributes, is_string(...)) !== $profileAttributes
+ ) {
+ throw new LDAPException('invalid_configuration');
+ }
+
+ foreach ($hosts as $host) {
+ if (filter_var($host, FILTER_VALIDATE_IP) === false
+ && filter_var($host, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) === false
+ ) {
+ throw new LDAPException('invalid_endpoint');
+ }
+ }
+
+ foreach ([$baseDn, $userBaseDn ?? $baseDn, $bindDn] as $dn) {
+ if (trim($dn) === '' || str_contains($dn, "\0")) {
+ throw new LDAPException('invalid_configuration');
+ }
+ }
+
+ if ($bindPassword === '' || str_contains($bindPassword, "\0")) {
+ throw new LDAPException('invalid_bind_secret');
+ }
+
+ LDAPFilter::validate($loginFilter);
+ LDAPFilter::validate($eligibilityFilter);
+
+ foreach ([$externalIdAttribute, ...$loginAttributes, ...array_values($profileAttributes)] as $attribute) {
+ LDAPFilter::validateAttribute($attribute);
+ }
+
+ // A closure keeps the secret out of JSON, var_export(), and serialization.
+ $this->readBindPassword = static fn (): string => $bindPassword;
+ }
+
+ /**
+ * Return the service account credential for the bind operation.
+ */
+ public function bindPassword(): string
+ {
+ return ($this->readBindPassword)();
+ }
+
+ /**
+ * Build a URI for a configured host with the configured or protocol-default port.
+ */
+ public function endpoint(string $host): string
+ {
+ $host = str_contains($host, ':') ? '[' . $host . ']' : $host;
+
+ return $this->encryption === 'ldaps'
+ ? 'ldaps://' . $host . ':' . ($this->port ?? 636)
+ : 'ldap://' . $host . ':' . ($this->port ?? 389);
+ }
+
+ /**
+ * Expose diagnostic connection settings while redacting the bind credential provider.
+ *
+ * @return array
+ */
+ public function __debugInfo(): array
+ {
+ $configuration = get_object_vars($this);
+ unset($configuration['readBindPassword']);
+
+ return $configuration;
+ }
+}
diff --git a/src/Authentication/LDAP/LDAPDirectoryInterface.php b/src/Authentication/LDAP/LDAPDirectoryInterface.php
new file mode 100644
index 000000000..5357f4c2e
--- /dev/null
+++ b/src/Authentication/LDAP/LDAPDirectoryInterface.php
@@ -0,0 +1,71 @@
+
+ *
+ * For the full copyright and license information, please view
+ * the LICENSE file that was distributed with this source code.
+ */
+
+namespace CodeIgniter\Shield\Authentication\LDAP;
+
+use CodeIgniter\Shield\Exceptions\LDAPException;
+
+/**
+ * Directory operations used for LDAP sign-in and application diagnostics.
+ */
+interface LDAPDirectoryInterface
+{
+ /**
+ * Check that the configured endpoint can establish and verify TLS.
+ *
+ * @throws LDAPException If no configured endpoint completes the TLS check.
+ */
+ public function testConnection(LDAPConnection $connection): void;
+
+ /**
+ * Check that an endpoint accepts the configured service account.
+ *
+ * @throws LDAPException If the service bind fails.
+ */
+ public function testBind(LDAPConnection $connection): void;
+
+ /**
+ * Search for one user, verify their password, and apply the eligibility filter.
+ *
+ * @param list $attributes
+ *
+ * @return array{dn: string, attributes: array>} Attribute names are lowercase.
+ *
+ * @throws LDAPException If the directory cannot verify one eligible user.
+ */
+ public function authenticate(
+ LDAPConnection $connection,
+ string $baseDn,
+ string $filter,
+ array $attributes,
+ string $password,
+ string $eligibilityFilter = '(objectClass=*)',
+ ): array;
+
+ /**
+ * Return a bounded sample using the service account.
+ *
+ * @param list $attributes
+ *
+ * @return list>}> Attribute names are lowercase.
+ *
+ * @throws LDAPException If the search fails or its inputs are invalid.
+ */
+ public function preview(
+ LDAPConnection $connection,
+ string $baseDn,
+ string $filter,
+ array $attributes,
+ int $limit = 20,
+ ): array;
+}
diff --git a/src/Authentication/LDAP/LDAPFilter.php b/src/Authentication/LDAP/LDAPFilter.php
new file mode 100644
index 000000000..238ee05a9
--- /dev/null
+++ b/src/Authentication/LDAP/LDAPFilter.php
@@ -0,0 +1,195 @@
+
+ *
+ * For the full copyright and license information, please view
+ * the LICENSE file that was distributed with this source code.
+ */
+
+namespace CodeIgniter\Shield\Authentication\LDAP;
+
+use CodeIgniter\Shield\Exceptions\LDAPException;
+
+/**
+ * Builds and validates LDAP filters, including safe encoding of assertion values.
+ */
+final class LDAPFilter
+{
+ private const IDENTIFIER = '(?:[a-zA-Z][a-zA-Z0-9-]*|(?:0|[1-9][0-9]*)(?:\.(?:0|[1-9][0-9]*))+)';
+ private const ATTRIBUTE = self::IDENTIFIER . '(?:;[a-zA-Z0-9-]+)*';
+
+ /**
+ * Match a literal attribute value, escaping wildcard characters as data.
+ */
+ public static function equal(string $attribute, string $value): string
+ {
+ self::validateAttribute($attribute);
+
+ return '(' . $attribute . '=' . self::escapeValue($value) . ')';
+ }
+
+ /**
+ * Combine one or more validated filters with LDAP's AND operator.
+ */
+ public static function all(string ...$filters): string
+ {
+ return self::combine('&', $filters);
+ }
+
+ /**
+ * Combine one or more validated filters with LDAP's OR operator.
+ */
+ public static function any(string ...$filters): string
+ {
+ return self::combine('|', $filters);
+ }
+
+ /**
+ * Negate a complete, validated LDAP filter.
+ */
+ public static function not(string $filter): string
+ {
+ self::validate($filter);
+
+ return '(!' . $filter . ')';
+ }
+
+ /**
+ * Encode assertion value bytes for interpolation into an LDAP filter per RFC 4515.
+ */
+ public static function escapeValue(string $value): string
+ {
+ return preg_replace_callback('/[\x00-\x1f\x7f-\xff()*\x5c]/', self::hexEscape(...), $value)
+ ?? throw new LDAPException('invalid_filter_value');
+ }
+
+ /**
+ * Encode a single naming attribute value in a distinguished name per RFC 4514.
+ */
+ public static function escapeDnComponent(string $value): string
+ {
+ return preg_replace_callback('/(^[ #]| $|[\x00-\x1f\x7f-\xff"+,;<>=\x5c])/', self::hexEscape(...), $value)
+ ?? throw new LDAPException('invalid_dn_component');
+ }
+
+ /**
+ * Check the syntax and length of an LDAP attribute description.
+ *
+ * @throws LDAPException If the attribute description is invalid.
+ */
+ public static function validateAttribute(string $attribute): void
+ {
+ if (strlen($attribute) > 128 || preg_match('/\A' . self::ATTRIBUTE . '\z/', $attribute) !== 1) {
+ throw new LDAPException('invalid_attribute');
+ }
+ }
+
+ /**
+ * Check the syntax, length, and nesting depth of a complete filter.
+ *
+ * @throws LDAPException If the filter is invalid or exceeds the parser limits.
+ */
+ public static function validate(string $filter): void
+ {
+ if (strlen($filter) > 16384 || preg_match('//u', $filter) !== 1 || self::parse($filter, 0, 0) !== strlen($filter)) {
+ throw new LDAPException('invalid_filter');
+ }
+ }
+
+ /**
+ * @param list $filters
+ */
+ private static function combine(string $operator, array $filters): string
+ {
+ foreach ($filters as $filter) {
+ self::validate($filter);
+ }
+
+ $combined = '(' . $operator . implode('', $filters) . ')';
+ self::validate($combined);
+
+ return $combined;
+ }
+
+ /**
+ * @param non-empty-list $match
+ */
+ private static function hexEscape(array $match): string
+ {
+ return '\\' . bin2hex($match[0]);
+ }
+
+ private static function parse(string $filter, int $offset, int $depth): int
+ {
+ if ($depth >= 32 || ($filter[$offset] ?? '') !== '(') {
+ throw new LDAPException('invalid_filter');
+ }
+
+ $offset++;
+ $operator = $filter[$offset] ?? '';
+
+ if ($operator === '&' || $operator === '|') {
+ $offset++;
+
+ do {
+ $offset = self::parse($filter, $offset, $depth + 1);
+ } while (($filter[$offset] ?? '') === '(');
+ } elseif ($operator === '!') {
+ $offset = self::parse($filter, $offset + 1, $depth + 1);
+ } else {
+ $length = strcspn($filter, '()', $offset);
+ self::validateItem(substr($filter, $offset, $length));
+ $offset += $length;
+ }
+
+ if (($filter[$offset] ?? '') !== ')') {
+ throw new LDAPException('invalid_filter');
+ }
+
+ return $offset + 1;
+ }
+
+ private static function validateItem(string $item): void
+ {
+ $delimiter = strpos($item, '=');
+
+ if ($delimiter === false) {
+ throw new LDAPException('invalid_filter');
+ }
+
+ $left = substr($item, 0, $delimiter);
+ $value = substr($item, $delimiter + 1);
+
+ if (str_ends_with($left, ':')) {
+ $name = '(?:' . self::ATTRIBUTE . '(?::dn)?(?::' . self::IDENTIFIER . ')?|(?::dn)?:' . self::IDENTIFIER . ')';
+
+ if (preg_match('/\A' . $name . ':\z/i', $left) !== 1) {
+ throw new LDAPException('invalid_filter');
+ }
+
+ self::validateValue($value, false);
+
+ return;
+ }
+
+ if (preg_match('/\A' . self::ATTRIBUTE . '(?[~<>]?)\z/', $left, $matches) !== 1) {
+ throw new LDAPException('invalid_filter');
+ }
+
+ self::validateValue($value, $matches['operator'] === '');
+ }
+
+ private static function validateValue(string $value, bool $allowWildcard): void
+ {
+ $excluded = $allowWildcard ? '\x00()' : '\x00()*';
+
+ if (preg_match('/\A(?:\x5c[0-9a-f]{2}|[^\x5c' . $excluded . '])*\z/i', $value) !== 1) {
+ throw new LDAPException('invalid_filter');
+ }
+ }
+}
diff --git a/src/Authentication/LDAP/LDAPUserResolver.php b/src/Authentication/LDAP/LDAPUserResolver.php
new file mode 100644
index 000000000..0ce60b4be
--- /dev/null
+++ b/src/Authentication/LDAP/LDAPUserResolver.php
@@ -0,0 +1,306 @@
+
+ *
+ * For the full copyright and license information, please view
+ * the LICENSE file that was distributed with this source code.
+ */
+
+namespace CodeIgniter\Shield\Authentication\LDAP;
+
+use Closure;
+use CodeIgniter\Database\BaseConnection;
+use CodeIgniter\Shield\Entities\User;
+use CodeIgniter\Shield\Entities\UserIdentity;
+use CodeIgniter\Shield\Exceptions\LDAPException;
+use CodeIgniter\Shield\Models\UserIdentityModel;
+use CodeIgniter\Shield\Models\UserModel;
+use Throwable;
+
+/**
+ * Resolves verified directory identities to Shield users.
+ */
+final readonly class LDAPUserResolver
+{
+ public const ID_TYPE = 'ldap';
+
+ private UserIdentityModel $identities;
+
+ /**
+ * Uses the standard identity model unless the caller supplies one.
+ */
+ public function __construct(private UserModel $users, ?UserIdentityModel $identities = null)
+ {
+ $this->identities = $identities ?? model(UserIdentityModel::class);
+ }
+
+ /**
+ * Resolve an immutable directory ID after credential and access checks.
+ *
+ * Profile keys must be explicitly mapped to writable UserModel columns.
+ * LDAP contact addresses cannot modify the local email/password identity.
+ *
+ * @param array $profile
+ */
+ public function resolve(
+ string $connectionId,
+ string $externalId,
+ array $profile = [],
+ bool $provision = false,
+ bool $updateProfile = true,
+ ): User {
+ $key = $this->identityKey($connectionId, $externalId);
+ $profile = $this->validateProfile($profile);
+
+ return $this->atomically(function () use ($connectionId, $key, $profile, $provision, $updateProfile): User {
+ $identity = $this->identities->getIdentityBySecret(self::ID_TYPE, $key);
+
+ if ($identity === null) {
+ if (! $provision) {
+ throw new LDAPException('user_not_provisioned');
+ }
+
+ $username = $profile['username'] ?? null;
+ if ($username === null) {
+ throw new LDAPException('invalid_profile');
+ }
+
+ $this->checkUsername($username);
+
+ $userId = $this->users->insert($profile);
+ if ($userId === true) {
+ throw new LDAPException('synchronization_conflict');
+ }
+
+ $user = $this->readBackProfile($userId, $profile);
+ $this->createIdentity($connectionId, $key, $userId);
+
+ return $user;
+ }
+
+ $user = $this->findUser($identity->user_id);
+ if (! $updateProfile || $user->isBanned() || ! $user->isActivated()) {
+ return $user;
+ }
+
+ $stored = $user->toRawArray();
+
+ foreach ($profile as $field => $value) {
+ if (array_key_exists($field, $stored) && $stored[$field] === $value) {
+ unset($profile[$field]);
+ }
+ }
+
+ if ($profile === []) {
+ return $user;
+ }
+
+ if (isset($profile['username'])) {
+ $this->checkUsername($profile['username'], $identity->user_id);
+ }
+
+ $this->users->update($identity->user_id, $profile);
+
+ return $this->readBackProfile($identity->user_id, $profile);
+ });
+ }
+
+ /**
+ * Explicitly associate a verified directory ID with a selected Shield user.
+ *
+ * The caller must authorize the link and verify the external ID. The
+ * resolver never selects the local account by a directory profile value.
+ */
+ public function link(string $connectionId, string $externalId, int|string $userId): User
+ {
+ $key = $this->identityKey($connectionId, $externalId);
+
+ return $this->atomically(function () use ($connectionId, $key, $userId): User {
+ $user = $this->findUser($userId);
+ $identity = $this->identities->getIdentityBySecret(self::ID_TYPE, $key);
+
+ if ($identity === null) {
+ $this->createIdentity($connectionId, $key, $userId);
+ } elseif ((string) $identity->user_id !== (string) $user->id) {
+ throw new LDAPException('identity_conflict');
+ }
+
+ return $user;
+ });
+ }
+
+ /**
+ * Convert AD's mixed-endian, 16-byte objectGUID to a canonical UUID.
+ */
+ public static function normalizeObjectGuid(string $bytes): string
+ {
+ if (strlen($bytes) !== 16) {
+ throw new LDAPException('invalid_identity');
+ }
+
+ return bin2hex(strrev(substr($bytes, 0, 4)))
+ . '-' . bin2hex(strrev(substr($bytes, 4, 2)))
+ . '-' . bin2hex(strrev(substr($bytes, 6, 2)))
+ . '-' . bin2hex(substr($bytes, 8, 2))
+ . '-' . bin2hex(substr($bytes, 10));
+ }
+
+ private function identityKey(string $connectionId, string $externalId): string
+ {
+ if (preg_match('/\A[a-zA-Z0-9_-]{1,64}\z/', $connectionId) !== 1 || $externalId === '' || strlen($externalId) > 1024) {
+ throw new LDAPException('invalid_identity');
+ }
+
+ return hash('sha256', $connectionId . "\0" . $externalId);
+ }
+
+ /**
+ * @param array $profile
+ *
+ * @return array
+ */
+ private function validateProfile(array $profile): array
+ {
+ $reserved = [
+ 'id', 'userid', 'email', 'password', 'passwordhash', 'secret', 'secret2',
+ 'identities', 'active', 'status', 'statusmessage', 'forcereset',
+ 'groups', 'permissions', 'createdat', 'updatedat', 'deletedat', 'lastactive',
+ ];
+
+ foreach (array_keys($profile) as $field) {
+ $collapsed = str_replace('_', '', strtolower($field));
+
+ if (preg_match('/\A[a-zA-Z][a-zA-Z0-9_]*\z/', $field) !== 1
+ || in_array($collapsed, $reserved, true)
+ || ($collapsed === 'username' && $field !== 'username')
+ ) {
+ throw new LDAPException('invalid_profile');
+ }
+ }
+
+ if (array_key_exists('username', $profile)) {
+ $username = $profile['username'];
+
+ if ($username === null
+ || trim($username) === ''
+ || str_contains($username, "\0")
+ || ! mb_check_encoding($username, 'UTF-8')
+ || mb_strlen($username, 'UTF-8') > 30
+ ) {
+ throw new LDAPException('invalid_profile');
+ }
+
+ $profile['username'] = strtolower($username);
+ }
+
+ return $profile;
+ }
+
+ private function checkUsername(string $username, int|string|null $ownerId = null): void
+ {
+ $owner = $this->users->findByCredentials(['username' => $username]);
+ if ($owner !== null && ($ownerId === null || (string) $owner->id !== (string) $ownerId)) {
+ throw new LDAPException('identity_conflict');
+ }
+ }
+
+ private function findUser(int|string $userId): User
+ {
+ $user = $this->users->findById($userId);
+ if ($user === null) {
+ throw new LDAPException('identity_conflict');
+ }
+
+ return $user;
+ }
+
+ /**
+ * @param array $profile
+ */
+ private function readBackProfile(int|string $userId, array $profile): User
+ {
+ $user = $this->findUser($userId);
+ $stored = $user->toRawArray();
+
+ foreach ($profile as $field => $value) {
+ if (! array_key_exists($field, $stored) || $stored[$field] !== $value) {
+ throw new LDAPException('invalid_profile');
+ }
+ }
+
+ return $user;
+ }
+
+ private function createIdentity(string $connectionId, string $key, int|string $userId): void
+ {
+ $this->identities->create(new UserIdentity([
+ 'user_id' => $userId,
+ 'type' => self::ID_TYPE,
+ 'name' => $connectionId,
+ 'secret' => $key,
+ ]));
+
+ $identity = $this->identities->getIdentityBySecret(self::ID_TYPE, $key);
+ if ($identity === null || (string) $identity->user_id !== (string) $userId) {
+ throw new LDAPException('synchronization_conflict');
+ }
+ }
+
+ /**
+ * @param Closure(): User $operation
+ */
+ private function atomically(Closure $operation): User
+ {
+ try {
+ $database = $this->users->builder()->db();
+ // CodeIgniter does not independently roll back nested transactions.
+ if ($database !== $this->identities->builder()->db()
+ || $database->transDepth !== 0
+ || ! $database->transStatus()
+ || ! $database->transBegin()
+ ) {
+ throw new LDAPException('synchronization_conflict');
+ }
+
+ $strict = $database->transStrict;
+ $database->transStrict(false);
+
+ try {
+ $user = $operation();
+ if (! $database->transComplete()) {
+ throw new LDAPException('synchronization_conflict');
+ }
+
+ return $user;
+ } finally {
+ try {
+ if ($database->transDepth !== 0) {
+ $this->rollBack($database);
+ }
+ } finally {
+ $database->transStrict($strict);
+ }
+ }
+ } catch (LDAPException $e) {
+ throw $e;
+ } catch (Throwable) {
+ // Model exceptions can contain SQL with directory and local account data.
+ throw new LDAPException('synchronization_conflict');
+ }
+ }
+
+ private function rollBack(BaseConnection $database): void
+ {
+ if ($database->transStatus()) {
+ $database->transRollback();
+ } else {
+ // Completing a failed non-strict transaction rolls back and resets its status.
+ $database->transComplete();
+ }
+ }
+}
diff --git a/src/Authentication/LDAP/NativeLDAPDirectory.php b/src/Authentication/LDAP/NativeLDAPDirectory.php
new file mode 100644
index 000000000..b91b18241
--- /dev/null
+++ b/src/Authentication/LDAP/NativeLDAPDirectory.php
@@ -0,0 +1,369 @@
+
+ *
+ * For the full copyright and license information, please view
+ * the LICENSE file that was distributed with this source code.
+ */
+
+namespace CodeIgniter\Shield\Authentication\LDAP;
+
+use CodeIgniter\Shield\Exceptions\LDAPException;
+use LDAP\Connection;
+use SensitiveParameter;
+
+/**
+ * Implements directory operations with PHP's LDAP extension and verified TLS.
+ *
+ * @phpstan-type DirectoryEntry array{dn: string, attributes: array>}
+ */
+final class NativeLDAPDirectory implements LDAPDirectoryInterface
+{
+ private const TIME_LIMIT_EXCEEDED = 3;
+ private const SIZE_LIMIT_EXCEEDED = 4;
+ private const REFERRAL = 10;
+ private const ADMIN_LIMIT = 11;
+ private const NO_SUCH_OBJECT = 32;
+ private const INVALID_CREDENTIALS = 49;
+ private const UNAVAILABLE = 52;
+
+ // OpenLDAP client-side result codes are not exposed by ext-ldap.
+ private const SERVER_DOWN = -1;
+ private const TIMEOUT = -5;
+ private const FILTER_ERROR = -7;
+ private const CONNECT_ERROR = -11;
+
+ /**
+ * {@inheritDoc}
+ *
+ * For LDAPS, an anonymous Root DSE lookup triggers the TLS handshake.
+ */
+ public function testConnection(LDAPConnection $connection): void
+ {
+ $ldap = $this->open($connection, false);
+ ldap_unbind($ldap);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public function testBind(LDAPConnection $connection): void
+ {
+ $ldap = $this->open($connection, true);
+ ldap_unbind($ldap);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * Rechecks the immutable identity on the same endpoint after the user bind.
+ */
+ public function authenticate(
+ LDAPConnection $connection,
+ string $baseDn,
+ string $filter,
+ array $attributes,
+ #[SensitiveParameter]
+ string $password,
+ string $eligibilityFilter = '(objectClass=*)',
+ ): array {
+ if ($password === '' || str_contains($password, "\0")) {
+ throw new LDAPException('invalid_credentials');
+ }
+
+ $attributes[] = $connection->externalIdAttribute;
+ $this->validateSearch($baseDn, $filter, $attributes);
+ LDAPFilter::validate($eligibilityFilter);
+
+ $ldap = $this->open($connection, true);
+
+ try {
+ $entry = $this->findExactlyOne($ldap, $connection, $baseDn, $filter, $attributes);
+ $idAttribute = strtolower($connection->externalIdAttribute);
+ $ids = $entry['attributes'][$idAttribute] ?? [];
+
+ if (count($ids) !== 1 || $ids[0] === '') {
+ throw new LDAPException('invalid_external_identity');
+ }
+
+ $sameIdentity = LDAPFilter::equal($connection->externalIdAttribute, $ids[0]);
+ $eligibility = LDAPFilter::all($filter, $eligibilityFilter, $sameIdentity);
+
+ // Keep all three binds on the selected endpoint, including behind load balancers.
+ // Any failure terminates this connection in the finally block.
+ $this->bind($ldap, $entry['dn'], $password, false);
+ $this->bind($ldap, $connection->bindDn, $connection->bindPassword(), true);
+
+ $verified = $this->findExactlyOne($ldap, $connection, $entry['dn'], $eligibility, $attributes, true);
+
+ if (($verified['attributes'][$idAttribute] ?? []) !== $ids) {
+ throw new LDAPException('directory_identity_changed');
+ }
+
+ return $verified;
+ } finally {
+ ldap_unbind($ldap);
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * Accepts a limit of one to 100 entries.
+ */
+ public function preview(
+ LDAPConnection $connection,
+ string $baseDn,
+ string $filter,
+ array $attributes,
+ int $limit = 20,
+ ): array {
+ if ($limit < 1 || $limit > 100) {
+ throw new LDAPException('invalid_search_limit');
+ }
+
+ $this->validateSearch($baseDn, $filter, $attributes);
+ $ldap = $this->open($connection, true);
+
+ try {
+ return $this->search($ldap, $connection, $baseDn, $filter, $attributes, $limit);
+ } finally {
+ ldap_unbind($ldap);
+ }
+ }
+
+ /**
+ * Use the OpenLDAP client's process-level TLS policy. Changing CA options at
+ * runtime can leave an older PHP build using a previously initialized context.
+ */
+ private function open(LDAPConnection $connection, bool $serviceBind): Connection
+ {
+ if (! extension_loaded('ldap')) {
+ throw new LDAPException('extension_unavailable');
+ }
+
+ if (! defined('LDAP_OPT_NETWORK_TIMEOUT') || ! defined('LDAP_OPT_TIMEOUT')
+ || ! defined('LDAP_OPT_X_TLS_REQUIRE_CERT') || ! defined('LDAP_OPT_X_TLS_DEMAND')
+ || ! defined('LDAP_OPT_X_TLS_HARD') || ! function_exists('ldap_start_tls')
+ ) {
+ throw new LDAPException('unsupported_ldap_client');
+ }
+
+ $failure = new LDAPException('directory_unavailable');
+
+ foreach ($connection->hosts as $host) {
+ $ldap = @ldap_connect($connection->endpoint($host));
+
+ if ($ldap === false) {
+ throw new LDAPException('tls_context_failed');
+ }
+
+ try {
+ $this->configure($ldap, $connection);
+
+ if ($connection->encryption === 'starttls' && ! @ldap_start_tls($ldap)) {
+ throw new LDAPException($this->transportFailure($ldap, ldap_errno($ldap)) ?? 'tls_failed');
+ }
+
+ if ($serviceBind) {
+ $this->bind($ldap, $connection->bindDn, $connection->bindPassword(), true);
+ } elseif ($connection->encryption === 'ldaps') {
+ // ldap_connect() does not perform I/O. Query the Root DSE without credentials.
+ $this->search($ldap, $connection, '', '(objectClass=*)', [], 1, true);
+ }
+
+ return $ldap;
+ } catch (LDAPException $exception) {
+ ldap_unbind($ldap);
+
+ if (! in_array($exception->reason, ['directory_unavailable', 'connection_timeout', 'search_timeout'], true)) {
+ throw $exception;
+ }
+
+ $failure = $exception;
+ }
+ }
+
+ throw $failure;
+ }
+
+ private function configure(Connection $ldap, LDAPConnection $connection): void
+ {
+ if (! ldap_get_option($ldap, LDAP_OPT_X_TLS_REQUIRE_CERT, $requireCert)
+ || ! in_array($requireCert, [LDAP_OPT_X_TLS_DEMAND, LDAP_OPT_X_TLS_HARD], true)
+ ) {
+ throw new LDAPException('tls_verification_required');
+ }
+
+ if (! ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3)
+ || ! ldap_set_option($ldap, LDAP_OPT_REFERRALS, false)
+ || ! ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_NEVER)
+ || ! ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, $connection->connectTimeout)
+ || ! ldap_set_option($ldap, LDAP_OPT_TIMEOUT, $connection->searchTimeout)
+ ) {
+ throw new LDAPException('connection_configuration_failed');
+ }
+ }
+
+ private function bind(Connection $ldap, string $dn, #[SensitiveParameter] string $password, bool $serviceAccount): void
+ {
+ // ext-ldap emits native warnings for rejected binds. Classify the result
+ // by LDAP error code so directory diagnostics stay out of PHP error output.
+ if (@ldap_bind($ldap, $dn, $password)) {
+ return;
+ }
+
+ $code = ldap_errno($ldap);
+
+ throw new LDAPException($this->transportFailure($ldap, $code)
+ ?? (! $serviceAccount && $code === self::INVALID_CREDENTIALS
+ ? 'invalid_credentials'
+ : ($serviceAccount ? 'service_bind_failed' : 'user_bind_failed')));
+ }
+
+ /**
+ * @param list $attributes
+ *
+ * @return DirectoryEntry
+ */
+ private function findExactlyOne(
+ Connection $ldap,
+ LDAPConnection $connection,
+ string $baseDn,
+ string $filter,
+ array $attributes,
+ bool $baseOnly = false,
+ ): array {
+ $entries = $this->search($ldap, $connection, $baseDn, $filter, $attributes, 2, $baseOnly);
+
+ if ($entries === []) {
+ throw new LDAPException($baseOnly ? 'ineligible_user' : 'user_not_found');
+ }
+
+ if (count($entries) > 1) {
+ throw new LDAPException('ambiguous_user');
+ }
+
+ return $entries[0];
+ }
+
+ /**
+ * @param list $attributes
+ *
+ * @return list
+ */
+ private function search(
+ Connection $ldap,
+ LDAPConnection $connection,
+ string $baseDn,
+ string $filter,
+ array $attributes,
+ int $limit,
+ bool $baseOnly = false,
+ ): array {
+ $attributes = $attributes === [] ? ['1.1'] : array_values(array_unique($attributes, SORT_STRING));
+ $search = $baseOnly ? ldap_read(...) : ldap_search(...);
+ $result = @$search($ldap, $baseDn, $filter, $attributes, 0, $limit, $connection->searchTimeout);
+
+ if ($result === false) {
+ $code = ldap_errno($ldap);
+
+ if ($baseOnly && $baseDn !== '' && $code === self::NO_SUCH_OBJECT) {
+ return [];
+ }
+
+ throw new LDAPException($this->searchFailure($ldap, $code));
+ }
+
+ if (! @ldap_parse_result($ldap, $result, $code) || ldap_first_reference($ldap, $result) !== false) {
+ throw new LDAPException('incomplete_search');
+ }
+
+ // Only accept the client-side size boundary when we actually received
+ // that many entries. A partial user search cannot establish uniqueness.
+ if ($code !== 0
+ && ($code !== self::SIZE_LIMIT_EXCEEDED || ldap_count_entries($ldap, $result) !== $limit)
+ ) {
+ throw new LDAPException($this->searchFailure($ldap, $code));
+ }
+
+ $entries = [];
+
+ for ($row = ldap_first_entry($ldap, $result); $row !== false; $row = ldap_next_entry($ldap, $row)) {
+ $dn = ldap_get_dn($ldap, $row);
+
+ if ($dn === false || ($dn === '' && $baseDn !== '') || str_contains($dn, "\0")) {
+ throw new LDAPException('invalid_directory_entry');
+ }
+
+ $values = [];
+
+ foreach ($attributes as $attribute) {
+ $found = @ldap_get_values_len($ldap, $row, $attribute);
+
+ if ($found !== false) {
+ unset($found['count']);
+ $values[strtolower($attribute)] = array_values($found);
+ }
+ }
+
+ $entries[] = ['dn' => $dn, 'attributes' => $values];
+ }
+
+ return $entries;
+ }
+
+ /**
+ * @param list $attributes
+ */
+ private function validateSearch(string $baseDn, string $filter, array $attributes): void
+ {
+ if (trim($baseDn) === '' || str_contains($baseDn, "\0") || count($attributes) > 64) {
+ throw new LDAPException('invalid_search');
+ }
+
+ LDAPFilter::validate($filter);
+
+ foreach ($attributes as $attribute) {
+ LDAPFilter::validateAttribute($attribute);
+ }
+ }
+
+ private function transportFailure(Connection $ldap, int $code): ?string
+ {
+ // These OpenLDAP errors also cover TLS validation failures. Recognize
+ // known certificate diagnostics without exposing the native message.
+ if (in_array($code, [self::SERVER_DOWN, self::CONNECT_ERROR], true)
+ && defined('LDAP_OPT_DIAGNOSTIC_MESSAGE')
+ && ldap_get_option($ldap, LDAP_OPT_DIAGNOSTIC_MESSAGE, $diagnostic)
+ && is_string($diagnostic)
+ && (str_starts_with($diagnostic, 'TLS: hostname does not match ')
+ || str_starts_with($diagnostic, 'TLS: unable to get subjectAltName')
+ || str_starts_with($diagnostic, 'TLS: peer cert untrusted')
+ || str_contains($diagnostic, 'certificate verify failed'))
+ ) {
+ return 'certificate_verification_failed';
+ }
+
+ return match ($code) {
+ self::TIMEOUT => 'connection_timeout',
+ self::SERVER_DOWN, self::CONNECT_ERROR, self::UNAVAILABLE => 'directory_unavailable',
+ default => null,
+ };
+ }
+
+ private function searchFailure(Connection $ldap, int $code): string
+ {
+ return match ($code) {
+ self::TIMEOUT, self::TIME_LIMIT_EXCEEDED => 'search_timeout',
+ self::SIZE_LIMIT_EXCEEDED, self::ADMIN_LIMIT, self::REFERRAL => 'incomplete_search',
+ self::FILTER_ERROR => 'invalid_filter',
+ default => $this->transportFailure($ldap, $code) ?? 'search_failed',
+ };
+ }
+}
diff --git a/src/Config/AuthLDAP.php b/src/Config/AuthLDAP.php
new file mode 100644
index 000000000..b16a95c6e
--- /dev/null
+++ b/src/Config/AuthLDAP.php
@@ -0,0 +1,125 @@
+
+ *
+ * For the full copyright and license information, please view
+ * the LICENSE file that was distributed with this source code.
+ */
+
+namespace CodeIgniter\Shield\Config;
+
+use CodeIgniter\Config\BaseConfig;
+use CodeIgniter\Shield\Authentication\LDAP\LDAPConnection;
+use CodeIgniter\Shield\Exceptions\LDAPException;
+use Throwable;
+
+/**
+ * Opt-in LDAP settings for choosing a directory or an explicitly reserved local account at login.
+ */
+class AuthLDAP extends BaseConfig
+{
+ /**
+ * Gate LDAP login even when the authenticator alias is registered.
+ */
+ public bool $enabled = false;
+
+ /**
+ * Connection ID used when the login identifier has no mapped UPN suffix.
+ */
+ public string $defaultConnection = '';
+
+ /**
+ * Directory settings keyed by connection ID. Declare bindPassword to allow
+ * CodeIgniter to override it through authldap.connections..bindPassword.
+ *
+ * @var array>
+ */
+ public array $connections = [
+ // 'corporate' => [
+ // 'hosts' => ['dc01.example.com', 'dc02.example.com'],
+ // 'baseDn' => 'DC=example,DC=com',
+ // 'bindDn' => 'CN=shield-reader,OU=Service Accounts,DC=example,DC=com',
+ // 'bindPassword' => '',
+ // 'encryption' => 'ldaps',
+ // 'userBaseDn' => 'OU=Users,DC=example,DC=com',
+ // 'loginFilter' => '(&(objectCategory=person)(objectClass=user))',
+ // 'loginAttributes' => ['sAMAccountName', 'userPrincipalName'],
+ // 'externalIdAttribute' => 'objectGUID',
+ // 'profileAttributes' => ['username' => 'sAMAccountName'],
+ // ],
+ ];
+
+ /**
+ * @var array Lowercase UPN suffix to connection ID.
+ */
+ public array $loginDomains = [];
+
+ /**
+ * @var array Case-insensitive login identifier to expected local user ID.
+ */
+ public array $localAccounts = [];
+
+ /**
+ * Retrieve the settings for the specified connection ID.
+ *
+ * Override this method to load a named connection from an application-owned provider.
+ *
+ * @throws LDAPException If the connection settings or bind password are missing or invalid.
+ */
+ public function getConnection(string $id): LDAPConnection
+ {
+ $settings = $this->connections[$id] ?? null;
+
+ if (! is_array($settings)
+ || ! isset($settings['hosts'], $settings['baseDn'], $settings['bindDn'])
+ || array_filter($settings, is_string(...), ARRAY_FILTER_USE_KEY) !== $settings
+ ) {
+ throw new LDAPException('invalid_configuration');
+ }
+
+ try {
+ return new LDAPConnection(
+ $id,
+ $settings['hosts'],
+ $settings['baseDn'],
+ $settings['bindDn'],
+ $settings['bindPassword'] ?? '',
+ ...array_diff_key($settings, ['hosts' => true, 'baseDn' => true, 'bindDn' => true, 'bindPassword' => true]),
+ );
+ } catch (Throwable $exception) {
+ // The constructor received the raw bind password as an argument.
+ throw new LDAPException($exception instanceof LDAPException ? $exception->reason : 'invalid_configuration');
+ }
+ }
+
+ /**
+ * List the connection IDs declared in the configuration.
+ *
+ * @return list
+ */
+ public function connectionIds(): array
+ {
+ return array_keys($this->connections);
+ }
+
+ /**
+ * Omit bind passwords from the PHP debug representation of this config.
+ *
+ * @return array
+ */
+ public function __debugInfo(): array
+ {
+ $configuration = get_object_vars($this);
+
+ foreach (array_filter($this->connections, is_array(...)) as $id => $settings) {
+ $configuration['connections'][$id] = array_diff_key($settings, ['bindPassword' => true]);
+ }
+
+ return $configuration;
+ }
+}
diff --git a/src/Config/Services.php b/src/Config/Services.php
index 88e5e05c2..f39c476a6 100644
--- a/src/Config/Services.php
+++ b/src/Config/Services.php
@@ -16,6 +16,8 @@
use CodeIgniter\Config\BaseService;
use CodeIgniter\Shield\Auth;
use CodeIgniter\Shield\Authentication\JWTManager;
+use CodeIgniter\Shield\Authentication\LDAP\LDAPDirectoryInterface;
+use CodeIgniter\Shield\Authentication\LDAP\NativeLDAPDirectory;
use CodeIgniter\Shield\Authentication\Passwords;
use CodeIgniter\Shield\Config\Auth as AuthConfig;
@@ -59,4 +61,16 @@ public static function jwtmanager(bool $getShared = true): JWTManager
return new JWTManager();
}
+
+ /**
+ * Supplies the directory transport used for LDAP sign-in and diagnostics.
+ */
+ public static function ldapDirectory(bool $getShared = true): LDAPDirectoryInterface
+ {
+ if ($getShared) {
+ return self::getSharedInstance('ldapDirectory');
+ }
+
+ return new NativeLDAPDirectory();
+ }
}
diff --git a/src/Exceptions/LDAPException.php b/src/Exceptions/LDAPException.php
new file mode 100644
index 000000000..828f46c0c
--- /dev/null
+++ b/src/Exceptions/LDAPException.php
@@ -0,0 +1,28 @@
+
+ *
+ * For the full copyright and license information, please view
+ * the LICENSE file that was distributed with this source code.
+ */
+
+namespace CodeIgniter\Shield\Exceptions;
+
+/**
+ * Reports LDAP failures using sanitized diagnostic reason codes.
+ */
+final class LDAPException extends RuntimeException
+{
+ /**
+ * Localizes the message for the supplied diagnostic reason code.
+ */
+ public function __construct(public readonly string $reason)
+ {
+ parent::__construct(lang('Auth.ldapOperationFailed', [$reason]));
+ }
+}
diff --git a/src/Language/ar/Auth.php b/src/Language/ar/Auth.php
index d90c15d05..d806de71d 100644
--- a/src/Language/ar/Auth.php
+++ b/src/Language/ar/Auth.php
@@ -14,6 +14,7 @@
return [
// Exceptions
'unknownAuthenticator' => '{0} ليس توثيق صحيح.',
+ 'ldapOperationFailed' => 'فشلت عملية LDAP ({0}).',
'unknownUserProvider' => 'تعذر تحديد موفر المستخدم الذي يجب استخدامه.',
'invalidUser' => 'تعذر تحديد المستخدم المدخل.',
'bannedUser' => 'لا يمكن تسجيل الدخول حيث أن حسابك موقوف حالياً.',
diff --git a/src/Language/bg/Auth.php b/src/Language/bg/Auth.php
index a52b52b7f..8c34bed01 100644
--- a/src/Language/bg/Auth.php
+++ b/src/Language/bg/Auth.php
@@ -14,6 +14,7 @@
return [
// Изключения
'unknownAuthenticator' => '{0} не е валиден аутентикатор.',
+ 'ldapOperationFailed' => 'Операцията с LDAP е неуспешна ({0}).',
'unknownUserProvider' => 'Не може да се определи използваният потребителски доставчик.',
'invalidUser' => 'Не може да се намери посоченият потребител.',
'bannedUser' => 'Не може да влезете в профила си, тъй като сте баннати.',
diff --git a/src/Language/cs/Auth.php b/src/Language/cs/Auth.php
index 47e0087e6..3eeecef20 100644
--- a/src/Language/cs/Auth.php
+++ b/src/Language/cs/Auth.php
@@ -14,6 +14,7 @@
return [
// Exceptions
'unknownAuthenticator' => '{0} není platný autentifikátor.',
+ 'ldapOperationFailed' => 'Operace LDAP se nezdařila ({0}).',
'unknownUserProvider' => 'Není možné určit providera uživatele, který se má použít.',
'invalidUser' => 'Nelze najít požadovaného uživatele.',
'bannedUser' => 'Přihlášení se nezdařilo, protože jste byli zablokováni.',
diff --git a/src/Language/de/Auth.php b/src/Language/de/Auth.php
index 334ab5602..0031746ca 100644
--- a/src/Language/de/Auth.php
+++ b/src/Language/de/Auth.php
@@ -14,6 +14,7 @@
return [
// Exceptions
'unknownAuthenticator' => '{0} ist kein gültiger Authentifikator.',
+ 'ldapOperationFailed' => 'Der LDAP-Vorgang ist fehlgeschlagen ({0}).',
'unknownUserProvider' => 'Der zu verwendende User Provider konnte nicht ermittelt werden.',
'invalidUser' => 'Der angegebene Benutzer kann nicht gefunden werden.',
'bannedUser' => 'Anmelden nicht möglich da Ihr Benutzer derzeit gesperrt ist.',
diff --git a/src/Language/en/Auth.php b/src/Language/en/Auth.php
index 53de815d2..8b75aa737 100644
--- a/src/Language/en/Auth.php
+++ b/src/Language/en/Auth.php
@@ -14,6 +14,7 @@
return [
// Exceptions
'unknownAuthenticator' => '{0} is not a valid authenticator.',
+ 'ldapOperationFailed' => 'LDAP operation failed ({0}).',
'unknownUserProvider' => 'Unable to determine the User Provider to use.',
'invalidUser' => 'Unable to locate the specified user.',
'bannedUser' => 'Can not log you in as you are currently banned.',
diff --git a/src/Language/es/Auth.php b/src/Language/es/Auth.php
index 45b55fa76..c5b04be39 100644
--- a/src/Language/es/Auth.php
+++ b/src/Language/es/Auth.php
@@ -14,6 +14,7 @@
return [
// Excepciones
'unknownAuthenticator' => '{0} no es un autenticador válido.',
+ 'ldapOperationFailed' => 'Error en la operación LDAP ({0}).',
'unknownUserProvider' => 'No se puede determinar el proveedor de usuario a utilizar.',
'invalidUser' => 'No se puede localizar al usuario especificado.',
'bannedUser' => 'No puedes iniciar sesión ya que estás actualmente vetado.',
diff --git a/src/Language/fa/Auth.php b/src/Language/fa/Auth.php
index 4ded5695c..6869944bc 100644
--- a/src/Language/fa/Auth.php
+++ b/src/Language/fa/Auth.php
@@ -14,6 +14,7 @@
return [
// Exceptions
'unknownAuthenticator' => '{0} احراز هویت معتبری نمی باشد.',
+ 'ldapOperationFailed' => 'عملیات LDAP ناموفق بود ({0}).',
'unknownUserProvider' => 'قادر به تعیین ارائه دهنده کاربر برای استفاده نیست.',
'invalidUser' => 'قادر به پیداکردن کاربر مشخص شده نیست',
'bannedUser' => 'در حال حاضر نمی توانید وارد شوید، چون مسدود شده اید.',
diff --git a/src/Language/fr/Auth.php b/src/Language/fr/Auth.php
index d0e326c4a..c72efd866 100644
--- a/src/Language/fr/Auth.php
+++ b/src/Language/fr/Auth.php
@@ -14,6 +14,7 @@
return [
// Exceptions
'unknownAuthenticator' => '{0} n\'est pas un authentificateur valide.',
+ 'ldapOperationFailed' => 'L’opération LDAP a échoué ({0}).',
'unknownUserProvider' => 'Impossible de déterminer le User Provider à utiliser.',
'invalidUser' => 'Impossible de trouver l\'utilisateur.',
'bannedUser' => 'Impossible de vous connecter car vous êtes actuellement banni.',
diff --git a/src/Language/id/Auth.php b/src/Language/id/Auth.php
index 76d99d88c..da651a641 100644
--- a/src/Language/id/Auth.php
+++ b/src/Language/id/Auth.php
@@ -14,6 +14,7 @@
return [
// Exceptions
'unknownAuthenticator' => '{0} bukan otentikator yang sah.',
+ 'ldapOperationFailed' => 'Operasi LDAP gagal ({0}).',
'unknownUserProvider' => 'Tidak dapat menentukan Penyedia Pengguna yang akan digunakan.',
'invalidUser' => 'Tidak dapat menemukan pengguna yang spesifik.',
'bannedUser' => 'Anda tidak dapat masuk karena saat ini Anda diblokir.',
diff --git a/src/Language/it/Auth.php b/src/Language/it/Auth.php
index 40b2517bf..cd37956ae 100644
--- a/src/Language/it/Auth.php
+++ b/src/Language/it/Auth.php
@@ -14,6 +14,7 @@
return [
// Exceptions
'unknownAuthenticator' => '{0} non è un autenticatore valido.',
+ 'ldapOperationFailed' => 'L’operazione LDAP non è riuscita ({0}).',
'unknownUserProvider' => 'Impossibile determinare lo User Provider da usare.',
'invalidUser' => 'Impossibile trovere l\'utente specificato.',
'bannedUser' => 'Impossibile effettuare il login, l\'account è stato disabilitato.',
diff --git a/src/Language/ja/Auth.php b/src/Language/ja/Auth.php
index 7bbda186a..e4fb90994 100644
--- a/src/Language/ja/Auth.php
+++ b/src/Language/ja/Auth.php
@@ -14,6 +14,7 @@
return [
// Exceptions
'unknownAuthenticator' => '{0} は有効なオーセンティケーターではありません。', // '{0} is not a valid authenticator.'
+ 'ldapOperationFailed' => 'LDAP 操作に失敗しました({0})。',
'unknownUserProvider' => '使用するユーザープロバイダーを決定できません。', // 'Unable to determine the User Provider to use.'
'invalidUser' => '指定されたユーザーを見つけることができません。', // 'Unable to locate the specified user.'
'bannedUser' => '現在あなたはアクセスが禁止されているため、ログインできません。', // 'Can not log you in as you are currently banned.'
diff --git a/src/Language/lt/Auth.php b/src/Language/lt/Auth.php
index 87c4727e0..acc3487a1 100644
--- a/src/Language/lt/Auth.php
+++ b/src/Language/lt/Auth.php
@@ -14,6 +14,7 @@
return [
// Exceptions
'unknownAuthenticator' => '{0} nėra galiojantis autentifikatorius.',
+ 'ldapOperationFailed' => 'LDAP operacija nepavyko ({0}).',
'unknownUserProvider' => 'Nepavyksta nustatyti, kokį naudotojų šaltinį naudoti.',
'invalidUser' => 'Nepavyksta rasti nurodyto naudotojo.',
'bannedUser' => 'Negalite prisijungti, nes esate užblokuotas.',
diff --git a/src/Language/nl/Auth.php b/src/Language/nl/Auth.php
index fa960198c..04e7c4c44 100644
--- a/src/Language/nl/Auth.php
+++ b/src/Language/nl/Auth.php
@@ -14,6 +14,7 @@
return [
// Exceptions
'unknownAuthenticator' => '{0} is geen geldige authenticator.',
+ 'ldapOperationFailed' => 'De LDAP-bewerking is mislukt ({0}).',
'unknownUserProvider' => 'Kan geen geldige gebruikersprovider bepalen.',
'invalidUser' => 'Kan de opgegeven gebruiker niet vinden.',
'bannedUser' => 'Je kan niet inloggen omdat je account geblokkeerd is.',
diff --git a/src/Language/pl/Auth.php b/src/Language/pl/Auth.php
index bca499379..8051821e1 100644
--- a/src/Language/pl/Auth.php
+++ b/src/Language/pl/Auth.php
@@ -14,6 +14,7 @@
return [
// Exceptions
'unknownAuthenticator' => '{0} nie jest poprawnym autentykatorem.',
+ 'ldapOperationFailed' => 'Operacja LDAP nie powiodła się ({0}).',
'unknownUserProvider' => 'Nie można określić User Provider do użycia.',
'invalidUser' => 'Nie można zlokalizować określonego użytkownika.',
'bannedUser' => 'Nie możesz cię zalogować, ponieważ jesteś obecnie zbanowany.',
diff --git a/src/Language/pt-BR/Auth.php b/src/Language/pt-BR/Auth.php
index a1f4a57fc..517ed37ff 100644
--- a/src/Language/pt-BR/Auth.php
+++ b/src/Language/pt-BR/Auth.php
@@ -14,6 +14,7 @@
return [
// Exceptions
'unknownAuthenticator' => '{0} não é um autenticador válido.',
+ 'ldapOperationFailed' => 'A operação LDAP falhou ({0}).',
'unknownUserProvider' => 'Não foi possível determinar o provedor de usuário a ser usado.',
'invalidUser' => 'Não foi possível localizar o usuário especificado.',
'bannedUser' => 'Não é possível fazer login, pois você está banido no momento.',
diff --git a/src/Language/pt/Auth.php b/src/Language/pt/Auth.php
index 3a41ca093..5338894ca 100644
--- a/src/Language/pt/Auth.php
+++ b/src/Language/pt/Auth.php
@@ -14,6 +14,7 @@
return [
// Exceptions
'unknownAuthenticator' => '{0} não é um autenticador válido.',
+ 'ldapOperationFailed' => 'A operação LDAP falhou ({0}).',
'unknownUserProvider' => 'Não foi possível determinar o provedor de utilizador a ser usado.',
'invalidUser' => 'Não foi possível localizar o utilizador especificado.',
'bannedUser' => 'Não é possível fazer login porque está banido de momento.',
diff --git a/src/Language/ru/Auth.php b/src/Language/ru/Auth.php
index f6da8aeed..d97e6a8e1 100644
--- a/src/Language/ru/Auth.php
+++ b/src/Language/ru/Auth.php
@@ -14,6 +14,7 @@
return [
// Exceptions
'unknownAuthenticator' => '{0} не является действительным аутентификатором.',
+ 'ldapOperationFailed' => 'Не удалось выполнить операцию LDAP ({0}).',
'unknownUserProvider' => 'Не удалось определить поставщика пользователей.',
'invalidUser' => 'Не удалось найти указанного пользователя.',
'bannedUser' => 'Невозможно войти, так как вы заблокированы.',
diff --git a/src/Language/sk/Auth.php b/src/Language/sk/Auth.php
index 6982b30a8..2fc83d3f2 100644
--- a/src/Language/sk/Auth.php
+++ b/src/Language/sk/Auth.php
@@ -14,6 +14,7 @@
return [
// Exceptions
'unknownAuthenticator' => '{0} nie je platný autentifikátor.',
+ 'ldapOperationFailed' => 'Operácia LDAP zlyhala ({0}).',
'unknownUserProvider' => 'Nie je možné určiť poskytovateľa používateľa, ktorý sa má použiť.',
'invalidUser' => 'Nie je možné nájsť zadaného používateľa.',
'bannedUser' => 'Prihlásenie zlyhalo, pretože ste dostali zákaz vstupu (ban).',
diff --git a/src/Language/sr/Auth.php b/src/Language/sr/Auth.php
index 372f849db..5cd8c151c 100644
--- a/src/Language/sr/Auth.php
+++ b/src/Language/sr/Auth.php
@@ -14,6 +14,7 @@
return [
// Exceptions
'unknownAuthenticator' => '{0} nije validan autentikator.',
+ 'ldapOperationFailed' => 'LDAP operacija nije uspela ({0}).',
'unknownUserProvider' => 'Nemoguće je odlučiti koji User Provider koristiti.',
'invalidUser' => 'Nemoguće locirati specifičnog korisnika.',
'bannedUser' => 'Nije moguće pristupanje sistemu.Vaš nalog je banovan.',
diff --git a/src/Language/sv-SE/Auth.php b/src/Language/sv-SE/Auth.php
index ecc97af1d..4192a09d9 100644
--- a/src/Language/sv-SE/Auth.php
+++ b/src/Language/sv-SE/Auth.php
@@ -14,6 +14,7 @@
return [
// Exceptions
'unknownAuthenticator' => '{0} är inte en giltig autentiseringsmetod.',
+ 'ldapOperationFailed' => 'LDAP-åtgärden misslyckades ({0}).',
'unknownUserProvider' => 'Kunde inte bestämma vilken User Provider som skall användas.',
'invalidUser' => 'Kan inte hitta angiven användare.',
'bannedUser' => 'Kan inte logga in dig eftersom du är avstängd.',
diff --git a/src/Language/tr/Auth.php b/src/Language/tr/Auth.php
index ac45a6b1f..9edcdb5ee 100644
--- a/src/Language/tr/Auth.php
+++ b/src/Language/tr/Auth.php
@@ -14,6 +14,7 @@
return [
// Exceptions
'unknownAuthenticator' => '{0} geçerli bir kimlik doğrulayıcı değil.',
+ 'ldapOperationFailed' => 'LDAP işlemi başarısız oldu ({0}).',
'unknownUserProvider' => 'Kullanılacak Kullanıcı Sağlayıcı belirlenemiyor.',
'invalidUser' => 'Belirtilen kullanıcı bulunamadı.',
'bannedUser' => 'Bu hesap yasaklandı. Şu anda giriş yapamazsınız.',
diff --git a/src/Language/uk/Auth.php b/src/Language/uk/Auth.php
index a71cb68c7..3e75470e8 100644
--- a/src/Language/uk/Auth.php
+++ b/src/Language/uk/Auth.php
@@ -14,6 +14,7 @@
return [
// Exceptions
'unknownAuthenticator' => '{0} не є дійсним автентифікатором.',
+ 'ldapOperationFailed' => 'Не вдалося виконати операцію LDAP ({0}).',
'unknownUserProvider' => 'Неможливо визначити постачальника користувача для використання.',
'invalidUser' => 'Неможливо знайти вказаного користувача.',
'bannedUser' => 'Неможливо увійти, оскільки ви зараз заблоковані.',
diff --git a/tests/Authentication/Authenticators/LDAPAuthenticatorTest.php b/tests/Authentication/Authenticators/LDAPAuthenticatorTest.php
new file mode 100644
index 000000000..5ae138453
--- /dev/null
+++ b/tests/Authentication/Authenticators/LDAPAuthenticatorTest.php
@@ -0,0 +1,210 @@
+
+ *
+ * For the full copyright and license information, please view
+ * the LICENSE file that was distributed with this source code.
+ */
+
+namespace CodeIgniter\Shield\Tests\Authentication\Authenticators;
+
+use CodeIgniter\Database\BaseBuilder;
+use CodeIgniter\Database\BaseConnection;
+use CodeIgniter\Shield\Authentication\Actions\EmailActivator;
+use CodeIgniter\Shield\Authentication\Authenticators\LDAP;
+use CodeIgniter\Shield\Authentication\LDAP\LDAPConnection;
+use CodeIgniter\Shield\Authentication\LDAP\LDAPDirectoryInterface;
+use CodeIgniter\Shield\Authentication\LDAP\LDAPUserResolver;
+use CodeIgniter\Shield\Config\AuthLDAP;
+use CodeIgniter\Shield\Entities\User;
+use CodeIgniter\Shield\Entities\UserIdentity;
+use CodeIgniter\Shield\Models\UserIdentityModel;
+use CodeIgniter\Shield\Models\UserModel;
+use CodeIgniter\Shield\Tests\TestCase;
+use PHPUnit\Framework\Attributes\DataProvider;
+use PHPUnit\Framework\MockObject\MockObject;
+
+/**
+ * @internal
+ */
+final class LDAPAuthenticatorTest extends TestCase
+{
+ private const CREDENTIALS = ['username' => 'directory-user', 'password' => 'test-password'];
+ private const ENTRY = ['uid' => ['directory-user'], 'employeenumber' => ['immutable-id']];
+
+ private LDAPDirectoryInterface&MockObject $directory;
+ private MockObject&UserModel $users;
+ private MockObject&UserIdentityModel $identities;
+
+ protected function setUp(): void
+ {
+ parent::setUp();
+
+ $this->directory = $this->createMock(LDAPDirectoryInterface::class);
+ $this->users = $this->createMock(UserModel::class);
+ $this->identities = $this->createMock(UserIdentityModel::class);
+ }
+
+ #[DataProvider('provideRejectsInvalidCredentialsBeforeDirectoryLookup')]
+ public function testRejectsInvalidCredentialsBeforeDirectoryLookup(string $field, string $value): void
+ {
+ $this->directory->expects($this->never())->method('authenticate');
+ $this->users->expects($this->never())->method('builder');
+ $result = $this->authenticator()->check([$field => $value] + self::CREDENTIALS);
+
+ $this->assertFalse($result->isOK());
+ $this->assertSame(lang('Auth.badAttempt'), $result->reason());
+ }
+
+ /**
+ * @return iterable
+ */
+ public static function provideRejectsInvalidCredentialsBeforeDirectoryLookup(): iterable
+ {
+ yield 'long identifier' => ['username', str_repeat('a', 256)];
+
+ yield 'control character in identifier' => ['username', "directory\nuser"];
+
+ yield 'long password' => ['password', str_repeat('p', 4097)];
+
+ yield 'NUL in password' => ['password', "pass\0word"];
+ }
+
+ #[DataProvider('provideRejectsMultipleValuesForSingleValuedAttributes')]
+ public function testRejectsMultipleValuesForSingleValuedAttributes(string $attribute, string $reason): void
+ {
+ $this->mockDirectoryEntry([$attribute => ['first', 'second']] + self::ENTRY);
+ $this->users->expects($this->never())->method('builder');
+ $result = $this->authenticator()->check(self::CREDENTIALS);
+
+ $this->assertFalse($result->isOK());
+ $this->assertSame(lang('Auth.badAttempt'), $result->reason());
+ $this->assertLogged('debug', "Shield LDAP login rejected ({$reason}).");
+ }
+
+ /**
+ * @return iterable
+ */
+ public static function provideRejectsMultipleValuesForSingleValuedAttributes(): iterable
+ {
+ yield 'external ID' => ['employeenumber', 'invalid_identity'];
+
+ yield 'mapped profile field' => ['uid', 'invalid_profile'];
+ }
+
+ #[DataProvider('provideRejectsIneligibleLinkedUsers')]
+ public function testRejectsIneligibleLinkedUsers(bool $banned): void
+ {
+ setting('Auth.actions', ['register' => EmailActivator::class, 'login' => null]);
+ $user = new User([
+ 'id' => 42,
+ 'username' => 'existing-user',
+ 'status' => $banned ? 'banned' : null,
+ 'active' => $banned,
+ ]);
+
+ $this->mockDirectoryEntry(self::ENTRY);
+ $this->mockIdentityLookup($user);
+ $this->users->expects($this->never())->method('update');
+ $result = $this->authenticator()->check(self::CREDENTIALS);
+
+ $this->assertFalse($result->isOK());
+ $this->assertSame(lang('Auth.badAttempt'), $result->reason());
+ }
+
+ /**
+ * @return iterable
+ */
+ public static function provideRejectsIneligibleLinkedUsers(): iterable
+ {
+ yield 'banned user' => [true];
+
+ yield 'unactivated user' => [false];
+ }
+
+ public function testRejectsUnlinkedUserWhenProvisioningIsDisabled(): void
+ {
+ $this->mockDirectoryEntry(self::ENTRY);
+ $this->mockIdentityLookup(null);
+ $this->users->expects($this->never())->method('insert');
+ $this->identities->expects($this->never())->method('create');
+ $result = $this->authenticator(provisionUsers: false)->check(self::CREDENTIALS);
+
+ $this->assertFalse($result->isOK());
+ $this->assertSame(lang('Auth.badAttempt'), $result->reason());
+ $this->assertLogged('debug', 'Shield LDAP login rejected (user_not_provisioned).');
+ }
+
+ public function testReturnsLinkedUserWithoutWritingWhenProfileUpdatesAreDisabled(): void
+ {
+ $user = new User(['id' => 42, 'username' => 'existing-user']);
+ $this->mockDirectoryEntry(self::ENTRY);
+ $this->mockIdentityLookup($user);
+ $this->users->expects($this->never())->method('update');
+ $result = $this->authenticator(updateProfile: false)->check(self::CREDENTIALS);
+
+ $this->assertTrue($result->isOK());
+ $this->assertSame($user, $result->extraInfo());
+ $this->assertSame('existing-user', $user->username);
+ }
+
+ private function authenticator(bool $provisionUsers = true, bool $updateProfile = true): LDAP
+ {
+ $connection = new LDAPConnection(
+ id: 'corporate',
+ hosts: ['ldap.example.test'],
+ baseDn: 'dc=example,dc=test',
+ bindDn: 'cn=reader,dc=example,dc=test',
+ bindPassword: 'test-service-password',
+ externalIdAttribute: 'employeeNumber',
+ profileAttributes: ['username' => 'uid'],
+ provisionUsers: $provisionUsers,
+ updateProfile: $updateProfile,
+ );
+ $config = $this->createPartialMock(AuthLDAP::class, ['getConnection']);
+ $config->enabled = true;
+ $config->defaultConnection = $connection->id;
+ $config->method('getConnection')->with($connection->id)->willReturn($connection);
+
+ return new LDAP($this->users, $config, $this->directory, new LDAPUserResolver($this->users, $this->identities));
+ }
+
+ /**
+ * @param array> $attributes
+ */
+ private function mockDirectoryEntry(array $attributes): void
+ {
+ $this->directory->expects($this->once())->method('authenticate')->willReturn([
+ 'dn' => 'uid=directory-user,dc=example,dc=test',
+ 'attributes' => $attributes,
+ ]);
+ }
+
+ private function mockIdentityLookup(?User $user): void
+ {
+ $database = $this->createMock(BaseConnection::class);
+ $database->method('__get')->willReturnMap([['transDepth', 0], ['transStrict', true]]);
+ $database->method('transStatus')->willReturn(true);
+ $database->method('transBegin')->willReturn(true);
+ $database->method('transComplete')->willReturn(true);
+
+ $builder = $this->createMock(BaseBuilder::class);
+ $builder->method('db')->willReturn($database);
+ $this->users->method('builder')->willReturn($builder);
+ $this->identities->method('builder')->willReturn($builder);
+
+ $identity = $user === null ? null : new UserIdentity(['user_id' => $user->id]);
+ $this->identities->expects($this->once())->method('getIdentityBySecret')
+ ->with(LDAPUserResolver::ID_TYPE, hash('sha256', "corporate\0immutable-id"))
+ ->willReturn($identity);
+
+ if ($user !== null) {
+ $this->users->expects($this->once())->method('findById')->with($user->id)->willReturn($user);
+ }
+ }
+}
diff --git a/tests/Authentication/LDAP/LDAPConnectionTest.php b/tests/Authentication/LDAP/LDAPConnectionTest.php
new file mode 100644
index 000000000..614f155fd
--- /dev/null
+++ b/tests/Authentication/LDAP/LDAPConnectionTest.php
@@ -0,0 +1,150 @@
+
+ *
+ * For the full copyright and license information, please view
+ * the LICENSE file that was distributed with this source code.
+ */
+
+namespace CodeIgniter\Shield\Tests\Authentication\LDAP;
+
+use CodeIgniter\Shield\Authentication\LDAP\LDAPConnection;
+use CodeIgniter\Shield\Exceptions\LDAPException;
+use PHPUnit\Framework\Attributes\DataProvider;
+use PHPUnit\Framework\TestCase;
+
+/**
+ * @internal
+ */
+final class LDAPConnectionTest extends TestCase
+{
+ #[DataProvider('provideAcceptsBoundaryValues')]
+ public function testAcceptsBoundaryValues(int $port, int $timeout, int $hostCount): void
+ {
+ $hosts = array_fill(0, $hostCount, 'ldap.example.test');
+ $connection = new LDAPConnection(
+ 'test',
+ $hosts,
+ 'dc=example,dc=test',
+ 'cn=reader,dc=example,dc=test',
+ 'readerPassword!',
+ port: $port,
+ connectTimeout: $timeout,
+ searchTimeout: $timeout,
+ );
+
+ $this->assertSame($port, $connection->port);
+ $this->assertSame($timeout, $connection->connectTimeout);
+ $this->assertSame($timeout, $connection->searchTimeout);
+ $this->assertSame($hosts, $connection->hosts);
+ }
+
+ /**
+ * @return iterable
+ */
+ public static function provideAcceptsBoundaryValues(): iterable
+ {
+ yield 'minimum' => [1, 1, 1];
+
+ yield 'maximum' => [65535, 60, 10];
+ }
+
+ #[DataProvider('provideRejectsOutOfRangeConfiguration')]
+ public function testRejectsOutOfRangeConfiguration(?int $port, int $connectTimeout, int $searchTimeout, int $hostCount): void
+ {
+ $this->expectException(LDAPException::class);
+ $this->expectExceptionMessage('invalid_configuration');
+
+ new LDAPConnection(
+ 'test',
+ array_fill(0, $hostCount, 'ldap.example.test'),
+ 'dc=example,dc=test',
+ 'cn=reader,dc=example,dc=test',
+ 'readerPassword!',
+ port: $port,
+ connectTimeout: $connectTimeout,
+ searchTimeout: $searchTimeout,
+ );
+ }
+
+ /**
+ * @return iterable
+ */
+ public static function provideRejectsOutOfRangeConfiguration(): iterable
+ {
+ yield 'port below minimum' => [0, 5, 5, 1];
+
+ yield 'port above maximum' => [65536, 5, 5, 1];
+
+ yield 'connect timeout below minimum' => [null, 0, 5, 1];
+
+ yield 'connect timeout above maximum' => [null, 61, 5, 1];
+
+ yield 'search timeout below minimum' => [null, 5, 0, 1];
+
+ yield 'search timeout above maximum' => [null, 5, 61, 1];
+
+ yield 'empty host list' => [null, 5, 5, 0];
+
+ yield 'too many hosts' => [null, 5, 5, 11];
+ }
+
+ #[DataProvider('provideFormatsIPv6Endpoints')]
+ public function testFormatsIPv6Endpoints(string $encryption, ?int $port, string $expected): void
+ {
+ $host = '2001:db8::1';
+ $connection = new LDAPConnection(
+ 'test',
+ [$host],
+ 'dc=example,dc=test',
+ 'cn=reader,dc=example,dc=test',
+ 'readerPassword!',
+ $encryption,
+ $port,
+ );
+
+ $this->assertSame($expected, $connection->endpoint($host));
+ }
+
+ /**
+ * @return iterable
+ */
+ public static function provideFormatsIPv6Endpoints(): iterable
+ {
+ yield 'LDAPS default port' => ['ldaps', null, 'ldaps://[2001:db8::1]:636'];
+
+ yield 'StartTLS default port' => ['starttls', null, 'ldap://[2001:db8::1]:389'];
+
+ yield 'StartTLS custom port' => ['starttls', 1389, 'ldap://[2001:db8::1]:1389'];
+ }
+
+ #[DataProvider('provideRejectsInvalidBindPassword')]
+ public function testRejectsInvalidBindPassword(string $password): void
+ {
+ $this->expectException(LDAPException::class);
+ $this->expectExceptionMessage('invalid_bind_secret');
+
+ new LDAPConnection(
+ 'test',
+ ['ldap.example.test'],
+ 'dc=example,dc=test',
+ 'cn=reader,dc=example,dc=test',
+ $password,
+ );
+ }
+
+ /**
+ * @return iterable
+ */
+ public static function provideRejectsInvalidBindPassword(): iterable
+ {
+ yield 'empty password' => [''];
+
+ yield 'NUL byte' => ["reader\0Password!"];
+ }
+}
diff --git a/tests/Authentication/LDAP/LDAPFilterTest.php b/tests/Authentication/LDAP/LDAPFilterTest.php
new file mode 100644
index 000000000..9bb442015
--- /dev/null
+++ b/tests/Authentication/LDAP/LDAPFilterTest.php
@@ -0,0 +1,86 @@
+
+ *
+ * For the full copyright and license information, please view
+ * the LICENSE file that was distributed with this source code.
+ */
+
+namespace CodeIgniter\Shield\Tests\Authentication\LDAP;
+
+use CodeIgniter\Shield\Authentication\LDAP\LDAPFilter;
+use CodeIgniter\Shield\Exceptions\LDAPException;
+use PHPUnit\Framework\Attributes\DataProvider;
+use PHPUnit\Framework\TestCase;
+
+/**
+ * @internal
+ */
+final class LDAPFilterTest extends TestCase
+{
+ public function testEscapesFilterOperatorsAndNonAsciiOctets(): void
+ {
+ $escaped = LDAPFilter::equal('uid', "a*)(objectClass=*)\\\x00\xff");
+
+ $this->assertSame('(uid=a\2a\29\28objectClass=\2a\29\5c\00\ff)', $escaped);
+ LDAPFilter::validate($escaped);
+ }
+
+ public function testEscapesDnComponents(): void
+ {
+ $this->assertSame('\23example\2c\3d\20', LDAPFilter::escapeDnComponent('#example,= '));
+ $this->assertSame('\20x\00', LDAPFilter::escapeDnComponent(" x\0"));
+ }
+
+ public function testCombinesNestedFiltersAndMatchingRules(): void
+ {
+ $disabled = '(userAccountControl:1.2.840.113556.1.4.803:=2)';
+ $login = LDAPFilter::any(LDAPFilter::equal('sAMAccountName', 'alice'), LDAPFilter::equal('userPrincipalName', 'alice'));
+ $filter = LDAPFilter::all('(objectCategory=person)', $login, LDAPFilter::not($disabled));
+
+ $this->assertSame(
+ '(&(objectCategory=person)(|(sAMAccountName=alice)(userPrincipalName=alice))(!(userAccountControl:1.2.840.113556.1.4.803:=2)))',
+ $filter,
+ );
+ }
+
+ #[DataProvider('provideRejectsInvalidFilters')]
+ public function testRejectsInvalidFilters(string $filter): void
+ {
+ $this->expectException(LDAPException::class);
+ $this->expectExceptionMessage('invalid_filter');
+
+ LDAPFilter::validate($filter);
+ }
+
+ /**
+ * @return iterable
+ */
+ public static function provideRejectsInvalidFilters(): iterable
+ {
+ yield 'missing parentheses' => ['uid=alice'];
+
+ yield 'multiple root filters' => ['(uid=alice)(uid=bob)'];
+
+ yield 'empty OR' => ['(|)'];
+
+ yield 'multiple NOT children' => ['(!(uid=alice)(uid=bob))'];
+
+ yield 'unescaped open parenthesis' => ['(uid=alice(bob)'];
+
+ yield 'malformed hex escape' => ['(uid=\0x)'];
+
+ yield 'unescaped invalid UTF-8' => ["(uid=\xff)"];
+
+ yield 'missing matching rule' => ['(:=abc)'];
+
+ yield 'raw wildcard in extensible match' => ['(uid:caseExactMatch:=*)'];
+
+ yield 'too deeply nested' => [str_repeat('(!', 40) . '(uid=*)' . str_repeat(')', 40)];
+ }
+}
diff --git a/tests/Authentication/LDAP/LDAPUserResolverTest.php b/tests/Authentication/LDAP/LDAPUserResolverTest.php
new file mode 100644
index 000000000..d23dcf185
--- /dev/null
+++ b/tests/Authentication/LDAP/LDAPUserResolverTest.php
@@ -0,0 +1,368 @@
+
+ *
+ * For the full copyright and license information, please view
+ * the LICENSE file that was distributed with this source code.
+ */
+
+namespace CodeIgniter\Shield\Tests\Authentication\LDAP;
+
+use CodeIgniter\Config\Factories;
+use CodeIgniter\Shield\Authentication\LDAP\LDAPUserResolver;
+use CodeIgniter\Shield\Config\Auth;
+use CodeIgniter\Shield\Database\Migrations\CreateAuthTables;
+use CodeIgniter\Shield\Entities\UserIdentity;
+use CodeIgniter\Shield\Exceptions\LDAPException;
+use CodeIgniter\Shield\Models\UserIdentityModel;
+use CodeIgniter\Shield\Models\UserModel;
+use CodeIgniter\Shield\Tests\DatabaseTestCase;
+use Config\Database;
+use RuntimeException;
+
+/**
+ * @internal
+ */
+final class LDAPUserResolverTest extends DatabaseTestCase
+{
+ protected $refresh = true;
+
+ public function testProvisioningStoresOnlyTheStableDirectoryIdentity(): void
+ {
+ $users = model(UserModel::class);
+ $resolver = new LDAPUserResolver($users);
+
+ $user = $resolver->resolve('corporate', 'immutable-object', ['username' => 'DirUser'], true);
+
+ $this->assertSame('diruser', $user->username);
+ $this->assertNull($user->email);
+ $this->assertNull($user->password_hash);
+
+ $this->seeInDatabase($this->tables['identities'], [
+ 'user_id' => $user->id,
+ 'type' => LDAPUserResolver::ID_TYPE,
+ 'name' => 'corporate',
+ 'secret' => hash('sha256', "corporate\0immutable-object"),
+ 'secret2' => null,
+ ]);
+ $this->seeNumRecords(1, $this->tables['identities'], ['user_id' => $user->id]);
+ }
+
+ public function testEntryRenameChangesOnlyTheConfiguredProfile(): void
+ {
+ $users = model(UserModel::class);
+ $resolver = new LDAPUserResolver($users);
+ $user = $resolver->resolve('corporate', 'immutable-object', ['username' => 'original'], true);
+
+ $users->update($user->id, ['status_message' => 'Local account note']);
+
+ $this->assertSame('original', $resolver->resolve(
+ 'corporate',
+ 'immutable-object',
+ ['username' => 'renamed'],
+ updateProfile: false,
+ )->username);
+
+ $renamed = $resolver->resolve('corporate', 'immutable-object', ['username' => 'renamed']);
+
+ $this->assertSame($user->id, $renamed->id);
+ $this->assertSame('renamed', $renamed->username);
+ $this->assertSame('Local account note', $renamed->status_message);
+ $this->seeNumRecords(1, $this->tables['identities'], ['user_id' => $user->id]);
+ }
+
+ public function testUsernameCollisionDoesNotLinkToLocalAccount(): void
+ {
+ $users = model(UserModel::class);
+ $resolver = new LDAPUserResolver($users);
+
+ $userId = $users->insert(['username' => 'Existing']);
+
+ try {
+ $resolver->resolve('corporate', 'immutable-object', ['username' => 'existing'], true);
+ $this->fail('A colliding username was accepted.');
+ } catch (LDAPException $exception) {
+ $this->assertSame('identity_conflict', $exception->reason);
+ }
+
+ $this->seeNumRecords(1, $this->tables['users'], ['id' => $userId]);
+ $this->dontSeeInDatabase($this->tables['identities'], ['type' => LDAPUserResolver::ID_TYPE]);
+ }
+
+ public function testCustomProviderCanSynchronizeAWritableProfileColumn(): void
+ {
+ $users = new class () extends UserModel {
+ protected $allowedFields = ['username', 'first_name'];
+ };
+
+ $forge = Database::forge($users->builder()->db());
+ $this->assertTrue($forge->addColumn($this->tables['users'], [
+ 'first_name' => ['type' => 'varchar', 'constraint' => 100, 'null' => true],
+ ]));
+
+ $resolver = new LDAPUserResolver($users);
+ $user = $resolver->resolve('corporate', 'immutable-object', [
+ 'username' => 'directory',
+ 'first_name' => 'Initial',
+ ], true);
+ $changed = $resolver->resolve('corporate', 'immutable-object', ['first_name' => 'Updated']);
+
+ $this->assertSame($user->id, $changed->id);
+ $this->assertSame('Updated', $changed->first_name);
+ $this->assertSame('directory', $changed->username);
+ }
+
+ public function testConnectionScopesExternalIdentity(): void
+ {
+ $resolver = new LDAPUserResolver(model(UserModel::class));
+
+ $corporate = $resolver->resolve('corporate', 'shared-id', ['username' => 'corporate.user'], true);
+ $partner = $resolver->resolve('partner', 'shared-id', ['username' => 'partner.user'], true);
+
+ $this->assertNotSame($corporate->id, $partner->id);
+ $this->assertSame($corporate->id, $resolver->resolve('corporate', 'shared-id')->id);
+ $this->assertSame($partner->id, $resolver->resolve('partner', 'shared-id')->id);
+ }
+
+ public function testExplicitLinkIsIdempotentAndPreservesTheLocalPassword(): void
+ {
+ $users = model(UserModel::class);
+ $resolver = new LDAPUserResolver($users);
+
+ $userId = $users->insert($users->createNewUser([
+ 'username' => 'existing',
+ 'email' => 'existing@example.test',
+ 'password' => 'local-password',
+ ]));
+ $user = $users->findById($userId);
+
+ $resolver->link('corporate', 'immutable-object', $userId);
+ $resolver->link('corporate', 'immutable-object', $userId);
+ $resolved = $resolver->resolve('corporate', 'immutable-object');
+
+ $this->assertSame($user->id, $resolved->id);
+ $this->assertSame($user->email, $resolved->email);
+ $this->assertSame($user->password_hash, $resolved->password_hash);
+ $this->assertTrue(password_verify('local-password', $resolved->password_hash));
+ $this->seeNumRecords(1, $this->tables['identities'], [
+ 'user_id' => $userId,
+ 'type' => LDAPUserResolver::ID_TYPE,
+ ]);
+ }
+
+ public function testCannotMoveAnExistingDirectoryIdentityToAnotherUser(): void
+ {
+ $users = model(UserModel::class);
+ $resolver = new LDAPUserResolver($users);
+ $user = $resolver->resolve('corporate', 'immutable-object', ['username' => 'directory'], true);
+ $otherId = $users->insert(['username' => 'another']);
+
+ try {
+ $resolver->link('corporate', 'immutable-object', $otherId);
+ $this->fail('A linked identity was reassigned.');
+ } catch (LDAPException $exception) {
+ $this->assertSame('identity_conflict', $exception->reason);
+ }
+
+ $this->assertSame($user->id, $resolver->resolve('corporate', 'immutable-object')->id);
+ }
+
+ public function testUnlinkedUserIsRejectedWhenProvisioningIsOff(): void
+ {
+ $resolver = new LDAPUserResolver(model(UserModel::class));
+
+ $this->expectException(LDAPException::class);
+ $this->expectExceptionMessage('user_not_provisioned');
+
+ $resolver->resolve('corporate', 'immutable-object', ['username' => 'directory']);
+ }
+
+ public function testProvisioningRollsBackWhenIdentityCannotBeStored(): void
+ {
+ $identities = $this->getMockBuilder(UserIdentityModel::class)->onlyMethods(['create'])->getMock();
+ $identities->expects($this->once())->method('create')->willThrowException(new RuntimeException('private data'));
+ $resolver = new LDAPUserResolver(model(UserModel::class), $identities);
+
+ try {
+ $resolver->resolve('corporate', 'immutable-object', ['username' => 'rolledback'], true);
+ $this->fail('Provisioning succeeded without recording an identity.');
+ } catch (LDAPException $exception) {
+ $this->assertSame('synchronization_conflict', $exception->reason);
+ $this->assertNull($exception->getPrevious());
+ $this->assertStringNotContainsString('private data', $exception->getMessage());
+ }
+
+ $this->dontSeeInDatabase($this->tables['users'], ['username' => 'rolledback']);
+ }
+
+ public function testFailedDirectoryWriteDoesNotPoisonTheSharedConnection(): void
+ {
+ $users = model(UserModel::class);
+ $identities = model(UserIdentityModel::class);
+ $failed = $this->getMockBuilder(UserIdentityModel::class)->onlyMethods(['create'])->getMock();
+ $failed->expects($this->once())->method('create')->willReturnCallback(static function (UserIdentity $identity) use ($identities): void {
+ $identities->create($identity);
+ $identities->create($identity);
+ });
+
+ $resolver = new LDAPUserResolver($users, $failed);
+
+ try {
+ $resolver->resolve('corporate', 'immutable-object', ['username' => 'rolledback'], true);
+ $this->fail('A duplicate LDAP identity was stored.');
+ } catch (LDAPException $exception) {
+ $this->assertSame('synchronization_conflict', $exception->reason);
+ }
+
+ $this->dontSeeInDatabase($this->tables['users'], ['username' => 'rolledback']);
+ $this->assertTrue($users->builder()->db()->transStrict);
+
+ $resolved = (new LDAPUserResolver($users))->resolve('corporate', 'immutable-object', ['username' => 'retried'], true);
+
+ $this->assertSame('retried', $resolved->username);
+ }
+
+ public function testConcurrentProvisioningKeepsOneUserAndDirectoryIdentity(): void
+ {
+ if (! extension_loaded('sqlite3')) {
+ $this->markTestSkipped('The setup for overlapping transactions requires SQLite3.');
+ }
+
+ $file = tmpfile();
+ $this->assertIsResource($file);
+
+ $original = config(Database::class);
+ $config = new class () extends Database {
+ /**
+ * @var array
+ */
+ public array $ldapProvisioningFirst = [];
+
+ /**
+ * @var array
+ */
+ public array $ldapProvisioningSecond = [];
+ };
+ $config->ldapProvisioningFirst = $config->ldapProvisioningSecond = [
+ 'DBDriver' => 'SQLite3',
+ 'database' => stream_get_meta_data($file)['uri'],
+ 'DBDebug' => false,
+ ];
+
+ Factories::injectMock('config', Database::class, $config);
+
+ $auth = config(Auth::class);
+ $originalGroup = $auth->DBGroup;
+ $first = Database::connect('ldapProvisioningFirst');
+ $second = Database::connect('ldapProvisioningSecond');
+
+ try {
+ $mode = $first->query('PRAGMA journal_mode = WAL');
+ $this->assertNotFalse($mode);
+ $this->assertSame('wal', $mode->getRowArray()['journal_mode']);
+
+ $auth->DBGroup = 'ldapProvisioningFirst';
+ (new CreateAuthTables())->up();
+ $users = new UserModel();
+ $identities = new UserIdentityModel();
+ $firstLookup = $this->getMockBuilder(UserIdentityModel::class)->onlyMethods(['getIdentityBySecret'])->getMock();
+
+ $auth->DBGroup = 'ldapProvisioningSecond';
+ $concurrent = new LDAPUserResolver(new UserModel(), new UserIdentityModel());
+ $profile = ['username' => 'directory.user'];
+ $winner = null;
+
+ $firstLookup->expects($this->once())->method('getIdentityBySecret')->willReturnCallback(
+ static function (string $type, ?string $secret) use ($identities, $concurrent, $profile, &$winner): ?UserIdentity {
+ // The first transaction's snapshot contains no link. Commit the
+ // competing login before the first transaction tries its write.
+ $identity = $identities->getIdentityBySecret($type, $secret);
+ $winner = $concurrent->resolve('corporate', 'immutable-object', $profile, true);
+
+ return $identity;
+ },
+ );
+
+ try {
+ (new LDAPUserResolver($users, $firstLookup))->resolve('corporate', 'immutable-object', $profile, true);
+ $this->fail('Both concurrent attempts provisioned the same directory identity.');
+ } catch (LDAPException $exception) {
+ $this->assertSame('synchronization_conflict', $exception->reason);
+ }
+
+ $this->assertNotNull($winner);
+ $retried = (new LDAPUserResolver($users, $identities))->resolve('corporate', 'immutable-object', $profile, true);
+ $this->assertSame($winner->id, $retried->id);
+ $this->assertSame(1, $first->table($this->tables['users'])->countAllResults());
+ $this->assertSame(1, $first->table($this->tables['identities'])->countAllResults());
+ } finally {
+ $auth->DBGroup = $originalGroup;
+ Factories::injectMock('config', Database::class, $original);
+ $first->close();
+ $second->close();
+ fclose($file);
+ }
+ }
+
+ public function testProfileCannotOverwriteLocalEmailOrPassword(): void
+ {
+ $resolver = new LDAPUserResolver(model(UserModel::class));
+
+ $this->expectException(LDAPException::class);
+ $this->expectExceptionMessage('invalid_profile');
+
+ $resolver->resolve('corporate', 'immutable-object', [
+ 'username' => 'directory',
+ 'email' => 'directory@example.test',
+ ], true);
+ }
+
+ public function testUnwritableProfileFieldRollsBackProvisioning(): void
+ {
+ $resolver = new LDAPUserResolver(model(UserModel::class));
+
+ try {
+ $resolver->resolve('corporate', 'immutable-object', [
+ 'username' => 'directory',
+ 'first_name' => 'First',
+ ], true);
+ $this->fail('The unmapped profile field was silently ignored.');
+ } catch (LDAPException $exception) {
+ $this->assertSame('invalid_profile', $exception->reason);
+ }
+
+ $this->dontSeeInDatabase($this->tables['users'], ['username' => 'directory']);
+ }
+
+ public function testProvisioningDoesNotJoinAnExistingTransaction(): void
+ {
+ $users = model(UserModel::class);
+ $resolver = new LDAPUserResolver($users);
+ $database = $users->builder()->db();
+
+ $this->assertTrue($database->transBegin());
+
+ try {
+ $resolver->resolve('corporate', 'immutable-object', ['username' => 'directory'], true);
+ $this->fail('The resolver joined the active transaction.');
+ } catch (LDAPException $exception) {
+ $this->assertSame('synchronization_conflict', $exception->reason);
+ } finally {
+ $this->assertTrue($database->transRollback());
+ }
+
+ $this->dontSeeInDatabase($this->tables['users'], ['username' => 'directory']);
+ }
+
+ public function testActiveDirectoryGuidUsesCanonicalByteOrder(): void
+ {
+ $bytes = hex2bin('785634123412cdab891023456789abcd');
+
+ $this->assertSame('12345678-1234-abcd-8910-23456789abcd', LDAPUserResolver::normalizeObjectGuid($bytes));
+ }
+}
diff --git a/tests/Authentication/LDAP/NativeLDAPDirectoryIntegrationTest.php b/tests/Authentication/LDAP/NativeLDAPDirectoryIntegrationTest.php
new file mode 100644
index 000000000..12ed490f1
--- /dev/null
+++ b/tests/Authentication/LDAP/NativeLDAPDirectoryIntegrationTest.php
@@ -0,0 +1,220 @@
+
+ *
+ * For the full copyright and license information, please view
+ * the LICENSE file that was distributed with this source code.
+ */
+
+namespace CodeIgniter\Shield\Tests\Authentication\LDAP;
+
+use CodeIgniter\Shield\Authentication\LDAP\LDAPConnection;
+use CodeIgniter\Shield\Authentication\LDAP\LDAPFilter;
+use CodeIgniter\Shield\Authentication\LDAP\NativeLDAPDirectory;
+use CodeIgniter\Shield\Exceptions\LDAPException;
+use PHPUnit\Framework\Attributes\DataProvider;
+use PHPUnit\Framework\Attributes\RunInSeparateProcess;
+use PHPUnit\Framework\TestCase;
+
+/**
+ * @internal
+ */
+final class NativeLDAPDirectoryIntegrationTest extends TestCase
+{
+ private const BASE_DN = 'dc=example,dc=test';
+ private const USER_BASE_DN = 'ou=people,' . self::BASE_DN;
+ private const GROUP_BASE_DN = 'ou=groups,' . self::BASE_DN;
+
+ #[DataProvider('provideUsesVerifiedTlsForLookupAndAuthentication')]
+ public function testUsesVerifiedTlsForLookupAndAuthentication(string $encryption): void
+ {
+ $connection = $this->connection($encryption);
+ $directory = new NativeLDAPDirectory();
+
+ $directory->testConnection($connection);
+ $directory->testBind($connection);
+
+ $entry = $directory->authenticate($connection, self::USER_BASE_DN, '(uid=alice)', ['uid', 'sn'], 'alicePassword!');
+
+ $this->assertSame('uid=alice,' . self::USER_BASE_DN, $entry['dn']);
+ $this->assertSame(['alice'], $entry['attributes']['uid']);
+ $this->assertSame(['Shared'], $entry['attributes']['sn']);
+ $this->assertMatchesRegularExpression('/\A[a-f0-9-]{36}\z/', $entry['attributes']['entryuuid'][0]);
+ }
+
+ /**
+ * @return iterable
+ */
+ public static function provideUsesVerifiedTlsForLookupAndAuthentication(): iterable
+ {
+ yield 'StartTLS' => ['starttls'];
+
+ yield 'LDAPS' => ['ldaps'];
+ }
+
+ public function testRejectsWrongCertificateHostname(): void
+ {
+ $host = getenv('SHIELD_LDAP_TEST_WRONG_HOST');
+
+ if ($host === false || $host === '') {
+ $this->markTestSkipped('Set SHIELD_LDAP_TEST_WRONG_HOST to test certificate hostname verification.');
+ }
+
+ $connection = $this->connection('starttls', [$host]);
+
+ $this->expectException(LDAPException::class);
+ $this->expectExceptionMessage('certificate_verification_failed');
+
+ (new NativeLDAPDirectory())->testConnection($connection);
+ }
+
+ #[RunInSeparateProcess]
+ public function testRejectsUntrustedCertificateChain(): void
+ {
+ $ca = getenv('SHIELD_LDAP_TEST_UNTRUSTED_CA');
+
+ if ($ca === false || $ca === '') {
+ $this->markTestSkipped('Set SHIELD_LDAP_TEST_UNTRUSTED_CA to another CA bundle to test certificate trust.');
+ }
+
+ $connection = $this->connection();
+ putenv('LDAPTLS_CACERT=' . $ca);
+ putenv('LDAPTLS_CACERTDIR=');
+
+ $this->expectException(LDAPException::class);
+ $this->expectExceptionMessage('certificate_verification_failed');
+
+ (new NativeLDAPDirectory())->testConnection($connection);
+ }
+
+ public function testRejectsAmbiguousSearchBeforeCheckingPassword(): void
+ {
+ $connection = $this->connection();
+
+ $this->expectException(LDAPException::class);
+ $this->expectExceptionMessage('ambiguous_user');
+
+ (new NativeLDAPDirectory())->authenticate($connection, self::USER_BASE_DN, '(sn=Shared)', [], 'alicePassword!');
+ }
+
+ public function testAppliesEligibilityFilterAfterBind(): void
+ {
+ $connection = $this->connection();
+
+ $this->expectException(LDAPException::class);
+ $this->expectExceptionMessage('ineligible_user');
+
+ (new NativeLDAPDirectory())->authenticate($connection, self::USER_BASE_DN, '(uid=alice)', [], 'alicePassword!', '(uid=bob)');
+ }
+
+ public function testRejectsInvalidCredentials(): void
+ {
+ $connection = $this->connection();
+
+ $this->expectException(LDAPException::class);
+ $this->expectExceptionMessage('invalid_credentials');
+
+ (new NativeLDAPDirectory())->authenticate($connection, self::USER_BASE_DN, '(uid=alice)', [], 'wrong-password');
+ }
+
+ public function testEscapesSubmittedIdentifier(): void
+ {
+ $connection = $this->connection();
+
+ $this->expectException(LDAPException::class);
+ $this->expectExceptionMessage('user_not_found');
+
+ (new NativeLDAPDirectory())->authenticate(
+ $connection,
+ self::USER_BASE_DN,
+ LDAPFilter::equal('uid', 'alice*)(uid=*'),
+ [],
+ 'alicePassword!',
+ );
+ }
+
+ public function testPreviewReturnsABoundedSample(): void
+ {
+ $entries = (new NativeLDAPDirectory())->preview($this->connection(), self::USER_BASE_DN, '(sn=Shared)', ['uid'], 1);
+
+ $this->assertCount(1, $entries);
+ $this->assertContains($entries[0]['attributes']['uid'][0], ['alice', 'bob']);
+ }
+
+ public function testPreviewFindsGroupMembershipByEntryDn(): void
+ {
+ $connection = $this->connection();
+ $directory = new NativeLDAPDirectory();
+ $aliceDn = 'uid=alice,' . self::USER_BASE_DN;
+ $bobDn = 'uid=bob,' . self::USER_BASE_DN;
+ $group = '(objectClass=groupOfNames)';
+
+ $entries = $directory->preview(
+ $connection,
+ self::GROUP_BASE_DN,
+ LDAPFilter::all($group, LDAPFilter::equal('member', $aliceDn)),
+ ['cn', 'member'],
+ );
+
+ $this->assertSame([[
+ 'dn' => 'cn=shield-users,' . self::GROUP_BASE_DN,
+ 'attributes' => ['cn' => ['shield-users'], 'member' => [$aliceDn]],
+ ]], $entries);
+
+ $this->assertSame([], $directory->preview(
+ $connection,
+ self::GROUP_BASE_DN,
+ LDAPFilter::all($group, LDAPFilter::equal('member', $bobDn)),
+ ['cn', 'member'],
+ ));
+ }
+
+ public function testAuthenticationDoesNotReturnAttributesProtectedFromTheServiceAccount(): void
+ {
+ $entry = (new NativeLDAPDirectory())->authenticate(
+ $this->connection(),
+ self::USER_BASE_DN,
+ '(uid=alice)',
+ ['uid', 'userPassword'],
+ 'alicePassword!',
+ );
+
+ $this->assertSame(['alice'], $entry['attributes']['uid']);
+ $this->assertArrayNotHasKey('userpassword', $entry['attributes']);
+ }
+
+ public function testUsesNextEndpointWhenTheFirstIsUnavailable(): void
+ {
+ $connection = $this->connection('starttls', ['127.0.0.3', '127.0.0.1']);
+ $entry = (new NativeLDAPDirectory())->authenticate($connection, self::USER_BASE_DN, '(uid=alice)', ['uid'], 'alicePassword!');
+
+ $this->assertSame(['alice'], $entry['attributes']['uid']);
+ }
+
+ /**
+ * @param list $hosts
+ */
+ private function connection(string $encryption = 'starttls', array $hosts = ['127.0.0.1']): LDAPConnection
+ {
+ $port = getenv($encryption === 'ldaps' ? 'SHIELD_LDAP_TEST_LDAPS_PORT' : 'SHIELD_LDAP_TEST_PORT');
+
+ if (! extension_loaded('ldap') || $port === false || ! ctype_digit($port)) {
+ $this->markTestSkipped('Start the OpenLDAP fixture and set its environment variables to run this test.');
+ }
+
+ return new LDAPConnection(
+ 'test',
+ $hosts,
+ self::BASE_DN,
+ 'cn=reader,' . self::BASE_DN,
+ 'readerPassword!',
+ $encryption,
+ (int) $port,
+ );
+ }
+}
diff --git a/tests/Authentication/LDAP/NativeLDAPDirectoryTest.php b/tests/Authentication/LDAP/NativeLDAPDirectoryTest.php
new file mode 100644
index 000000000..be8099769
--- /dev/null
+++ b/tests/Authentication/LDAP/NativeLDAPDirectoryTest.php
@@ -0,0 +1,74 @@
+
+ *
+ * For the full copyright and license information, please view
+ * the LICENSE file that was distributed with this source code.
+ */
+
+namespace CodeIgniter\Shield\Tests\Authentication\LDAP;
+
+use CodeIgniter\Shield\Authentication\LDAP\LDAPConnection;
+use CodeIgniter\Shield\Authentication\LDAP\NativeLDAPDirectory;
+use CodeIgniter\Shield\Exceptions\LDAPException;
+use CodeIgniter\Shield\Exceptions\RuntimeException;
+use PHPUnit\Framework\Attributes\DataProvider;
+use PHPUnit\Framework\TestCase;
+
+/**
+ * @internal
+ */
+final class NativeLDAPDirectoryTest extends TestCase
+{
+ public function testRedactsBindSecretInConfigurationInspection(): void
+ {
+ $connection = new LDAPConnection('test', ['ldap.example.test'], 'dc=example,dc=test', 'cn=reader,dc=example,dc=test', 'readerPassword!');
+
+ $this->assertSame('readerPassword!', $connection->bindPassword());
+ $this->assertStringNotContainsString('readerPassword!', print_r($connection, true));
+ $this->assertStringNotContainsString('readerPassword!', var_export($connection, true));
+ $this->assertStringNotContainsString('readerPassword!', json_encode($connection, JSON_THROW_ON_ERROR));
+ }
+
+ public function testInvalidEndpointThrowsLocalizedShieldException(): void
+ {
+ $language = service('language');
+ $locale = $language->getLocale();
+ $language->setLocale('sr');
+
+ $this->expectException(RuntimeException::class);
+ $this->expectExceptionMessage('LDAP operacija nije uspela (invalid_endpoint).');
+
+ try {
+ new LDAPConnection('test', ['ldap://example.test'], 'dc=example,dc=test', 'cn=reader,dc=example,dc=test', 'readerPassword!');
+ } finally {
+ $language->setLocale($locale);
+ }
+ }
+
+ #[DataProvider('provideRejectsPasswordsBeforeContactingDirectory')]
+ public function testRejectsPasswordsBeforeContactingDirectory(string $password): void
+ {
+ $connection = new LDAPConnection('test', ['invalid.test'], 'dc=example,dc=test', 'cn=reader,dc=example,dc=test', 'readerPassword!');
+
+ $this->expectException(LDAPException::class);
+ $this->expectExceptionMessage('invalid_credentials');
+
+ (new NativeLDAPDirectory())->authenticate($connection, $connection->baseDn, '(uid=alice)', [], $password);
+ }
+
+ /**
+ * @return iterable
+ */
+ public static function provideRejectsPasswordsBeforeContactingDirectory(): iterable
+ {
+ yield 'empty password' => [''];
+
+ yield 'NUL byte' => ["\0abc"];
+ }
+}
diff --git a/tests/Authentication/LDAP/NativeLDAPTransportTest.php b/tests/Authentication/LDAP/NativeLDAPTransportTest.php
new file mode 100644
index 000000000..e60044dc3
--- /dev/null
+++ b/tests/Authentication/LDAP/NativeLDAPTransportTest.php
@@ -0,0 +1,237 @@
+
+ *
+ * For the full copyright and license information, please view
+ * the LICENSE file that was distributed with this source code.
+ */
+
+namespace CodeIgniter\Shield\Tests\Authentication\LDAP;
+
+use CodeIgniter\Shield\Authentication\LDAP\LDAPConnection;
+use CodeIgniter\Shield\Authentication\LDAP\NativeLDAPDirectory;
+use CodeIgniter\Shield\Exceptions\LDAPException;
+use PHPUnit\Framework\Attributes\DataProvider;
+use PHPUnit\Framework\Attributes\PreserveGlobalState;
+use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses;
+use PHPUnit\Framework\TestCase;
+use Tests\Support\LDAP\NativeLDAPStub;
+
+/**
+ * @internal
+ */
+#[PreserveGlobalState(false)]
+#[RunTestsInSeparateProcesses]
+final class NativeLDAPTransportTest extends TestCase
+{
+ private const FIRST_ENDPOINT = 'ldaps://first.example.test:636';
+ private const SECOND_ENDPOINT = 'ldaps://second.example.test:636';
+ private const FIRST_ENTRY_DN = 'uid=alice,dc=example,dc=test';
+ private const SECOND_ENTRY_DN = 'uid=bob,dc=example,dc=test';
+
+ protected function setUp(): void
+ {
+ parent::setUp();
+
+ require __DIR__ . '/../../_support/LDAP/native_ldap_functions.inc';
+ }
+
+ public function testExtensionUnavailableDoesNotOpenAnEndpoint(): void
+ {
+ NativeLDAPStub::$available = false;
+
+ $this->expectException(LDAPException::class);
+ $this->expectExceptionMessage('extension_unavailable');
+
+ try {
+ (new NativeLDAPDirectory())->testBind($this->connection());
+ } finally {
+ $this->assertSame([], NativeLDAPStub::$connected);
+ }
+ }
+
+ #[DataProvider('provideMapsSearchErrors')]
+ public function testMapsSearchErrors(int $code, bool $searchFails, string $reason): void
+ {
+ NativeLDAPStub::$searchCode = $code;
+ NativeLDAPStub::$searchFails = $searchFails;
+
+ $this->expectException(LDAPException::class);
+ $this->expectExceptionMessage($reason);
+
+ (new NativeLDAPDirectory())->preview($this->connection(), 'dc=example,dc=test', '(uid=*)', ['uid']);
+ }
+
+ /**
+ * @return iterable
+ */
+ public static function provideMapsSearchErrors(): iterable
+ {
+ yield 'client timeout' => [-5, true, 'search_timeout'];
+
+ yield 'server time limit' => [3, false, 'search_timeout'];
+
+ yield 'administrative limit' => [11, false, 'incomplete_search'];
+
+ yield 'referral result code' => [10, false, 'incomplete_search'];
+
+ yield 'invalid filter' => [-7, true, 'invalid_filter'];
+
+ yield 'server unavailable' => [52, false, 'directory_unavailable'];
+
+ yield 'other search error' => [80, false, 'search_failed'];
+ }
+
+ public function testRejectsSearchReferenceEvenWithSuccessfulResultCode(): void
+ {
+ NativeLDAPStub::$hasReference = true;
+ NativeLDAPStub::$entries = [self::FIRST_ENTRY_DN];
+
+ $this->expectException(LDAPException::class);
+ $this->expectExceptionMessage('incomplete_search');
+
+ (new NativeLDAPDirectory())->preview($this->connection(), 'dc=example,dc=test', '(uid=*)', ['uid']);
+ }
+
+ public function testSizeLimitReturnsSampleOnlyWhenRequestedNumberOfEntriesWereReceived(): void
+ {
+ NativeLDAPStub::$searchCode = 4;
+ NativeLDAPStub::$entries = [self::FIRST_ENTRY_DN, self::SECOND_ENTRY_DN];
+
+ $result = (new NativeLDAPDirectory())->preview($this->connection(), 'dc=example,dc=test', '(uid=*)', ['uid'], 2);
+
+ $this->assertSame([
+ ['dn' => self::FIRST_ENTRY_DN, 'attributes' => []],
+ ['dn' => self::SECOND_ENTRY_DN, 'attributes' => []],
+ ], $result);
+ }
+
+ public function testRejectsSizeLimitWithFewerEntriesThanRequested(): void
+ {
+ NativeLDAPStub::$searchCode = 4;
+ NativeLDAPStub::$entries = [self::FIRST_ENTRY_DN];
+
+ $this->expectException(LDAPException::class);
+ $this->expectExceptionMessage('incomplete_search');
+
+ (new NativeLDAPDirectory())->preview($this->connection(), 'dc=example,dc=test', '(uid=*)', ['uid'], 2);
+ }
+
+ #[DataProvider('provideRetriesAlternativeEndpointOnTransportFailure')]
+ public function testRetriesAlternativeEndpointOnTransportFailure(int $code): void
+ {
+ NativeLDAPStub::$bindErrors = [self::FIRST_ENDPOINT => $code];
+
+ (new NativeLDAPDirectory())->testBind($this->connection());
+
+ $this->assertSame([self::FIRST_ENDPOINT, self::SECOND_ENDPOINT], NativeLDAPStub::$connected);
+ $this->assertSame(2, NativeLDAPStub::$unbound);
+ }
+
+ /**
+ * @return iterable
+ */
+ public static function provideRetriesAlternativeEndpointOnTransportFailure(): iterable
+ {
+ yield 'server down' => [-1];
+
+ yield 'connection timeout' => [-5];
+
+ yield 'client connection error' => [-11];
+
+ yield 'server unavailable' => [52];
+ }
+
+ public function testReportsConnectionTimeoutWhenEndpointsAreExhausted(): void
+ {
+ NativeLDAPStub::$bindErrors = [self::FIRST_ENDPOINT => -1, self::SECOND_ENDPOINT => -5];
+
+ $this->expectException(LDAPException::class);
+ $this->expectExceptionMessage('connection_timeout');
+
+ try {
+ (new NativeLDAPDirectory())->testBind($this->connection());
+ } finally {
+ $this->assertSame([self::FIRST_ENDPOINT, self::SECOND_ENDPOINT], NativeLDAPStub::$connected);
+ $this->assertSame(2, NativeLDAPStub::$unbound);
+ }
+ }
+
+ public function testCertificateVerificationFailureStopsFailoverAndRedactsTheDiagnostic(): void
+ {
+ NativeLDAPStub::$bindErrors = [self::FIRST_ENDPOINT => -11];
+ NativeLDAPStub::$diagnostic = 'TLS: hostname does not match private-diagnostic.example.test';
+
+ try {
+ (new NativeLDAPDirectory())->testBind($this->connection());
+ $this->fail('Expected a certificate verification failure.');
+ } catch (LDAPException $exception) {
+ $this->assertSame('certificate_verification_failed', $exception->reason);
+ $this->assertStringNotContainsString('private-diagnostic.example.test', $exception->getMessage());
+ }
+
+ $this->assertSame([self::FIRST_ENDPOINT], NativeLDAPStub::$connected);
+ $this->assertSame(1, NativeLDAPStub::$unbound);
+ }
+
+ public function testInvalidServiceCredentialsStopFailover(): void
+ {
+ NativeLDAPStub::$bindErrors = [self::FIRST_ENDPOINT => 49];
+ NativeLDAPStub::$warnOnBindFailure = true;
+
+ $this->expectException(LDAPException::class);
+ $this->expectExceptionMessage('service_bind_failed');
+
+ try {
+ (new NativeLDAPDirectory())->testBind($this->connection());
+ } finally {
+ $this->assertSame([self::FIRST_ENDPOINT], NativeLDAPStub::$connected);
+ $this->assertSame(1, NativeLDAPStub::$unbound);
+ }
+ }
+
+ public function testNativeTraceRedactsSubmittedAndServicePasswords(): void
+ {
+ $this->assertNotFalse(ini_set('zend.exception_ignore_args', '0'));
+
+ NativeLDAPStub::$bindErrors = [self::FIRST_ENDPOINT => 49];
+ $connection = $this->connection();
+
+ try {
+ (new NativeLDAPDirectory())->authenticate(
+ $connection,
+ $connection->baseDn,
+ '(uid=alice)',
+ ['uid'],
+ 'synthetic-user-password',
+ );
+ $this->fail('Expected a bind failure.');
+ } catch (LDAPException $exception) {
+ $frames = array_filter(
+ $exception->getTrace(),
+ static fn (array $frame): bool => ($frame['class'] ?? null) === NativeLDAPDirectory::class,
+ );
+ $arguments = array_column($frames, 'args', 'function');
+
+ $this->assertSame('service_bind_failed', $exception->reason);
+ $this->assertSame('SensitiveParameterValue', get_debug_type($arguments['authenticate'][4]));
+ $this->assertSame('SensitiveParameterValue', get_debug_type($arguments['bind'][2]));
+ }
+ }
+
+ private function connection(): LDAPConnection
+ {
+ return new LDAPConnection(
+ 'test',
+ ['first.example.test', 'second.example.test'],
+ 'dc=example,dc=test',
+ 'cn=reader,dc=example,dc=test',
+ 'readerPassword!',
+ );
+ }
+}
diff --git a/tests/Controllers/LDAPLoginTest.php b/tests/Controllers/LDAPLoginTest.php
new file mode 100644
index 000000000..354e24679
--- /dev/null
+++ b/tests/Controllers/LDAPLoginTest.php
@@ -0,0 +1,286 @@
+
+ *
+ * For the full copyright and license information, please view
+ * the LICENSE file that was distributed with this source code.
+ */
+
+namespace CodeIgniter\Shield\Tests\Controllers;
+
+use CodeIgniter\Config\Factories;
+use CodeIgniter\Shield\Authentication\Actions\Email2FA;
+use CodeIgniter\Shield\Authentication\Authenticators\LDAP;
+use CodeIgniter\Shield\Authentication\Authenticators\Session;
+use CodeIgniter\Shield\Authentication\LDAP\LDAPConnection;
+use CodeIgniter\Shield\Authentication\LDAP\LDAPDirectoryInterface;
+use CodeIgniter\Shield\Authentication\LDAP\LDAPUserResolver;
+use CodeIgniter\Shield\Config\AuthLDAP;
+use CodeIgniter\Shield\Entities\User;
+use CodeIgniter\Shield\Exceptions\LDAPException;
+use CodeIgniter\Shield\Models\UserIdentityModel;
+use CodeIgniter\Shield\Tests\DatabaseTestCase;
+use CodeIgniter\Shield\Tests\FakeUser;
+use CodeIgniter\Test\FeatureTestTrait;
+use Config\Services;
+use PHPUnit\Framework\Attributes\DataProvider;
+use PHPUnit\Framework\MockObject\MockObject;
+
+/**
+ * @internal
+ */
+final class LDAPLoginTest extends DatabaseTestCase
+{
+ use FakeUser;
+ use FeatureTestTrait;
+
+ private AuthLDAP $ldap;
+ private LDAPDirectoryInterface&MockObject $directory;
+
+ protected function setUp(): void
+ {
+ parent::setUp();
+
+ $auth = config('Auth');
+ $auth->authenticators['ldap'] = LDAP::class;
+ $auth->sessionConfig['allowRemembering'] = false;
+
+ $this->ldap = new AuthLDAP();
+ $this->ldap->enabled = true;
+ $this->ldap->defaultConnection = 'example';
+ $this->ldap->connections['example'] = [
+ 'hosts' => ['ldap.example.com'],
+ 'baseDn' => 'dc=example,dc=com',
+ 'bindDn' => 'cn=reader,dc=example,dc=com',
+ 'bindPassword' => 'example-test-service-password',
+ 'profileAttributes' => ['username' => 'uid'],
+ 'provisionUsers' => true,
+ ];
+ Factories::injectMock('config', 'AuthLDAP', $this->ldap);
+
+ $this->directory = $this->createMock(LDAPDirectoryInterface::class);
+ Services::injectMock('ldapDirectory', $this->directory);
+
+ $routes = service('routes');
+ auth()->routes($routes, ['except' => ['login']]);
+ $routes->get('login', '\CodeIgniter\Shield\Controllers\LoginController::loginView', ['as' => 'login']);
+ $routes->post('login', '\Tests\Support\LDAP\LoginController::loginAction');
+ Services::injectMock('routes', $routes);
+ }
+
+ public function testDirectoryLoginUsesShieldSessionAndDoesNotRememberPassword(): void
+ {
+ $this->directory->expects($this->once())->method('authenticate')->willReturn($this->entry());
+
+ $response = $this->post('/login', ['username' => 'directory-user', 'password' => 'directory-secret', 'remember' => '1']);
+
+ $response->assertStatus(302);
+ $response->assertSessionMissing('error');
+ $this->assertTrue(auth('session')->loggedIn());
+ $user = auth('session')->user();
+ $this->assertInstanceOf(User::class, $user);
+ $this->assertSame('directory-user', $user->username);
+ $this->assertNull($user->getEmailIdentity());
+ $this->seeInDatabase($this->tables['logins'], ['user_id' => $user->id, 'success' => 1]);
+ $this->dontSeeInDatabase($this->tables['remember_tokens'], ['user_id' => $user->id]);
+ $this->assertNull(session('_ci_old_input'));
+ }
+
+ public function testLinkedDirectoryAccountStillRequiresConfiguredLoginAction(): void
+ {
+ config('Auth')->actions['login'] = Email2FA::class;
+ $this->user->createEmailIdentity(['email' => 'safe-contact@example.com', 'password' => 'local-password']);
+ $this->user->addGroup('admin');
+ (new LDAPUserResolver(auth()->getProvider()))->link('example', 'stable-id', $this->user->id);
+ $this->directory->expects($this->once())->method('authenticate')->willReturn($this->entry($this->user->username));
+
+ $response = $this->post('/login', ['username' => $this->user->username, 'password' => 'directory-secret', 'remember' => '1']);
+
+ $response->assertStatus(302);
+ $this->assertSame(site_url('auth/a/show'), $response->getRedirectUrl());
+ $authenticator = auth('session')->getAuthenticator();
+ $this->assertSame(Session::class, $authenticator::class);
+ $this->assertTrue($authenticator->isPending());
+ $this->assertFalse(auth('session')->loggedIn());
+ $this->assertTrue($authenticator->getPendingUser()->inGroup('admin'));
+ $this->seeInDatabase($this->tables['identities'], [
+ 'user_id' => $this->user->id,
+ 'type' => LDAP::ID_TYPE_EMAIL_PASSWORD,
+ 'last_used_at' => null,
+ ]);
+ $this->dontSeeInDatabase($this->tables['remember_tokens'], ['user_id' => $this->user->id]);
+ }
+
+ public function testReservedLocalAccountRequiresConfiguredMfaWithoutQueryingDirectory(): void
+ {
+ config('Auth')->actions['login'] = Email2FA::class;
+ $this->user->createEmailIdentity(['email' => 'operator@example.com', 'password' => 'local-password']);
+ $this->ldap->localAccounts[$this->user->username] = $this->user->id;
+ $this->directory->expects($this->never())->method('authenticate');
+
+ $response = $this->post('/login', [
+ 'username' => strtoupper($this->user->username),
+ 'password' => 'local-password',
+ 'remember' => '1',
+ ]);
+
+ $response->assertStatus(302);
+ $this->assertSame(site_url('auth/a/show'), $response->getRedirectUrl());
+ $this->assertFalse(auth('session')->loggedIn());
+ $this->dontSeeInDatabase($this->tables['remember_tokens'], ['user_id' => $this->user->id]);
+
+ $identity = model(UserIdentityModel::class)->getIdentityByType($this->user, Session::ID_TYPE_EMAIL_2FA);
+ $this->assertNotNull($identity);
+ $response = $this->withSession(['user' => session('user')])
+ ->post('/auth/a/verify', ['token' => $identity->secret]);
+
+ $response->assertStatus(302);
+ $this->assertSame($this->user->id, auth('session')->id());
+ }
+
+ public function testReservedLocalAccountWithoutAnApplicableActionCannotSignIn(): void
+ {
+ $this->user->createEmailIdentity(['email' => 'operator@example.com', 'password' => 'local-password']);
+ $this->ldap->localAccounts[$this->user->username] = $this->user->id;
+ $this->directory->expects($this->never())->method('authenticate');
+
+ $response = $this->post('/login', ['username' => $this->user->username, 'password' => 'local-password']);
+
+ $response->assertSessionHas('error', lang('Auth.badAttempt'));
+ $this->assertFalse(auth('session')->loggedIn());
+ }
+
+ public function testReservedLocalAccountIdentifiersCannotDifferOnlyByCase(): void
+ {
+ $this->ldap->localAccounts = ['Operator' => 1, 'operator' => 2];
+
+ $this->expectException(LDAPException::class);
+ $this->expectExceptionMessage('invalid_configuration');
+
+ auth('ldap')->getAuthenticator();
+ }
+
+ #[DataProvider('provideDirectoryFailureNeverFallsBackOrFlashesPassword')]
+ public function testDirectoryFailureNeverFallsBackOrFlashesPassword(string $reason): void
+ {
+ $this->user->createEmailIdentity(['email' => 'operator@example.com', 'password' => 'local-password']);
+ $this->directory->expects($this->once())->method('authenticate')->willThrowException(new LDAPException($reason));
+
+ $response = $this->post('/login', ['username' => $this->user->username, 'password' => 'local-password']);
+
+ $response->assertSessionHas('error', lang('Auth.badAttempt'));
+ $this->assertFalse(auth('session')->loggedIn());
+ $response->assertSessionMissing('_ci_old_input');
+ }
+
+ /**
+ * @return iterable>
+ */
+ public static function provideDirectoryFailureNeverFallsBackOrFlashesPassword(): iterable
+ {
+ yield ['invalid_credentials'];
+
+ yield ['ambiguous_user'];
+
+ yield ['tls_failed'];
+
+ yield ['directory_unavailable'];
+
+ yield ['ineligible_user'];
+ }
+
+ public function testEmptyPasswordFailsBeforeDirectoryAccess(): void
+ {
+ $this->directory->expects($this->never())->method('authenticate');
+
+ $response = $this->post('/login', ['username' => 'directory-user', 'password' => '']);
+
+ $response->assertStatus(302);
+ $response->assertSessionHas('error', lang('Auth.badAttempt'));
+ $response->assertSessionMissing('_ci_old_input');
+ }
+
+ public function testDisabledAuthenticatorFailsClosed(): void
+ {
+ $this->ldap->enabled = false;
+ $this->directory->expects($this->never())->method('authenticate');
+
+ $response = $this->post('/login', ['username' => 'directory-user', 'password' => 'directory-secret']);
+
+ $response->assertSessionHas('error', lang('Auth.badAttempt'));
+ $this->assertFalse(auth('session')->loggedIn());
+ }
+
+ public function testUpnRoutesToNamedConnectionAndEscapesAssertionValue(): void
+ {
+ $this->ldap->connections['corporate'] = [
+ 'hosts' => ['ad.example.com'],
+ 'baseDn' => 'dc=ad,dc=example,dc=com',
+ 'bindDn' => 'cn=reader,dc=ad,dc=example,dc=com',
+ 'bindPassword' => 'corporate-test-service-password',
+ 'loginAttributes' => ['sAMAccountName', 'userPrincipalName'],
+ 'externalIdAttribute' => 'objectGUID',
+ ];
+ $this->ldap->loginDomains['ad.example.com'] = 'corporate';
+ $this->directory->expects($this->once())->method('authenticate')->with(
+ $this->isInstanceOf(LDAPConnection::class),
+ 'dc=ad,dc=example,dc=com',
+ '(&(objectClass=person)(|(sAMAccountName=a\28\2a\29@AD.EXAMPLE.COM)(userPrincipalName=a\28\2a\29@AD.EXAMPLE.COM)))',
+ ['objectGUID'],
+ 'directory-secret',
+ '(objectClass=*)',
+ )->willReturnCallback(static function (LDAPConnection $connection): never {
+ self::assertSame('corporate', $connection->id);
+ self::assertSame(['ad.example.com'], $connection->hosts);
+ self::assertSame('corporate-test-service-password', $connection->bindPassword());
+
+ throw new LDAPException('user_not_found');
+ });
+
+ $response = $this->post('/login', ['username' => 'a(*)@AD.EXAMPLE.COM', 'password' => 'directory-secret']);
+
+ $response->assertSessionHas('error', lang('Auth.badAttempt'));
+ }
+
+ public function testDirectoryGuidResolvesTheExplicitLinkAfterLoginRename(): void
+ {
+ $this->ldap->connections['example'] = [
+ 'hosts' => ['ad.example.com'],
+ 'baseDn' => 'dc=ad,dc=example,dc=com',
+ 'bindDn' => 'cn=reader,dc=ad,dc=example,dc=com',
+ 'bindPassword' => 'example-test-service-password',
+ 'loginAttributes' => ['userPrincipalName'],
+ 'externalIdAttribute' => 'objectGUID',
+ ];
+ (new LDAPUserResolver(auth()->getProvider()))->link(
+ 'example',
+ '00112233-4455-6677-8899-aabbccddeeff',
+ $this->user->id,
+ );
+ $this->directory->expects($this->once())->method('authenticate')->willReturn([
+ 'dn' => 'cn=New Name,dc=ad,dc=example,dc=com',
+ 'attributes' => ['objectguid' => ["\x33\x22\x11\x00\x55\x44\x77\x66\x88\x99\xaa\xbb\xcc\xdd\xee\xff"]],
+ ]);
+
+ $response = $this->post('/login', ['username' => 'renamed@ad.example.com', 'password' => 'directory-secret']);
+
+ $response->assertSessionMissing('error');
+ $this->assertSame($this->user->id, auth('session')->id());
+ }
+
+ /**
+ * @return array{dn: string, attributes: array>}
+ */
+ private function entry(string $uid = 'directory-user'): array
+ {
+ return [
+ 'dn' => 'uid=' . $uid . ',dc=example,dc=com',
+ 'attributes' => ['uid' => [$uid], 'entryuuid' => ['stable-id']],
+ ];
+ }
+}
diff --git a/tests/Unit/AuthLDAPTest.php b/tests/Unit/AuthLDAPTest.php
new file mode 100644
index 000000000..707bd1fa6
--- /dev/null
+++ b/tests/Unit/AuthLDAPTest.php
@@ -0,0 +1,199 @@
+
+ *
+ * For the full copyright and license information, please view
+ * the LICENSE file that was distributed with this source code.
+ */
+
+namespace CodeIgniter\Shield\Tests\Unit;
+
+use CodeIgniter\Shield\Config\AuthLDAP;
+use CodeIgniter\Shield\Exceptions\LDAPException;
+use PHPUnit\Framework\Attributes\DataProvider;
+use PHPUnit\Framework\TestCase;
+use ReflectionClass;
+
+/**
+ * @internal
+ */
+final class AuthLDAPTest extends TestCase
+{
+ private const CONNECTION_METADATA = [
+ 'hosts' => ['ldap.example.test', 'ldap-backup.example.test'],
+ 'baseDn' => 'dc=example,dc=test',
+ 'bindDn' => 'cn=reader,dc=example,dc=test',
+ 'bindPassword' => 'metadata-test-password',
+ 'encryption' => 'starttls',
+ 'port' => 1389,
+ 'connectTimeout' => 4,
+ 'searchTimeout' => 8,
+ 'userBaseDn' => 'ou=users,dc=example,dc=test',
+ 'loginFilter' => '(objectClass=inetOrgPerson)',
+ 'loginAttributes' => ['cn', 'mail'],
+ 'externalIdAttribute' => 'objectGUID',
+ 'profileAttributes' => ['email' => 'mail'],
+ 'provisionUsers' => true,
+ 'eligibilityFilter' => '(accountStatus=active)',
+ 'updateProfile' => false,
+ ];
+
+ public function testDefaultConfigurationHasNoConnections(): void
+ {
+ $this->assertSame([], (new AuthLDAP())->connectionIds());
+ }
+
+ public function testBuildsConnectionFromConfiguredMetadata(): void
+ {
+ $metadata = self::CONNECTION_METADATA;
+ unset($metadata['bindPassword']);
+
+ $config = new AuthLDAP();
+ $config->connections = [
+ 'missing-bind-secret-test' => $metadata,
+ 'corporate' => self::CONNECTION_METADATA,
+ ];
+
+ $this->assertSame(['missing-bind-secret-test', 'corporate'], $config->connectionIds());
+
+ $connection = $config->getConnection('corporate');
+
+ $this->assertSame('corporate', $connection->id);
+ $this->assertSame($metadata, array_intersect_key(get_object_vars($connection), $metadata));
+ $this->assertSame('metadata-test-password', $connection->bindPassword());
+ }
+
+ #[DataProvider('provideLoadsNestedEnvironmentOverrides')]
+ public function testLoadsNestedEnvironmentOverrides(string $separator): void
+ {
+ $overrides = [
+ 'authldap.connections.corporate.bindPassword' => 'environment-test-password',
+ 'authldap.connections.corporate.hosts.0' => 'ldap-env.example.test',
+ 'authldap.connections.corporate.port' => '1636',
+ 'authldap.connections.corporate.provisionUsers' => 'false',
+ ];
+
+ $original = [];
+
+ try {
+ foreach ($overrides as $name => $value) {
+ $key = str_replace('.', $separator, $name);
+ $original[$key] = getenv($key);
+ putenv($key . '=' . $value);
+ }
+
+ // Seed defaults before BaseConfig loads the nested environment overrides.
+ $reflection = new ReflectionClass(AuthLDAP::class);
+ $config = $reflection->newInstanceWithoutConstructor();
+ $config->connections = ['corporate' => self::CONNECTION_METADATA];
+ $reflection->getConstructor()?->invoke($config);
+
+ $connection = $config->getConnection('corporate');
+
+ $this->assertSame('environment-test-password', $connection->bindPassword());
+ $this->assertSame(['ldap-env.example.test', 'ldap-backup.example.test'], $connection->hosts);
+ $this->assertSame(1636, $connection->port);
+ $this->assertFalse($connection->provisionUsers);
+ } finally {
+ foreach ($original as $key => $value) {
+ putenv($value === false ? $key : $key . '=' . $value);
+ }
+ }
+ }
+
+ /**
+ * @return iterable
+ */
+ public static function provideLoadsNestedEnvironmentOverrides(): iterable
+ {
+ yield 'dotted' => ['.'];
+
+ yield 'underscored' => ['_'];
+ }
+
+ public function testRedactsBindPasswordFromDiagnosticOutput(): void
+ {
+ $config = new AuthLDAP();
+ $config->connections = ['corporate' => self::CONNECTION_METADATA];
+ $connection = $config->getConnection('corporate');
+
+ $this->assertStringNotContainsString('metadata-test-password', print_r($config, true));
+ $this->assertStringNotContainsString('metadata-test-password', var_export($connection, true));
+ }
+
+ /**
+ * @param array $settings
+ */
+ #[DataProvider('provideRejectsMissingOrEmptyBindPassword')]
+ public function testRejectsMissingOrEmptyBindPassword(array $settings): void
+ {
+ $config = new AuthLDAP();
+ $config->connections = ['missing-bind-secret-test' => $settings];
+
+ $this->assertSame(['missing-bind-secret-test'], $config->connectionIds());
+
+ $this->expectException(LDAPException::class);
+ $this->expectExceptionMessage('invalid_bind_secret');
+
+ $config->getConnection('missing-bind-secret-test');
+ }
+
+ /**
+ * @return iterable}>
+ */
+ public static function provideRejectsMissingOrEmptyBindPassword(): iterable
+ {
+ yield 'missing' => [array_diff_key(self::CONNECTION_METADATA, ['bindPassword' => true])];
+
+ yield 'empty' => [['bindPassword' => ''] + self::CONNECTION_METADATA];
+ }
+
+ /**
+ * @param array $options
+ */
+ #[DataProvider('provideRejectsInvalidConnectionOptions')]
+ public function testRejectsInvalidConnectionOptions(array $options): void
+ {
+ $config = new AuthLDAP();
+ $config->connections = ['corporate' => $options + self::CONNECTION_METADATA];
+
+ try {
+ $config->getConnection('corporate');
+ $this->fail('Invalid connection options must be rejected.');
+ } catch (LDAPException $exception) {
+ $this->assertSame('invalid_configuration', $exception->reason);
+ $this->assertStringNotContainsString('metadata-test-password', $exception->getMessage());
+ $this->assertNull($exception->getPrevious());
+ }
+ }
+
+ /**
+ * @return iterable}>
+ */
+ public static function provideRejectsInvalidConnectionOptions(): iterable
+ {
+ yield 'nested connection ID' => [['id' => 'invalid-inline-id']];
+
+ yield 'invalid port type' => [['port' => 'not-a-port']];
+
+ yield 'numeric host' => [['hosts' => [123]]];
+
+ yield 'positional option' => [['starttls']];
+ }
+
+ public function testRejectsUnknownConnectionId(): void
+ {
+ $config = new AuthLDAP();
+ $config->connections = ['corporate' => self::CONNECTION_METADATA];
+
+ $this->expectException(LDAPException::class);
+ $this->expectExceptionMessage('invalid_configuration');
+
+ $config->getConnection('unknown');
+ }
+}
diff --git a/tests/Unit/LDAPServicesTest.php b/tests/Unit/LDAPServicesTest.php
new file mode 100644
index 000000000..627de7586
--- /dev/null
+++ b/tests/Unit/LDAPServicesTest.php
@@ -0,0 +1,45 @@
+
+ *
+ * For the full copyright and license information, please view
+ * the LICENSE file that was distributed with this source code.
+ */
+
+namespace CodeIgniter\Shield\Tests\Unit;
+
+use CodeIgniter\Shield\Authentication\LDAP\NativeLDAPDirectory;
+use CodeIgniter\Shield\Config\Services;
+use CodeIgniter\Shield\Tests\TestCase;
+
+/**
+ * @internal
+ */
+final class LDAPServicesTest extends TestCase
+{
+ public function testSharesTheDirectoryByDefault(): void
+ {
+ $directory = Services::ldapDirectory();
+
+ $this->assertInstanceOf(NativeLDAPDirectory::class, $directory);
+ $this->assertSame($directory, Services::ldapDirectory(true));
+ $this->assertSame($directory, service('ldapDirectory'));
+ }
+
+ public function testNonSharedDirectoryCallsCreateIndependentInstances(): void
+ {
+ $first = Services::ldapDirectory(false);
+ $second = Services::ldapDirectory(false);
+ $shared = Services::ldapDirectory();
+
+ $this->assertInstanceOf(NativeLDAPDirectory::class, $first);
+ $this->assertNotSame($first, $second);
+ $this->assertNotSame($first, $shared);
+ $this->assertNotSame($second, $shared);
+ }
+}
diff --git a/tests/_support/LDAP/Dockerfile b/tests/_support/LDAP/Dockerfile
new file mode 100644
index 000000000..f714a6ee1
--- /dev/null
+++ b/tests/_support/LDAP/Dockerfile
@@ -0,0 +1,17 @@
+FROM debian:bookworm-slim
+
+RUN apt-get update \
+ && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends slapd ldap-utils \
+ && mkdir /var/lib/shield-ldap
+
+COPY slapd.conf entries.ldif /etc/shield-ldap/
+
+EXPOSE 1389 1636
+
+HEALTHCHECK --interval=1s --timeout=5s --retries=10 \
+ CMD export LDAPTLS_CACERT=/tls/ca.pem LDAPTLS_REQCERT=demand LDAPTLS_REQSAN=demand \
+ && reader_dn='cn=reader,dc=example,dc=test' && reader_password='readerPassword!' \
+ && ldapwhoami -x -H ldaps://127.0.0.1:1636 -D "$reader_dn" -w "$reader_password" \
+ && ldapwhoami -x -ZZ -H ldap://127.0.0.1:1389 -D "$reader_dn" -w "$reader_password"
+
+CMD ["sh", "-ec", "slapadd -f /etc/shield-ldap/slapd.conf -l /etc/shield-ldap/entries.ldif && exec slapd -f /etc/shield-ldap/slapd.conf -d 0 -h 'ldap://0.0.0.0:1389/ ldaps://0.0.0.0:1636/'"]
diff --git a/tests/_support/LDAP/LoginController.php b/tests/_support/LDAP/LoginController.php
new file mode 100644
index 000000000..d01ccf597
--- /dev/null
+++ b/tests/_support/LDAP/LoginController.php
@@ -0,0 +1,42 @@
+
+ *
+ * For the full copyright and license information, please view
+ * the LICENSE file that was distributed with this source code.
+ */
+
+namespace Tests\Support\LDAP;
+
+use App\Controllers\BaseController;
+use CodeIgniter\HTTP\RedirectResponse;
+use CodeIgniter\Shield\Authentication\Authenticators\LDAP;
+
+/**
+ * Exercises the application login action described in the LDAP guide.
+ */
+final class LoginController extends BaseController
+{
+ /**
+ * Signs the user in with LDAP and continues any pending Shield login action.
+ */
+ public function loginAction(): RedirectResponse
+ {
+ /** @var LDAP $ldap */
+ $ldap = auth('ldap')->getAuthenticator();
+ $result = $ldap->attempt($this->request->getPost(['username', 'password']));
+
+ if (! $result->isOK()) {
+ return redirect()->route('login')->with('error', $result->reason());
+ }
+
+ return $ldap->hasAction()
+ ? redirect()->route('auth-action-show')->withCookies()
+ : redirect()->to(config('Auth')->loginRedirect())->withCookies();
+ }
+}
diff --git a/tests/_support/LDAP/NativeLDAPStub.php b/tests/_support/LDAP/NativeLDAPStub.php
new file mode 100644
index 000000000..a1d1aec6b
--- /dev/null
+++ b/tests/_support/LDAP/NativeLDAPStub.php
@@ -0,0 +1,46 @@
+
+ *
+ * For the full copyright and license information, please view
+ * the LICENSE file that was distributed with this source code.
+ */
+
+namespace Tests\Support\LDAP;
+
+/**
+ * Scripted state for the LDAP functions loaded in isolated PHPUnit processes.
+ */
+final class NativeLDAPStub
+{
+ public static bool $available = true;
+
+ /**
+ * @var list
+ */
+ public static array $connected = [];
+
+ public static int $unbound = 0;
+
+ /**
+ * @var array Endpoints whose service bind fails with the given LDAP code.
+ */
+ public static array $bindErrors = [];
+
+ public static bool $warnOnBindFailure = false;
+ public static int $lastError = 0;
+ public static string $diagnostic = '';
+ public static bool $searchFails = false;
+ public static int $searchCode = 0;
+ public static bool $hasReference = false;
+
+ /**
+ * @var list Distinguished names in the search result.
+ */
+ public static array $entries = [];
+}
diff --git a/tests/_support/LDAP/entries.ldif b/tests/_support/LDAP/entries.ldif
new file mode 100644
index 000000000..be5149e18
--- /dev/null
+++ b/tests/_support/LDAP/entries.ldif
@@ -0,0 +1,38 @@
+dn: dc=example,dc=test
+objectClass: dcObject
+objectClass: organization
+dc: example
+o: Shield LDAP test directory
+
+dn: cn=reader,dc=example,dc=test
+objectClass: organizationalRole
+objectClass: simpleSecurityObject
+cn: reader
+userPassword: readerPassword!
+
+dn: ou=people,dc=example,dc=test
+objectClass: organizationalUnit
+ou: people
+
+dn: uid=alice,ou=people,dc=example,dc=test
+objectClass: inetOrgPerson
+cn: Alice Shared
+sn: Shared
+uid: alice
+userPassword: alicePassword!
+
+dn: uid=bob,ou=people,dc=example,dc=test
+objectClass: inetOrgPerson
+cn: Bob Shared
+sn: Shared
+uid: bob
+userPassword: bobPassword!
+
+dn: ou=groups,dc=example,dc=test
+objectClass: organizationalUnit
+ou: groups
+
+dn: cn=shield-users,ou=groups,dc=example,dc=test
+objectClass: groupOfNames
+cn: shield-users
+member: uid=alice,ou=people,dc=example,dc=test
diff --git a/tests/_support/LDAP/native_ldap_functions.inc b/tests/_support/LDAP/native_ldap_functions.inc
new file mode 100644
index 000000000..f21a76f38
--- /dev/null
+++ b/tests/_support/LDAP/native_ldap_functions.inc
@@ -0,0 +1,149 @@
+
+ *
+ * For the full copyright and license information, please view
+ * the LICENSE file that was distributed with this source code.
+ */
+
+namespace CodeIgniter\Shield\Authentication\LDAP;
+
+use LDAP\Connection;
+use ReflectionClass;
+use stdClass;
+use Tests\Support\LDAP\NativeLDAPStub;
+
+// Keep these shadow functions in an include used only by the isolated transport tests.
+if (! \extension_loaded('ldap')) {
+ class_alias(NativeLDAPStub::class, Connection::class);
+
+ foreach ([
+ 'LDAP_OPT_NETWORK_TIMEOUT' => 20_485,
+ 'LDAP_OPT_TIMEOUT' => 20_482,
+ 'LDAP_OPT_X_TLS_REQUIRE_CERT' => 24_582,
+ 'LDAP_OPT_X_TLS_DEMAND' => 2,
+ 'LDAP_OPT_X_TLS_HARD' => 1,
+ 'LDAP_OPT_PROTOCOL_VERSION' => 17,
+ 'LDAP_OPT_REFERRALS' => 8,
+ 'LDAP_OPT_DEREF' => 2,
+ 'LDAP_DEREF_NEVER' => 0,
+ 'LDAP_OPT_DIAGNOSTIC_MESSAGE' => 50,
+ ] as $option => $value) {
+ define($option, $value);
+ }
+}
+
+function extension_loaded(string $extension): bool
+{
+ return $extension === 'ldap' ? NativeLDAPStub::$available : \extension_loaded($extension);
+}
+
+function function_exists(string $function): bool
+{
+ return $function === 'ldap_start_tls' || \function_exists($function);
+}
+
+function ldap_connect(string $uri): Connection|false
+{
+ NativeLDAPStub::$connected[] = $uri;
+
+ // The native constructor creates a handle without connecting to the URI.
+ return \extension_loaded('ldap')
+ ? \ldap_connect($uri)
+ : (new ReflectionClass(Connection::class))->newInstance();
+}
+
+function ldap_get_option(Connection $connection, int $option, int|string|null &$value): bool
+{
+ $value = match ($option) {
+ LDAP_OPT_X_TLS_REQUIRE_CERT => LDAP_OPT_X_TLS_DEMAND,
+ LDAP_OPT_DIAGNOSTIC_MESSAGE => NativeLDAPStub::$diagnostic,
+ default => null,
+ };
+
+ return $value !== null;
+}
+
+function ldap_set_option(Connection $connection, int $option, bool|int $value): bool
+{
+ return true;
+}
+
+function ldap_bind(Connection $connection, string $dn, string $password): bool
+{
+ $uri = NativeLDAPStub::$connected[array_key_last(NativeLDAPStub::$connected)];
+ NativeLDAPStub::$lastError = NativeLDAPStub::$bindErrors[$uri] ?? 0;
+
+ if (NativeLDAPStub::$lastError !== 0 && NativeLDAPStub::$warnOnBindFailure) {
+ trigger_error('Untrusted LDAP bind diagnostic', E_USER_WARNING);
+ }
+
+ return NativeLDAPStub::$lastError === 0;
+}
+
+function ldap_unbind(Connection $connection): bool
+{
+ NativeLDAPStub::$unbound++;
+
+ return true;
+}
+
+function ldap_errno(Connection $connection): int
+{
+ return NativeLDAPStub::$lastError;
+}
+
+/**
+ * @param list $attributes
+ */
+function ldap_search(Connection $connection, string $base, string $filter, array $attributes, int $attributesOnly, int $sizeLimit, int $timeLimit): false|stdClass
+{
+ NativeLDAPStub::$lastError = NativeLDAPStub::$searchCode;
+
+ return NativeLDAPStub::$searchFails ? false : new stdClass();
+}
+
+function ldap_parse_result(Connection $connection, stdClass $result, ?int &$code): bool
+{
+ $code = NativeLDAPStub::$searchCode;
+
+ return true;
+}
+
+function ldap_first_reference(Connection $connection, stdClass $result): false|stdClass
+{
+ return NativeLDAPStub::$hasReference ? new stdClass() : false;
+}
+
+function ldap_count_entries(Connection $connection, stdClass $result): int
+{
+ return count(NativeLDAPStub::$entries);
+}
+
+function ldap_first_entry(Connection $connection, stdClass $result): false|int
+{
+ return NativeLDAPStub::$entries === [] ? false : 0;
+}
+
+function ldap_next_entry(Connection $connection, int $entry): false|int
+{
+ $next = $entry + 1;
+
+ return array_key_exists($next, NativeLDAPStub::$entries) ? $next : false;
+}
+
+function ldap_get_dn(Connection $connection, int $entry): string
+{
+ return NativeLDAPStub::$entries[$entry];
+}
+
+function ldap_get_values_len(Connection $connection, int $entry, string $attribute): false
+{
+ // These cases only inspect distinguished names, so no attributes are returned.
+ return false;
+}
diff --git a/tests/_support/LDAP/run-integration-tests.sh b/tests/_support/LDAP/run-integration-tests.sh
new file mode 100644
index 000000000..84fa587c5
--- /dev/null
+++ b/tests/_support/LDAP/run-integration-tests.sh
@@ -0,0 +1,56 @@
+#!/usr/bin/env bash
+
+set -euo pipefail
+
+cd "$(dirname "${BASH_SOURCE[0]}")/../../.."
+
+tls_dir=$(mktemp -d)
+openssl req -x509 -newkey rsa:2048 -noenc -days 2 \
+ -subj '/CN=Shield LDAP test CA' -addext 'basicConstraints=critical,CA:TRUE' \
+ -keyout "$tls_dir/ca.key" -out "$tls_dir/ca.pem"
+openssl req -newkey rsa:2048 -noenc -subj '/CN=Shield LDAP fixture' \
+ -keyout "$tls_dir/server.key" -out "$tls_dir/server.csr"
+printf 'subjectAltName=IP:127.0.0.1\nextendedKeyUsage=serverAuth\n' > "$tls_dir/server.ext"
+openssl x509 -req -days 2 -in "$tls_dir/server.csr" -CA "$tls_dir/ca.pem" \
+ -CAkey "$tls_dir/ca.key" -CAcreateserial -extfile "$tls_dir/server.ext" \
+ -out "$tls_dir/server.pem"
+openssl req -x509 -newkey rsa:2048 -noenc -days 2 \
+ -subj '/CN=Untrusted Shield LDAP test CA' -addext 'basicConstraints=critical,CA:TRUE' \
+ -keyout /dev/null -out "$tls_dir/untrusted-ca.pem"
+
+image=$(docker build --quiet tests/_support/LDAP)
+container=$(docker run --rm --detach \
+ -p 127.0.0.1::1389 -p 127.0.0.1::1636 \
+ --mount "type=bind,src=$tls_dir,dst=/tls,readonly" "$image")
+
+stop_fixture() {
+ local status=$?
+ if (( status != 0 )); then
+ docker logs --tail 30 "$container" >&2 || true
+ docker inspect --format '{{range .State.Health.Log}}{{.Output}}{{end}}' "$container" >&2 || true
+ fi
+ docker stop "$container" > /dev/null || true
+}
+trap stop_fixture EXIT
+
+for (( attempt = 0; attempt < 30; attempt++ )); do
+ health=$(docker inspect --format '{{.State.Health.Status}}' "$container")
+ case "$health" in
+ healthy|unhealthy) break ;;
+ esac
+ sleep 1
+done
+
+if [[ "$health" != healthy ]]; then
+ printf 'OpenLDAP fixture failed its TLS and service bind checks (%s).\n' "$health" >&2
+ exit 1
+fi
+printf 'OpenLDAP smoke check passed for LDAPS and StartTLS.\n'
+
+starttls=$(docker port "$container" 1389/tcp)
+ldaps=$(docker port "$container" 1636/tcp)
+LDAPTLS_CACERT="$tls_dir/ca.pem" LDAPTLS_REQCERT=demand LDAPTLS_REQSAN=demand \
+ SHIELD_LDAP_TEST_PORT="${starttls##*:}" SHIELD_LDAP_TEST_LDAPS_PORT="${ldaps##*:}" \
+ SHIELD_LDAP_TEST_WRONG_HOST=localhost SHIELD_LDAP_TEST_UNTRUSTED_CA="$tls_dir/untrusted-ca.pem" \
+ vendor/bin/phpunit --no-extensions --no-coverage --fail-on-skipped --fail-on-empty-test-suite \
+ tests/Authentication/LDAP/NativeLDAPDirectoryIntegrationTest.php
diff --git a/tests/_support/LDAP/slapd.conf b/tests/_support/LDAP/slapd.conf
new file mode 100644
index 000000000..303bcadd7
--- /dev/null
+++ b/tests/_support/LDAP/slapd.conf
@@ -0,0 +1,24 @@
+include /etc/ldap/schema/core.schema
+include /etc/ldap/schema/cosine.schema
+include /etc/ldap/schema/inetorgperson.schema
+
+modulepath /usr/lib/ldap
+moduleload back_mdb
+TLSCertificateFile /tls/server.pem
+TLSCertificateKeyFile /tls/server.key
+TLSCACertificateFile /tls/ca.pem
+security simple_bind=128
+
+database mdb
+maxsize 10485760
+suffix "dc=example,dc=test"
+rootdn "cn=operator,dc=example,dc=test"
+directory /var/lib/shield-ldap
+
+access to attrs=userPassword
+ by anonymous auth
+ by self write
+ by * none
+access to *
+ by dn.exact="cn=reader,dc=example,dc=test" read
+ by * none
From d1965af1647b60b2e86030d52d1d6c7321162469 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Amel=20Junuzovi=C4=87?=
Date: Tue, 24 Nov 2026 12:19:32 +0100
Subject: [PATCH 2/2] test: separate live LDAP integration into its own PHPUnit
suite
---
docs/addons/ldap.md | 13 +++++++------
phpunit.dist.xml | 5 +++++
.../NativeLDAPDirectoryIntegrationTest.php | 2 +-
tests/_support/LDAP/run-integration-tests.sh | 2 +-
4 files changed, 14 insertions(+), 8 deletions(-)
rename tests/Authentication/LDAP/{ => Integration}/NativeLDAPDirectoryIntegrationTest.php (99%)
diff --git a/docs/addons/ldap.md b/docs/addons/ldap.md
index a9c2ba436..851ec1766 100644
--- a/docs/addons/ldap.md
+++ b/docs/addons/ldap.md
@@ -442,11 +442,12 @@ application group assignments, permissions, and revocation through the
## Testing Against OpenLDAP
-The **OpenLDAP Integration Tests** workflow runs
-`NativeLDAPDirectoryIntegrationTest` against the Docker fixture in
-`tests/_support/LDAP`. It uses test certificates and waits for the fixture to
-accept service-account binds over both LDAPS and StartTLS. The integration
-test run fails if any test is skipped.
+The **OpenLDAP Integration Tests** workflow runs the `ldap-integration`
+PHPUnit suite against the Docker fixture in `tests/_support/LDAP`. The suite
+automatically discovers `*Test.php` files in
+`tests/Authentication/LDAP/Integration/`. The workflow uses test certificates
+and waits for the fixture to accept service-account binds over both LDAPS and
+StartTLS. The integration test run fails if any test is skipped.
To run the same checks locally, install the test dependencies and make sure
Docker, OpenSSL, and PHP's `ldap` extension are available. Run the following
@@ -457,6 +458,6 @@ bash tests/_support/LDAP/run-integration-tests.sh
```
The script publishes the fixture's ports on loopback and stops the container
-when the run finishes. The regular PHPUnit suite can run without the fixture.
+when the run finishes. The default `main` PHPUnit suite runs without Docker.
Test AD-specific GUIDs, account filters, and transitive group membership
separately against a disposable AD DS or Samba AD test domain.
diff --git a/phpunit.dist.xml b/phpunit.dist.xml
index 653cacae3..bff0b6e71 100644
--- a/phpunit.dist.xml
+++ b/phpunit.dist.xml
@@ -6,6 +6,7 @@
colors="true"
columns="max"
executionOrder="random"
+ defaultTestSuite="main"
failOnRisky="true"
failOnWarning="true"
cacheDirectory="build/.phpunit.cache"
@@ -29,6 +30,10 @@
./tests
+ ./tests/Authentication/LDAP/Integration
+
+
+ ./tests/Authentication/LDAP/Integration
diff --git a/tests/Authentication/LDAP/NativeLDAPDirectoryIntegrationTest.php b/tests/Authentication/LDAP/Integration/NativeLDAPDirectoryIntegrationTest.php
similarity index 99%
rename from tests/Authentication/LDAP/NativeLDAPDirectoryIntegrationTest.php
rename to tests/Authentication/LDAP/Integration/NativeLDAPDirectoryIntegrationTest.php
index 12ed490f1..56408e2f9 100644
--- a/tests/Authentication/LDAP/NativeLDAPDirectoryIntegrationTest.php
+++ b/tests/Authentication/LDAP/Integration/NativeLDAPDirectoryIntegrationTest.php
@@ -11,7 +11,7 @@
* the LICENSE file that was distributed with this source code.
*/
-namespace CodeIgniter\Shield\Tests\Authentication\LDAP;
+namespace CodeIgniter\Shield\Tests\Authentication\LDAP\Integration;
use CodeIgniter\Shield\Authentication\LDAP\LDAPConnection;
use CodeIgniter\Shield\Authentication\LDAP\LDAPFilter;
diff --git a/tests/_support/LDAP/run-integration-tests.sh b/tests/_support/LDAP/run-integration-tests.sh
index 84fa587c5..1bbfacd18 100644
--- a/tests/_support/LDAP/run-integration-tests.sh
+++ b/tests/_support/LDAP/run-integration-tests.sh
@@ -53,4 +53,4 @@ LDAPTLS_CACERT="$tls_dir/ca.pem" LDAPTLS_REQCERT=demand LDAPTLS_REQSAN=demand \
SHIELD_LDAP_TEST_PORT="${starttls##*:}" SHIELD_LDAP_TEST_LDAPS_PORT="${ldaps##*:}" \
SHIELD_LDAP_TEST_WRONG_HOST=localhost SHIELD_LDAP_TEST_UNTRUSTED_CA="$tls_dir/untrusted-ca.pem" \
vendor/bin/phpunit --no-extensions --no-coverage --fail-on-skipped --fail-on-empty-test-suite \
- tests/Authentication/LDAP/NativeLDAPDirectoryIntegrationTest.php
+ --testsuite ldap-integration