]> BookStack Code Mirror - bookstack/blob - app/Auth/Permissions/PermissionApplicator.php
58ee7d93a1db4a58ac3da711bb41b1672e61827a
[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             // See dev/docs/permission-scenario-testing.md for technical details
98             // on how permissions should be enforced.
99
100             $allowedByTypeById = ['fallback' => [], 'user' => [], 'role' => []];
101             /** @var EntityPermission $permission */
102             foreach ($relevantPermissions as $permission) {
103                 $allowedByTypeById[$permission->getAssignedType()][$permission->getAssignedTypeId()] = boolval($permission->$action);
104             }
105
106             $inheriting = !isset($allowedByTypeById['fallback'][0]);
107
108             // Continue up the chain if no applicable entity permission overrides.
109             if (count($relevantPermissions) === 0) {
110                 continue;
111             }
112
113             // If we have user-specific permissions set, return the status of that
114             // since it's the most specific possible.
115             if (isset($allowedByTypeById['user'][$userId])) {
116                 return $allowedByTypeById['user'][$userId];
117             }
118
119             // If we have role-specific permissions set, allow if any of those
120             // role permissions allow access. We do not allow if the role has been previously
121             // blocked by a high-priority inheriting level.
122             // If we're inheriting at this level, and there's an explicit non-allow permission, we record
123             // it for checking up the chain.
124             foreach ($allowedByTypeById['role'] as $roleId => $allowed) {
125                 if ($allowed && !in_array($roleId, $blockedRoleIds)) {
126                     return true;
127                 } else if (!$allowed) {
128                     $blockedRoleIds[] = $roleId;
129                 }
130             }
131
132             // If we had role permissions, and none of them allowed (via above loop), and
133             // we are not inheriting, exit here since we only have role permissions in play blocking access.
134             if (count($allowedByTypeById['role']) > 0 && !$inheriting) {
135                 return false;
136             }
137
138             // Continue up the chain if inheriting
139             if ($inheriting) {
140                 continue;
141             }
142
143             // Otherwise, return the default "Other roles" fallback value.
144             return $allowedByTypeById['fallback'][0];
145         }
146
147         // If we have relevant roles conditions that are actively blocking
148         // return false since these are more specific than potential role-level permissions.
149         if (count($blockedRoleIds) > 0) {
150             return false;
151         }
152
153         return null;
154     }
155
156     /**
157      * Checks if a user has the given permission for any items in the system.
158      * Can be passed an entity instance to filter on a specific type.
159      */
160     public function checkUserHasEntityPermissionOnAny(string $action, string $entityClass = ''): bool
161     {
162         $this->ensureValidEntityAction($action);
163
164         $permissionQuery = EntityPermission::query()
165             ->where($action, '=', true)
166             ->where(function (Builder $query) {
167                 $query->whereIn('role_id', $this->getCurrentUserRoleIds())
168                 ->orWhere('user_id', '=', $this->currentUser()->id);
169             });
170
171         if (!empty($entityClass)) {
172             /** @var Entity $entityInstance */
173             $entityInstance = app()->make($entityClass);
174             $permissionQuery = $permissionQuery->where('entity_type', '=', $entityInstance->getMorphClass());
175         }
176
177         $hasPermission = $permissionQuery->count() > 0;
178
179         return $hasPermission;
180     }
181
182     /**
183      * Limit the given entity query so that the query will only
184      * return items that the user has view permission for.
185      */
186     public function restrictEntityQuery(Builder $query): Builder
187     {
188         return $query->where(function (Builder $parentQuery) {
189             $parentQuery->whereHas('jointPermissions', function (Builder $permissionQuery) {
190                 $permissionQuery->whereIn('role_id', $this->getCurrentUserRoleIds())
191                     ->where(function (Builder $query) {
192                         $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
193                     });
194             })->orWhereHas('jointUserPermissions', function (Builder $query) {
195                 $query->where('user_id', '=', $this->currentUser()->id)->where('has_permission', '=', true);
196             });
197         })->whereDoesntHave('jointUserPermissions', function (Builder $query) {
198             $query->where('user_id', '=', $this->currentUser()->id)->where('has_permission', '=', false);
199         });
200     }
201
202     /**
203      * Extend the given page query to ensure draft items are not visible
204      * unless created by the given user.
205      */
206     public function restrictDraftsOnPageQuery(Builder $query): Builder
207     {
208         return $query->where(function (Builder $query) {
209             $query->where('draft', '=', false)
210                 ->orWhere(function (Builder $query) {
211                     $query->where('draft', '=', true)
212                         ->where('owned_by', '=', $this->currentUser()->id);
213                 });
214         });
215     }
216
217     /**
218      * Filter items that have entities set as a polymorphic relation.
219      * For simplicity, this will not return results attached to draft pages.
220      * Draft pages should never really have related items though.
221      *
222      * @param Builder|QueryBuilder $query
223      */
224     public function restrictEntityRelationQuery($query, string $tableName, string $entityIdColumn, string $entityTypeColumn)
225     {
226         $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
227         $pageMorphClass = (new Page())->getMorphClass();
228
229         $q = $query->where(function ($query) use ($tableDetails) {
230             $query->whereExists(function ($permissionQuery) use ($tableDetails) {
231                 /** @var Builder $permissionQuery */
232                 $permissionQuery->select(['role_id'])->from('joint_permissions')
233                     ->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
234                     ->whereColumn('joint_permissions.entity_type', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
235                     ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoleIds())
236                     ->where(function (QueryBuilder $query) {
237                         $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
238                     });
239             })->orWhereExists(function ($permissionQuery) use ($tableDetails) {
240                 /** @var Builder $permissionQuery */
241                 $permissionQuery->select(['user_id'])->from('joint_user_permissions')
242                     ->whereColumn('joint_user_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
243                     ->whereColumn('joint_user_permissions.entity_type', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
244                     ->where('joint_user_permissions.user_id', '=', $this->currentUser()->id)
245                     ->where('joint_user_permissions.has_permission', '=', true);
246             });
247         })->whereNotExists(function ($query) use ($tableDetails) {
248             $query->select(['user_id'])->from('joint_user_permissions')
249                 ->whereColumn('joint_user_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
250                 ->whereColumn('joint_user_permissions.entity_type', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
251                 ->where('joint_user_permissions.user_id', '=', $this->currentUser()->id)
252                 ->where('joint_user_permissions.has_permission', '=', false);
253         })->where(function ($query) use ($tableDetails, $pageMorphClass) {
254             /** @var Builder $query */
255             $query->where($tableDetails['entityTypeColumn'], '!=', $pageMorphClass)
256                 ->orWhereExists(function (QueryBuilder $query) use ($tableDetails, $pageMorphClass) {
257                     $query->select('id')->from('pages')
258                         ->whereColumn('pages.id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
259                         ->where($tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'], '=', $pageMorphClass)
260                         ->where('pages.draft', '=', false);
261                 });
262         });
263
264         return $q;
265     }
266
267     /**
268      * Add conditions to a query for a model that's a relation of a page, so only the model results
269      * on visible pages are returned by the query.
270      * Is effectively the same as "restrictEntityRelationQuery" but takes into account page drafts
271      * while not expecting a polymorphic relation, Just a simpler one-page-to-many-relations set-up.
272      */
273     public function restrictPageRelationQuery(Builder $query, string $tableName, string $pageIdColumn): Builder
274     {
275         $fullPageIdColumn = $tableName . '.' . $pageIdColumn;
276         $morphClass = (new Page())->getMorphClass();
277
278         $existsQuery = function ($permissionQuery) use ($fullPageIdColumn, $morphClass) {
279             /** @var Builder $permissionQuery */
280             $permissionQuery->select('joint_permissions.role_id')->from('joint_permissions')
281                 ->whereColumn('joint_permissions.entity_id', '=', $fullPageIdColumn)
282                 ->where('joint_permissions.entity_type', '=', $morphClass)
283                 ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoleIds())
284                 ->where(function (QueryBuilder $query) {
285                     $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
286                 });
287         };
288
289         $userExistsQuery = function ($hasPermission) use ($fullPageIdColumn, $morphClass) {
290             return function ($permissionQuery) use ($fullPageIdColumn, $morphClass) {
291                 /** @var Builder $permissionQuery */
292                 $permissionQuery->select('joint_user_permissions.user_id')->from('joint_user_permissions')
293                     ->whereColumn('joint_user_permissions.entity_id', '=', $fullPageIdColumn)
294                     ->where('joint_user_permissions.entity_type', '=', $morphClass)
295                     ->where('joint_user_permissions.user_id', $this->currentUser()->id)
296                     ->where('has_permission', '=', true);
297             };
298         };
299
300         $q = $query->where(function ($query) use ($existsQuery, $userExistsQuery, $fullPageIdColumn) {
301             $query->whereExists($existsQuery)
302                 ->orWhereExists($userExistsQuery(true))
303                 ->orWhere($fullPageIdColumn, '=', 0);
304         })->whereNotExists($userExistsQuery(false));
305
306         // Prevent visibility of non-owned draft pages
307         $q->whereExists(function (QueryBuilder $query) use ($fullPageIdColumn) {
308             $query->select('id')->from('pages')
309                 ->whereColumn('pages.id', '=', $fullPageIdColumn)
310                 ->where(function (QueryBuilder $query) {
311                     $query->where('pages.draft', '=', false)
312                         ->orWhere('pages.owned_by', '=', $this->currentUser()->id);
313                 });
314         });
315
316         return $q;
317     }
318
319     /**
320      * Add the query for checking the given user id has permission
321      * within the join_permissions table.
322      *
323      * @param QueryBuilder|Builder $query
324      */
325     protected function addJointHasPermissionCheck($query, int $userIdToCheck)
326     {
327         $query->where('joint_permissions.has_permission', '=', true)->orWhere(function ($query) use ($userIdToCheck) {
328             $query->where('joint_permissions.has_permission_own', '=', true)
329                 ->where('joint_permissions.owned_by', '=', $userIdToCheck);
330         });
331     }
332
333     /**
334      * Get the current user.
335      */
336     protected function currentUser(): User
337     {
338         return user();
339     }
340
341     /**
342      * Get the roles for the current logged-in user.
343      *
344      * @return int[]
345      */
346     protected function getCurrentUserRoleIds(): array
347     {
348         if (auth()->guest()) {
349             return [Role::getSystemRole('public')->id];
350         }
351
352         return $this->currentUser()->roles->pluck('id')->values()->all();
353     }
354
355     /**
356      * Ensure the given action is a valid and expected entity action.
357      * Throws an exception if invalid otherwise does nothing.
358      * @throws InvalidArgumentException
359      */
360     protected function ensureValidEntityAction(string $action): void
361     {
362         if (!in_array($action, EntityPermission::PERMISSIONS)) {
363             throw new InvalidArgumentException('Action should be a simple entity permission action, not a role permission');
364         }
365     }
366 }