-
-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathManager.php
More file actions
542 lines (448 loc) · 16.8 KB
/
Manager.php
File metadata and controls
542 lines (448 loc) · 16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
<?php
declare(strict_types=1);
namespace Yiisoft\Rbac;
use Closure;
use InvalidArgumentException;
use Psr\Clock\ClockInterface;
use RuntimeException;
use Stringable;
use Yiisoft\Access\AccessCheckerInterface;
use Yiisoft\Rbac\Exception\DefaultRolesNotFoundException;
use Yiisoft\Rbac\Exception\ItemAlreadyExistsException;
use function is_array;
/**
* Helps to manage RBAC hierarchy and check for permissions.
*/
final class Manager implements ManagerInterface
{
private readonly RuleFactoryInterface $ruleFactory;
/**
* @var string[] A list of role names that are assigned to every user automatically without calling {@see assign()}.
* Note that these roles are applied to users, regardless of their state of authentication.
*/
private array $defaultRoleNames = [];
private ?string $guestRoleName = null;
/**
* @param ItemsStorageInterface $itemsStorage Items storage.
* @param AssignmentsStorageInterface $assignmentsStorage Assignments storage.
* @param RuleFactoryInterface|null $ruleFactory Rule factory.
* @param bool $enableDirectPermissions Whether to enable assigning permissions directly to user. Prefer assigning
* roles only.
* @param bool $includeRolesInAccessChecks Whether to include roles (in addition to permissions) during access
* checks in {@see Manager::userHasPermission()}.
* @param ClockInterface|null $clock Instance of `ClockInterface` implementation to be used for getting current
* time.
*/
public function __construct(
private readonly ItemsStorageInterface $itemsStorage,
private readonly AssignmentsStorageInterface $assignmentsStorage,
?RuleFactoryInterface $ruleFactory = null,
private readonly bool $enableDirectPermissions = false,
private readonly bool $includeRolesInAccessChecks = false,
private readonly ?ClockInterface $clock = null,
) {
$this->ruleFactory = $ruleFactory ?? new SimpleRuleFactory();
}
public function userHasPermission(
int|string|Stringable|null $userId,
string $permissionName,
array $parameters = [],
): bool {
$item = $this->itemsStorage->get($permissionName);
if ($item === null) {
return false;
}
if (!$this->includeRolesInAccessChecks && $item->getType() === Item::TYPE_ROLE) {
return false;
}
if ($userId !== null) {
$guestRole = null;
} else {
$guestRole = $this->getGuestRole();
if ($guestRole === null) {
return false;
}
}
$hierarchy = $this->itemsStorage->getHierarchy($item->getName());
$itemNames = array_map(static fn(array $treeItem): string => $treeItem['item']->getName(), $hierarchy);
$userItemNames = $guestRole !== null
? [$guestRole->getName()]
: $this->filterUserItemNames((string) $userId, $itemNames);
$userItemNamesMap = [];
foreach ($userItemNames as $userItemName) {
$userItemNamesMap[$userItemName] = null;
}
foreach ($hierarchy as $data) {
if (
!array_key_exists($data['item']->getName(), $userItemNamesMap) ||
!$this->executeRule($userId === null ? $userId : (string) $userId, $data['item'], $parameters)
) {
continue;
}
$hasPermission = true;
foreach ($data['children'] as $childItem) {
if (!$this->executeRule($userId === null ? $userId : (string) $userId, $childItem, $parameters)) {
$hasPermission = false;
/**
* @infection-ignore-all Break_
* Replacing with `continue` works as well, but there is no point in further checks, because at
* least one failed rule execution means access is not granted via current iterated hierarchy
* branch.
*/
break;
}
}
if ($hasPermission) {
return true;
}
}
return false;
}
public function canAddChild(string $parentName, string $childName): bool
{
try {
$this->assertFutureChild($parentName, $childName);
} catch (RuntimeException) {
return false;
}
return true;
}
public function addChild(string $parentName, string $childName): self
{
$this->assertFutureChild($parentName, $childName);
$this->itemsStorage->addChild($parentName, $childName);
return $this;
}
public function removeChild(string $parentName, string $childName): self
{
$this->itemsStorage->removeChild($parentName, $childName);
return $this;
}
public function removeChildren(string $parentName): self
{
$this->itemsStorage->removeChildren($parentName);
return $this;
}
public function hasChild(string $parentName, string $childName): bool
{
return $this->itemsStorage->hasDirectChild($parentName, $childName);
}
public function hasChildren(string $parentName): bool
{
return $this->itemsStorage->hasChildren($parentName);
}
public function assign(string $itemName, int|Stringable|string $userId, ?int $createdAt = null): self
{
$userId = (string) $userId;
$item = $this->itemsStorage->get($itemName);
if ($item === null) {
throw new InvalidArgumentException("There is no item named \"$itemName\".");
}
if (!$this->enableDirectPermissions && $item->getType() === Item::TYPE_PERMISSION) {
throw new InvalidArgumentException(
'Assigning permissions directly is disabled. Prefer assigning roles only.'
);
}
if ($this->assignmentsStorage->exists($itemName, $userId)) {
return $this;
}
$assignment = new Assignment($userId, $itemName, $createdAt ?? $this->getCurrentTimestamp());
$this->assignmentsStorage->add($assignment);
return $this;
}
public function revoke(string $itemName, int|Stringable|string $userId): self
{
$this->assignmentsStorage->remove($itemName, (string) $userId);
return $this;
}
public function revokeAll(int|Stringable|string $userId): self
{
$this->assignmentsStorage->removeByUserId((string) $userId);
return $this;
}
public function getItemsByUserId(int|Stringable|string $userId): array
{
$userId = (string) $userId;
$assignments = $this->assignmentsStorage->getByUserId($userId);
$assignmentNames = array_keys($assignments);
return array_merge(
$this->getDefaultRoles(),
$this->itemsStorage->getByNames($assignmentNames),
$this->itemsStorage->getAllChildren($assignmentNames),
);
}
public function getRolesByUserId(int|Stringable|string $userId): array
{
$userId = (string) $userId;
$assignments = $this->assignmentsStorage->getByUserId($userId);
$assignmentNames = array_keys($assignments);
return array_merge(
$this->getDefaultRoles(),
$this->itemsStorage->getRolesByNames($assignmentNames),
$this->itemsStorage->getAllChildRoles($assignmentNames)
);
}
public function getChildRoles(string $roleName): array
{
if (!$this->itemsStorage->roleExists($roleName)) {
throw new InvalidArgumentException("Role \"$roleName\" not found.");
}
return $this->itemsStorage->getAllChildRoles($roleName);
}
public function getPermissionsByRoleName(string $roleName): array
{
return $this->itemsStorage->getAllChildPermissions($roleName);
}
public function getPermissionsByUserId(int|Stringable|string $userId): array
{
$userId = (string) $userId;
$assignments = $this->assignmentsStorage->getByUserId($userId);
if (empty($assignments)) {
return [];
}
$assignmentNames = array_keys($assignments);
return array_merge(
$this->itemsStorage->getPermissionsByNames($assignmentNames),
$this->itemsStorage->getAllChildPermissions($assignmentNames),
);
}
public function getUserIdsByRoleName(string $roleName): array
{
$roleNames = [$roleName, ...array_keys($this->itemsStorage->getParents($roleName))];
return array_map(
static fn(Assignment $assignment): string => $assignment->getUserId(),
$this->assignmentsStorage->getByItemNames($roleNames),
);
}
public function addRole(Role $role): self
{
$this->addItem($role);
return $this;
}
public function getRole(string $name): ?Role
{
return $this->itemsStorage->getRole($name);
}
public function updateRole(string $name, Role $role): self
{
$this->assertItemNameForUpdate($role, $name);
$this->itemsStorage->update($name, $role);
$this->assignmentsStorage->renameItem($name, $role->getName());
return $this;
}
public function removeRole(string $name): self
{
$this->removeItem($name);
return $this;
}
public function addPermission(Permission $permission): self
{
$this->addItem($permission);
return $this;
}
public function getPermission(string $name): ?Permission
{
return $this->itemsStorage->getPermission($name);
}
public function updatePermission(string $name, Permission $permission): self
{
$this->assertItemNameForUpdate($permission, $name);
$this->itemsStorage->update($name, $permission);
$this->assignmentsStorage->renameItem($name, $permission->getName());
return $this;
}
public function removePermission(string $name): self
{
$this->removeItem($name);
return $this;
}
public function setDefaultRoleNames(array|Closure $roleNames): self
{
$this->defaultRoleNames = $this->getDefaultRoleNamesForUpdate($roleNames);
return $this;
}
public function getDefaultRoleNames(): array
{
return $this->defaultRoleNames;
}
public function getDefaultRoles(): array
{
return $this->filterStoredRoles($this->defaultRoleNames);
}
public function setGuestRoleName(?string $name): self
{
$this->guestRoleName = $name;
return $this;
}
public function getGuestRoleName(): ?string
{
return $this->guestRoleName;
}
public function getGuestRole(): ?Role
{
if ($this->guestRoleName === null) {
return null;
}
$role = $this->getRole($this->guestRoleName);
if ($role === null) {
throw new RuntimeException("Guest role with name \"$this->guestRoleName\" does not exist.");
}
return $role;
}
/**
* Executes the rule associated with the specified role or permission.
*
* If the item does not specify a rule, this method will return `true`. Otherwise, it will
* return the value of {@see RuleInterface::execute()}.
*
* @param string|null $userId The user ID. This should be a string representing the unique identifier of a user. For
* guests the value is `null`.
* @param Item $item The role or the permission that needs to execute its rule.
* @param array $params Parameters passed to {@see AccessCheckerInterface::userHasPermission()} and will be passed
* to the rule.
*
* @throws RuntimeException If the role or the permission has an invalid rule.
* @return bool The return value of {@see RuleInterface::execute()}. If the role or the permission does not specify
* a rule, `true` will be returned.
*/
private function executeRule(?string $userId, Item $item, array $params): bool
{
if ($item->getRuleName() === null) {
return true;
}
return $this->ruleFactory
->create($item->getRuleName())
->execute($userId, $item, new RuleContext($this->ruleFactory, $params));
}
/**
* @throws ItemAlreadyExistsException
*/
private function addItem(Permission|Role $item): void
{
if ($this->itemsStorage->exists($item->getName())) {
throw new ItemAlreadyExistsException($item);
}
$time = $this->getCurrentTimestamp();
if (!$item->hasCreatedAt()) {
$item = $item->withCreatedAt($time);
}
if (!$item->hasUpdatedAt()) {
$item = $item->withUpdatedAt($time);
}
$this->itemsStorage->add($item);
}
private function removeItem(string $name): void
{
if ($this->itemsStorage->exists($name)) {
$this->itemsStorage->remove($name);
$this->assignmentsStorage->removeByItemName($name);
}
}
/**
* @throws RuntimeException
*/
private function assertFutureChild(string $parentName, string $childName): void
{
if ($parentName === $childName) {
throw new RuntimeException("Cannot add \"$parentName\" as a child of itself.");
}
$parent = $this->itemsStorage->get($parentName);
if ($parent === null) {
throw new RuntimeException("Parent \"$parentName\" does not exist.");
}
$child = $this->itemsStorage->get($childName);
if ($child === null) {
throw new RuntimeException("Child \"$childName\" does not exist.");
}
if ($parent instanceof Permission && $child instanceof Role) {
throw new RuntimeException(
"Can not add \"$childName\" role as a child of \"$parentName\" permission.",
);
}
if ($this->itemsStorage->hasDirectChild($parentName, $childName)) {
throw new RuntimeException("The item \"$parentName\" already has a child \"$childName\".");
}
if ($this->itemsStorage->hasChild($childName, $parentName)) {
throw new RuntimeException(
"Cannot add \"$childName\" as a child of \"$parentName\". A loop has been detected.",
);
}
}
private function assertItemNameForUpdate(Item $item, string $name): void
{
if ($item->getName() === $name || !$this->itemsStorage->exists($item->getName())) {
return;
}
throw new InvalidArgumentException(
'Unable to change the role or the permission name. ' .
"The name \"{$item->getName()}\" is already used by another role or permission.",
);
}
/**
* @throws InvalidArgumentException
* @return string[]
*/
private function getDefaultRoleNamesForUpdate(array|Closure $roleNames): array
{
if (is_array($roleNames)) {
$this->assertDefaultRoleNamesListForUpdate($roleNames);
return $roleNames;
}
$roleNames = $roleNames();
if (!is_array($roleNames)) {
throw new InvalidArgumentException('Default role names closure must return an array.');
}
$this->assertDefaultRoleNamesListForUpdate($roleNames);
return $roleNames;
}
/**
* @psalm-assert string[] $roleNames
*
* @throws InvalidArgumentException
*/
private function assertDefaultRoleNamesListForUpdate(array $roleNames): void
{
foreach ($roleNames as $roleName) {
if (!is_string($roleName)) {
throw new InvalidArgumentException('Each role name must be a string.');
}
}
}
/**
* @param string[] $roleNames
*
* @throws DefaultRolesNotFoundException
* @return array<string, Role>
*/
private function filterStoredRoles(array $roleNames): array
{
$storedRoles = $this->itemsStorage->getRolesByNames($roleNames);
$missingRoles = array_diff($roleNames, array_keys($storedRoles));
if (!empty($missingRoles)) {
$missingRolesStr = '"' . implode('", "', $missingRoles) . '"';
throw new DefaultRolesNotFoundException("The following default roles were not found: $missingRolesStr.");
}
return $storedRoles;
}
/**
* Filters item names leaving only the ones that are assigned to specific user or assigned by default.
*
* @param string $userId User id.
* @param string[] $itemNames List of item names.
*
* @return string[] Filtered item names.
*/
private function filterUserItemNames(string $userId, array $itemNames): array
{
return array_merge(
$this->assignmentsStorage->filterUserItemNames($userId, $itemNames),
$this->defaultRoleNames,
);
}
private function getCurrentTimestamp(): int
{
return $this->clock === null
? time()
: $this->clock->now()->getTimestamp();
}
}