]> BookStack Code Mirror - bookstack/blob - app/Auth/Permissions/JointPermissionBuilder.php
Added more complexity in an attempt to make ldap host failover fit
[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 $entityCache;
26
27     /**
28      * Re-generate all entity permission from scratch.
29      */
30     public function rebuildForAll()
31     {
32         JointPermission::query()->truncate();
33
34         // Get all roles (Should be the most limited dimension)
35         $roles = Role::query()->with('permissions')->get()->all();
36
37         // Chunk through all books
38         $this->bookFetchQuery()->chunk(5, function (EloquentCollection $books) use ($roles) {
39             $this->buildJointPermissionsForBooks($books, $roles);
40         });
41
42         // Chunk through all bookshelves
43         Bookshelf::query()->withTrashed()->select(['id', 'owned_by'])
44             ->chunk(50, function (EloquentCollection $shelves) use ($roles) {
45                 $this->createManyJointPermissions($shelves->all(), $roles);
46             });
47     }
48
49     /**
50      * Rebuild the entity jointPermissions for a particular entity.
51      */
52     public function rebuildForEntity(Entity $entity)
53     {
54         $entities = [$entity];
55         if ($entity instanceof Book) {
56             $books = $this->bookFetchQuery()->where('id', '=', $entity->id)->get();
57             $this->buildJointPermissionsForBooks($books, Role::query()->with('permissions')->get()->all(), true);
58
59             return;
60         }
61
62         /** @var BookChild $entity */
63         if ($entity->book) {
64             $entities[] = $entity->book;
65         }
66
67         if ($entity instanceof Page && $entity->chapter_id) {
68             $entities[] = $entity->chapter;
69         }
70
71         if ($entity instanceof Chapter) {
72             foreach ($entity->pages as $page) {
73                 $entities[] = $page;
74             }
75         }
76
77         $this->buildJointPermissionsForEntities($entities);
78     }
79
80     /**
81      * Build the entity jointPermissions for a particular role.
82      */
83     public function rebuildForRole(Role $role)
84     {
85         $roles = [$role];
86         $role->jointPermissions()->delete();
87         $role->load('permissions');
88
89         // Chunk through all books
90         $this->bookFetchQuery()->chunk(20, function ($books) use ($roles) {
91             $this->buildJointPermissionsForBooks($books, $roles);
92         });
93
94         // Chunk through all bookshelves
95         Bookshelf::query()->select(['id', 'owned_by'])
96             ->chunk(50, function ($shelves) use ($roles) {
97                 $this->createManyJointPermissions($shelves->all(), $roles);
98             });
99     }
100
101     /**
102      * Prepare the local entity cache and ensure it's empty.
103      *
104      * @param SimpleEntityData[] $entities
105      */
106     protected function readyEntityCache(array $entities)
107     {
108         $this->entityCache = [];
109
110         foreach ($entities as $entity) {
111             if (!isset($this->entityCache[$entity->type])) {
112                 $this->entityCache[$entity->type] = [];
113             }
114
115             $this->entityCache[$entity->type][$entity->id] = $entity;
116         }
117     }
118
119     /**
120      * Get a book via ID, Checks local cache.
121      */
122     protected function getBook(int $bookId): SimpleEntityData
123     {
124         return $this->entityCache['book'][$bookId];
125     }
126
127     /**
128      * Get a chapter via ID, Checks local cache.
129      */
130     protected function getChapter(int $chapterId): SimpleEntityData
131     {
132         return $this->entityCache['chapter'][$chapterId];
133     }
134
135     /**
136      * Get a query for fetching a book with its children.
137      */
138     protected function bookFetchQuery(): Builder
139     {
140         return Book::query()->withTrashed()
141             ->select(['id', 'owned_by'])->with([
142                 'chapters' => function ($query) {
143                 },
144                 'pages' => function ($query) {
145                     $query->withTrashed()->select(['id', 'owned_by', 'book_id', 'chapter_id']);
146                 },
147             ]);
148     }
149
150     /**
151      * Build joint permissions for the given book and role combinations.
152      */
153     protected function buildJointPermissionsForBooks(EloquentCollection $books, array $roles, bool $deleteOld = false)
154     {
155         $entities = clone $books;
156
157         /** @var Book $book */
158         foreach ($books->all() as $book) {
159             foreach ($book->getRelation('chapters') as $chapter) {
160                 $entities->push($chapter);
161             }
162             foreach ($book->getRelation('pages') as $page) {
163                 $entities->push($page);
164             }
165         }
166
167         if ($deleteOld) {
168             $this->deleteManyJointPermissionsForEntities($entities->all());
169         }
170
171         $this->createManyJointPermissions($entities->all(), $roles);
172     }
173
174     /**
175      * Rebuild the entity jointPermissions for a collection of entities.
176      */
177     protected function buildJointPermissionsForEntities(array $entities)
178     {
179         $roles = Role::query()->get()->values()->all();
180         $this->deleteManyJointPermissionsForEntities($entities);
181         $this->createManyJointPermissions($entities, $roles);
182     }
183
184     /**
185      * Delete all the entity jointPermissions for a list of entities.
186      *
187      * @param Entity[] $entities
188      */
189     protected function deleteManyJointPermissionsForEntities(array $entities)
190     {
191         $simpleEntities = $this->entitiesToSimpleEntities($entities);
192         $idsByType = $this->entitiesToTypeIdMap($simpleEntities);
193
194         DB::transaction(function () use ($idsByType) {
195             foreach ($idsByType as $type => $ids) {
196                 foreach (array_chunk($ids, 1000) as $idChunk) {
197                     DB::table('joint_permissions')
198                         ->where('entity_type', '=', $type)
199                         ->whereIn('entity_id', $idChunk)
200                         ->delete();
201                 }
202             }
203         });
204     }
205
206     /**
207      * @param Entity[] $entities
208      *
209      * @return SimpleEntityData[]
210      */
211     protected function entitiesToSimpleEntities(array $entities): array
212     {
213         $simpleEntities = [];
214
215         foreach ($entities as $entity) {
216             $attrs = $entity->getAttributes();
217             $simple = new SimpleEntityData();
218             $simple->id = $attrs['id'];
219             $simple->type = $entity->getMorphClass();
220             $simple->owned_by = $attrs['owned_by'] ?? 0;
221             $simple->book_id = $attrs['book_id'] ?? null;
222             $simple->chapter_id = $attrs['chapter_id'] ?? null;
223             $simpleEntities[] = $simple;
224         }
225
226         return $simpleEntities;
227     }
228
229     /**
230      * Create & Save entity jointPermissions for many entities and roles.
231      *
232      * @param Entity[] $entities
233      * @param Role[]   $roles
234      */
235     protected function createManyJointPermissions(array $originalEntities, array $roles)
236     {
237         $entities = $this->entitiesToSimpleEntities($originalEntities);
238         $this->readyEntityCache($entities);
239         $jointPermissions = [];
240
241         // Fetch related entity permissions
242         $permissions = $this->getEntityPermissionsForEntities($entities);
243
244         // Create a mapping of explicit entity permissions
245         $permissionMap = [];
246         foreach ($permissions as $permission) {
247             $key = $permission->entity_type . ':' . $permission->entity_id . ':' . $permission->role_id;
248             $permissionMap[$key] = $permission->view;
249         }
250
251         // Create a mapping of role permissions
252         $rolePermissionMap = [];
253         foreach ($roles as $role) {
254             foreach ($role->permissions as $permission) {
255                 $rolePermissionMap[$role->getRawAttribute('id') . ':' . $permission->getRawAttribute('name')] = true;
256             }
257         }
258
259         // Create Joint Permission Data
260         foreach ($entities as $entity) {
261             foreach ($roles as $role) {
262                 $jointPermissions[] = $this->createJointPermissionData(
263                     $entity,
264                     $role->getRawAttribute('id'),
265                     $permissionMap,
266                     $rolePermissionMap,
267                     $role->system_name === 'admin'
268                 );
269             }
270         }
271
272         DB::transaction(function () use ($jointPermissions) {
273             foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) {
274                 DB::table('joint_permissions')->insert($jointPermissionChunk);
275             }
276         });
277     }
278
279     /**
280      * From the given entity list, provide back a mapping of entity types to
281      * the ids of that given type. The type used is the DB morph class.
282      *
283      * @param SimpleEntityData[] $entities
284      *
285      * @return array<string, int[]>
286      */
287     protected function entitiesToTypeIdMap(array $entities): array
288     {
289         $idsByType = [];
290
291         foreach ($entities as $entity) {
292             if (!isset($idsByType[$entity->type])) {
293                 $idsByType[$entity->type] = [];
294             }
295
296             $idsByType[$entity->type][] = $entity->id;
297         }
298
299         return $idsByType;
300     }
301
302     /**
303      * Get the entity permissions for all the given entities.
304      *
305      * @param SimpleEntityData[] $entities
306      *
307      * @return EntityPermission[]
308      */
309     protected function getEntityPermissionsForEntities(array $entities): array
310     {
311         $idsByType = $this->entitiesToTypeIdMap($entities);
312         $permissionFetch = EntityPermission::query()
313             ->where(function (Builder $query) use ($idsByType) {
314                 foreach ($idsByType as $type => $ids) {
315                     $query->orWhere(function (Builder $query) use ($type, $ids) {
316                         $query->where('entity_type', '=', $type)->whereIn('entity_id', $ids);
317                     });
318                 }
319             });
320
321         return $permissionFetch->get()->all();
322     }
323
324     /**
325      * Create entity permission data for an entity and role
326      * for a particular action.
327      */
328     protected function createJointPermissionData(SimpleEntityData $entity, int $roleId, array $permissionMap, array $rolePermissionMap, bool $isAdminRole): array
329     {
330         $permissionPrefix = $entity->type . '-view';
331         $roleHasPermission = isset($rolePermissionMap[$roleId . ':' . $permissionPrefix . '-all']);
332         $roleHasPermissionOwn = isset($rolePermissionMap[$roleId . ':' . $permissionPrefix . '-own']);
333
334         if ($isAdminRole) {
335             return $this->createJointPermissionDataArray($entity, $roleId, true, true);
336         }
337
338         if ($this->entityPermissionsActiveForRole($permissionMap, $entity, $roleId)) {
339             $hasAccess = $this->mapHasActiveRestriction($permissionMap, $entity, $roleId);
340
341             return $this->createJointPermissionDataArray($entity, $roleId, $hasAccess, $hasAccess);
342         }
343
344         if ($entity->type === 'book' || $entity->type === 'bookshelf') {
345             return $this->createJointPermissionDataArray($entity, $roleId, $roleHasPermission, $roleHasPermissionOwn);
346         }
347
348         // For chapters and pages, Check if explicit permissions are set on the Book.
349         $book = $this->getBook($entity->book_id);
350         $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $book, $roleId);
351         $hasPermissiveAccessToParents = !$this->entityPermissionsActiveForRole($permissionMap, $book, $roleId);
352
353         // For pages with a chapter, Check if explicit permissions are set on the Chapter
354         if ($entity->type === 'page' && $entity->chapter_id !== 0) {
355             $chapter = $this->getChapter($entity->chapter_id);
356             $chapterRestricted = $this->entityPermissionsActiveForRole($permissionMap, $chapter, $roleId);
357             $hasPermissiveAccessToParents = $hasPermissiveAccessToParents && !$chapterRestricted;
358             if ($chapterRestricted) {
359                 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $chapter, $roleId);
360             }
361         }
362
363         return $this->createJointPermissionDataArray(
364             $entity,
365             $roleId,
366             ($hasExplicitAccessToParents || ($roleHasPermission && $hasPermissiveAccessToParents)),
367             ($hasExplicitAccessToParents || ($roleHasPermissionOwn && $hasPermissiveAccessToParents))
368         );
369     }
370
371     /**
372      * Check if entity permissions are defined within the given map, for the given entity and role.
373      * Checks for the default `role_id=0` backup option as a fallback.
374      */
375     protected function entityPermissionsActiveForRole(array $permissionMap, SimpleEntityData $entity, int $roleId): bool
376     {
377         $keyPrefix = $entity->type . ':' . $entity->id . ':';
378         return isset($permissionMap[$keyPrefix . $roleId]) || isset($permissionMap[$keyPrefix . '0']);
379     }
380
381     /**
382      * Check for an active restriction in an entity map.
383      */
384     protected function mapHasActiveRestriction(array $entityMap, SimpleEntityData $entity, int $roleId): bool
385     {
386         $roleKey = $entity->type . ':' . $entity->id . ':' . $roleId;
387         $defaultKey = $entity->type . ':' . $entity->id . ':0';
388
389         return $entityMap[$roleKey] ?? $entityMap[$defaultKey] ?? false;
390     }
391
392     /**
393      * Create an array of data with the information of an entity jointPermissions.
394      * Used to build data for bulk insertion.
395      */
396     protected function createJointPermissionDataArray(SimpleEntityData $entity, int $roleId, bool $permissionAll, bool $permissionOwn): array
397     {
398         return [
399             'entity_id'          => $entity->id,
400             'entity_type'        => $entity->type,
401             'has_permission'     => $permissionAll,
402             'has_permission_own' => $permissionOwn,
403             'owned_by'           => $entity->owned_by,
404             'role_id'            => $roleId,
405         ];
406     }
407 }