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