]> BookStack Code Mirror - bookstack/blob - tests/SharedTestHelpers.php
Extracted permission building out of permission service
[bookstack] / tests / SharedTestHelpers.php
1 <?php
2
3 namespace Tests;
4
5 use BookStack\Auth\Permissions\JointPermissionBuilder;
6 use BookStack\Auth\Permissions\PermissionService;
7 use BookStack\Auth\Permissions\PermissionsRepo;
8 use BookStack\Auth\Permissions\RolePermission;
9 use BookStack\Auth\Role;
10 use BookStack\Auth\User;
11 use BookStack\Entities\Models\Book;
12 use BookStack\Entities\Models\Bookshelf;
13 use BookStack\Entities\Models\Chapter;
14 use BookStack\Entities\Models\Entity;
15 use BookStack\Entities\Models\Page;
16 use BookStack\Entities\Repos\BookRepo;
17 use BookStack\Entities\Repos\BookshelfRepo;
18 use BookStack\Entities\Repos\ChapterRepo;
19 use BookStack\Entities\Repos\PageRepo;
20 use BookStack\Settings\SettingService;
21 use BookStack\Uploads\HttpFetcher;
22 use GuzzleHttp\Client;
23 use GuzzleHttp\Handler\MockHandler;
24 use GuzzleHttp\HandlerStack;
25 use GuzzleHttp\Middleware;
26 use Illuminate\Http\JsonResponse;
27 use Illuminate\Support\Env;
28 use Illuminate\Support\Facades\Log;
29 use Illuminate\Testing\Assert as PHPUnit;
30 use Mockery;
31 use Monolog\Handler\TestHandler;
32 use Monolog\Logger;
33 use Psr\Http\Client\ClientInterface;
34
35 trait SharedTestHelpers
36 {
37     protected $admin;
38     protected $editor;
39
40     /**
41      * Set the current user context to be an admin.
42      */
43     public function asAdmin()
44     {
45         return $this->actingAs($this->getAdmin());
46     }
47
48     /**
49      * Get the current admin user.
50      */
51     public function getAdmin(): User
52     {
53         if (is_null($this->admin)) {
54             $adminRole = Role::getSystemRole('admin');
55             $this->admin = $adminRole->users->first();
56         }
57
58         return $this->admin;
59     }
60
61     /**
62      * Set the current user context to be an editor.
63      */
64     public function asEditor()
65     {
66         return $this->actingAs($this->getEditor());
67     }
68
69     /**
70      * Get a editor user.
71      */
72     protected function getEditor(): User
73     {
74         if ($this->editor === null) {
75             $editorRole = Role::getRole('editor');
76             $this->editor = $editorRole->users->first();
77         }
78
79         return $this->editor;
80     }
81
82     /**
83      * Get an instance of a user with 'viewer' permissions.
84      */
85     protected function getViewer(array $attributes = []): User
86     {
87         $user = Role::getRole('viewer')->users()->first();
88         if (!empty($attributes)) {
89             $user->forceFill($attributes)->save();
90         }
91
92         return $user;
93     }
94
95     /**
96      * Get a user that's not a system user such as the guest user.
97      */
98     public function getNormalUser(): User
99     {
100         return User::query()->where('system_name', '=', null)->get()->last();
101     }
102
103     /**
104      * Regenerate the permission for an entity.
105      */
106     protected function regenEntityPermissions(Entity $entity): void
107     {
108         $entity->rebuildPermissions();
109         $entity->load('jointPermissions');
110     }
111
112     /**
113      * Create and return a new bookshelf.
114      */
115     public function newShelf(array $input = ['name' => 'test shelf', 'description' => 'My new test shelf']): Bookshelf
116     {
117         return app(BookshelfRepo::class)->create($input, []);
118     }
119
120     /**
121      * Create and return a new book.
122      */
123     public function newBook(array $input = ['name' => 'test book', 'description' => 'My new test book']): Book
124     {
125         return app(BookRepo::class)->create($input);
126     }
127
128     /**
129      * Create and return a new test chapter.
130      */
131     public function newChapter(array $input, Book $book): Chapter
132     {
133         return app(ChapterRepo::class)->create($input, $book);
134     }
135
136     /**
137      * Create and return a new test page.
138      */
139     public function newPage(array $input = ['name' => 'test page', 'html' => 'My new test page']): Page
140     {
141         $book = Book::query()->first();
142         $pageRepo = app(PageRepo::class);
143         $draftPage = $pageRepo->getNewDraftPage($book);
144
145         return $pageRepo->publishDraft($draftPage, $input);
146     }
147
148     /**
149      * Quickly sets an array of settings.
150      */
151     protected function setSettings(array $settingsArray): void
152     {
153         $settings = app(SettingService::class);
154         foreach ($settingsArray as $key => $value) {
155             $settings->put($key, $value);
156         }
157     }
158
159     /**
160      * Manually set some permissions on an entity.
161      */
162     protected function setEntityRestrictions(Entity $entity, array $actions = [], array $roles = []): void
163     {
164         $entity->restricted = true;
165         $entity->permissions()->delete();
166
167         $permissions = [];
168         foreach ($actions as $action) {
169             foreach ($roles as $role) {
170                 $permissions[] = [
171                     'role_id' => $role->id,
172                     'action'  => strtolower($action),
173                 ];
174             }
175         }
176         $entity->permissions()->createMany($permissions);
177
178         $entity->save();
179         $entity->load('permissions');
180         $this->app->make(JointPermissionBuilder::class)->buildJointPermissionsForEntity($entity);
181         $entity->load('jointPermissions');
182     }
183
184     /**
185      * Give the given user some permissions.
186      */
187     protected function giveUserPermissions(User $user, array $permissions = []): void
188     {
189         $newRole = $this->createNewRole($permissions);
190         $user->attachRole($newRole);
191         $user->load('roles');
192         $user->clearPermissionCache();
193     }
194
195     /**
196      * Completely remove the given permission name from the given user.
197      */
198     protected function removePermissionFromUser(User $user, string $permissionName)
199     {
200         $permissionBuilder = app()->make(JointPermissionBuilder::class);
201
202         /** @var RolePermission $permission */
203         $permission = RolePermission::query()->where('name', '=', $permissionName)->firstOrFail();
204
205         $roles = $user->roles()->whereHas('permissions', function ($query) use ($permission) {
206             $query->where('id', '=', $permission->id);
207         })->get();
208
209         /** @var Role $role */
210         foreach ($roles as $role) {
211             $role->detachPermission($permission);
212             $permissionBuilder->buildJointPermissionForRole($role);
213         }
214
215         $user->clearPermissionCache();
216     }
217
218     /**
219      * Create a new basic role for testing purposes.
220      */
221     protected function createNewRole(array $permissions = []): Role
222     {
223         $permissionRepo = app(PermissionsRepo::class);
224         $roleData = Role::factory()->make()->toArray();
225         $roleData['permissions'] = array_flip($permissions);
226
227         return $permissionRepo->saveNewRole($roleData);
228     }
229
230     /**
231      * Create a group of entities that belong to a specific user.
232      *
233      * @return array{book: Book, chapter: Chapter, page: Page}
234      */
235     protected function createEntityChainBelongingToUser(User $creatorUser, ?User $updaterUser = null): array
236     {
237         if (empty($updaterUser)) {
238             $updaterUser = $creatorUser;
239         }
240
241         $userAttrs = ['created_by' => $creatorUser->id, 'owned_by' => $creatorUser->id, 'updated_by' => $updaterUser->id];
242         $book = Book::factory()->create($userAttrs);
243         $chapter = Chapter::factory()->create(array_merge(['book_id' => $book->id], $userAttrs));
244         $page = Page::factory()->create(array_merge(['book_id' => $book->id, 'chapter_id' => $chapter->id], $userAttrs));
245
246         $this->app->make(JointPermissionBuilder::class)->buildJointPermissionsForEntity($book);
247
248         return compact('book', 'chapter', 'page');
249     }
250
251     /**
252      * Mock the HttpFetcher service and return the given data on fetch.
253      */
254     protected function mockHttpFetch($returnData, int $times = 1)
255     {
256         $mockHttp = Mockery::mock(HttpFetcher::class);
257         $this->app[HttpFetcher::class] = $mockHttp;
258         $mockHttp->shouldReceive('fetch')
259             ->times($times)
260             ->andReturn($returnData);
261     }
262
263     /**
264      * Mock the http client used in BookStack.
265      * Returns a reference to the container which holds all history of http transactions.
266      *
267      * @link https://docs.guzzlephp.org/en/stable/testing.html#history-middleware
268      */
269     protected function &mockHttpClient(array $responses = []): array
270     {
271         $container = [];
272         $history = Middleware::history($container);
273         $mock = new MockHandler($responses);
274         $handlerStack = new HandlerStack($mock);
275         $handlerStack->push($history);
276         $this->app[ClientInterface::class] = new Client(['handler' => $handlerStack]);
277
278         return $container;
279     }
280
281     /**
282      * Run a set test with the given env variable.
283      * Remembers the original and resets the value after test.
284      */
285     protected function runWithEnv(string $name, $value, callable $callback)
286     {
287         Env::disablePutenv();
288         $originalVal = $_SERVER[$name] ?? null;
289
290         if (is_null($value)) {
291             unset($_SERVER[$name]);
292         } else {
293             $_SERVER[$name] = $value;
294         }
295
296         $this->refreshApplication();
297         $callback();
298
299         if (is_null($originalVal)) {
300             unset($_SERVER[$name]);
301         } else {
302             $_SERVER[$name] = $originalVal;
303         }
304     }
305
306     /**
307      * Check the keys and properties in the given map to include
308      * exist, albeit not exclusively, within the map to check.
309      */
310     protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
311     {
312         $passed = true;
313
314         foreach ($mapToInclude as $key => $value) {
315             if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
316                 $passed = false;
317             }
318         }
319
320         $toIncludeStr = print_r($mapToInclude, true);
321         $toCheckStr = print_r($mapToCheck, true);
322         self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
323     }
324
325     /**
326      * Assert a permission error has occurred.
327      */
328     protected function assertPermissionError($response)
329     {
330         PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
331     }
332
333     /**
334      * Assert a permission error has occurred.
335      */
336     protected function assertNotPermissionError($response)
337     {
338         PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
339     }
340
341     /**
342      * Check if the given response is a permission error.
343      */
344     private function isPermissionError($response): bool
345     {
346         return $response->status() === 302
347             && (
348                 (
349                     $response->headers->get('Location') === url('/')
350                     && strpos(session()->pull('error', ''), 'You do not have permission to access') === 0
351                 )
352                 ||
353                 (
354                     $response instanceof JsonResponse &&
355                     $response->json(['error' => 'You do not have permission to perform the requested action.'])
356                 )
357             );
358     }
359
360     /**
361      * Assert that the session has a particular error notification message set.
362      */
363     protected function assertSessionError(string $message)
364     {
365         $error = session()->get('error');
366         PHPUnit::assertTrue($error === $message, "Failed asserting the session contains an error. \nFound: {$error}\nExpecting: {$message}");
367     }
368
369     /**
370      * Set a test handler as the logging interface for the application.
371      * Allows capture of logs for checking against during tests.
372      */
373     protected function withTestLogger(): TestHandler
374     {
375         $monolog = new Logger('testing');
376         $testHandler = new TestHandler();
377         $monolog->pushHandler($testHandler);
378
379         Log::extend('testing', function () use ($monolog) {
380             return $monolog;
381         });
382         Log::setDefaultDriver('testing');
383
384         return $testHandler;
385     }
386 }