]> BookStack Code Mirror - bookstack/blob - app/Auth/Permissions/PermissionApplicator.php
Added method for using enity ownership in relation queries
[bookstack] / app / Auth / Permissions / PermissionApplicator.php
1 <?php
2
3 namespace BookStack\Auth\Permissions;
4
5 use BookStack\Auth\Role;
6 use BookStack\Auth\User;
7 use BookStack\Entities\Models\Chapter;
8 use BookStack\Entities\Models\Entity;
9 use BookStack\Entities\Models\Page;
10 use BookStack\Model;
11 use BookStack\Traits\HasCreatorAndUpdater;
12 use BookStack\Traits\HasOwner;
13 use Illuminate\Database\Eloquent\Builder;
14 use Illuminate\Database\Query\Builder as QueryBuilder;
15 use Illuminate\Database\Query\JoinClause;
16 use Illuminate\Support\Facades\DB;
17 use InvalidArgumentException;
18
19 class PermissionApplicator
20 {
21     /**
22      * Checks if an entity has a restriction set upon it.
23      *
24      * @param HasCreatorAndUpdater|HasOwner $ownable
25      */
26     public function checkOwnableUserAccess(Model $ownable, string $permission): bool
27     {
28         $explodedPermission = explode('-', $permission);
29         $action = $explodedPermission[1] ?? $explodedPermission[0];
30         $fullPermission = count($explodedPermission) > 1 ? $permission : $ownable->getMorphClass() . '-' . $permission;
31
32         $user = $this->currentUser();
33         $userRoleIds = $this->getCurrentUserRoleIds();
34
35         $allRolePermission = $user->can($fullPermission . '-all');
36         $ownRolePermission = $user->can($fullPermission . '-own');
37         $nonJointPermissions = ['restrictions', 'image', 'attachment', 'comment'];
38         $ownerField = ($ownable instanceof Entity) ? 'owned_by' : 'created_by';
39         $ownableFieldVal = $ownable->getAttribute($ownerField);
40
41         if (is_null($ownableFieldVal)) {
42             throw new InvalidArgumentException("{$ownerField} field used but has not been loaded");
43         }
44
45         $isOwner = $user->id === $ownableFieldVal;
46         $hasRolePermission = $allRolePermission || ($isOwner && $ownRolePermission);
47
48         // Handle non entity specific jointPermissions
49         if (in_array($explodedPermission[0], $nonJointPermissions)) {
50             return $hasRolePermission;
51         }
52
53         $hasApplicableEntityPermissions = $this->hasEntityPermission($ownable, $userRoleIds, $user->id, $action);
54
55         return is_null($hasApplicableEntityPermissions) ? $hasRolePermission : $hasApplicableEntityPermissions;
56     }
57
58     /**
59      * Check if there are permissions that are applicable for the given entity item, action and roles.
60      * Returns null when no entity permissions are in force.
61      */
62     protected function hasEntityPermission(Entity $entity, array $userRoleIds, int $userId, string $action): ?bool
63     {
64         $this->ensureValidEntityAction($action);
65
66         $adminRoleId = Role::getSystemRole('admin')->id;
67         if (in_array($adminRoleId, $userRoleIds)) {
68             return true;
69         }
70
71         // The array order here is very important due to the fact we walk up the chain
72         // in the flattening loop below. Earlier items in the chain have higher priority.
73         $typeIdList = [$entity->getMorphClass() . ':' . $entity->id];
74         if ($entity instanceof Page && $entity->chapter_id) {
75             $typeIdList[] = 'chapter:' . $entity->chapter_id;
76         }
77
78         if ($entity instanceof Page || $entity instanceof Chapter) {
79             $typeIdList[] = 'book:' . $entity->book_id;
80         }
81
82         $relevantPermissions = EntityPermission::query()
83             ->where(function (Builder $query) use ($typeIdList) {
84                 foreach ($typeIdList as $typeId) {
85                     $query->orWhere(function (Builder $query) use ($typeId) {
86                         [$type, $id] = explode(':', $typeId);
87                         $query->where('entity_type', '=', $type)
88                             ->where('entity_id', '=', $id);
89                     });
90                 }
91             })->where(function (Builder $query) use ($userRoleIds, $userId) {
92                 $query->whereIn('role_id', $userRoleIds)
93                     ->orWhere('user_id', '=', $userId)
94                     ->orWhere(function (Builder $query) {
95                         $query->whereNull(['role_id', 'user_id']);
96                     });
97             })->get(['entity_id', 'entity_type', 'role_id', 'user_id', $action])
98             ->all();
99
100         $permissionMap = new EntityPermissionMap($relevantPermissions);
101         $permitsByType = ['user' => [], 'fallback' => [], 'role' => []];
102
103         // Collapse and simplify permission structure
104         foreach ($typeIdList as $typeId) {
105             $permissions = $permissionMap->getForEntity($typeId);
106             foreach ($permissions as $permission) {
107                 $related = $permission->getAssignedType();
108                 $relatedId = $permission->getAssignedTypeId();
109                 if (!isset($permitsByType[$related][$relatedId])) {
110                     $permitsByType[$related][$relatedId] = $permission->$action;
111                 }
112             }
113         }
114
115         // Return user-level permission if exists
116         if (count($permitsByType['user']) > 0) {
117             return boolval(array_values($permitsByType['user'])[0]);
118         }
119
120         // Return grant or reject from role-level if exists
121         if (count($permitsByType['role']) > 0) {
122             return boolval(max($permitsByType['role']));
123         }
124
125         // Return fallback permission if exists
126         if (count($permitsByType['fallback']) > 0) {
127             return boolval($permitsByType['fallback'][0]);
128         }
129
130         return null;
131     }
132
133     /**
134      * Checks if a user has the given permission for any items in the system.
135      * Can be passed an entity instance to filter on a specific type.
136      */
137     public function checkUserHasEntityPermissionOnAny(string $action, string $entityClass = ''): bool
138     {
139         $this->ensureValidEntityAction($action);
140
141         $permissionQuery = EntityPermission::query()
142             ->where($action, '=', true)
143             ->where(function (Builder $query) {
144                 $query->whereIn('role_id', $this->getCurrentUserRoleIds())
145                 ->orWhere('user_id', '=', $this->currentUser()->id);
146             });
147
148         if (!empty($entityClass)) {
149             /** @var Entity $entityInstance */
150             $entityInstance = app()->make($entityClass);
151             $permissionQuery = $permissionQuery->where('entity_type', '=', $entityInstance->getMorphClass());
152         }
153
154         $hasPermission = $permissionQuery->count() > 0;
155
156         return $hasPermission;
157     }
158
159     /**
160      * Limit the given entity query so that the query will only
161      * return items that the user has view permission for.
162      */
163     public function restrictEntityQuery(Builder $query, string $morphClass): Builder
164     {
165         $this->applyPermissionsToQuery($query, $query->getModel()->getTable(), $morphClass, 'id', '');
166
167         return $query;
168     }
169
170     /**
171      * @param Builder|QueryBuilder $query
172      */
173     protected function applyPermissionsToQuery($query, string $queryTable, string $entityTypeLimiter, string $entityIdColumn, string $entityTypeColumn): void
174     {
175         if ($this->currentUser()->hasSystemRole('admin')) {
176             return;
177         }
178
179         $this->applyFallbackJoin($query, $queryTable, $entityTypeLimiter, $entityIdColumn, $entityTypeColumn);
180         $this->applyRoleJoin($query, $queryTable, $entityTypeLimiter, $entityIdColumn, $entityTypeColumn);
181         $this->applyUserJoin($query, $queryTable, $entityTypeLimiter, $entityIdColumn, $entityTypeColumn);
182         $this->applyPermissionWhereFilter($query, $queryTable, $entityTypeLimiter, $entityTypeColumn);
183     }
184
185     /**
186      * Apply the where condition to a permission restricting query, to limit based upon the values of the joined
187      * permission data. Query must have joins pre-applied.
188      * Either entityTypeLimiter or entityTypeColumn should be supplied, with the other empty.
189      * Both should not be applied since that would conflict upon intent.
190      * @param Builder|QueryBuilder $query
191      */
192     protected function applyPermissionWhereFilter($query, string $queryTable, string $entityTypeLimiter, string $entityTypeColumn)
193     {
194         $abilities = ['all' => [], 'own' => []];
195         $types = $entityTypeLimiter ? [$entityTypeLimiter] : ['page', 'chapter', 'bookshelf', 'book'];
196         $fullEntityTypeColumn = $queryTable . '.' . $entityTypeColumn;
197         foreach ($types as $type) {
198             $abilities['all'][$type] = userCan($type . '-view-all');
199             $abilities['own'][$type] = userCan($type . '-view-own');
200         }
201
202         $abilities['all'] = array_filter($abilities['all']);
203         $abilities['own'] = array_filter($abilities['own']);
204
205         $query->where(function (Builder $query) use ($abilities, $fullEntityTypeColumn, $entityTypeColumn) {
206             $query->where('perms_user', '=', 1)
207                 ->orWhere(function (Builder $query) {
208                     $query->whereNull('perms_user')->where('perms_role', '=', 1);
209                 })->orWhere(function (Builder $query) {
210                     $query->whereNull(['perms_user', 'perms_role'])
211                         ->where('perms_fallback', '=', 1);
212                 });
213
214             if (count($abilities['all']) > 0) {
215                 $query->orWhere(function (Builder $query) use ($abilities, $fullEntityTypeColumn, $entityTypeColumn) {
216                     $query->whereNull(['perms_user', 'perms_role', 'perms_fallback']);
217                     if ($entityTypeColumn) {
218                         $query->whereIn($fullEntityTypeColumn, array_keys($abilities['all']));
219                     }
220                 });
221             }
222
223             if (count($abilities['own']) > 0) {
224                 $query->orWhere(function (Builder $query) use ($abilities, $fullEntityTypeColumn, $entityTypeColumn) {
225                     $query->whereNull(['perms_user', 'perms_role', 'perms_fallback'])
226                         ->where('owned_by', '=', $this->currentUser()->id);
227                     if ($entityTypeColumn) {
228                         $query->whereIn($fullEntityTypeColumn, array_keys($abilities['all']));
229                     }
230                 });
231             }
232         });
233     }
234
235     /**
236      * @param Builder|QueryBuilder $query
237      */
238     protected function applyPermissionJoin(callable $joinCallable, string $subAlias, $query, string $queryTable, string $entityTypeLimiter, string $entityIdColumn, string $entityTypeColumn)
239     {
240         $joinCondition = $this->getJoinCondition($queryTable, $subAlias, $entityIdColumn, $entityTypeColumn);
241
242         $query->joinSub(function (QueryBuilder $joinQuery) use ($joinCallable, $entityTypeLimiter) {
243             $joinQuery->select(['entity_id', 'entity_type'])->from('entity_permissions_collapsed')
244                 ->groupBy('entity_id', 'entity_type');
245             $joinCallable($joinQuery);
246
247             if ($entityTypeLimiter) {
248                 $joinQuery->where('entity_type', '=', $entityTypeLimiter);
249             }
250         }, $subAlias, $joinCondition, null, null, 'left');
251     }
252
253     /**
254      * @param Builder|QueryBuilder $query
255      */
256     protected function applyUserJoin($query, string $queryTable, string $entityTypeLimiter, string $entityIdColumn, string $entityTypeColumn)
257     {
258         $this->applyPermissionJoin(function (QueryBuilder $joinQuery) {
259             $joinQuery->selectRaw('max(view) as perms_user')
260                 ->where('user_id', '=', $this->currentUser()->id);
261         }, 'p_u', $query, $queryTable, $entityTypeLimiter, $entityIdColumn, $entityTypeColumn);
262     }
263
264
265     /**
266      * @param Builder|QueryBuilder $query
267      */
268     protected function applyRoleJoin($query, string $queryTable, string $entityTypeLimiter, string $entityIdColumn, string $entityTypeColumn)
269     {
270         $this->applyPermissionJoin(function (QueryBuilder $joinQuery) {
271             $joinQuery->selectRaw('max(view) as perms_role')
272                 ->whereIn('role_id', $this->getCurrentUserRoleIds());
273         }, 'p_r', $query, $queryTable, $entityTypeLimiter, $entityIdColumn, $entityTypeColumn);
274     }
275
276     /**
277      * @param Builder|QueryBuilder $query
278      */
279     protected function applyFallbackJoin($query, string $queryTable, string $entityTypeLimiter, string $entityIdColumn, string $entityTypeColumn)
280     {
281         $this->applyPermissionJoin(function (QueryBuilder $joinQuery) {
282             $joinQuery->selectRaw('max(view) as perms_fallback')
283                 ->whereNull(['role_id', 'user_id']);
284         }, 'p_f', $query, $queryTable, $entityTypeLimiter, $entityIdColumn, $entityTypeColumn);
285     }
286
287     protected function getJoinCondition(string $queryTable, string $joinTableName, string $entityIdColumn, string $entityTypeColumn): callable
288     {
289         return function (JoinClause $join) use ($queryTable, $joinTableName, $entityIdColumn, $entityTypeColumn) {
290             $join->on($queryTable . '.' . $entityIdColumn, '=', $joinTableName . '.entity_id');
291             if ($entityTypeColumn) {
292                 $join->on($queryTable . '.' . $entityTypeColumn, '=', $joinTableName . '.entity_type');
293             }
294         };
295     }
296
297     /**
298      * Extend the given page query to ensure draft items are not visible
299      * unless created by the given user.
300      */
301     public function restrictDraftsOnPageQuery(Builder $query): Builder
302     {
303         return $query->where(function (Builder $query) {
304             $query->where('draft', '=', false)
305                 ->orWhere(function (Builder $query) {
306                     $query->where('draft', '=', true)
307                         ->where('owned_by', '=', $this->currentUser()->id);
308                 });
309         });
310     }
311
312     /**
313      * Filter items that have entities set as a polymorphic relation.
314      * For simplicity, this will not return results attached to draft pages.
315      * Draft pages should never really have related items though.
316      *
317      * @param Builder|QueryBuilder $query
318      */
319     public function restrictEntityRelationQuery($query, string $tableName, string $entityIdColumn, string $entityTypeColumn)
320     {
321         $query->leftJoinSub(function (QueryBuilder $query) {
322             $query->select(['id as entity_id', DB::raw("'page' as entity_type"), 'owned_by', 'deleted_at', 'draft'])->from('pages');
323             $tablesByType = ['page' => 'pages', 'book' => 'books', 'chapter' => 'chapters', 'bookshelf' => 'bookshelves'];
324             foreach ($tablesByType as $type => $table) {
325                 $query->unionAll(function (QueryBuilder $query) use ($type, $table) {
326                     $query->select(['id as entity_id', DB::raw("'{$type}' as entity_type"), 'owned_by', 'deleted_at', DB::raw('0 as draft')])->from($table);
327                 });
328             }
329         }, 'entities', function (JoinClause $join) use ($tableName, $entityIdColumn, $entityTypeColumn) {
330             $join->on($tableName . '.' . $entityIdColumn, '=', 'entities.entity_id')
331                  ->on($tableName . '.' . $entityTypeColumn, '=', 'entities.entity_type');
332         });
333
334         $this->applyPermissionsToQuery($query, $tableName, '', $entityIdColumn, $entityTypeColumn);
335         // TODO - Test page draft access (Might allow drafts which should not be seen)
336
337         return $query;
338     }
339
340     /**
341      * Add conditions to a query for a model that's a relation of a page, so only the model results
342      * on visible pages are returned by the query.
343      * Is effectively the same as "restrictEntityRelationQuery" but takes into account page drafts
344      * while not expecting a polymorphic relation, Just a simpler one-page-to-many-relations set-up.
345      */
346     public function restrictPageRelationQuery(Builder $query, string $tableName, string $pageIdColumn): Builder
347     {
348         $morphClass = (new Page())->getMorphClass();
349
350         $this->applyPermissionsToQuery($query, $tableName, $morphClass, $pageIdColumn, '');
351         // TODO - Draft display
352         // TODO - Likely need owned_by entity join workaround as used above
353         return $query;
354     }
355
356     /**
357      * Get the current user.
358      */
359     protected function currentUser(): User
360     {
361         return user();
362     }
363
364     /**
365      * Get the roles for the current logged-in user.
366      *
367      * @return int[]
368      */
369     protected function getCurrentUserRoleIds(): array
370     {
371         if (auth()->guest()) {
372             return [Role::getSystemRole('public')->id];
373         }
374
375         return $this->currentUser()->roles->pluck('id')->values()->all();
376     }
377
378     /**
379      * Ensure the given action is a valid and expected entity action.
380      * Throws an exception if invalid otherwise does nothing.
381      * @throws InvalidArgumentException
382      */
383     protected function ensureValidEntityAction(string $action): void
384     {
385         if (!in_array($action, EntityPermission::PERMISSIONS)) {
386             throw new InvalidArgumentException('Action should be a simple entity permission action, not a role permission');
387         }
388     }
389 }