]> BookStack Code Mirror - bookstack/blob - app/Auth/Permissions/PermissionApplicator.php
Started more formal permission test case definitions
[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 InvalidArgumentException;
16
17 class PermissionApplicator
18 {
19     /**
20      * Checks if an entity has a restriction set upon it.
21      *
22      * @param HasCreatorAndUpdater|HasOwner $ownable
23      */
24     public function checkOwnableUserAccess(Model $ownable, string $permission): bool
25     {
26         $explodedPermission = explode('-', $permission);
27         $action = $explodedPermission[1] ?? $explodedPermission[0];
28         $fullPermission = count($explodedPermission) > 1 ? $permission : $ownable->getMorphClass() . '-' . $permission;
29
30         $user = $this->currentUser();
31         $userRoleIds = $this->getCurrentUserRoleIds();
32
33         $allRolePermission = $user->can($fullPermission . '-all');
34         $ownRolePermission = $user->can($fullPermission . '-own');
35         $nonJointPermissions = ['restrictions', 'image', 'attachment', 'comment'];
36         $ownerField = ($ownable instanceof Entity) ? 'owned_by' : 'created_by';
37         $ownableFieldVal = $ownable->getAttribute($ownerField);
38
39         if (is_null($ownableFieldVal)) {
40             throw new InvalidArgumentException("{$ownerField} field used but has not been loaded");
41         }
42
43         $isOwner = $user->id === $ownableFieldVal;
44         $hasRolePermission = $allRolePermission || ($isOwner && $ownRolePermission);
45
46         // Handle non entity specific jointPermissions
47         if (in_array($explodedPermission[0], $nonJointPermissions)) {
48             return $hasRolePermission;
49         }
50
51         $hasApplicableEntityPermissions = $this->hasEntityPermission($ownable, $userRoleIds, $user->id, $action);
52
53         return is_null($hasApplicableEntityPermissions) ? $hasRolePermission : $hasApplicableEntityPermissions;
54     }
55
56     /**
57      * Check if there are permissions that are applicable for the given entity item, action and roles.
58      * Returns null when no entity permissions are in force.
59      */
60     protected function hasEntityPermission(Entity $entity, array $userRoleIds, int $userId, string $action): ?bool
61     {
62         $this->ensureValidEntityAction($action);
63
64         $adminRoleId = Role::getSystemRole('admin')->id;
65         if (in_array($adminRoleId, $userRoleIds)) {
66             return true;
67         }
68
69         // The chain order here is very important due to the fact we walk up the chain
70         // in the loop below. Earlier items in the chain have higher priority.
71         $chain = [$entity];
72         if ($entity instanceof Page && $entity->chapter_id) {
73             $chain[] = $entity->chapter;
74         }
75
76         if ($entity instanceof Page || $entity instanceof Chapter) {
77             $chain[] = $entity->book;
78         }
79
80         // Record role access preventions.
81         // Used when we encounter a negative role permission where inheritance is active and therefore
82         // need to check permissive status on parent items.
83         $blockedRoleIds = [];
84
85         foreach ($chain as $currentEntity) {
86             $relevantPermissions = $currentEntity->permissions()
87                 ->where(function (Builder $query) use ($userRoleIds, $userId) {
88                     $query->whereIn('role_id', $userRoleIds)
89                     ->orWhere('user_id', '=', $userId)
90                     ->orWhere(function (Builder $query) {
91                         $query->whereNull(['role_id', 'user_id']);
92                     });
93                 })
94                 ->get(['role_id', 'user_id', $action])
95                 ->all();
96
97             // Permissions work on specificity, in order of:
98             // 1. User-specific permissions
99             // 2. Role-specific permissions
100             // 3. Fallback-specific permissions
101             // For role permissions, the system tries to be fairly permissive, in that if the user has two roles,
102             // one lacking and one permitting an action, they will be permitted.
103             // This can be complex when multiple roles and inheritance gets involved. If permission is prevented
104             // via "Role A" on an item, but inheritance is active and permission is granted via "Role B" on parent item,
105             // the user will be granted permission.
106
107             $allowedByTypeById = ['fallback' => [], 'user' => [], 'role' => []];
108             /** @var EntityPermission $permission */
109             foreach ($relevantPermissions as $permission) {
110                 $allowedByTypeById[$permission->getAssignedType()][$permission->getAssignedTypeId()] = boolval($permission->$action);
111             }
112
113             $inheriting = !isset($allowedByTypeById['fallback'][0]);
114
115             // Continue up the chain if no applicable entity permission overrides.
116             if (count($relevantPermissions) === 0) {
117                 continue;
118             }
119
120             // If we have user-specific permissions set, return the status of that
121             // since it's the most specific possible.
122             if (isset($allowedByTypeById['user'][$userId])) {
123                 return $allowedByTypeById['user'][$userId];
124             }
125
126             // If we have role-specific permissions set, allow if any of those
127             // role permissions allow access. We do not allow if the role has been previously
128             // blocked by a high-priority inheriting level.
129             // If we're inheriting at this level, and there's an explicit non-allow permission, we record
130             // it for checking up the chain.
131             foreach ($allowedByTypeById['role'] as $roleId => $allowed) {
132                 if ($allowed && !in_array($roleId, $blockedRoleIds)) {
133                     return true;
134                 } else if (!$allowed) {
135                     $blockedRoleIds[] = $roleId;
136                 }
137             }
138
139             // If we had role permissions, and none of them allowed (via above loop), and
140             // we are not inheriting, exit here since we only have role permissions in play blocking access.
141             if (count($allowedByTypeById['role']) > 0 && !$inheriting) {
142                 return false;
143             }
144
145             // Continue up the chain if inheriting
146             if ($inheriting) {
147                 continue;
148             }
149
150             // Otherwise, return the default "Other roles" fallback value.
151             return $allowedByTypeById['fallback'][0];
152         }
153
154         // If we have roles that need to be assessed, but we are also inheriting, pass back the prevented
155         // role IDs so they can be excluded from the role permission check.
156         if (count($blockedRoleIds) > 0) {
157             // TODO - Need to use these ids in some form in outer permission check, as blockers when access
158             return false;
159         }
160
161         return null;
162     }
163
164     /**
165      * Checks if a user has the given permission for any items in the system.
166      * Can be passed an entity instance to filter on a specific type.
167      */
168     public function checkUserHasEntityPermissionOnAny(string $action, string $entityClass = ''): bool
169     {
170         $this->ensureValidEntityAction($action);
171
172         $permissionQuery = EntityPermission::query()
173             ->where($action, '=', true)
174             ->where(function (Builder $query) {
175                 $query->whereIn('role_id', $this->getCurrentUserRoleIds())
176                 ->orWhere('user_id', '=', $this->currentUser()->id);
177             });
178
179         if (!empty($entityClass)) {
180             /** @var Entity $entityInstance */
181             $entityInstance = app()->make($entityClass);
182             $permissionQuery = $permissionQuery->where('entity_type', '=', $entityInstance->getMorphClass());
183         }
184
185         $hasPermission = $permissionQuery->count() > 0;
186
187         return $hasPermission;
188     }
189
190     /**
191      * Limit the given entity query so that the query will only
192      * return items that the user has view permission for.
193      */
194     public function restrictEntityQuery(Builder $query): Builder
195     {
196         return $query->where(function (Builder $parentQuery) {
197             $parentQuery->whereHas('jointPermissions', function (Builder $permissionQuery) {
198                 $permissionQuery->whereIn('role_id', $this->getCurrentUserRoleIds())
199                     ->where(function (Builder $query) {
200                         $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
201                     });
202             })->orWhereHas('jointUserPermissions', function (Builder $query) {
203                 $query->where('user_id', '=', $this->currentUser()->id)->where('has_permission', '=', true);
204             });
205         })->whereDoesntHave('jointUserPermissions', function (Builder $query) {
206             $query->where('user_id', '=', $this->currentUser()->id)->where('has_permission', '=', false);
207         });
208     }
209
210     /**
211      * Extend the given page query to ensure draft items are not visible
212      * unless created by the given user.
213      */
214     public function restrictDraftsOnPageQuery(Builder $query): Builder
215     {
216         return $query->where(function (Builder $query) {
217             $query->where('draft', '=', false)
218                 ->orWhere(function (Builder $query) {
219                     $query->where('draft', '=', true)
220                         ->where('owned_by', '=', $this->currentUser()->id);
221                 });
222         });
223     }
224
225     /**
226      * Filter items that have entities set as a polymorphic relation.
227      * For simplicity, this will not return results attached to draft pages.
228      * Draft pages should never really have related items though.
229      *
230      * @param Builder|QueryBuilder $query
231      */
232     public function restrictEntityRelationQuery($query, string $tableName, string $entityIdColumn, string $entityTypeColumn)
233     {
234         $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
235         $pageMorphClass = (new Page())->getMorphClass();
236
237         $q = $query->where(function ($query) use ($tableDetails) {
238             $query->whereExists(function ($permissionQuery) use ($tableDetails) {
239                 /** @var Builder $permissionQuery */
240                 $permissionQuery->select(['role_id'])->from('joint_permissions')
241                     ->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
242                     ->whereColumn('joint_permissions.entity_type', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
243                     ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoleIds())
244                     ->where(function (QueryBuilder $query) {
245                         $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
246                     });
247             })->orWhereExists(function ($permissionQuery) use ($tableDetails) {
248                 /** @var Builder $permissionQuery */
249                 $permissionQuery->select(['user_id'])->from('joint_user_permissions')
250                     ->whereColumn('joint_user_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
251                     ->whereColumn('joint_user_permissions.entity_type', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
252                     ->where('joint_user_permissions.user_id', '=', $this->currentUser()->id)
253                     ->where('joint_user_permissions.has_permission', '=', true);
254             });
255         })->whereNotExists(function ($query) use ($tableDetails) {
256             $query->select(['user_id'])->from('joint_user_permissions')
257                 ->whereColumn('joint_user_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
258                 ->whereColumn('joint_user_permissions.entity_type', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
259                 ->where('joint_user_permissions.user_id', '=', $this->currentUser()->id)
260                 ->where('joint_user_permissions.has_permission', '=', false);
261         })->where(function ($query) use ($tableDetails, $pageMorphClass) {
262             /** @var Builder $query */
263             $query->where($tableDetails['entityTypeColumn'], '!=', $pageMorphClass)
264                 ->orWhereExists(function (QueryBuilder $query) use ($tableDetails, $pageMorphClass) {
265                     $query->select('id')->from('pages')
266                         ->whereColumn('pages.id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
267                         ->where($tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'], '=', $pageMorphClass)
268                         ->where('pages.draft', '=', false);
269                 });
270         });
271
272         return $q;
273     }
274
275     /**
276      * Add conditions to a query for a model that's a relation of a page, so only the model results
277      * on visible pages are returned by the query.
278      * Is effectively the same as "restrictEntityRelationQuery" but takes into account page drafts
279      * while not expecting a polymorphic relation, Just a simpler one-page-to-many-relations set-up.
280      */
281     public function restrictPageRelationQuery(Builder $query, string $tableName, string $pageIdColumn): Builder
282     {
283         $fullPageIdColumn = $tableName . '.' . $pageIdColumn;
284         $morphClass = (new Page())->getMorphClass();
285
286         $existsQuery = function ($permissionQuery) use ($fullPageIdColumn, $morphClass) {
287             /** @var Builder $permissionQuery */
288             $permissionQuery->select('joint_permissions.role_id')->from('joint_permissions')
289                 ->whereColumn('joint_permissions.entity_id', '=', $fullPageIdColumn)
290                 ->where('joint_permissions.entity_type', '=', $morphClass)
291                 ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoleIds())
292                 ->where(function (QueryBuilder $query) {
293                     $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
294                 });
295         };
296
297         $userExistsQuery = function ($hasPermission) use ($fullPageIdColumn, $morphClass) {
298             return function ($permissionQuery) use ($fullPageIdColumn, $morphClass) {
299                 /** @var Builder $permissionQuery */
300                 $permissionQuery->select('joint_user_permissions.user_id')->from('joint_user_permissions')
301                     ->whereColumn('joint_user_permissions.entity_id', '=', $fullPageIdColumn)
302                     ->where('joint_user_permissions.entity_type', '=', $morphClass)
303                     ->where('joint_user_permissions.user_id', $this->currentUser()->id)
304                     ->where('has_permission', '=', true);
305             };
306         };
307
308         $q = $query->where(function ($query) use ($existsQuery, $userExistsQuery, $fullPageIdColumn) {
309             $query->whereExists($existsQuery)
310                 ->orWhereExists($userExistsQuery(true))
311                 ->orWhere($fullPageIdColumn, '=', 0);
312         })->whereNotExists($userExistsQuery(false));
313
314         // Prevent visibility of non-owned draft pages
315         $q->whereExists(function (QueryBuilder $query) use ($fullPageIdColumn) {
316             $query->select('id')->from('pages')
317                 ->whereColumn('pages.id', '=', $fullPageIdColumn)
318                 ->where(function (QueryBuilder $query) {
319                     $query->where('pages.draft', '=', false)
320                         ->orWhere('pages.owned_by', '=', $this->currentUser()->id);
321                 });
322         });
323
324         return $q;
325     }
326
327     /**
328      * Add the query for checking the given user id has permission
329      * within the join_permissions table.
330      *
331      * @param QueryBuilder|Builder $query
332      */
333     protected function addJointHasPermissionCheck($query, int $userIdToCheck)
334     {
335         $query->where('joint_permissions.has_permission', '=', true)->orWhere(function ($query) use ($userIdToCheck) {
336             $query->where('joint_permissions.has_permission_own', '=', true)
337                 ->where('joint_permissions.owned_by', '=', $userIdToCheck);
338         });
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 }