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