]> BookStack Code Mirror - bookstack/blob - app/Auth/Permissions/PermissionApplicator.php
Aligned admin permission check restriction ignore
[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, $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 $entityTypeLimiter, string $entityTypeColumn)
192     {
193         $abilities = ['all' => [], 'own' => []];
194         $types = $entityTypeLimiter ? [$entityTypeLimiter] : ['page', 'chapter', 'bookshelf', 'book'];
195         foreach ($types as $type) {
196             $abilities['all'][$type] = userCan($type . '-view-all');
197             $abilities['own'][$type] = userCan($type . '-view-own');
198         }
199
200         $abilities['all'] = array_filter($abilities['all']);
201         $abilities['own'] = array_filter($abilities['own']);
202
203         $query->where(function (Builder $query) use ($abilities, $entityTypeColumn) {
204             $query->where('perms_user', '=', 1)
205                 ->orWhere(function (Builder $query) {
206                     $query->whereNull('perms_user')->where('perms_role', '=', 1);
207                 })->orWhere(function (Builder $query) {
208                     $query->whereNull(['perms_user', 'perms_role'])
209                         ->where('perms_fallback', '=', 1);
210                 });
211
212             if (count($abilities['all']) > 0) {
213                 $query->orWhere(function (Builder $query) use ($abilities, $entityTypeColumn) {
214                     $query->whereNull(['perms_user', 'perms_role', 'perms_fallback']);
215                     if ($entityTypeColumn) {
216                         $query->whereIn($entityTypeColumn, array_keys($abilities['all']));
217                     }
218                 });
219             }
220
221             if (count($abilities['own']) > 0) {
222                 $query->orWhere(function (Builder $query) use ($abilities, $entityTypeColumn) {
223                     $query->whereNull(['perms_user', 'perms_role', 'perms_fallback'])
224                         ->where('owned_by', '=', $this->currentUser()->id);
225                     if ($entityTypeColumn) {
226                         $query->whereIn($entityTypeColumn, array_keys($abilities['all']));
227                     }
228                 });
229             }
230         });
231     }
232
233     /**
234      * @param Builder|QueryBuilder $query
235      */
236     protected function applyPermissionJoin(callable $joinCallable, string $subAlias, $query, string $queryTable, string $entityTypeLimiter, string $entityIdColumn, string $entityTypeColumn)
237     {
238         $joinCondition = $this->getJoinCondition($queryTable, $subAlias, $entityIdColumn, $entityTypeColumn);
239
240         $query->joinSub(function (QueryBuilder $joinQuery) use ($joinCallable, $entityTypeLimiter) {
241             $joinQuery->select(['entity_id', 'entity_type'])->from('entity_permissions_collapsed')
242                 ->groupBy('entity_id', 'entity_type');
243             $joinCallable($joinQuery);
244
245             if ($entityTypeLimiter) {
246                 $joinQuery->where('entity_type', '=', $entityTypeLimiter);
247             }
248         }, $subAlias, $joinCondition, null, null, 'left');
249     }
250
251     /**
252      * @param Builder|QueryBuilder $query
253      */
254     protected function applyUserJoin($query, string $queryTable, string $entityTypeLimiter, string $entityIdColumn, string $entityTypeColumn)
255     {
256         $this->applyPermissionJoin(function (QueryBuilder $joinQuery) {
257             $joinQuery->selectRaw('max(view) as perms_user')
258                 ->where('user_id', '=', $this->currentUser()->id);
259         }, 'p_u', $query, $queryTable, $entityTypeLimiter, $entityIdColumn, $entityTypeColumn);
260     }
261
262
263     /**
264      * @param Builder|QueryBuilder $query
265      */
266     protected function applyRoleJoin($query, string $queryTable, string $entityTypeLimiter, string $entityIdColumn, string $entityTypeColumn)
267     {
268         $this->applyPermissionJoin(function (QueryBuilder $joinQuery) {
269             $joinQuery->selectRaw('max(view) as perms_role')
270                 ->whereIn('role_id', $this->getCurrentUserRoleIds());
271         }, 'p_r', $query, $queryTable, $entityTypeLimiter, $entityIdColumn, $entityTypeColumn);
272     }
273
274     /**
275      * @param Builder|QueryBuilder $query
276      */
277     protected function applyFallbackJoin($query, string $queryTable, string $entityTypeLimiter, string $entityIdColumn, string $entityTypeColumn)
278     {
279         $this->applyPermissionJoin(function (QueryBuilder $joinQuery) {
280             $joinQuery->selectRaw('max(view) as perms_fallback')
281                 ->whereNull(['role_id', 'user_id']);
282         }, 'p_f', $query, $queryTable, $entityTypeLimiter, $entityIdColumn, $entityTypeColumn);
283     }
284
285     protected function getJoinCondition(string $queryTable, string $joinTableName, string $entityIdColumn, string $entityTypeColumn): callable
286     {
287         return function (JoinClause $join) use ($queryTable, $joinTableName, $entityIdColumn, $entityTypeColumn) {
288             $join->on($queryTable . '.' . $entityIdColumn, '=', $joinTableName . '.entity_id');
289             if ($entityTypeColumn) {
290                 $join->on($queryTable . '.' . $entityTypeColumn, '=', $joinTableName . '.entity_type');
291             }
292         };
293     }
294
295     /**
296      * Extend the given page query to ensure draft items are not visible
297      * unless created by the given user.
298      */
299     public function restrictDraftsOnPageQuery(Builder $query): Builder
300     {
301         return $query->where(function (Builder $query) {
302             $query->where('draft', '=', false)
303                 ->orWhere(function (Builder $query) {
304                     $query->where('draft', '=', true)
305                         ->where('owned_by', '=', $this->currentUser()->id);
306                 });
307         });
308     }
309
310     /**
311      * Filter items that have entities set as a polymorphic relation.
312      * For simplicity, this will not return results attached to draft pages.
313      * Draft pages should never really have related items though.
314      *
315      * @param Builder|QueryBuilder $query
316      */
317     public function restrictEntityRelationQuery($query, string $tableName, string $entityIdColumn, string $entityTypeColumn)
318     {
319         $this->applyPermissionsToQuery($query, $tableName, '', $entityIdColumn, $entityTypeColumn);
320         // TODO - Test page draft access (Might allow drafts which should not be seen)
321
322         return $query;
323     }
324
325     /**
326      * Add conditions to a query for a model that's a relation of a page, so only the model results
327      * on visible pages are returned by the query.
328      * Is effectively the same as "restrictEntityRelationQuery" but takes into account page drafts
329      * while not expecting a polymorphic relation, Just a simpler one-page-to-many-relations set-up.
330      */
331     public function restrictPageRelationQuery(Builder $query, string $tableName, string $pageIdColumn): Builder
332     {
333         $morphClass = (new Page())->getMorphClass();
334
335         $this->applyPermissionsToQuery($query, $tableName, $morphClass, $pageIdColumn, '');
336         // TODO - Draft display
337         return $query;
338     }
339
340     /**
341      * Get the current user.
342      */
343     protected function currentUser(): User
344     {
345         return user();
346     }
347
348     /**
349      * Get the roles for the current logged-in user.
350      *
351      * @return int[]
352      */
353     protected function getCurrentUserRoleIds(): array
354     {
355         if (auth()->guest()) {
356             return [Role::getSystemRole('public')->id];
357         }
358
359         return $this->currentUser()->roles->pluck('id')->values()->all();
360     }
361
362     /**
363      * Ensure the given action is a valid and expected entity action.
364      * Throws an exception if invalid otherwise does nothing.
365      * @throws InvalidArgumentException
366      */
367     protected function ensureValidEntityAction(string $action): void
368     {
369         if (!in_array($action, EntityPermission::PERMISSIONS)) {
370             throw new InvalidArgumentException('Action should be a simple entity permission action, not a role permission');
371         }
372     }
373 }