]> BookStack Code Mirror - bookstack/blob - app/Auth/Permissions/JointPermissionBuilder.php
Added, and built perm. gen for, joint_user_permissions table
[bookstack] / app / Auth / Permissions / JointPermissionBuilder.php
1 <?php
2
3 namespace BookStack\Auth\Permissions;
4
5 use BookStack\Auth\Role;
6 use BookStack\Entities\Models\Book;
7 use BookStack\Entities\Models\BookChild;
8 use BookStack\Entities\Models\Bookshelf;
9 use BookStack\Entities\Models\Chapter;
10 use BookStack\Entities\Models\Entity;
11 use BookStack\Entities\Models\Page;
12 use Illuminate\Database\Eloquent\Builder;
13 use Illuminate\Database\Eloquent\Collection as EloquentCollection;
14 use Illuminate\Support\Facades\DB;
15
16 /**
17  * Joint permissions provide a pre-query "cached" table of view permissions for all core entity
18  * types for all roles in the system. This class generates out that table for different scenarios.
19  */
20 class JointPermissionBuilder
21 {
22     /**
23      * @var array<string, array<int, SimpleEntityData>>
24      */
25     protected array $entityCache;
26
27     /**
28      * Re-generate all entity permission from scratch.
29      */
30     public function rebuildForAll()
31     {
32         JointPermission::query()->truncate();
33         JointUserPermission::query()->truncate();
34
35         // Get all roles (Should be the most limited dimension)
36         $roles = Role::query()->with('permissions')->get()->all();
37
38         // Chunk through all books
39         $this->bookFetchQuery()->chunk(5, function (EloquentCollection $books) use ($roles) {
40             $this->buildJointPermissionsForBooks($books, $roles);
41         });
42
43         // Chunk through all bookshelves
44         Bookshelf::query()->withTrashed()->select(['id', 'owned_by'])
45             ->chunk(50, function (EloquentCollection $shelves) use ($roles) {
46                 $this->createManyJointPermissions($shelves->all(), $roles);
47             });
48     }
49
50     /**
51      * Rebuild the entity jointPermissions for a particular entity.
52      */
53     public function rebuildForEntity(Entity $entity)
54     {
55         $entities = [$entity];
56         if ($entity instanceof Book) {
57             $books = $this->bookFetchQuery()->where('id', '=', $entity->id)->get();
58             $this->buildJointPermissionsForBooks($books, Role::query()->with('permissions')->get()->all(), true);
59
60             return;
61         }
62
63         /** @var BookChild $entity */
64         if ($entity->book) {
65             $entities[] = $entity->book;
66         }
67
68         if ($entity instanceof Page && $entity->chapter_id) {
69             $entities[] = $entity->chapter;
70         }
71
72         if ($entity instanceof Chapter) {
73             foreach ($entity->pages as $page) {
74                 $entities[] = $page;
75             }
76         }
77
78         $this->buildJointPermissionsForEntities($entities);
79     }
80
81     /**
82      * Build the entity jointPermissions for a particular role.
83      */
84     public function rebuildForRole(Role $role)
85     {
86         $roles = [$role];
87         $role->jointPermissions()->delete();
88         $role->load('permissions');
89
90         // Chunk through all books
91         $this->bookFetchQuery()->chunk(20, function ($books) use ($roles) {
92             $this->buildJointPermissionsForBooks($books, $roles);
93         });
94
95         // Chunk through all bookshelves
96         Bookshelf::query()->select(['id', 'owned_by'])
97             ->chunk(50, function ($shelves) use ($roles) {
98                 $this->createManyJointPermissions($shelves->all(), $roles);
99             });
100     }
101
102     /**
103      * Prepare the local entity cache and ensure it's empty.
104      *
105      * @param SimpleEntityData[] $entities
106      */
107     protected function readyEntityCache(array $entities)
108     {
109         $this->entityCache = [];
110
111         foreach ($entities as $entity) {
112             if (!isset($this->entityCache[$entity->type])) {
113                 $this->entityCache[$entity->type] = [];
114             }
115
116             $this->entityCache[$entity->type][$entity->id] = $entity;
117         }
118     }
119
120     /**
121      * Get a book via ID, Checks local cache.
122      */
123     protected function getBook(int $bookId): SimpleEntityData
124     {
125         return $this->entityCache['book'][$bookId];
126     }
127
128     /**
129      * Get a chapter via ID, Checks local cache.
130      */
131     protected function getChapter(int $chapterId): SimpleEntityData
132     {
133         return $this->entityCache['chapter'][$chapterId];
134     }
135
136     /**
137      * Get a query for fetching a book with its children.
138      */
139     protected function bookFetchQuery(): Builder
140     {
141         return Book::query()->withTrashed()
142             ->select(['id', 'owned_by'])->with([
143                 'chapters' => function ($query) {
144                     $query->withTrashed()->select(['id', 'owned_by', 'book_id']);
145                 },
146                 'pages' => function ($query) {
147                     $query->withTrashed()->select(['id', 'owned_by', 'book_id', 'chapter_id']);
148                 },
149             ]);
150     }
151
152     /**
153      * Build joint permissions for the given book and role combinations.
154      */
155     protected function buildJointPermissionsForBooks(EloquentCollection $books, array $roles, bool $deleteOld = false)
156     {
157         $entities = clone $books;
158
159         /** @var Book $book */
160         foreach ($books->all() as $book) {
161             foreach ($book->getRelation('chapters') as $chapter) {
162                 $entities->push($chapter);
163             }
164             foreach ($book->getRelation('pages') as $page) {
165                 $entities->push($page);
166             }
167         }
168
169         if ($deleteOld) {
170             $this->deleteManyJointPermissionsForEntities($entities->all());
171         }
172
173         $this->createManyJointPermissions($entities->all(), $roles);
174     }
175
176     /**
177      * Rebuild the entity jointPermissions for a collection of entities.
178      */
179     protected function buildJointPermissionsForEntities(array $entities)
180     {
181         $roles = Role::query()->get()->values()->all();
182         $this->deleteManyJointPermissionsForEntities($entities);
183         $this->createManyJointPermissions($entities, $roles);
184     }
185
186     /**
187      * Delete all the entity jointPermissions for a list of entities.
188      *
189      * @param Entity[] $entities
190      */
191     protected function deleteManyJointPermissionsForEntities(array $entities)
192     {
193         $simpleEntities = $this->entitiesToSimpleEntities($entities);
194         $idsByType = $this->entitiesToTypeIdMap($simpleEntities);
195
196         DB::transaction(function () use ($idsByType) {
197             foreach ($idsByType as $type => $ids) {
198                 foreach (array_chunk($ids, 1000) as $idChunk) {
199                     DB::table('joint_permissions')
200                         ->where('entity_type', '=', $type)
201                         ->whereIn('entity_id', $idChunk)
202                         ->delete();
203                     DB::table('joint_user_permissions')
204                         ->where('entity_type', '=', $type)
205                         ->whereIn('entity_id', $idChunk)
206                         ->delete();
207                 }
208             }
209         });
210     }
211
212     /**
213      * @param Entity[] $entities
214      *
215      * @return SimpleEntityData[]
216      */
217     protected function entitiesToSimpleEntities(array $entities): array
218     {
219         $simpleEntities = [];
220
221         foreach ($entities as $entity) {
222             $attrs = $entity->getAttributes();
223             $simple = new SimpleEntityData();
224             $simple->id = $attrs['id'];
225             $simple->type = $entity->getMorphClass();
226             $simple->owned_by = $attrs['owned_by'] ?? 0;
227             $simple->book_id = $attrs['book_id'] ?? null;
228             $simple->chapter_id = $attrs['chapter_id'] ?? null;
229             $simpleEntities[] = $simple;
230         }
231
232         return $simpleEntities;
233     }
234
235     /**
236      * Create & Save entity jointPermissions for many entities and roles.
237      *
238      * @param Entity[] $originalEntities
239      * @param Role[]   $roles
240      */
241     protected function createManyJointPermissions(array $originalEntities, array $roles)
242     {
243         $entities = $this->entitiesToSimpleEntities($originalEntities);
244         $this->readyEntityCache($entities);
245         $jointPermissions = [];
246         $jointUserPermissions = [];
247
248         // Fetch related entity permissions
249         $permissions = $this->getEntityPermissionsForEntities($entities);
250
251         // Create a mapping of explicit entity permissions
252         $permissionMap = [];
253         $controlledUserIds = [];
254         foreach ($permissions as $permission) {
255             $type = $permission->role_id ? 'role' : ($permission->user_id ? 'user' : 'fallback');
256             $id = $permission->role_id ?? $permission->user_id ?? '0';
257             $key = $permission->entity_type . ':' . $permission->entity_id . ':' . $type  . ':' .  $id;
258             if ($type === 'user') {
259                 $controlledUserIds[$id] = true;
260             }
261             $permissionMap[$key] = $permission->view;
262         }
263
264         // Create a mapping of role permissions
265         $rolePermissionMap = [];
266         foreach ($roles as $role) {
267             foreach ($role->permissions as $permission) {
268                 $rolePermissionMap[$role->getRawAttribute('id') . ':' . $permission->getRawAttribute('name')] = true;
269             }
270         }
271
272         // Create Joint Permission Data
273         foreach ($entities as $entity) {
274             foreach ($roles as $role) {
275                 $jointPermissions[] = $this->createJointPermissionData(
276                     $entity,
277                     $role->getRawAttribute('id'),
278                     $permissionMap,
279                     $rolePermissionMap,
280                     $role->system_name === 'admin'
281                 );
282             }
283             foreach ($controlledUserIds as $userId => $exists) {
284                 $userPermitted = $this->getUserPermissionOverrideStatus($entity, $userId, $permissionMap);
285                 if ($userPermitted !== null) {
286                     $jointUserPermissions[] = $this->createJointUserPermissionDataArray($entity, $userId, $userPermitted);
287                 }
288             }
289         }
290
291         DB::transaction(function () use ($jointPermissions) {
292             foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) {
293                 DB::table('joint_permissions')->insert($jointPermissionChunk);
294             }
295         });
296
297         DB::transaction(function () use ($jointUserPermissions) {
298             foreach (array_chunk($jointUserPermissions, 1000) as $jointUserPermissionsChunk) {
299                 DB::table('joint_user_permissions')->insert($jointUserPermissionsChunk);
300             }
301         });
302     }
303
304     /**
305      * From the given entity list, provide back a mapping of entity types to
306      * the ids of that given type. The type used is the DB morph class.
307      *
308      * @param SimpleEntityData[] $entities
309      *
310      * @return array<string, int[]>
311      */
312     protected function entitiesToTypeIdMap(array $entities): array
313     {
314         $idsByType = [];
315
316         foreach ($entities as $entity) {
317             if (!isset($idsByType[$entity->type])) {
318                 $idsByType[$entity->type] = [];
319             }
320
321             $idsByType[$entity->type][] = $entity->id;
322         }
323
324         return $idsByType;
325     }
326
327     /**
328      * Get the entity permissions for all the given entities.
329      *
330      * @param SimpleEntityData[] $entities
331      *
332      * @return EntityPermission[]
333      */
334     protected function getEntityPermissionsForEntities(array $entities): array
335     {
336         $idsByType = $this->entitiesToTypeIdMap($entities);
337         $permissionFetch = EntityPermission::query()
338             ->where(function (Builder $query) use ($idsByType) {
339                 foreach ($idsByType as $type => $ids) {
340                     $query->orWhere(function (Builder $query) use ($type, $ids) {
341                         $query->where('entity_type', '=', $type)->whereIn('entity_id', $ids);
342                     });
343                 }
344             });
345
346         return $permissionFetch->get()->all();
347     }
348
349     /**
350      * Create entity permission data for an entity and role
351      * for a particular action.
352      */
353     protected function createJointPermissionData(SimpleEntityData $entity, int $roleId, array $permissionMap, array $rolePermissionMap, bool $isAdminRole): array
354     {
355         $permissionPrefix = $entity->type . '-view';
356         $roleHasPermission = isset($rolePermissionMap[$roleId . ':' . $permissionPrefix . '-all']);
357         $roleHasPermissionOwn = isset($rolePermissionMap[$roleId . ':' . $permissionPrefix . '-own']);
358
359         if ($isAdminRole) {
360             return $this->createJointPermissionDataArray($entity, $roleId, true, true);
361         }
362
363         if ($this->entityPermissionsActiveForRole($permissionMap, $entity, $roleId)) {
364             $hasAccess = $this->mapHasActiveRestriction($permissionMap, $entity, $roleId);
365
366             return $this->createJointPermissionDataArray($entity, $roleId, $hasAccess, $hasAccess);
367         }
368
369         if ($entity->type === 'book' || $entity->type === 'bookshelf') {
370             return $this->createJointPermissionDataArray($entity, $roleId, $roleHasPermission, $roleHasPermissionOwn);
371         }
372
373         // For chapters and pages, Check if explicit permissions are set on the Book.
374         $book = $this->getBook($entity->book_id);
375         $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $book, $roleId);
376         $hasPermissiveAccessToParents = !$this->entityPermissionsActiveForRole($permissionMap, $book, $roleId);
377
378         // For pages with a chapter, Check if explicit permissions are set on the Chapter
379         if ($entity->type === 'page' && $entity->chapter_id !== 0) {
380             $chapter = $this->getChapter($entity->chapter_id);
381             $chapterRestricted = $this->entityPermissionsActiveForRole($permissionMap, $chapter, $roleId);
382             $hasPermissiveAccessToParents = $hasPermissiveAccessToParents && !$chapterRestricted;
383             if ($chapterRestricted) {
384                 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $chapter, $roleId);
385             }
386         }
387
388         return $this->createJointPermissionDataArray(
389             $entity,
390             $roleId,
391             ($hasExplicitAccessToParents || ($roleHasPermission && $hasPermissiveAccessToParents)),
392             ($hasExplicitAccessToParents || ($roleHasPermissionOwn && $hasPermissiveAccessToParents))
393         );
394     }
395
396     /**
397      * Get the status of a user-specific permission override for the given entity user combo if existing.
398      * This can return null where no user-specific permission overrides are applicable.
399      */
400     protected function getUserPermissionOverrideStatus(SimpleEntityData $entity, int $userId, array $permissionMap): ?bool
401     {
402         // If direct permissions exists, return those
403         $directKey = $entity->type . ':' . $entity->id . ':user:' . $userId;
404         if (isset($permissionMap[$directKey])) {
405             return $permissionMap[$directKey];
406         }
407
408         // If a book or shelf, exit out since no parents to check
409         if ($entity->type === 'book' || $entity->type === 'bookshelf') {
410             return null;
411         }
412
413         // If a chapter or page, get the parent book permission status.
414         // defaults to null where no permission is set.
415         $bookKey = 'book:' . $entity->book_id . ':user:' . $userId;
416         $bookPermission = $permissionMap[$bookKey] ?? null;
417
418         // If a page within a chapter, return the chapter permission if existing otherwise
419         // default ot the parent book permission.
420         if ($entity->type === 'page' && $entity->chapter_id !== 0) {
421             $chapterKey = 'chapter:' . $entity->chapter_id . ':user:' . $userId;
422             $chapterPermission = $permissionMap[$chapterKey] ?? null;
423             return $chapterPermission ?? $bookPermission;
424         }
425
426         // Return the book permission status
427         return $bookPermission;
428     }
429
430     /**
431      * Check if entity permissions are defined within the given map, for the given entity and role.
432      * Checks for the default `role_id=0` backup option as a fallback.
433      */
434     protected function entityPermissionsActiveForRole(array $permissionMap, SimpleEntityData $entity, int $roleId): bool
435     {
436         $keyPrefix = $entity->type . ':' . $entity->id . ':';
437         return isset($permissionMap[$keyPrefix . 'role:' . $roleId]) || isset($permissionMap[$keyPrefix . 'fallback:0']);
438     }
439
440     /**
441      * Check for an active restriction in an entity map.
442      */
443     protected function mapHasActiveRestriction(array $permissionMap, SimpleEntityData $entity, int $roleId): bool
444     {
445         $roleKey = $entity->type . ':' . $entity->id . ':role:' . $roleId;
446         $defaultKey = $entity->type . ':' . $entity->id . ':fallback:0';
447
448         return $permissionMap[$roleKey] ?? $permissionMap[$defaultKey] ?? false;
449     }
450
451     /**
452      * Create an array of data with the information of an entity jointPermissions.
453      * Used to build data for bulk insertion.
454      */
455     protected function createJointPermissionDataArray(SimpleEntityData $entity, int $roleId, bool $permissionAll, bool $permissionOwn): array
456     {
457         return [
458             'entity_id'          => $entity->id,
459             'entity_type'        => $entity->type,
460             'has_permission'     => $permissionAll,
461             'has_permission_own' => $permissionOwn,
462             'owned_by'           => $entity->owned_by,
463             'role_id'            => $roleId,
464         ];
465     }
466
467     /**
468      * Create an array of data with the information of an JointUserPermission.
469      * Used to build data for bulk insertion.
470      */
471     protected function createJointUserPermissionDataArray(SimpleEntityData $entity, int $userId, bool $hasPermission): array
472     {
473         return [
474             'entity_id'          => $entity->id,
475             'entity_type'        => $entity->type,
476             'has_permission'     => $hasPermission,
477             'user_id'            => $userId,
478         ];
479     }
480 }