Repository navigation
Description
Environment:
- LDAP Server Type: ActiveDirectory
- PHP Version: 8.5
- LdapRecord Version: v4.1.1 (worked in v3.8.6)
Describe the bug:
Since v4, a global scope that calls whereMemberOf() (or whereMember(), whereManager(), etc.) recurses until PHP runs out of memory. This happens as soon as the query is built. No LDAP server is needed to reproduce it.
Cause: ActiveDirectoryBuilder::whereMemberOf() calls $this->substituteBaseDn($dn). In v4, Model\Builder wraps a Query\Builder instead of extending it, and substitutebasedn is in $passthru, so the call goes through __call() → toBase() → applyScopes(). applyScopes() clones the builder and calls the scope again, and the scope only gets added to $appliedScopes after apply() returns. So each call to apply() starts another one, and the recursion never ends.
In v3, Model\Builder extended Query\Builder, so substituteBaseDn() was a plain method call and did not apply scopes.
Steps to reproduce:
<?php
require __DIR__.'/vendor/autoload.php';
use LdapRecord\Connection;
use LdapRecord\Container;
use LdapRecord\Models\ActiveDirectory\User;
use LdapRecord\Models\Model;
use LdapRecord\Models\Scope;
use LdapRecord\Query\Model\Builder;
class GroupScope implements Scope
{
public function apply(Builder $query, Model $model): void
{
$query->whereMemberOf('cn=Accounting,{base}');
}
}
class ScopedUser extends User
{
protected static function boot(): void
{
parent::boot();
static::addGlobalScope(new GroupScope);
}
}
Container::addConnection(new Connection([
'hosts' => ['127.0.0.1'],
'base_dn' => 'dc=local,dc=com',
]));
echo ScopedUser::query()->getUnescapedQuery(), PHP_EOL;Result:
PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 2097152 bytes) in vendor/directorytree/ldaprecord/src/Query/Model/Builder.php on line 139
Expected behavior:
The query has the scope's filter applied once, as in v3:
(&(objectclass=top)(objectclass=person)(objectclass=organizationalperson)(objectclass=user)(!(objectclass=computer))(memberof=cn=Accounting,dc=local,dc=com))
In LdapRecord-Laravel, this breaks every LDAP login when a scope like this is registered under the provider's database.scopes config.
Workaround:
Call substituteBaseDn() on the underlying query builder from inside the scope:
$query->whereEquals('memberof', $query->getQuery()->substituteBaseDn('cn=Accounting,{base}'));Possible fix:
Either of these should work (I haven't tested them against the test suite):
- In
ActiveDirectoryBuilder, call$this->query->substituteBaseDn($dn)instead of$this->substituteBaseDn($dn)in the 12where*Member*/where*Managermethods. That avoids applying scopes just to substitute the base DN. - In
Model\Builder::applyScopes(), mark the scope as applied before calling it, so a call back intotoBase()from inside a scope skips it.
The first fix is narrower. The second also covers user scopes that call any passthru method.
Activity