Passed
Pull Request — master (#28)
by Tim
02:52
created

AttributeAddUsersGroups::search()   B

Complexity

Conditions 11
Paths 16

Size

Total Lines 56
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 11
eloc 24
c 1
b 0
f 0
nc 16
nop 1
dl 0
loc 56
rs 7.3166

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * Does a reverse membership lookup on the logged in user,
5
 * looking for groups it is a member of and adds them to
6
 * a defined attribute, in DN format.
7
 *
8
 * @package simplesamlphp/simplesamlphp-module-ldap
9
 */
10
11
declare(strict_types=1);
12
13
namespace SimpleSAML\Module\ldap\Auth\Process;
14
15
use SimpleSAML\Assert\Assert;
16
use SimpleSAML\Error;
17
use SimpleSAML\Logger;
18
use SimpleSAML\Module\ldap\Utils\Ldap as LdapUtils;
19
use SimpleSAML\Utils;
20
use Symfony\Component\Ldap\Adapter\ExtLdap\Query;
21
22
class AttributeAddUsersGroups extends BaseFilter
23
{
24
    /** @var string */
25
    protected string $searchUsername;
26
27
    /** @var string */
28
    protected string $searchPassword;
29
30
    /** @var string */
31
    protected string $product;
32
33
34
    /**
35
     * Initialize this filter.
36
     *
37
     * @param array $config Configuration information about this filter.
38
     * @param mixed $reserved For future use.
39
     */
40
    public function __construct(array $config, $reserved)
41
    {
42
        parent::__construct($config, $reserved);
43
44
        // Get filter specific config options
45
        $this->searchUsername = $this->config->getString('search.username');
46
        $this->searchPassword = $this->config->getString('search.password', null);
47
        $this->product = $this->config->getString('product', 'ActiveDirectory');
48
    }
49
50
51
    /**
52
     * LDAP search filters to be added to the base filters for this authproc-filter.
53
     * It's an array of key => value pairs that will be translated to (key=value) in the ldap query.
54
     *
55
     * @var array
56
     */
57
    protected array $additional_filters;
58
59
60
    /**
61
     * This is run when the filter is processed by SimpleSAML.
62
     * It will attempt to find the current users groups using
63
     * the best method possible for the LDAP product. The groups
64
     * are then added to the request attributes.
65
     *
66
     * @throws \SimpleSAML\Error\Exception
67
     * @param array &$state
68
     */
69
    public function process(array &$state): void
70
    {
71
        Assert::keyExists($state, 'Attributes');
72
73
        // Log the process
74
        Logger::debug(sprintf(
75
            '%s : Attempting to get the users groups...',
76
            $this->title
77
        ));
78
79
        $this->additional_filters = $this->config->getArray('additional_filters', []);
80
81
        // Reference the attributes, just to make the names shorter
82
        $attributes = &$state['Attributes'];
83
        $map = &$this->attribute_map;
84
85
        // Get the users groups from LDAP
86
        $groups = $this->getGroups($attributes);
87
88
        // If there are none, do not proceed
89
        if (empty($groups)) {
90
            return;
91
        }
92
93
        // Make the array if it is not set already
94
        if (!isset($attributes[$map['groups']])) {
95
            $attributes[$map['groups']] = [];
96
        }
97
98
        // Must be an array, else cannot merge groups
99
        if (!is_array($attributes[$map['groups']])) {
100
            throw new Error\Exception(sprintf(
101
                '%s : The group attribute [%s] is not an array of group DNs. %s',
102
                $this->title,
103
                $map['groups'],
104
                $this->varExport($attributes[$map['groups']])
105
            ));
106
        }
107
108
        // Add the users group(s)
109
        $group_attribute = &$attributes[$map['groups']];
110
        $group_attribute = array_merge($group_attribute, $groups);
111
        $group_attribute = array_unique($group_attribute);
112
113
        // All done
114
        Logger::debug(sprintf(
115
            '%s : Added users groups to the group attribute[%s]: %s',
116
            $this->title,
117
            $map['groups'],
118
            implode('; ', $groups)
119
        ));
120
    }
121
122
123
    /**
124
     * Will perform a search using the required attribute values from the user to
125
     * get their group membership, recursively.
126
     *
127
     * @throws \SimpleSAML\Error\Exception
128
     * @param array $attributes
129
     * @return array
130
     */
131
    protected function getGroups(array $attributes): array
132
    {
133
        // Log the request
134
        Logger::debug(sprintf(
135
            '%s : Checking for groups based on the best method for the LDAP product.',
136
            $this->title
137
        ));
138
139
        $ldapUtils = new LdapUtils();
140
        $ldap = $ldapUtils->bind($this->ldapServers, $this->searchUsername, $this->searchPassword);
141
142
        $options = [
143
            'scope' => $this->config->getString('search.scope', Query::SCOPE_SUB),
144
            'timeout' => $this->config->getInteger('timeout', 3),
145
        ];
146
147
        // Reference the map, just to make the name shorter
148
        $map = &$this->attribute_map;
149
150
151
        // All map-properties are guaranteed to exist and have a default value
152
        $dn_attribute = $map['dn'];
153
        $return_attribute = $map['return'];
154
155
        // Based on the directory service, search LDAP for groups
156
        // If any attributes are needed, prepare them before calling search method
157
        switch ($this->product) {
158
            case 'ActiveDirectory':
159
                $arrayUtils = new Utils\Arrays();
160
161
                // Log the AD specific search
162
                Logger::debug(sprintf(
163
                    '%s : Searching LDAP using ActiveDirectory specific method.',
164
                    $this->title
165
                ));
166
167
                // Make sure the defined DN attribute exists
168
                if (!isset($attributes[$dn_attribute])) {
169
                    Logger::warning(sprintf(
170
                        "%s : The DN attribute [%s] is not defined in the user's Attributes: %s",
171
                        $this->title,
172
                        $dn_attribute,
173
                        implode(', ', array_keys($attributes)),
174
                    ));
175
176
                    return [];
177
                }
178
179
                // Make sure the defined DN attribute has a value
180
                if (!isset($attributes[$dn_attribute][0]) || !$attributes[$dn_attribute][0]) {
181
                    Logger::warning(sprintf(
182
                        '%s : The DN attribute [%s] does not have a [0] value defined. %s',
183
                        $this->title,
184
                        $dn_attribute,
185
                        $this->varExport($attributes[$dn_attribute])
186
                    ));
187
188
                    return [];
189
                }
190
191
                // Log the search
192
                Logger::debug(sprintf(
193
                    '%s : Searching ActiveDirectory group membership.'
194
                        . ' DN: %s DN Attribute: %s Member Attribute: %s Type Attribute: %s Type Value: %s Base: %s',
195
                    $this->title,
196
                    $attributes[$dn_attribute][0],
197
                    $dn_attribute,
198
                    $map['member'],
199
                    $map['type'],
200
                    $this->type_map['group'],
201
                    implode('; ', $arrayUtils->arrayize($this->searchBase))
202
                ));
203
204
                $filter = sprintf(
205
                    "(&(%s=%s)(%s=%s))",
206
                    $map['type'],
207
                    $this->type_map['group'],
208
                    $map['member'] . ':1.2.840.113556.1.4.1941:',
209
                    $attributes[$dn_attribute][0],
210
                );
211
212
                break;
213
            case 'OpenLDAP':
214
                // Log the OpenLDAP specific search
215
                Logger::debug(sprintf(
216
                    '%s : Searching LDAP using OpenLDAP specific method.',
217
                    $this->title
218
                ));
219
220
                Logger::debug(sprintf(
221
                    '%s : Searching for groups in base [%s] with filter (%s=%s) and attributes %s',
222
                    $this->title,
223
                    implode(', ', $this->searchBase),
224
                    $map['memberof'],
225
                    $attributes[$map['username']][0],
226
                    $map['member']
227
                ));
228
229
                $filter = sprintf(
230
                    '(&(%s=%s))',
231
                    $map['memberof'],
232
                    $attributes[$map['username']][0]
233
                );
234
                break;
235
            default:
236
                // Log the generic search
237
                Logger::debug(
238
                    $this->title . 'Searching LDAP using the generic search method.'
239
                );
240
241
                Logger::debug(sprintf(
242
                    '%s : Checking DNs for groups. DNs: %s Attributes: %s, %s Group Type: %s',
243
                    $this->title,
244
                    implode('; ', $memberof),
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $memberof seems to be never defined.
Loading history...
245
                    $map['memberof'],
246
                    $map['type'],
247
                    $this->type_map['group']
248
                ));
249
250
/**
251
 * @ TODO: finish generic search  method
252
 *
253
 *               // Search for the users group membership, recursively
254
 *               $groups = $this->search($attributes[$map['memberof']]);
255
 */
256
        }
257
258
        $entries = $ldapUtils->searchForMultiple(
259
            $ldap,
260
            $this->searchBase,
261
            $filter,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $filter does not seem to be defined for all execution paths leading up to this point.
Loading history...
262
            $options,
263
            true
264
        );
265
266
        $groups = [];
267
        foreach ($entries as $entry) {
268
            if ($entry->hasAttribute($return_attribute)) {
269
                $values = $entry->getAttribute($return_attribute);
270
                $groups[] = array_pop($values);
271
                continue;
272
            } elseif ($entry->hasAttribute(strtolower($return_attribute))) {
273
                // Some backends return lowercase attributes
274
                $values = $entry->getAttribute(strtolower($return_attribute));
275
                $groups[] = array_pop($values);
276
                continue;
277
            } elseif ($entry->hasAttribute('dn')) {
278
                // AD queries also seem to return the objects dn by default
279
                $values = $entry->getAttribute('dn');
280
                $groups[] = array_pop($values);
281
                continue;
282
            }
283
284
            // Could not find DN, log and continue
285
            Logger::notice(sprintf(
286
                '%s : The return attribute [%s] could not be found in the entry. %s',
287
                $this->title,
288
                implode(', ', [$map['return'], strtolower($map['return'], 'dn')]),
0 ignored issues
show
Unused Code introduced by
The call to strtolower() has too many arguments starting with 'dn'. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

288
                implode(', ', [$map['return'], /** @scrutinizer ignore-call */ strtolower($map['return'], 'dn')]),

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
289
                $this->varExport($entry),
290
            ));
291
        }
292
293
        // All done
294
        Logger::debug(sprintf(
295
            '%s : User found to be a member of the groups: %s',
296
            $this->title,
297
            implode('; ', $groups),
298
        ));
299
300
        return $groups;
301
    }
302
303
304
    /**
305
     * Looks for groups from the list of DN's passed. Also
306
     * recursively searches groups for further membership.
307
     * Avoids loops by only searching a DN once. Returns
308
     * the list of groups found.
309
     *
310
     * @param array $memberof
311
     * @return array
312
     */
313
    protected function search(array $memberof): array
314
    {
315
        // Used to determine what DN's have already been searched
316
        static $searched = [];
317
318
        // Init the groups variable
319
        $groups = [];
320
321
        // Shorten the variable name
322
        //$map = &$this->attribute_map;
323
324
        // Work out what attributes to get for a group
325
        $use_group_name = false;
326
        $get_attributes = [$map['memberof'], $map['type']];
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $map seems to be never defined.
Loading history...
327
        if (isset($map['name']) && $map['name']) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $map seems to never exist and therefore isset should always be false.
Loading history...
328
            $get_attributes[] = $map['name'];
329
            $use_group_name = true;
330
        }
331
332
        // Check each DN of the passed memberOf
333
        foreach ($memberof as $dn) {
334
            // Avoid infinite loops, only need to check a DN once
335
            if (isset($searched[$dn])) {
336
                continue;
337
            }
338
339
            // Track all DN's that are searched
340
            // Use DN for key as well, isset() is faster than in_array()
341
            $searched[$dn] = $dn;
342
343
            // Query LDAP for the attribute values for the DN
344
            try {
345
                $attributes = $this->getLdap()->getAttributes($dn, $get_attributes);
0 ignored issues
show
Bug introduced by
The method getLdap() does not exist on SimpleSAML\Module\ldap\A...AttributeAddUsersGroups. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

345
                $attributes = $this->/** @scrutinizer ignore-call */ getLdap()->getAttributes($dn, $get_attributes);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
346
            } catch (Error\AuthSource $e) {
347
                continue; // DN must not exist, just continue. Logged by the LDAP object
348
            }
349
350
            // Only look for groups
351
            if (!in_array($this->type_map['group'], $attributes[$map['type']], true)) {
352
                continue;
353
            }
354
355
            // Add to found groups array
356
            if ($use_group_name && isset($attributes[$map['name']]) && is_array($attributes[$map['name']])) {
357
                $groups[] = $attributes[$map['name']][0];
358
            } else {
359
                $groups[] = $dn;
360
            }
361
362
            // Recursively search "sub" groups
363
            if (!empty($attributes[$map['memberof']])) {
364
                $groups = array_merge($groups, $this->search($attributes[$map['memberof']]));
365
            }
366
        }
367
368
        return $groups;
369
    }
370
}
371