repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Entity/BookTest.php
tests/Entity/BookTest.php
<?php namespace Tests\Entity; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\BookChild; use BookStack\Entities\Models\Bookshelf; use BookStack\Entities\Repos\BookRepo; use Tests\TestCase; class BookTest extends TestCase { public function test_create() { $book = Book::factory()->make([ 'name' => 'My First Book', ]); $resp = $this->asEditor()->get('/books'); $this->withHtml($resp)->assertElementContains('a[href="' . url('/create-book') . '"]', 'Create New Book'); $resp = $this->get('/create-book'); $this->withHtml($resp)->assertElementContains('form[action="' . url('/books') . '"][method="POST"]', 'Save Book'); $resp = $this->post('/books', $book->only('name', 'description_html')); $resp->assertRedirect('/books/my-first-book'); $resp = $this->get('/books/my-first-book'); $resp->assertSee($book->name); $resp->assertSee($book->descriptionInfo()->getPlain()); } public function test_create_uses_different_slugs_when_name_reused() { $book = Book::factory()->make([ 'name' => 'My First Book', ]); $this->asEditor()->post('/books', $book->only('name', 'description_html')); $this->asEditor()->post('/books', $book->only('name', 'description_html')); $books = Book::query()->where('name', '=', $book->name) ->orderBy('id', 'desc') ->take(2) ->get(); $this->assertMatchesRegularExpression('/my-first-book-[0-9a-zA-Z]{3}/', $books[0]->slug); $this->assertEquals('my-first-book', $books[1]->slug); } public function test_create_sets_tags() { // Cheeky initial update to refresh slug $this->asEditor()->post('books', [ 'name' => 'My book with tags', 'description_html' => '<p>A book with tags</p>', 'tags' => [ [ 'name' => 'Category', 'value' => 'Donkey Content', ], [ 'name' => 'Level', 'value' => '5', ], ], ]); /** @var Book $book */ $book = Book::query()->where('name', '=', 'My book with tags')->firstOrFail(); $tags = $book->tags()->get(); $this->assertEquals(2, $tags->count()); $this->assertEquals('Donkey Content', $tags[0]->value); $this->assertEquals('Level', $tags[1]->name); } public function test_update() { $book = $this->entities->book(); // Cheeky initial update to refresh slug $this->asEditor()->put($book->getUrl(), ['name' => $book->name . '5', 'description_html' => $book->description_html]); $book->refresh(); $newName = $book->name . ' Updated'; $newDesc = $book->description_html . '<p>with more content</p>'; $resp = $this->get($book->getUrl('/edit')); $resp->assertSee($book->name); $resp->assertSee($book->description_html); $this->withHtml($resp)->assertElementContains('form[action="' . $book->getUrl() . '"]', 'Save Book'); $resp = $this->put($book->getUrl(), ['name' => $newName, 'description_html' => $newDesc]); $resp->assertRedirect($book->getUrl() . '-updated'); $resp = $this->get($book->getUrl() . '-updated'); $resp->assertSee($newName); $resp->assertSee($newDesc, false); } public function test_update_sets_tags() { $book = $this->entities->book(); $this->assertEquals(0, $book->tags()->count()); // Cheeky initial update to refresh slug $this->asEditor()->put($book->getUrl(), [ 'name' => $book->name, 'tags' => [ [ 'name' => 'Category', 'value' => 'Dolphin Content', ], [ 'name' => 'Level', 'value' => '5', ], ], ]); $book->refresh(); $tags = $book->tags()->get(); $this->assertEquals(2, $tags->count()); $this->assertEquals('Dolphin Content', $tags[0]->value); $this->assertEquals('Level', $tags[1]->name); } public function test_delete() { $book = Book::query()->whereHas('pages')->whereHas('chapters')->first(); $this->assertNull($book->deleted_at); $pageCount = $book->pages()->count(); $chapterCount = $book->chapters()->count(); $deleteViewReq = $this->asEditor()->get($book->getUrl('/delete')); $deleteViewReq->assertSeeText('Are you sure you want to delete this book?'); $deleteReq = $this->delete($book->getUrl()); $deleteReq->assertRedirect(url('/books')); $this->assertActivityExists('book_delete', $book); $book->refresh(); $this->assertNotNull($book->deleted_at); $this->assertTrue($book->pages()->count() === 0); $this->assertTrue($book->chapters()->count() === 0); $this->assertTrue($book->pages()->withTrashed()->count() === $pageCount); $this->assertTrue($book->chapters()->withTrashed()->count() === $chapterCount); $this->assertTrue($book->deletions()->count() === 1); $redirectReq = $this->get($deleteReq->baseResponse->headers->get('location')); $this->assertNotificationContains($redirectReq, 'Book Successfully Deleted'); } public function test_cancel_on_create_page_leads_back_to_books_listing() { $resp = $this->asEditor()->get('/create-book'); $this->withHtml($resp)->assertElementContains('form a[href="' . url('/books') . '"]', 'Cancel'); } public function test_cancel_on_edit_book_page_leads_back_to_book() { $book = $this->entities->book(); $resp = $this->asEditor()->get($book->getUrl('/edit')); $this->withHtml($resp)->assertElementContains('form a[href="' . $book->getUrl() . '"]', 'Cancel'); } public function test_next_previous_navigation_controls_show_within_book_content() { $book = $this->entities->book(); $chapter = $book->chapters->first(); $resp = $this->asEditor()->get($chapter->getUrl()); $this->withHtml($resp)->assertElementContains('#sibling-navigation', 'Next'); $this->withHtml($resp)->assertElementContains('#sibling-navigation', substr($chapter->pages[0]->name, 0, 20)); $resp = $this->get($chapter->pages[0]->getUrl()); $this->withHtml($resp)->assertElementContains('#sibling-navigation', substr($chapter->pages[1]->name, 0, 20)); $this->withHtml($resp)->assertElementContains('#sibling-navigation', 'Previous'); $this->withHtml($resp)->assertElementContains('#sibling-navigation', substr($chapter->name, 0, 20)); } public function test_recently_viewed_books_updates_as_expected() { $books = Book::take(2)->get(); $resp = $this->asAdmin()->get('/books'); $this->withHtml($resp)->assertElementNotContains('#recents', $books[0]->name) ->assertElementNotContains('#recents', $books[1]->name); $this->get($books[0]->getUrl()); $this->get($books[1]->getUrl()); $resp = $this->get('/books'); $this->withHtml($resp)->assertElementContains('#recents', $books[0]->name) ->assertElementContains('#recents', $books[1]->name); } public function test_popular_books_updates_upon_visits() { $books = Book::take(2)->get(); $resp = $this->asAdmin()->get('/books'); $this->withHtml($resp)->assertElementNotContains('#popular', $books[0]->name) ->assertElementNotContains('#popular', $books[1]->name); $this->get($books[0]->getUrl()); $this->get($books[1]->getUrl()); $this->get($books[0]->getUrl()); $resp = $this->get('/books'); $this->withHtml($resp)->assertElementContains('#popular .book:nth-child(1)', $books[0]->name) ->assertElementContains('#popular .book:nth-child(2)', $books[1]->name); } public function test_books_view_shows_view_toggle_option() { /** @var Book $book */ $editor = $this->users->editor(); setting()->putUser($editor, 'books_view_type', 'list'); $resp = $this->actingAs($editor)->get('/books'); $this->withHtml($resp)->assertElementContains('form[action$="/preferences/change-view/books"]', 'Grid View'); $this->withHtml($resp)->assertElementExists('button[name="view"][value="grid"]'); $resp = $this->patch("/preferences/change-view/books", ['view' => 'grid']); $resp->assertRedirect(); $this->assertEquals('grid', setting()->getUser($editor, 'books_view_type')); $resp = $this->actingAs($editor)->get('/books'); $this->withHtml($resp)->assertElementContains('form[action$="/preferences/change-view/books"]', 'List View'); $this->withHtml($resp)->assertElementExists('button[name="view"][value="list"]'); $resp = $this->patch("/preferences/change-view/books", ['view_type' => 'list']); $resp->assertRedirect(); $this->assertEquals('list', setting()->getUser($editor, 'books_view_type')); } public function test_description_limited_to_specific_html() { $book = $this->entities->book(); $input = '<h1>Test</h1><p id="abc" href="beans">Content<a href="#cat" target="_blank" data-a="b">a</a><section>Hello</section></p>'; $expected = '<p>Content<a href="#cat" target="_blank">a</a></p>'; $this->asEditor()->put($book->getUrl(), [ 'name' => $book->name, 'description_html' => $input ]); $book->refresh(); $this->assertEquals($expected, $book->description_html); } public function test_show_view_displays_description_if_no_description_html_set() { $book = $this->entities->book(); $book->description_html = ''; $book->description = "My great\ndescription\n\nwith newlines"; $book->save(); $resp = $this->asEditor()->get($book->getUrl()); $resp->assertSee("<p>My great<br>\ndescription<br>\n<br>\nwith newlines</p>", false); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Entity/ConvertTest.php
tests/Entity/ConvertTest.php
<?php namespace Tests\Entity; use BookStack\Activity\ActivityType; use BookStack\Activity\Models\Tag; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Bookshelf; use BookStack\Entities\Models\Chapter; use BookStack\Entities\Models\Page; use Tests\TestCase; class ConvertTest extends TestCase { public function test_chapter_edit_view_shows_convert_option() { $chapter = $this->entities->chapter(); $resp = $this->asEditor()->get($chapter->getUrl('/edit')); $resp->assertSee('Convert to Book'); $resp->assertSee('Convert Chapter'); $this->withHtml($resp)->assertElementExists('form[action$="/convert-to-book"] button'); } public function test_convert_chapter_to_book() { $chapter = $this->entities->chapterHasPages(); $chapter->tags()->save(new Tag(['name' => 'Category', 'value' => 'Penguins'])); /** @var Page $childPage */ $childPage = $chapter->pages()->first(); $resp = $this->asEditor()->post($chapter->getUrl('/convert-to-book')); $resp->assertRedirectContains('/books/'); /** @var Book $newBook */ $newBook = Book::query()->orderBy('id', 'desc')->first(); $this->assertDatabaseMissing('entities', ['id' => $chapter->id, 'type' => 'chapter']); $this->assertDatabaseHasEntityData('page', ['id' => $childPage->id, 'book_id' => $newBook->id, 'chapter_id' => 0]); $this->assertCount(1, $newBook->tags); $this->assertEquals('Category', $newBook->tags->first()->name); $this->assertEquals('Penguins', $newBook->tags->first()->value); $this->assertEquals($chapter->name, $newBook->name); $this->assertEquals($chapter->description, $newBook->description); $this->assertEquals($chapter->description_html, $newBook->description_html); $this->assertActivityExists(ActivityType::BOOK_CREATE_FROM_CHAPTER, $newBook); } public function test_convert_chapter_to_book_requires_permissions() { $chapter = $this->entities->chapter(); $user = $this->users->viewer(); $permissions = ['chapter-delete-all', 'book-create-all', 'chapter-update-all']; $this->permissions->grantUserRolePermissions($user, $permissions); foreach ($permissions as $permission) { $this->permissions->removeUserRolePermissions($user, [$permission]); $resp = $this->actingAs($user)->post($chapter->getUrl('/convert-to-book')); $this->assertPermissionError($resp); $this->permissions->grantUserRolePermissions($user, [$permission]); } $resp = $this->actingAs($user)->post($chapter->getUrl('/convert-to-book')); $this->assertNotPermissionError($resp); $resp->assertRedirect(); } public function test_book_edit_view_shows_convert_option() { $book = $this->entities->book(); $resp = $this->asEditor()->get($book->getUrl('/edit')); $resp->assertSee('Convert to Shelf'); $resp->assertSee('Convert Book'); $resp->assertSee('Note that permissions on shelves do not auto-cascade to content'); $this->withHtml($resp)->assertElementExists('form[action$="/convert-to-shelf"] button'); } public function test_book_convert_to_shelf() { /** @var Book $book */ $book = Book::query()->whereHas('directPages')->whereHas('chapters')->firstOrFail(); $book->tags()->save(new Tag(['name' => 'Category', 'value' => 'Ducks'])); /** @var Page $childPage */ $childPage = $book->directPages()->first(); /** @var Chapter $childChapter */ $childChapter = $book->chapters()->whereHas('pages')->firstOrFail(); /** @var Page $chapterChildPage */ $chapterChildPage = $childChapter->pages()->firstOrFail(); $bookChapterCount = $book->chapters()->count(); $systemBookCount = Book::query()->count(); // Run conversion $resp = $this->asEditor()->post($book->getUrl('/convert-to-shelf')); /** @var Bookshelf $newShelf */ $newShelf = Bookshelf::query()->orderBy('id', 'desc')->first(); // Checks for new shelf $resp->assertRedirectContains('/shelves/'); $this->assertDatabaseMissing('entities', ['id' => $childChapter->id, 'type' => 'chapter']); $this->assertCount(1, $newShelf->tags); $this->assertEquals('Category', $newShelf->tags->first()->name); $this->assertEquals('Ducks', $newShelf->tags->first()->value); $this->assertEquals($book->name, $newShelf->name); $this->assertEquals($book->description, $newShelf->description); $this->assertEquals($book->description_html, $newShelf->description_html); $this->assertEquals($newShelf->books()->count(), $bookChapterCount + 1); $this->assertEquals($systemBookCount + $bookChapterCount, Book::query()->count()); $this->assertActivityExists(ActivityType::BOOKSHELF_CREATE_FROM_BOOK, $newShelf); // Checks for old book to contain child pages $this->assertDatabaseHasEntityData('book', ['id' => $book->id, 'name' => $book->name . ' Pages']); $this->assertDatabaseHasEntityData('page', ['id' => $childPage->id, 'book_id' => $book->id, 'chapter_id' => null]); // Checks for nested page $chapterChildPage->refresh(); $this->assertEquals(0, $chapterChildPage->chapter_id); $this->assertEquals($childChapter->name, $chapterChildPage->book->name); } public function test_book_convert_to_shelf_requires_permissions() { $book = $this->entities->book(); $user = $this->users->viewer(); $permissions = ['book-delete-all', 'bookshelf-create-all', 'book-update-all', 'book-create-all']; $this->permissions->grantUserRolePermissions($user, $permissions); foreach ($permissions as $permission) { $this->permissions->removeUserRolePermissions($user, [$permission]); $resp = $this->actingAs($user)->post($book->getUrl('/convert-to-shelf')); $this->assertPermissionError($resp); $this->permissions->grantUserRolePermissions($user, [$permission]); } $resp = $this->actingAs($user)->post($book->getUrl('/convert-to-shelf')); $this->assertNotPermissionError($resp); $resp->assertRedirect(); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Entity/MarkdownToHtmlTest.php
tests/Entity/MarkdownToHtmlTest.php
<?php namespace Tests\Entity; use BookStack\Entities\Tools\Markdown\HtmlToMarkdown; use Tests\TestCase; class MarkdownToHtmlTest extends TestCase { public function test_basic_formatting_conversion() { $this->assertConversion( '<h1>Dogcat</h1><p>Some <strong>bold</strong> text</p>', "# Dogcat\n\nSome **bold** text" ); } public function test_callouts_remain_html() { $this->assertConversion( '<h1>Dogcat</h1><p class="callout info">Some callout text</p><p>Another line</p>', "# Dogcat\n\n<p class=\"callout info\">Some callout text</p>\n\nAnother line" ); } public function test_wysiwyg_code_format_handled_cleanly() { $this->assertConversion( '<h1>Dogcat</h1>' . "\r\n" . '<pre id="bkmrk-var-a-%3D-%27cat%27%3B"><code class="language-JavaScript">var a = \'cat\';</code></pre><p>Another line</p>', "# Dogcat\n\n```JavaScript\nvar a = 'cat';\n```\n\nAnother line" ); } public function test_tasklist_checkboxes_are_handled() { $this->assertConversion( '<ul><li><input type="checkbox" checked="checked">Item A</li><li><input type="checkbox">Item B</li></ul>', "- [x] Item A\n- [ ] Item B" ); } public function test_drawing_blocks_remain_html() { $this->assertConversion( '<div drawio-diagram="190" id="bkmrk--0" contenteditable="false"><img src="http://example.com/uploads/images/drawio/2022-04/drawing-1.png" alt="" /></div>Some text', '<div drawio-diagram="190"><img src="http://example.com/uploads/images/drawio/2022-04/drawing-1.png" alt=""/></div>' . "\n\nSome text" ); } public function test_summary_tags_have_newlines_after_to_separate_content() { $this->assertConversion( '<details><summary>Toggle</summary><p>Test</p></details>', "<details><summary>Toggle</summary>\n\nTest\n\n</details>" ); } public function test_iframes_tags_have_newlines_after_to_separate_content() { $this->assertConversion( '<iframe src="https://example.com"></iframe><p>Beans</p>', "<iframe src=\"https://example.com\"></iframe>\n\nBeans" ); } protected function assertConversion(string $html, string $expectedMarkdown, bool $partialMdMatch = false) { $markdown = (new HtmlToMarkdown($html))->convert(); if ($partialMdMatch) { static::assertStringContainsString($expectedMarkdown, $markdown); } else { static::assertEquals($expectedMarkdown, $markdown); } } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Entity/EntityAccessTest.php
tests/Entity/EntityAccessTest.php
<?php namespace Tests\Entity; use BookStack\Entities\Models\Entity; use BookStack\Users\UserRepo; use Tests\TestCase; class EntityAccessTest extends TestCase { public function test_entities_viewable_after_creator_deletion() { // Create required assets and revisions $creator = $this->users->editor(); $updater = $this->users->viewer(); $entities = $this->entities->createChainBelongingToUser($creator, $updater); app()->make(UserRepo::class)->destroy($creator); $this->entities->updatePage($entities['page'], ['html' => '<p>hello!</p>>']); $this->checkEntitiesViewable($entities); } public function test_entities_viewable_after_updater_deletion() { // Create required assets and revisions $creator = $this->users->viewer(); $updater = $this->users->editor(); $entities = $this->entities->createChainBelongingToUser($creator, $updater); app()->make(UserRepo::class)->destroy($updater); $this->entities->updatePage($entities['page'], ['html' => '<p>Hello there!</p>']); $this->checkEntitiesViewable($entities); } /** * @param array<string, Entity> $entities */ private function checkEntitiesViewable(array $entities) { // Check pages and books are visible. $this->asAdmin(); foreach ($entities as $entity) { $this->get($entity->getUrl()) ->assertStatus(200) ->assertSee($entity->name); } // Check revision listing shows no errors. $this->get($entities['page']->getUrl('/revisions'))->assertStatus(200); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Entity/PageContentTest.php
tests/Entity/PageContentTest.php
<?php namespace Tests\Entity; use BookStack\Entities\Models\Page; use BookStack\Entities\Tools\PageContent; use Tests\TestCase; class PageContentTest extends TestCase { protected string $base64Jpeg = '/9j/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/yQALCAABAAEBAREA/8wABgAQEAX/2gAIAQEAAD8A0s8g/9k='; public function test_page_includes() { $page = $this->entities->page(); $secondPage = $this->entities->page(); $secondPage->html = "<p id='section1'>Hello, This is a test</p><p id='section2'>This is a second block of content</p>"; $secondPage->save(); $this->asEditor(); $pageContent = $this->get($page->getUrl()); $pageContent->assertDontSee('Hello, This is a test'); $originalHtml = $page->html; $page->html .= "{{@{$secondPage->id}}}"; $page->save(); $pageContent = $this->get($page->getUrl()); $pageContent->assertSee('Hello, This is a test'); $pageContent->assertSee('This is a second block of content'); $page->html = $originalHtml . " Well {{@{$secondPage->id}#section2}}"; $page->save(); $pageContent = $this->get($page->getUrl()); $pageContent->assertDontSee('Hello, This is a test'); $pageContent->assertSee('Well This is a second block of content'); } public function test_saving_page_with_includes() { $page = $this->entities->page(); $secondPage = $this->entities->page(); $this->asEditor(); $includeTag = '{{@' . $secondPage->id . '}}'; $page->html = '<p>' . $includeTag . '</p>'; $resp = $this->put($page->getUrl(), ['name' => $page->name, 'html' => $page->html, 'summary' => '']); $resp->assertStatus(302); $page = Page::find($page->id); $this->assertStringContainsString($includeTag, $page->html); $this->assertEquals('', $page->text); } public function test_page_includes_rendered_on_book_export() { $page = $this->entities->page(); $secondPage = Page::query() ->where('book_id', '!=', $page->book_id) ->first(); $content = '<p id="bkmrk-meow">my cat is awesome and scratchy</p>'; $secondPage->html = $content; $secondPage->save(); $page->html = "{{@{$secondPage->id}#bkmrk-meow}}"; $page->save(); $this->asEditor(); $htmlContent = $this->get($page->book->getUrl('/export/html')); $htmlContent->assertSee('my cat is awesome and scratchy'); } public function test_page_includes_can_be_nested_up_to_three_times() { $page = $this->entities->page(); $tag = "{{@{$page->id}#bkmrk-test}}"; $page->html = '<p id="bkmrk-test">Hello Barry ' . $tag . '</p>'; $page->save(); $pageResp = $this->asEditor()->get($page->getUrl()); $this->withHtml($pageResp)->assertElementContains('#bkmrk-test', 'Hello Barry Hello Barry Hello Barry Hello Barry ' . $tag); $this->withHtml($pageResp)->assertElementNotContains('#bkmrk-test', 'Hello Barry Hello Barry Hello Barry Hello Barry Hello Barry ' . $tag); } public function test_page_includes_to_nonexisting_pages_does_not_error() { $page = $this->entities->page(); $missingId = Page::query()->max('id') + 1; $tag = "{{@{$missingId}}}"; $page->html = '<p id="bkmrk-test">Hello Barry ' . $tag . '</p>'; $page->save(); $pageResp = $this->asEditor()->get($page->getUrl()); $pageResp->assertOk(); $pageResp->assertSee('Hello Barry'); } public function test_page_content_scripts_removed_by_default() { $this->asEditor(); $page = $this->entities->page(); $script = 'abc123<script>console.log("hello-test")</script>abc123'; $page->html = "escape {$script}"; $page->save(); $pageView = $this->get($page->getUrl()); $pageView->assertStatus(200); $pageView->assertDontSee($script, false); $pageView->assertSee('abc123abc123'); } public function test_more_complex_content_script_escaping_scenarios() { $checks = [ "<p>Some script</p><script>alert('cat')</script>", "<div><div><div><div><p>Some script</p><script>alert('cat')</script></div></div></div></div>", "<p>Some script<script>alert('cat')</script></p>", "<p>Some script <div><script>alert('cat')</script></div></p>", "<p>Some script <script><div>alert('cat')</script></div></p>", "<p>Some script <script><div>alert('cat')</script><script><div>alert('cat')</script></p><script><div>alert('cat')</script>", ]; $this->asEditor(); $page = $this->entities->page(); foreach ($checks as $check) { $page->html = $check; $page->save(); $pageView = $this->get($page->getUrl()); $pageView->assertStatus(200); $this->withHtml($pageView)->assertElementNotContains('.page-content', '<script>'); $this->withHtml($pageView)->assertElementNotContains('.page-content', '</script>'); } } public function test_js_and_base64_src_urls_are_removed() { $checks = [ '<iframe src="javascript:alert(document.cookie)"></iframe>', '<iframe src="JavAScRipT:alert(document.cookie)"></iframe>', '<iframe src="JavAScRipT:alert(document.cookie)"></iframe>', '<iframe SRC=" javascript: alert(document.cookie)"></iframe>', '<iframe src="data:text/html;base64,PHNjcmlwdD5hbGVydCgnaGVsbG8nKTwvc2NyaXB0Pg==" frameborder="0"></iframe>', '<iframe src="DaTa:text/html;base64,PHNjcmlwdD5hbGVydCgnaGVsbG8nKTwvc2NyaXB0Pg==" frameborder="0"></iframe>', '<iframe src=" data:text/html;base64,PHNjcmlwdD5hbGVydCgnaGVsbG8nKTwvc2NyaXB0Pg==" frameborder="0"></iframe>', '<img src="javascript:alert(document.cookie)"/>', '<img src="JavAScRipT:alert(document.cookie)"/>', '<img src="JavAScRipT:alert(document.cookie)"/>', '<img SRC=" javascript: alert(document.cookie)"/>', '<img src="data:text/html;base64,PHNjcmlwdD5hbGVydCgnaGVsbG8nKTwvc2NyaXB0Pg=="/>', '<img src="DaTa:text/html;base64,PHNjcmlwdD5hbGVydCgnaGVsbG8nKTwvc2NyaXB0Pg=="/>', '<img src=" data:text/html;base64,PHNjcmlwdD5hbGVydCgnaGVsbG8nKTwvc2NyaXB0Pg=="/>', '<iframe srcdoc="<script>window.alert(document.cookie)</script>"></iframe>', '<iframe SRCdoc="<script>window.alert(document.cookie)</script>"></iframe>', '<IMG SRC=`javascript:alert("RSnake says, \'XSS\'")`>', ]; $this->asEditor(); $page = $this->entities->page(); foreach ($checks as $check) { $page->html = $check; $page->save(); $pageView = $this->get($page->getUrl()); $pageView->assertStatus(200); $html = $this->withHtml($pageView); $html->assertElementNotContains('.page-content', '<iframe>'); $html->assertElementNotContains('.page-content', '<img'); $html->assertElementNotContains('.page-content', '</iframe>'); $html->assertElementNotContains('.page-content', 'src='); $html->assertElementNotContains('.page-content', 'javascript:'); $html->assertElementNotContains('.page-content', 'data:'); $html->assertElementNotContains('.page-content', 'base64'); } } public function test_javascript_uri_links_are_removed() { $checks = [ '<a id="xss" href="javascript:alert(document.cookie)>Click me</a>', '<a id="xss" href="javascript: alert(document.cookie)>Click me</a>', '<a id="xss" href="JaVaScRiPt: alert(document.cookie)>Click me</a>', '<a id="xss" href=" JaVaScRiPt: alert(document.cookie)>Click me</a>', ]; $this->asEditor(); $page = $this->entities->page(); foreach ($checks as $check) { $page->html = $check; $page->save(); $pageView = $this->get($page->getUrl()); $pageView->assertStatus(200); $this->withHtml($pageView)->assertElementNotContains('.page-content', '<a id="xss"'); $this->withHtml($pageView)->assertElementNotContains('.page-content', 'href=javascript:'); } } public function test_form_actions_with_javascript_are_removed() { $checks = [ '<form><input id="xss" type=submit formaction=javascript:alert(document.domain) value=Submit><input></form>', '<form ><button id="xss" formaction="JaVaScRiPt:alert(document.domain)">Click me</button></form>', '<form ><button id="xss" formaction=javascript:alert(document.domain)>Click me</button></form>', '<form id="xss" action=javascript:alert(document.domain)><input type=submit value=Submit></form>', '<form id="xss" action="JaVaScRiPt:alert(document.domain)"><input type=submit value=Submit></form>', ]; $this->asEditor(); $page = $this->entities->page(); foreach ($checks as $check) { $page->html = $check; $page->save(); $pageView = $this->get($page->getUrl()); $pageView->assertStatus(200); $this->withHtml($pageView)->assertElementNotContains('.page-content', '<button id="xss"'); $this->withHtml($pageView)->assertElementNotContains('.page-content', '<input id="xss"'); $this->withHtml($pageView)->assertElementNotContains('.page-content', '<form id="xss"'); $this->withHtml($pageView)->assertElementNotContains('.page-content', 'action=javascript:'); $this->withHtml($pageView)->assertElementNotContains('.page-content', 'formaction=javascript:'); } } public function test_metadata_redirects_are_removed() { $checks = [ '<meta http-equiv="refresh" content="0; url=//external_url">', '<meta http-equiv="refresh" ConTeNt="0; url=//external_url">', '<meta http-equiv="refresh" content="0; UrL=//external_url">', ]; $this->asEditor(); $page = $this->entities->page(); foreach ($checks as $check) { $page->html = $check; $page->save(); $pageView = $this->get($page->getUrl()); $pageView->assertStatus(200); $this->withHtml($pageView)->assertElementNotContains('.page-content', '<meta>'); $this->withHtml($pageView)->assertElementNotContains('.page-content', '</meta>'); $this->withHtml($pageView)->assertElementNotContains('.page-content', 'content='); $this->withHtml($pageView)->assertElementNotContains('.page-content', 'external_url'); } } public function test_page_inline_on_attributes_removed_by_default() { $this->asEditor(); $page = $this->entities->page(); $script = '<p onmouseenter="console.log(\'test\')">Hello</p>'; $page->html = "escape {$script}"; $page->save(); $pageView = $this->get($page->getUrl()); $pageView->assertStatus(200); $pageView->assertDontSee($script, false); $pageView->assertSee('<p>Hello</p>', false); } public function test_more_complex_inline_on_attributes_escaping_scenarios() { $checks = [ '<p onclick="console.log(\'test\')">Hello</p>', '<p OnCliCk="console.log(\'test\')">Hello</p>', '<div>Lorem ipsum dolor sit amet.</div><p onclick="console.log(\'test\')">Hello</p>', '<div>Lorem ipsum dolor sit amet.<p onclick="console.log(\'test\')">Hello</p></div>', '<div><div><div><div>Lorem ipsum dolor sit amet.<p onclick="console.log(\'test\')">Hello</p></div></div></div></div>', '<div onclick="console.log(\'test\')">Lorem ipsum dolor sit amet.</div><p onclick="console.log(\'test\')">Hello</p><div></div>', '<a a="<img src=1 onerror=\'alert(1)\'> ', '\<a onclick="alert(document.cookie)"\>xss link\</a\>', ]; $this->asEditor(); $page = $this->entities->page(); foreach ($checks as $check) { $page->html = $check; $page->save(); $pageView = $this->get($page->getUrl()); $pageView->assertStatus(200); $this->withHtml($pageView)->assertElementNotContains('.page-content', 'onclick'); } } public function test_page_content_scripts_show_when_configured() { $this->asEditor(); $page = $this->entities->page(); config()->set('app.allow_content_scripts', 'true'); $script = 'abc123<script>console.log("hello-test")</script>abc123'; $page->html = "no escape {$script}"; $page->save(); $pageView = $this->get($page->getUrl()); $pageView->assertSee($script, false); $pageView->assertDontSee('abc123abc123'); } public function test_svg_script_usage_is_removed() { $checks = [ '<svg id="test" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="100"><a xlink:href="javascript:alert(document.domain)"><rect x="0" y="0" width="100" height="100" /></a></svg>', '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><use xlink:href="data:application/xml;base64 ,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIj4KPGRlZnM+CjxjaXJjbGUgaWQ9InRlc3QiIHI9IjAiIGN4PSIwIiBjeT0iMCIgc3R5bGU9ImZpbGw6ICNGMDAiPgo8c2V0IGF0dHJpYnV0ZU5hbWU9ImZpbGwiIGF0dHJpYnV0ZVR5cGU9IkNTUyIgb25iZWdpbj0nYWxlcnQoZG9jdW1lbnQuZG9tYWluKScKb25lbmQ9J2FsZXJ0KCJvbmVuZCIpJyB0bz0iIzAwRiIgYmVnaW49IjBzIiBkdXI9Ijk5OXMiIC8+CjwvY2lyY2xlPgo8L2RlZnM+Cjx1c2UgeGxpbms6aHJlZj0iI3Rlc3QiLz4KPC9zdmc+#test"/></svg>', '<svg><animate href=#xss attributeName=href values=javascript:alert(1) /></svg>', '<svg><animate href="#xss" attributeName="href" values="a;javascript:alert(1)" /></svg>', '<svg><animate href="#xss" attributeName="href" values="a;data:alert(1)" /></svg>', '<svg><animate href=#xss attributeName=href from=javascript:alert(1) to=1 /><a id=xss><text x=20 y=20>XSS</text></a>', '<svg><set href=#xss attributeName=href from=? to=javascript:alert(1) /><a id=xss><text x=20 y=20>XSS</text></a>', '<svg><g><g><g><animate href=#xss attributeName=href values=javascript:alert(1) /></g></g></g></svg>', ]; $this->asEditor(); $page = $this->entities->page(); foreach ($checks as $check) { $page->html = $check; $page->save(); $pageView = $this->get($page->getUrl()); $pageView->assertStatus(200); $html = $this->withHtml($pageView); $html->assertElementNotContains('.page-content', 'alert'); $html->assertElementNotContains('.page-content', 'xlink:href'); $html->assertElementNotContains('.page-content', 'application/xml'); $html->assertElementNotContains('.page-content', 'javascript'); } } public function test_page_inline_on_attributes_show_if_configured() { $this->asEditor(); $page = $this->entities->page(); config()->set('app.allow_content_scripts', 'true'); $script = '<p onmouseenter="console.log(\'test\')">Hello</p>'; $page->html = "escape {$script}"; $page->save(); $pageView = $this->get($page->getUrl()); $pageView->assertSee($script, false); $pageView->assertDontSee('<p>Hello</p>', false); } public function test_duplicate_ids_does_not_break_page_render() { $this->asEditor(); $pageA = Page::query()->first(); $pageB = Page::query()->where('id', '!=', $pageA->id)->first(); $content = '<ul id="bkmrk-xxx-%28"></ul> <ul id="bkmrk-xxx-%28"></ul>'; $pageA->html = $content; $pageA->save(); $pageB->html = '<ul id="bkmrk-xxx-%28"></ul> <p>{{@' . $pageA->id . '#test}}</p>'; $pageB->save(); $pageView = $this->get($pageB->getUrl()); $pageView->assertSuccessful(); } public function test_duplicate_ids_fixed_on_page_save() { $this->asEditor(); $page = $this->entities->page(); $content = '<ul id="bkmrk-test"><li>test a</li><li><ul id="bkmrk-test"><li>test b</li></ul></li></ul>'; $pageSave = $this->put($page->getUrl(), [ 'name' => $page->name, 'html' => $content, 'summary' => '', ]); $pageSave->assertRedirect(); $updatedPage = Page::query()->where('id', '=', $page->id)->first(); $this->assertEquals(substr_count($updatedPage->html, 'bkmrk-test"'), 1); } public function test_anchors_referencing_non_bkmrk_ids_rewritten_after_save() { $this->asEditor(); $page = $this->entities->page(); $content = '<h1 id="non-standard-id">test</h1><p><a href="#non-standard-id">link</a></p>'; $this->put($page->getUrl(), [ 'name' => $page->name, 'html' => $content, 'summary' => '', ]); $updatedPage = Page::query()->where('id', '=', $page->id)->first(); $this->assertStringContainsString('id="bkmrk-test"', $updatedPage->html); $this->assertStringContainsString('href="#bkmrk-test"', $updatedPage->html); } public function test_get_page_nav_sets_correct_properties() { $content = '<h1 id="testa">Hello</h1><h2 id="testb">There</h2><h3 id="testc">Donkey</h3>'; $pageContent = new PageContent(new Page(['html' => $content])); $navMap = $pageContent->getNavigation($content); $this->assertCount(3, $navMap); $this->assertArrayMapIncludes([ 'nodeName' => 'h1', 'link' => '#testa', 'text' => 'Hello', 'level' => 1, ], $navMap[0]); $this->assertArrayMapIncludes([ 'nodeName' => 'h2', 'link' => '#testb', 'text' => 'There', 'level' => 2, ], $navMap[1]); $this->assertArrayMapIncludes([ 'nodeName' => 'h3', 'link' => '#testc', 'text' => 'Donkey', 'level' => 3, ], $navMap[2]); } public function test_get_page_nav_does_not_show_empty_titles() { $content = '<h1 id="testa">Hello</h1><h2 id="testb">&nbsp;</h2><h3 id="testc"></h3>'; $pageContent = new PageContent(new Page(['html' => $content])); $navMap = $pageContent->getNavigation($content); $this->assertCount(1, $navMap); $this->assertArrayMapIncludes([ 'nodeName' => 'h1', 'link' => '#testa', 'text' => 'Hello', ], $navMap[0]); } public function test_get_page_nav_shifts_headers_if_only_smaller_ones_are_used() { $content = '<h4 id="testa">Hello</h4><h5 id="testb">There</h5><h6 id="testc">Donkey</h6>'; $pageContent = new PageContent(new Page(['html' => $content])); $navMap = $pageContent->getNavigation($content); $this->assertCount(3, $navMap); $this->assertArrayMapIncludes([ 'nodeName' => 'h4', 'level' => 1, ], $navMap[0]); $this->assertArrayMapIncludes([ 'nodeName' => 'h5', 'level' => 2, ], $navMap[1]); $this->assertArrayMapIncludes([ 'nodeName' => 'h6', 'level' => 3, ], $navMap[2]); } public function test_get_page_nav_respects_non_breaking_spaces() { $content = '<h1 id="testa">Hello&nbsp;There</h1>'; $pageContent = new PageContent(new Page(['html' => $content])); $navMap = $pageContent->getNavigation($content); $this->assertEquals([ 'nodeName' => 'h1', 'link' => '#testa', 'text' => 'Hello There', 'level' => 1, ], $navMap[0]); } public function test_page_text_decodes_html_entities() { $page = $this->entities->page(); $this->actingAs($this->users->admin()) ->put($page->getUrl(''), [ 'name' => 'Testing', 'html' => '<p>&quot;Hello &amp; welcome&quot;</p>', ]); $page->refresh(); $this->assertEquals('"Hello & welcome"', $page->text); } public function test_page_markdown_table_rendering() { $this->asEditor(); $page = $this->entities->page(); $content = '| Syntax | Description | | ----------- | ----------- | | Header | Title | | Paragraph | Text |'; $this->put($page->getUrl(), [ 'name' => $page->name, 'markdown' => $content, 'html' => '', 'summary' => '', ]); $page->refresh(); $this->assertStringContainsString('</tbody>', $page->html); $pageView = $this->get($page->getUrl()); $this->withHtml($pageView)->assertElementExists('.page-content table tbody td'); } public function test_page_markdown_task_list_rendering() { $this->asEditor(); $page = $this->entities->page(); $content = '- [ ] Item a - [x] Item b'; $this->put($page->getUrl(), [ 'name' => $page->name, 'markdown' => $content, 'html' => '', 'summary' => '', ]); $page->refresh(); $this->assertStringContainsString('input', $page->html); $this->assertStringContainsString('type="checkbox"', $page->html); $pageView = $this->get($page->getUrl()); $this->withHtml($pageView)->assertElementExists('.page-content li.task-list-item input[type=checkbox]'); $this->withHtml($pageView)->assertElementExists('.page-content li.task-list-item input[type=checkbox][checked]'); } public function test_page_markdown_strikethrough_rendering() { $this->asEditor(); $page = $this->entities->page(); $content = '~~some crossed out text~~'; $this->put($page->getUrl(), [ 'name' => $page->name, 'markdown' => $content, 'html' => '', 'summary' => '', ]); $page->refresh(); $this->assertStringMatchesFormat('%A<s%A>some crossed out text</s>%A', $page->html); $pageView = $this->get($page->getUrl()); $this->withHtml($pageView)->assertElementExists('.page-content p > s'); } public function test_page_markdown_single_html_comment_saving() { $this->asEditor(); $page = $this->entities->page(); $content = '<!-- Test Comment -->'; $this->put($page->getUrl(), [ 'name' => $page->name, 'markdown' => $content, 'html' => '', 'summary' => '', ]); $page->refresh(); $this->assertStringMatchesFormat($content, $page->html); $pageView = $this->get($page->getUrl()); $pageView->assertStatus(200); $pageView->assertSee($content, false); } public function test_base64_images_get_extracted_from_page_content() { $this->asEditor(); $page = $this->entities->page(); $this->put($page->getUrl(), [ 'name' => $page->name, 'summary' => '', 'html' => '<p>test<img src="data:image/jpeg;base64,' . $this->base64Jpeg . '"/></p>', ]); $page->refresh(); $this->assertStringMatchesFormat('%A<p%A>test<img src="http://localhost/uploads/images/gallery/%A.jpeg">%A</p>%A', $page->html); $matches = []; preg_match('/src="http:\/\/localhost(.*?)"/', $page->html, $matches); $imagePath = $matches[1]; $imageFile = public_path($imagePath); $this->assertEquals(base64_decode($this->base64Jpeg), file_get_contents($imageFile)); $this->files->deleteAtRelativePath($imagePath); } public function test_base64_images_get_extracted_when_containing_whitespace() { $this->asEditor(); $page = $this->entities->page(); $base64PngWithWhitespace = "iVBORw0KGg\noAAAANSUhE\tUgAAAAEAAAA BCA YAAAAfFcSJAAA\n\t ACklEQVR4nGMAAQAABQAB"; $base64PngWithoutWhitespace = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQAB'; $this->put($page->getUrl(), [ 'name' => $page->name, 'summary' => '', 'html' => '<p>test<img src="data:image/png;base64,' . $base64PngWithWhitespace . '"/></p>', ]); $page->refresh(); $this->assertStringMatchesFormat('%A<p%A>test<img src="http://localhost/uploads/images/gallery/%A.png">%A</p>%A', $page->html); $matches = []; preg_match('/src="http:\/\/localhost(.*?)"/', $page->html, $matches); $imagePath = $matches[1]; $imageFile = public_path($imagePath); $this->assertEquals(base64_decode($base64PngWithoutWhitespace), file_get_contents($imageFile)); $this->files->deleteAtRelativePath($imagePath); } public function test_base64_images_within_html_blanked_if_not_supported_extension_for_extract() { // Relevant to https://github.com/BookStackApp/BookStack/issues/3010 and other cases $extensions = [ 'jiff', 'pngr', 'png ', ' png', '.png', 'png.', 'p.ng', ',png', 'data:image/png', ',data:image/png', ]; foreach ($extensions as $extension) { $this->asEditor(); $page = $this->entities->page(); $this->put($page->getUrl(), [ 'name' => $page->name, 'summary' => '', 'html' => '<p>test<img src="data:image/' . $extension . ';base64,' . $this->base64Jpeg . '"/></p>', ]); $page->refresh(); $this->assertStringContainsString('<img src=""', $page->html); } } public function test_base64_images_within_html_blanked_if_no_image_create_permission() { $editor = $this->users->editor(); $page = $this->entities->page(); $this->permissions->removeUserRolePermissions($editor, ['image-create-all']); $this->actingAs($editor)->put($page->getUrl(), [ 'name' => $page->name, 'html' => '<p>test<img src="data:image/jpeg;base64,' . $this->base64Jpeg . '"/></p>', ]); $page->refresh(); $this->assertStringMatchesFormat('%A<p%A>test<img src="">%A</p>%A', $page->html); } public function test_base64_images_within_html_blanked_if_content_does_not_appear_like_an_image() { $page = $this->entities->page(); $imgContent = base64_encode('file://test/a/b/c'); $this->asEditor()->put($page->getUrl(), [ 'name' => $page->name, 'html' => '<p>test<img src="data:image/jpeg;base64,' . $imgContent . '"/></p>', ]); $page->refresh(); $this->assertStringMatchesFormat('%A<p%A>test<img src="">%A</p>%A', $page->html); } public function test_base64_images_get_extracted_from_markdown_page_content() { $this->asEditor(); $page = $this->entities->page(); $this->put($page->getUrl(), [ 'name' => $page->name, 'summary' => '', 'markdown' => 'test ![test](data:image/jpeg;base64,' . $this->base64Jpeg . ')', ]); $page->refresh(); $this->assertStringMatchesFormat('%A<p%A>test <img src="http://localhost/uploads/images/gallery/%A.jpeg" alt="test">%A</p>%A', $page->html); $matches = []; preg_match('/src="http:\/\/localhost(.*?)"/', $page->html, $matches); $imagePath = $matches[1]; $imageFile = public_path($imagePath); $this->assertEquals(base64_decode($this->base64Jpeg), file_get_contents($imageFile)); $this->files->deleteAtRelativePath($imagePath); } public function test_markdown_base64_extract_not_limited_by_pcre_limits() { $pcreBacktrackLimit = ini_get('pcre.backtrack_limit'); $pcreRecursionLimit = ini_get('pcre.recursion_limit'); $this->asEditor(); $page = $this->entities->page(); ini_set('pcre.backtrack_limit', '500'); ini_set('pcre.recursion_limit', '500'); $content = str_repeat(base64_decode($this->base64Jpeg), 50); $base64Content = base64_encode($content); $this->put($page->getUrl(), [ 'name' => $page->name, 'summary' => '', 'markdown' => 'test ![test](data:image/jpeg;base64,' . $base64Content . ') ![test](data:image/jpeg;base64,' . $base64Content . ')', ]); $page->refresh(); $this->assertStringMatchesFormat('<p%A>test <img src="http://localhost/uploads/images/gallery/%A.jpeg" alt="test"> <img src="http://localhost/uploads/images/gallery/%A.jpeg" alt="test">%A</p>%A', $page->html); $matches = []; preg_match('/src="http:\/\/localhost(.*?)"/', $page->html, $matches); $imagePath = $matches[1]; $imageFile = public_path($imagePath); $this->assertEquals($content, file_get_contents($imageFile)); $this->files->deleteAtRelativePath($imagePath); ini_set('pcre.backtrack_limit', $pcreBacktrackLimit); ini_set('pcre.recursion_limit', $pcreRecursionLimit); } public function test_base64_images_within_markdown_blanked_if_not_supported_extension_for_extract() { $page = $this->entities->page(); $this->asEditor()->put($page->getUrl(), [ 'name' => $page->name, 'summary' => '', 'markdown' => 'test ![test](data:image/jiff;base64,' . $this->base64Jpeg . ')', ]); $this->assertStringContainsString('<img src=""', $page->refresh()->html); } public function test_base64_images_within_markdown_blanked_if_no_image_create_permission() { $editor = $this->users->editor(); $page = $this->entities->page(); $this->permissions->removeUserRolePermissions($editor, ['image-create-all']); $this->actingAs($editor)->put($page->getUrl(), [ 'name' => $page->name, 'markdown' => 'test ![test](data:image/jpeg;base64,' . $this->base64Jpeg . ')', ]); $this->assertStringContainsString('<img src=""', $page->refresh()->html); } public function test_base64_images_within_markdown_blanked_if_content_does_not_appear_like_an_image() { $page = $this->entities->page(); $imgContent = base64_encode('file://test/a/b/c'); $this->asEditor()->put($page->getUrl(), [ 'name' => $page->name, 'markdown' => 'test ![test](data:image/jpeg;base64,' . $imgContent . ')', ]); $page->refresh(); $this->assertStringContainsString('<img src=""', $page->refresh()->html); } public function test_nested_headers_gets_assigned_an_id() { $page = $this->entities->page(); $content = '<table><tbody><tr><td><h5>Simple Test</h5></td></tr></tbody></table>'; $this->asEditor()->put($page->getUrl(), [ 'name' => $page->name, 'html' => $content, ]); // The top level <table> node will get assign the bkmrk-simple-test id because the system will // take the node value of h5 // So the h5 should get the bkmrk-simple-test-1 id $this->assertStringContainsString('<h5 id="bkmrk-simple-test-1">Simple Test</h5>', $page->refresh()->html); } public function test_non_breaking_spaces_are_preserved() { $page = $this->entities->page(); $content = '<p>&nbsp;</p>'; $this->asEditor()->put($page->getUrl(), [ 'name' => $page->name, 'html' => $content, ]); $this->assertStringContainsString('<p id="bkmrk-%C2%A0">&nbsp;</p>', $page->refresh()->html); } public function test_page_save_with_many_headers_and_links_is_reasonable() { $page = $this->entities->page(); $content = ''; for ($i = 0; $i < 500; $i++) { $content .= "<table><tbody><tr><td><h5 id='header-{$i}'>Simple Test</h5><a href='#header-{$i}'></a></td></tr></tbody></table>"; } $time = time(); $this->asEditor()->put($page->getUrl(), [ 'name' => $page->name, 'html' => $content, ])->assertRedirect();
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
true
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Entity/BookShelfTest.php
tests/Entity/BookShelfTest.php
<?php namespace Tests\Entity; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Bookshelf; use BookStack\Uploads\Image; use BookStack\Users\Models\User; use Illuminate\Support\Str; use Tests\TestCase; class BookShelfTest extends TestCase { public function test_shelves_shows_in_header_if_have_view_permissions() { $viewer = $this->users->viewer(); $resp = $this->actingAs($viewer)->get('/'); $this->withHtml($resp)->assertElementContains('header', 'Shelves'); $viewer->roles()->delete(); $this->permissions->grantUserRolePermissions($viewer, []); $resp = $this->actingAs($viewer)->get('/'); $this->withHtml($resp)->assertElementNotContains('header', 'Shelves'); $this->permissions->grantUserRolePermissions($viewer, ['bookshelf-view-all']); $resp = $this->actingAs($viewer)->get('/'); $this->withHtml($resp)->assertElementContains('header', 'Shelves'); $viewer->roles()->delete(); $this->permissions->grantUserRolePermissions($viewer, ['bookshelf-view-own']); $resp = $this->actingAs($viewer)->get('/'); $this->withHtml($resp)->assertElementContains('header', 'Shelves'); } public function test_shelves_shows_in_header_if_have_any_shelve_view_permission() { $user = User::factory()->create(); $this->permissions->grantUserRolePermissions($user, ['image-create-all']); $shelf = $this->entities->shelf(); $userRole = $user->roles()->first(); $resp = $this->actingAs($user)->get('/'); $this->withHtml($resp)->assertElementNotContains('header', 'Shelves'); $this->permissions->setEntityPermissions($shelf, ['view'], [$userRole]); $resp = $this->get('/'); $this->withHtml($resp)->assertElementContains('header', 'Shelves'); } public function test_shelves_page_contains_create_link() { $resp = $this->asEditor()->get('/shelves'); $this->withHtml($resp)->assertElementContains('a', 'New Shelf'); } public function test_book_not_visible_in_shelf_list_view_if_user_cant_view_shelf() { config()->set([ 'setting-defaults.user.bookshelves_view_type' => 'list', ]); $shelf = $this->entities->shelf(); $book = $shelf->books()->first(); $resp = $this->asEditor()->get('/shelves'); $resp->assertSee($book->name); $resp->assertSee($book->getUrl()); $this->permissions->setEntityPermissions($book, []); $resp = $this->asEditor()->get('/shelves'); $resp->assertDontSee($book->name); $resp->assertDontSee($book->getUrl()); } public function test_shelves_create() { $booksToInclude = Book::take(2)->get(); $shelfInfo = [ 'name' => 'My test shelf' . Str::random(4), 'description_html' => '<p>Test book description ' . Str::random(10) . '</p>', ]; $resp = $this->asEditor()->post('/shelves', array_merge($shelfInfo, [ 'books' => $booksToInclude->implode('id', ','), 'tags' => [ [ 'name' => 'Test Category', 'value' => 'Test Tag Value', ], ], ])); $resp->assertRedirect(); $editorId = $this->users->editor()->id; $this->assertDatabaseHasEntityData('bookshelf', array_merge($shelfInfo, ['created_by' => $editorId, 'updated_by' => $editorId])); $shelf = Bookshelf::where('name', '=', $shelfInfo['name'])->first(); $shelfPage = $this->get($shelf->getUrl()); $shelfPage->assertSee($shelfInfo['name']); $shelfPage->assertSee($shelfInfo['description_html'], false); $this->withHtml($shelfPage)->assertElementContains('.tag-item', 'Test Category'); $this->withHtml($shelfPage)->assertElementContains('.tag-item', 'Test Tag Value'); $this->assertDatabaseHas('bookshelves_books', ['bookshelf_id' => $shelf->id, 'book_id' => $booksToInclude[0]->id]); $this->assertDatabaseHas('bookshelves_books', ['bookshelf_id' => $shelf->id, 'book_id' => $booksToInclude[1]->id]); } public function test_shelves_create_sets_cover_image() { $shelfInfo = [ 'name' => 'My test shelf' . Str::random(4), 'description_html' => '<p>Test book description ' . Str::random(10) . '</p>', ]; $imageFile = $this->files->uploadedImage('shelf-test.png'); $resp = $this->asEditor()->call('POST', '/shelves', $shelfInfo, [], ['image' => $imageFile]); $resp->assertRedirect(); $lastImage = Image::query()->orderByDesc('id')->firstOrFail(); $shelf = Bookshelf::query()->where('name', '=', $shelfInfo['name'])->first(); $this->assertDatabaseHas('entity_container_data', [ 'entity_id' => $shelf->id, 'entity_type' => 'bookshelf', 'image_id' => $lastImage->id, ]); $this->assertEquals($lastImage->id, $shelf->coverInfo()->getImage()->id); $this->assertEquals('cover_bookshelf', $lastImage->type); } public function test_shelf_view() { $shelf = $this->entities->shelf(); $resp = $this->asEditor()->get($shelf->getUrl()); $resp->assertStatus(200); $resp->assertSeeText($shelf->name); $resp->assertSeeText($shelf->description); foreach ($shelf->books as $book) { $resp->assertSee($book->name); } } public function test_shelf_view_shows_action_buttons() { $shelf = $this->entities->shelf(); $resp = $this->asAdmin()->get($shelf->getUrl()); $resp->assertSee($shelf->getUrl('/create-book')); $resp->assertSee($shelf->getUrl('/edit')); $resp->assertSee($shelf->getUrl('/permissions')); $resp->assertSee($shelf->getUrl('/delete')); $this->withHtml($resp)->assertElementContains('a', 'New Book'); $this->withHtml($resp)->assertElementContains('a', 'Edit'); $this->withHtml($resp)->assertElementContains('a', 'Permissions'); $this->withHtml($resp)->assertElementContains('a', 'Delete'); $resp = $this->asEditor()->get($shelf->getUrl()); $resp->assertDontSee($shelf->getUrl('/permissions')); } public function test_shelf_view_has_sort_control_that_defaults_to_default() { $shelf = $this->entities->shelf(); $resp = $this->asAdmin()->get($shelf->getUrl()); $this->withHtml($resp)->assertElementExists('form[action$="change-sort/shelf_books"]'); $this->withHtml($resp)->assertElementContains('form[action$="change-sort/shelf_books"] [aria-haspopup="true"]', 'Default'); } public function test_shelf_view_sort_takes_action() { $shelf = Bookshelf::query()->whereHas('books')->with('books')->first(); $books = Book::query()->take(3)->get(['id', 'name']); $books[0]->fill(['name' => 'bsfsdfsdfsd'])->save(); $books[1]->fill(['name' => 'adsfsdfsdfsd'])->save(); $books[2]->fill(['name' => 'hdgfgdfg'])->save(); // Set book ordering $this->asAdmin()->put($shelf->getUrl(), [ 'books' => $books->implode('id', ','), 'tags' => [], 'description_html' => 'abc', 'name' => 'abc', ]); $this->assertEquals(3, $shelf->books()->count()); $shelf->refresh(); $resp = $this->asEditor()->get($shelf->getUrl()); $this->withHtml($resp)->assertElementContains('.book-content a.grid-card:nth-child(1)', $books[0]->name); $this->withHtml($resp)->assertElementNotContains('.book-content a.grid-card:nth-child(3)', $books[0]->name); setting()->putUser($this->users->editor(), 'shelf_books_sort_order', 'desc'); $resp = $this->asEditor()->get($shelf->getUrl()); $this->withHtml($resp)->assertElementNotContains('.book-content a.grid-card:nth-child(1)', $books[0]->name); $this->withHtml($resp)->assertElementContains('.book-content a.grid-card:nth-child(3)', $books[0]->name); setting()->putUser($this->users->editor(), 'shelf_books_sort_order', 'desc'); setting()->putUser($this->users->editor(), 'shelf_books_sort', 'name'); $resp = $this->asEditor()->get($shelf->getUrl()); $this->withHtml($resp)->assertElementContains('.book-content a.grid-card:nth-child(1)', 'hdgfgdfg'); $this->withHtml($resp)->assertElementContains('.book-content a.grid-card:nth-child(2)', 'bsfsdfsdfsd'); $this->withHtml($resp)->assertElementContains('.book-content a.grid-card:nth-child(3)', 'adsfsdfsdfsd'); } public function test_shelf_view_sorts_by_name_case_insensitively() { $shelf = Bookshelf::query()->whereHas('books')->with('books')->first(); $books = Book::query()->take(3)->get(['id', 'name']); $books[0]->fill(['name' => 'Book Ab'])->save(); $books[1]->fill(['name' => 'Book ac'])->save(); $books[2]->fill(['name' => 'Book AD'])->save(); // Set book ordering $this->asAdmin()->put($shelf->getUrl(), [ 'books' => $books->implode('id', ','), 'tags' => [], 'description_html' => 'abc', 'name' => 'abc', ]); $this->assertEquals(3, $shelf->books()->count()); $shelf->refresh(); setting()->putUser($this->users->editor(), 'shelf_books_sort', 'name'); setting()->putUser($this->users->editor(), 'shelf_books_sort_order', 'asc'); $html = $this->withHtml($this->asEditor()->get($shelf->getUrl())); $html->assertElementContains('.book-content a.grid-card:nth-child(1)', 'Book Ab'); $html->assertElementContains('.book-content a.grid-card:nth-child(2)', 'Book ac'); $html->assertElementContains('.book-content a.grid-card:nth-child(3)', 'Book AD'); } public function test_shelf_edit() { $shelf = $this->entities->shelf(); $resp = $this->asEditor()->get($shelf->getUrl('/edit')); $resp->assertSeeText('Edit Shelf'); $booksToInclude = Book::take(2)->get(); $shelfInfo = [ 'name' => 'My test shelf' . Str::random(4), 'description_html' => '<p>Test book description ' . Str::random(10) . '</p>', ]; $resp = $this->asEditor()->put($shelf->getUrl(), array_merge($shelfInfo, [ 'books' => $booksToInclude->implode('id', ','), 'tags' => [ [ 'name' => 'Test Category', 'value' => 'Test Tag Value', ], ], ])); $shelf = Bookshelf::find($shelf->id); $resp->assertRedirect($shelf->getUrl()); $this->assertSessionHas('success'); $editorId = $this->users->editor()->id; $this->assertDatabaseHasEntityData('bookshelf', array_merge($shelfInfo, ['id' => $shelf->id, 'created_by' => $editorId, 'updated_by' => $editorId])); $shelfPage = $this->get($shelf->getUrl()); $shelfPage->assertSee($shelfInfo['name']); $shelfPage->assertSee($shelfInfo['description_html'], false); $this->withHtml($shelfPage)->assertElementContains('.tag-item', 'Test Category'); $this->withHtml($shelfPage)->assertElementContains('.tag-item', 'Test Tag Value'); $this->assertDatabaseHas('bookshelves_books', ['bookshelf_id' => $shelf->id, 'book_id' => $booksToInclude[0]->id]); $this->assertDatabaseHas('bookshelves_books', ['bookshelf_id' => $shelf->id, 'book_id' => $booksToInclude[1]->id]); } public function test_shelf_edit_does_not_alter_books_we_dont_have_access_to() { $shelf = $this->entities->shelf(); $shelf->books()->detach(); $this->entities->book(); $this->entities->book(); $newBooks = [$this->entities->book(), $this->entities->book()]; $originalBooks = [$this->entities->book(), $this->entities->book()]; foreach ($originalBooks as $book) { $this->permissions->disableEntityInheritedPermissions($book); $shelf->books()->attach($book->id); } $this->asEditor()->put($shelf->getUrl(), [ 'name' => $shelf->name, 'books' => "{$newBooks[0]->id},{$newBooks[1]->id}", ])->assertRedirect($shelf->getUrl()); $resultingBooksById = $shelf->books()->get()->keyBy('id')->toArray(); $this->assertCount(4, $resultingBooksById); foreach ($newBooks as $book) { $this->assertArrayHasKey($book->id, $resultingBooksById); } foreach ($originalBooks as $book) { $this->assertArrayHasKey($book->id, $resultingBooksById); } } public function test_shelf_create_new_book() { $shelf = $this->entities->shelf(); $resp = $this->asEditor()->get($shelf->getUrl('/create-book')); $resp->assertSee('Create New Book'); $resp->assertSee($shelf->getShortName()); $testName = 'Test Book in Shelf Name'; $createBookResp = $this->asEditor()->post($shelf->getUrl('/create-book'), [ 'name' => $testName, 'description_html' => 'Book in shelf description', ]); $createBookResp->assertRedirect(); $newBook = Book::query()->orderBy('id', 'desc')->first(); $this->assertDatabaseHas('bookshelves_books', [ 'bookshelf_id' => $shelf->id, 'book_id' => $newBook->id, ]); $resp = $this->asEditor()->get($shelf->getUrl()); $resp->assertSee($testName); } public function test_shelf_delete() { $shelf = Bookshelf::query()->whereHas('books')->first(); $this->assertNull($shelf->deleted_at); $bookCount = $shelf->books()->count(); $deleteViewReq = $this->asEditor()->get($shelf->getUrl('/delete')); $deleteViewReq->assertSeeText('Are you sure you want to delete this shelf?'); $deleteReq = $this->delete($shelf->getUrl()); $deleteReq->assertRedirect(url('/shelves')); $this->assertActivityExists('bookshelf_delete', $shelf); $shelf->refresh(); $this->assertNotNull($shelf->deleted_at); $this->assertTrue($shelf->books()->count() === $bookCount); $this->assertTrue($shelf->deletions()->count() === 1); $redirectReq = $this->get($deleteReq->baseResponse->headers->get('location')); $this->assertNotificationContains($redirectReq, 'Shelf Successfully Deleted'); } public function test_shelf_copy_permissions() { $shelf = $this->entities->shelf(); $resp = $this->asAdmin()->get($shelf->getUrl('/permissions')); $resp->assertSeeText('Copy Permissions'); $resp->assertSee("action=\"{$shelf->getUrl('/copy-permissions')}\"", false); $child = $shelf->books()->first(); $editorRole = $this->users->editor()->roles()->first(); $this->assertFalse($child->hasPermissions(), 'Child book should not be restricted by default'); $this->assertTrue($child->permissions()->count() === 0, 'Child book should have no permissions by default'); $this->permissions->setEntityPermissions($shelf, ['view', 'update'], [$editorRole]); $resp = $this->post($shelf->getUrl('/copy-permissions')); $child = $shelf->books()->first(); $resp->assertRedirect($shelf->getUrl()); $this->assertTrue($child->hasPermissions(), 'Child book should now be restricted'); $this->assertTrue($child->permissions()->count() === 2, 'Child book should have copied permissions'); $this->assertDatabaseHas('entity_permissions', [ 'entity_type' => 'book', 'entity_id' => $child->id, 'role_id' => $editorRole->id, 'view' => true, 'update' => true, 'create' => false, 'delete' => false, ]); } public function test_permission_page_has_a_warning_about_no_cascading() { $shelf = $this->entities->shelf(); $resp = $this->asAdmin()->get($shelf->getUrl('/permissions')); $resp->assertSeeText('Permissions on shelves do not automatically cascade to contained books.'); } public function test_bookshelves_show_in_breadcrumbs_if_in_context() { $shelf = $this->entities->shelf(); $shelfBook = $shelf->books()->first(); $shelfPage = $shelfBook->pages()->first(); $this->asAdmin(); $bookVisit = $this->get($shelfBook->getUrl()); $this->withHtml($bookVisit)->assertElementNotContains('.breadcrumbs', 'Shelves'); $this->withHtml($bookVisit)->assertElementNotContains('.breadcrumbs', $shelf->getShortName()); $this->get($shelf->getUrl()); $bookVisit = $this->get($shelfBook->getUrl()); $this->withHtml($bookVisit)->assertElementContains('.breadcrumbs', 'Shelves'); $this->withHtml($bookVisit)->assertElementContains('.breadcrumbs', $shelf->getShortName()); $pageVisit = $this->get($shelfPage->getUrl()); $this->withHtml($pageVisit)->assertElementContains('.breadcrumbs', 'Shelves'); $this->withHtml($pageVisit)->assertElementContains('.breadcrumbs', $shelf->getShortName()); $this->get('/books'); $pageVisit = $this->get($shelfPage->getUrl()); $this->withHtml($pageVisit)->assertElementNotContains('.breadcrumbs', 'Shelves'); $this->withHtml($pageVisit)->assertElementNotContains('.breadcrumbs', $shelf->getShortName()); } public function test_bookshelves_show_on_book() { // Create shelf $shelfInfo = [ 'name' => 'My test shelf' . Str::random(4), 'description_html' => '<p>Test shelf description ' . Str::random(10) . '</p>', ]; $this->asEditor()->post('/shelves', $shelfInfo); $shelf = Bookshelf::where('name', '=', $shelfInfo['name'])->first(); // Create book and add to shelf $this->asEditor()->post($shelf->getUrl('/create-book'), [ 'name' => 'Test book name', 'description_html' => '<p>Book in shelf description</p>', ]); $newBook = Book::query()->orderBy('id', 'desc')->first(); $resp = $this->asEditor()->get($newBook->getUrl()); $this->withHtml($resp)->assertElementContains('.tri-layout-left-contents', $shelfInfo['name']); // Remove shelf $this->delete($shelf->getUrl()); $resp = $this->asEditor()->get($newBook->getUrl()); $resp->assertDontSee($shelfInfo['name']); } public function test_cancel_on_child_book_creation_returns_to_original_shelf() { $shelf = $this->entities->shelf(); $resp = $this->asEditor()->get($shelf->getUrl('/create-book')); $this->withHtml($resp)->assertElementContains('form a[href="' . $shelf->getUrl() . '"]', 'Cancel'); } public function test_show_view_displays_description_if_no_description_html_set() { $shelf = $this->entities->shelf(); $shelf->description_html = ''; $shelf->description = "My great\ndescription\n\nwith newlines"; $shelf->save(); $resp = $this->asEditor()->get($shelf->getUrl()); $resp->assertSee("<p>My great<br>\ndescription<br>\n<br>\nwith newlines</p>", false); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Entity/PageRevisionTest.php
tests/Entity/PageRevisionTest.php
<?php namespace Tests\Entity; use BookStack\Activity\ActivityType; use BookStack\Entities\Models\Page; use Tests\TestCase; class PageRevisionTest extends TestCase { public function test_revision_links_visible_to_viewer() { $page = $this->entities->page(); $html = $this->withHtml($this->asViewer()->get($page->getUrl())); $html->assertLinkExists($page->getUrl('/revisions')); $html->assertElementContains('a', 'Revisions'); $html->assertElementContains('a', 'Revision #1'); } public function test_page_revision_views_viewable() { $this->asEditor(); $page = $this->entities->page(); $this->createRevisions($page, 1, ['name' => 'updated page', 'html' => '<p>new content</p>']); $pageRevision = $page->revisions->last(); $resp = $this->get($page->getUrl() . '/revisions/' . $pageRevision->id); $resp->assertStatus(200); $resp->assertSee('new content'); $resp = $this->get($page->getUrl() . '/revisions/' . $pageRevision->id . '/changes'); $resp->assertStatus(200); $resp->assertSee('new content'); } public function test_page_revision_preview_shows_content_of_revision() { $this->asEditor(); $page = $this->entities->page(); $this->createRevisions($page, 1, ['name' => 'updated page', 'html' => '<p>new revision content</p>']); $pageRevision = $page->revisions->last(); $this->createRevisions($page, 1, ['name' => 'updated page', 'html' => '<p>Updated content</p>']); $revisionView = $this->get($page->getUrl() . '/revisions/' . $pageRevision->id); $revisionView->assertStatus(200); $revisionView->assertSee('new revision content'); } public function test_page_revision_restore_updates_content() { $this->asEditor(); $page = $this->entities->page(); $this->createRevisions($page, 1, ['name' => 'updated page abc123', 'html' => '<p>new contente def456</p>']); $this->createRevisions($page, 1, ['name' => 'updated page again', 'html' => '<p>new content</p>']); $page = Page::find($page->id); $pageView = $this->get($page->getUrl()); $pageView->assertDontSee('abc123'); $pageView->assertDontSee('def456'); $revToRestore = $page->revisions()->where('name', 'like', '%abc123')->first(); $restoreReq = $this->put($page->getUrl() . '/revisions/' . $revToRestore->id . '/restore'); $page = Page::find($page->id); $restoreReq->assertStatus(302); $restoreReq->assertRedirect($page->getUrl()); $pageView = $this->get($page->getUrl()); $pageView->assertSee('abc123'); $pageView->assertSee('def456'); } public function test_page_revision_restore_with_markdown_retains_markdown_content() { $this->asEditor(); $page = $this->entities->page(); $this->createRevisions($page, 1, ['name' => 'updated page abc123', 'markdown' => '## New Content def456']); $this->createRevisions($page, 1, ['name' => 'updated page again', 'markdown' => '## New Content Updated']); $page = Page::find($page->id); $pageView = $this->get($page->getUrl()); $pageView->assertDontSee('abc123'); $pageView->assertDontSee('def456'); $revToRestore = $page->revisions()->where('name', 'like', '%abc123')->first(); $restoreReq = $this->put($page->getUrl() . '/revisions/' . $revToRestore->id . '/restore'); $page = Page::find($page->id); $restoreReq->assertStatus(302); $restoreReq->assertRedirect($page->getUrl()); $pageView = $this->get($page->getUrl()); $this->assertDatabaseHasEntityData('page', [ 'id' => $page->id, 'markdown' => '## New Content def456', ]); $pageView->assertSee('abc123'); $pageView->assertSee('def456'); } public function test_page_revision_restore_sets_new_revision_with_summary() { $this->asEditor(); $page = $this->entities->page(); $this->createRevisions($page, 1, ['name' => 'updated page abc123', 'html' => '<p>new contente def456</p>', 'summary' => 'My first update']); $this->createRevisions($page, 1, ['html' => '<p>new content</p>']); $page->refresh(); $revToRestore = $page->revisions()->where('name', 'like', '%abc123')->first(); $this->put($page->getUrl() . '/revisions/' . $revToRestore->id . '/restore'); $page->refresh(); $this->assertDatabaseHas('page_revisions', [ 'page_id' => $page->id, 'text' => 'new contente def456', 'type' => 'version', 'summary' => "Restored from #{$revToRestore->id}; My first update", ]); $detail = "Revision #{$revToRestore->revision_number} (ID: {$revToRestore->id}) for page ID {$revToRestore->page_id}"; $this->assertActivityExists(ActivityType::REVISION_RESTORE, null, $detail); } public function test_page_revision_count_increments_on_update() { $page = $this->entities->page(); $startCount = $page->revision_count; $this->createRevisions($page, 1); $this->assertTrue(Page::find($page->id)->revision_count === $startCount + 1); } public function test_revision_count_shown_in_page_meta() { $page = $this->entities->page(); $this->createRevisions($page, 2); $pageView = $this->asViewer()->get($page->getUrl()); $pageView->assertSee('Revision #' . $page->revision_count); } public function test_revision_deletion() { $page = $this->entities->page(); $this->createRevisions($page, 2); $beforeRevisionCount = $page->revisions->count(); // Delete the first revision $revision = $page->revisions->get(1); $resp = $this->asEditor()->delete($revision->getUrl('/delete/')); $resp->assertRedirect($page->getUrl('/revisions')); $page->refresh(); $afterRevisionCount = $page->revisions->count(); $this->assertTrue($beforeRevisionCount === ($afterRevisionCount + 1)); $detail = "Revision #{$revision->revision_number} (ID: {$revision->id}) for page ID {$revision->page_id}"; $this->assertActivityExists(ActivityType::REVISION_DELETE, null, $detail); // Try to delete the latest revision $beforeRevisionCount = $page->revisions->count(); $resp = $this->asEditor()->delete($page->currentRevision->getUrl('/delete/')); $resp->assertRedirect($page->getUrl('/revisions')); $page->refresh(); $afterRevisionCount = $page->revisions->count(); $this->assertTrue($beforeRevisionCount === $afterRevisionCount); } public function test_revision_limit_enforced() { config()->set('app.revision_limit', 2); $page = $this->entities->page(); $this->createRevisions($page, 12); $revisionCount = $page->revisions()->count(); $this->assertEquals(2, $revisionCount); } public function test_false_revision_limit_allows_many_revisions() { config()->set('app.revision_limit', false); $page = $this->entities->page(); $this->createRevisions($page, 12); $revisionCount = $page->revisions()->count(); $this->assertEquals(12, $revisionCount); } public function test_revision_list_shows_editor_type() { $page = $this->entities->page(); $this->createRevisions($page, 1, ['html' => 'new page html']); $resp = $this->asAdmin()->get($page->refresh()->getUrl('/revisions')); $this->withHtml($resp)->assertElementContains('.item-list-row > div:nth-child(2)', 'WYSIWYG)'); $this->withHtml($resp)->assertElementNotContains('.item-list-row > div:nth-child(2)', 'Markdown)'); $this->createRevisions($page, 1, ['markdown' => '# Some markdown content']); $resp = $this->get($page->refresh()->getUrl('/revisions')); $this->withHtml($resp)->assertElementContains('.item-list-row > div:nth-child(2)', 'Markdown)'); } public function test_revision_changes_link_not_shown_for_oldest_revision() { $page = $this->entities->page(); $this->createRevisions($page, 3, ['html' => 'new page html']); $resp = $this->asAdmin()->get($page->refresh()->getUrl('/revisions')); $html = $this->withHtml($resp); $html->assertElementNotExists('.item-list > .item-list-row:last-child a[href*="/changes"]'); $html->assertElementContains('.item-list > .item-list-row:nth-child(2)', 'Changes'); } public function test_revision_restore_action_only_visible_with_permission() { $page = $this->entities->page(); $this->createRevisions($page, 2); $viewer = $this->users->viewer(); $this->actingAs($viewer); $respHtml = $this->withHtml($this->get($page->getUrl('/revisions'))); $respHtml->assertElementNotContains('.actions a', 'Restore'); $respHtml->assertElementNotExists('form[action$="/restore"]'); $this->permissions->grantUserRolePermissions($viewer, ['page-update-all']); $respHtml = $this->withHtml($this->get($page->getUrl('/revisions'))); $respHtml->assertElementContains('.actions a', 'Restore'); $respHtml->assertElementExists('form[action$="/restore"]'); } public function test_revision_delete_action_only_visible_with_permission() { $page = $this->entities->page(); $this->createRevisions($page, 2); $viewer = $this->users->viewer(); $this->actingAs($viewer); $respHtml = $this->withHtml($this->get($page->getUrl('/revisions'))); $respHtml->assertElementNotContains('.actions a', 'Delete'); $respHtml->assertElementNotExists('form[action$="/delete"]'); $this->permissions->grantUserRolePermissions($viewer, ['page-delete-all']); $respHtml = $this->withHtml($this->get($page->getUrl('/revisions'))); $respHtml->assertElementContains('.actions a', 'Delete'); $respHtml->assertElementExists('form[action$="/delete"]'); } protected function createRevisions(Page $page, int $times, array $attrs = []) { $user = user(); for ($i = 0; $i < $times; $i++) { $data = ['name' => 'Page update' . $i, 'summary' => 'Update entry' . $i]; if (!isset($attrs['markdown'])) { $data['html'] = '<p>My update page</p>'; } $this->asAdmin()->put($page->getUrl(), array_merge($data, $attrs)); $page->refresh(); } $this->actingAs($user); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Entity/PageEditorTest.php
tests/Entity/PageEditorTest.php
<?php namespace Tests\Entity; use BookStack\Entities\Models\Chapter; use BookStack\Entities\Models\Page; use BookStack\Entities\Tools\PageEditorType; use Tests\TestCase; class PageEditorTest extends TestCase { protected Page $page; protected function setUp(): void { parent::setUp(); $this->page = $this->entities->page(); } public function test_default_editor_is_wysiwyg_for_new_pages() { $this->assertEquals('wysiwyg', setting('app-editor')); $resp = $this->asAdmin()->get($this->page->book->getUrl('/create-page')); $this->withHtml($this->followRedirects($resp))->assertElementExists('#html-editor'); } public function test_editor_set_for_new_pages() { $book = $this->page->book; $this->asEditor()->get($book->getUrl('/create-page')); $newPage = $book->pages()->orderBy('id', 'desc')->first(); $this->assertEquals('wysiwyg', $newPage->editor); $this->setSettings(['app-editor' => PageEditorType::Markdown->value]); $this->asEditor()->get($book->getUrl('/create-page')); $newPage = $book->pages()->orderBy('id', 'desc')->first(); $this->assertEquals('markdown', $newPage->editor); } public function test_markdown_setting_shows_markdown_editor_for_new_pages() { $this->setSettings(['app-editor' => PageEditorType::Markdown->value]); $resp = $this->asAdmin()->get($this->page->book->getUrl('/create-page')); $this->withHtml($this->followRedirects($resp)) ->assertElementNotExists('#html-editor') ->assertElementExists('#markdown-editor'); } public function test_markdown_content_given_to_editor() { $mdContent = '# hello. This is a test'; $this->page->markdown = $mdContent; $this->page->editor = PageEditorType::Markdown; $this->page->save(); $resp = $this->asAdmin()->get($this->page->getUrl('/edit')); $this->withHtml($resp)->assertElementContains('[name="markdown"]', $mdContent); } public function test_html_content_given_to_editor_if_no_markdown() { $this->page->editor = 'markdown'; $this->page->save(); $resp = $this->asAdmin()->get($this->page->getUrl() . '/edit'); $this->withHtml($resp)->assertElementContains('[name="markdown"]', $this->page->html); } public function test_empty_markdown_still_saves_without_error() { $this->setSettings(['app-editor' => 'markdown']); $book = $this->entities->book(); $this->asEditor()->get($book->getUrl('/create-page')); $draft = Page::query()->where('book_id', '=', $book->id) ->where('draft', '=', true)->first(); $details = [ 'name' => 'my page', 'markdown' => '', ]; $resp = $this->post($book->getUrl("/draft/{$draft->id}"), $details); $resp->assertRedirect(); $this->assertDatabaseHasEntityData('page', [ 'markdown' => $details['markdown'], 'id' => $draft->id, 'draft' => false, ]); } public function test_back_link_in_editor_has_correct_url() { $book = $this->entities->bookHasChaptersAndPages(); $this->asEditor()->get($book->getUrl('/create-page')); /** @var Chapter $chapter */ $chapter = $book->chapters()->firstOrFail(); /** @var Page $draft */ $draft = $book->pages()->where('draft', '=', true)->firstOrFail(); // Book draft goes back to book $resp = $this->get($book->getUrl("/draft/{$draft->id}")); $this->withHtml($resp)->assertElementContains('a[href="' . $book->getUrl() . '"]', 'Back'); // Chapter draft goes back to chapter $draft->chapter_id = $chapter->id; $draft->save(); $resp = $this->get($book->getUrl("/draft/{$draft->id}")); $this->withHtml($resp)->assertElementContains('a[href="' . $chapter->getUrl() . '"]', 'Back'); // Saved page goes back to page $this->post($book->getUrl("/draft/{$draft->id}"), ['name' => 'Updated', 'html' => 'Updated']); $draft->refresh(); $resp = $this->get($draft->getUrl('/edit')); $this->withHtml($resp)->assertElementContains('a[href="' . $draft->getUrl() . '"]', 'Back'); } public function test_switching_from_html_to_clean_markdown_works() { $page = $this->entities->page(); $page->html = '<h2>A Header</h2><p>Some <strong>bold</strong> content.</p>'; $page->save(); $resp = $this->asAdmin()->get($page->getUrl('/edit?editor=markdown-clean')); $resp->assertStatus(200); $resp->assertSee("## A Header\n\nSome **bold** content."); $this->withHtml($resp)->assertElementExists('#markdown-editor'); } public function test_switching_from_html_to_stable_markdown_works() { $page = $this->entities->page(); $page->html = '<h2>A Header</h2><p>Some <strong>bold</strong> content.</p>'; $page->save(); $resp = $this->asAdmin()->get($page->getUrl('/edit?editor=markdown-stable')); $resp->assertStatus(200); $resp->assertSee('<h2>A Header</h2><p>Some <strong>bold</strong> content.</p>', true); $this->withHtml($resp)->assertElementExists('[component="markdown-editor"]'); } public function test_switching_from_markdown_to_wysiwyg_works() { $page = $this->entities->page(); $page->html = ''; $page->markdown = "## A Header\n\nSome content with **bold** text!"; $page->save(); $resp = $this->asAdmin()->get($page->getUrl('/edit?editor=wysiwyg')); $resp->assertStatus(200); $this->withHtml($resp)->assertElementExists('[component="wysiwyg-editor-tinymce"]'); $resp->assertSee("<h2>A Header</h2>\n<p>Some content with <strong>bold</strong> text!</p>", true); } public function test_switching_from_markdown_to_wysiwyg2024_works() { $page = $this->entities->page(); $page->html = ''; $page->markdown = "## A Header\n\nSome content with **bold** text!"; $page->save(); $resp = $this->asAdmin()->get($page->getUrl('/edit?editor=wysiwyg2024')); $resp->assertStatus(200); $this->withHtml($resp)->assertElementExists('[component="wysiwyg-editor"]'); $resp->assertSee("<h2>A Header</h2>\n<p>Some content with <strong>bold</strong> text!</p>", true); } public function test_page_editor_changes_with_editor_property() { $resp = $this->asAdmin()->get($this->page->getUrl('/edit')); $this->withHtml($resp)->assertElementExists('[component="wysiwyg-editor-tinymce"]'); $this->page->markdown = "## A Header\n\nSome content with **bold** text!"; $this->page->editor = 'markdown'; $this->page->save(); $resp = $this->asAdmin()->get($this->page->getUrl('/edit')); $this->withHtml($resp)->assertElementExists('[component="markdown-editor"]'); $this->page->editor = 'wysiwyg2024'; $this->page->save(); $resp = $this->asAdmin()->get($this->page->getUrl('/edit')); $this->withHtml($resp)->assertElementExists('[component="wysiwyg-editor"]'); } public function test_editor_type_switch_options_show() { $resp = $this->asAdmin()->get($this->page->getUrl('/edit')); $editLink = $this->page->getUrl('/edit') . '?editor='; $this->withHtml($resp)->assertElementContains("a[href=\"{$editLink}markdown-clean\"]", '(Clean Content)'); $this->withHtml($resp)->assertElementContains("a[href=\"{$editLink}markdown-stable\"]", '(Stable Content)'); $this->withHtml($resp)->assertElementContains("a[href=\"{$editLink}wysiwyg2024\"]", '(In Beta Testing)'); $resp = $this->asAdmin()->get($this->page->getUrl('/edit?editor=markdown-stable')); $editLink = $this->page->getUrl('/edit') . '?editor='; $this->withHtml($resp)->assertElementContains("a[href=\"{$editLink}wysiwyg\"]", 'Switch to WYSIWYG Editor'); } public function test_editor_type_switch_options_dont_show_if_without_change_editor_permissions() { $resp = $this->asEditor()->get($this->page->getUrl('/edit')); $editLink = $this->page->getUrl('/edit') . '?editor='; $this->withHtml($resp)->assertElementNotExists("a[href*=\"{$editLink}\"]"); } public function test_page_editor_type_switch_does_not_work_without_change_editor_permissions() { $page = $this->entities->page(); $page->html = '<h2>A Header</h2><p>Some <strong>bold</strong> content.</p>'; $page->save(); $resp = $this->asEditor()->get($page->getUrl('/edit?editor=markdown-stable')); $resp->assertStatus(200); $this->withHtml($resp)->assertElementExists('[component="wysiwyg-editor-tinymce"]'); $this->withHtml($resp)->assertElementNotExists('[component="markdown-editor"]'); } public function test_page_save_does_not_change_active_editor_without_change_editor_permissions() { $page = $this->entities->page(); $page->html = '<h2>A Header</h2><p>Some <strong>bold</strong> content.</p>'; $page->editor = 'wysiwyg'; $page->save(); $this->asEditor()->put($page->getUrl(), ['name' => $page->name, 'markdown' => '## Updated content abc']); $this->assertEquals('wysiwyg', $page->refresh()->editor); } public function test_editor_type_change_to_wysiwyg_infers_type_from_request_or_uses_system_default() { $tests = [ [ 'setting' => 'wysiwyg', 'request' => 'wysiwyg2024', 'expected' => 'wysiwyg2024', ], [ 'setting' => 'wysiwyg2024', 'request' => 'wysiwyg', 'expected' => 'wysiwyg', ], [ 'setting' => 'wysiwyg', 'request' => null, 'expected' => 'wysiwyg', ], [ 'setting' => 'wysiwyg2024', 'request' => null, 'expected' => 'wysiwyg2024', ] ]; $page = $this->entities->page(); foreach ($tests as $test) { $page->editor = 'markdown'; $page->save(); $this->setSettings(['app-editor' => $test['setting']]); $this->asAdmin()->put($page->getUrl(), ['name' => $page->name, 'html' => '<p>Hello</p>', 'editor' => $test['request']]); $this->assertEquals($test['expected'], $page->refresh()->editor, "Failed asserting global editor {$test['setting']} with request editor {$test['request']} results in {$test['expected']} set for the page"); } } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Entity/CopyTest.php
tests/Entity/CopyTest.php
<?php namespace Tests\Entity; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\BookChild; use BookStack\Entities\Models\Bookshelf; use BookStack\Entities\Models\Chapter; use BookStack\Entities\Models\Page; use BookStack\Entities\Repos\BookRepo; use Tests\TestCase; class CopyTest extends TestCase { public function test_book_show_view_has_copy_button() { $book = $this->entities->book(); $resp = $this->asEditor()->get($book->getUrl()); $this->withHtml($resp)->assertElementContains("a[href=\"{$book->getUrl('/copy')}\"]", 'Copy'); } public function test_book_copy_view() { $book = $this->entities->book(); $resp = $this->asEditor()->get($book->getUrl('/copy')); $resp->assertOk(); $resp->assertSee('Copy Book'); $this->withHtml($resp)->assertElementExists("input[name=\"name\"][value=\"{$book->name}\"]"); } public function test_book_copy() { /** @var Book $book */ $book = Book::query()->whereHas('chapters')->whereHas('pages')->first(); $resp = $this->asEditor()->post($book->getUrl('/copy'), ['name' => 'My copy book']); /** @var Book $copy */ $copy = Book::query()->where('name', '=', 'My copy book')->first(); $resp->assertRedirect($copy->getUrl()); $this->assertEquals($book->getDirectVisibleChildren()->count(), $copy->getDirectVisibleChildren()->count()); $this->get($copy->getUrl())->assertSee($book->description_html, false); } public function test_book_copy_does_not_copy_non_visible_content() { /** @var Book $book */ $book = Book::query()->whereHas('chapters')->whereHas('pages')->first(); // Hide child content /** @var BookChild $page */ foreach ($book->getDirectVisibleChildren() as $child) { $this->permissions->setEntityPermissions($child, [], []); } $this->asEditor()->post($book->getUrl('/copy'), ['name' => 'My copy book']); /** @var Book $copy */ $copy = Book::query()->where('name', '=', 'My copy book')->first(); $this->assertEquals(0, $copy->getDirectVisibleChildren()->count()); } public function test_book_copy_does_not_copy_pages_or_chapters_if_user_cant_create() { /** @var Book $book */ $book = Book::query()->whereHas('chapters')->whereHas('directPages')->whereHas('chapters')->first(); $viewer = $this->users->viewer(); $this->permissions->grantUserRolePermissions($viewer, ['book-create-all']); $this->actingAs($viewer)->post($book->getUrl('/copy'), ['name' => 'My copy book']); /** @var Book $copy */ $copy = Book::query()->where('name', '=', 'My copy book')->first(); $this->assertEquals(0, $copy->pages()->count()); $this->assertEquals(0, $copy->chapters()->count()); } public function test_book_copy_clones_cover_image_if_existing() { $book = $this->entities->book(); $bookRepo = $this->app->make(BookRepo::class); $coverImageFile = $this->files->uploadedImage('cover.png'); $bookRepo->updateCoverImage($book, $coverImageFile); $this->asEditor()->post($book->getUrl('/copy'), ['name' => 'My copy book'])->assertRedirect(); /** @var Book $copy */ $copy = Book::query()->where('name', '=', 'My copy book')->first(); $this->assertNotNull($copy->coverInfo()->getImage()); $this->assertNotEquals($book->coverInfo()->getImage()->id, $copy->coverInfo()->getImage()->id); } public function test_book_copy_adds_book_to_shelves_if_edit_permissions_allows() { /** @var Bookshelf $shelfA */ /** @var Bookshelf $shelfB */ [$shelfA, $shelfB] = Bookshelf::query()->take(2)->get(); $book = $this->entities->book(); $shelfA->appendBook($book); $shelfB->appendBook($book); $viewer = $this->users->viewer(); $this->permissions->grantUserRolePermissions($viewer, ['book-update-all', 'book-create-all', 'bookshelf-update-all']); $this->permissions->setEntityPermissions($shelfB); $this->asEditor()->post($book->getUrl('/copy'), ['name' => 'My copy book']); /** @var Book $copy */ $copy = Book::query()->where('name', '=', 'My copy book')->first(); $this->assertTrue($copy->shelves()->where('id', '=', $shelfA->id)->exists()); $this->assertFalse($copy->shelves()->where('id', '=', $shelfB->id)->exists()); } public function test_chapter_show_view_has_copy_button() { $chapter = $this->entities->chapter(); $resp = $this->asEditor()->get($chapter->getUrl()); $this->withHtml($resp)->assertElementContains("a[href$=\"{$chapter->getUrl('/copy')}\"]", 'Copy'); } public function test_chapter_copy_view() { $chapter = $this->entities->chapter(); $resp = $this->asEditor()->get($chapter->getUrl('/copy')); $resp->assertOk(); $resp->assertSee('Copy Chapter'); $this->withHtml($resp)->assertElementExists("input[name=\"name\"][value=\"{$chapter->name}\"]"); $this->withHtml($resp)->assertElementExists('input[name="entity_selection"]'); } public function test_chapter_copy() { /** @var Chapter $chapter */ $chapter = Chapter::query()->whereHas('pages')->first(); /** @var Book $otherBook */ $otherBook = Book::query()->where('id', '!=', $chapter->book_id)->first(); $resp = $this->asEditor()->post($chapter->getUrl('/copy'), [ 'name' => 'My copied chapter', 'entity_selection' => 'book:' . $otherBook->id, ]); /** @var Chapter $newChapter */ $newChapter = Chapter::query()->where('name', '=', 'My copied chapter')->first(); $resp->assertRedirect($newChapter->getUrl()); $this->assertEquals($otherBook->id, $newChapter->book_id); $this->assertEquals($chapter->pages->count(), $newChapter->pages->count()); } public function test_chapter_copy_does_not_copy_non_visible_pages() { $chapter = $this->entities->chapterHasPages(); // Hide pages to all non-admin roles /** @var Page $page */ foreach ($chapter->pages as $page) { $this->permissions->setEntityPermissions($page, [], []); } $this->asEditor()->post($chapter->getUrl('/copy'), [ 'name' => 'My copied chapter', ]); /** @var Chapter $newChapter */ $newChapter = Chapter::query()->where('name', '=', 'My copied chapter')->first(); $this->assertEquals(0, $newChapter->pages()->count()); } public function test_chapter_copy_does_not_copy_pages_if_user_cant_page_create() { $chapter = $this->entities->chapterHasPages(); $viewer = $this->users->viewer(); $this->permissions->grantUserRolePermissions($viewer, ['chapter-create-all']); // Lacking permission results in no copied pages $this->actingAs($viewer)->post($chapter->getUrl('/copy'), [ 'name' => 'My copied chapter', ]); /** @var Chapter $newChapter */ $newChapter = Chapter::query()->where('name', '=', 'My copied chapter')->first(); $this->assertEquals(0, $newChapter->pages()->count()); $this->permissions->grantUserRolePermissions($viewer, ['page-create-all']); // Having permission rules in copied pages $this->actingAs($viewer)->post($chapter->getUrl('/copy'), [ 'name' => 'My copied again chapter', ]); /** @var Chapter $newChapter2 */ $newChapter2 = Chapter::query()->where('name', '=', 'My copied again chapter')->first(); $this->assertEquals($chapter->pages()->count(), $newChapter2->pages()->count()); } public function test_book_copy_updates_internal_references() { $book = $this->entities->bookHasChaptersAndPages(); /** @var Chapter $chapter */ $chapter = $book->chapters()->first(); /** @var Page $page */ $page = $chapter->pages()->first(); $this->asEditor(); $this->entities->updatePage($page, [ 'name' => 'reference test page', 'html' => '<p>This is a test <a href="' . $book->getUrl() . '">book link</a></p>', ]); // Quick pre-update to get stable slug $this->put($book->getUrl(), ['name' => 'Internal ref test']); $book->refresh(); $page->refresh(); $html = '<p>This is a test <a href="' . $page->getUrl() . '">page link</a></p>'; $this->put($book->getUrl(), ['name' => 'Internal ref test', 'description_html' => $html]); $this->post($book->getUrl('/copy'), ['name' => 'My copied book']); $newBook = Book::query()->where('name', '=', 'My copied book')->first(); $newPage = $newBook->pages()->where('name', '=', 'reference test page')->first(); $this->assertStringContainsString($newBook->getUrl(), $newPage->html); $this->assertStringContainsString($newPage->getUrl(), $newBook->description_html); $this->assertStringNotContainsString($book->getUrl(), $newPage->html); $this->assertStringNotContainsString($page->getUrl(), $newBook->description_html); } public function test_chapter_copy_updates_internal_references() { $chapter = $this->entities->chapterHasPages(); /** @var Page $page */ $page = $chapter->pages()->first(); $this->asEditor(); $this->entities->updatePage($page, [ 'name' => 'reference test page', 'html' => '<p>This is a test <a href="' . $chapter->getUrl() . '">chapter link</a></p>', ]); // Quick pre-update to get stable slug $this->put($chapter->getUrl(), ['name' => 'Internal ref test']); $chapter->refresh(); $page->refresh(); $html = '<p>This is a test <a href="' . $page->getUrl() . '">page link</a></p>'; $this->put($chapter->getUrl(), ['name' => 'Internal ref test', 'description_html' => $html]); $this->post($chapter->getUrl('/copy'), ['name' => 'My copied chapter']); $newChapter = Chapter::query()->where('name', '=', 'My copied chapter')->first(); $newPage = $newChapter->pages()->where('name', '=', 'reference test page')->first(); $this->assertStringContainsString($newChapter->getUrl() . '"', $newPage->html); $this->assertStringContainsString($newPage->getUrl() . '"', $newChapter->description_html); $this->assertStringNotContainsString($chapter->getUrl() . '"', $newPage->html); $this->assertStringNotContainsString($page->getUrl() . '"', $newChapter->description_html); } public function test_chapter_copy_updates_internal_permalink_references_in_its_description() { $chapter = $this->entities->chapterHasPages(); /** @var Page $page */ $page = $chapter->pages()->first(); $this->asEditor()->put($chapter->getUrl(), [ 'name' => 'Internal ref test', 'description_html' => '<p>This is a test <a href="' . $page->getPermalink() . '">page link</a></p>', ]); $chapter->refresh(); $this->post($chapter->getUrl('/copy'), ['name' => 'My copied chapter']); $newChapter = Chapter::query()->where('name', '=', 'My copied chapter')->first(); $this->assertStringContainsString('/link/', $newChapter->description_html); $this->assertStringNotContainsString($page->getPermalink() . '"', $newChapter->description_html); } public function test_page_copy_updates_internal_self_references() { $page = $this->entities->page(); $this->asEditor(); // Initial update to get stable slug $this->entities->updatePage($page, ['name' => 'reference test page']); $page->refresh(); $this->entities->updatePage($page, [ 'name' => 'reference test page', 'html' => '<p>This is a test <a href="' . $page->getUrl() . '">page link</a></p>', ]); $this->post($page->getUrl('/copy'), ['name' => 'My copied page']); $newPage = Page::query()->where('name', '=', 'My copied page')->first(); $this->assertNotNull($newPage); $this->assertStringContainsString($newPage->getUrl(), $newPage->html); $this->assertStringNotContainsString($page->getUrl(), $newPage->html); } public function test_page_copy() { $page = $this->entities->page(); $page->html = '<p>This is some test content</p>'; $page->save(); $currentBook = $page->book; $newBook = Book::where('id', '!=', $currentBook->id)->first(); $resp = $this->asEditor()->get($page->getUrl('/copy')); $resp->assertSee('Copy Page'); $movePageResp = $this->post($page->getUrl('/copy'), [ 'entity_selection' => 'book:' . $newBook->id, 'name' => 'My copied test page', ]); $pageCopy = Page::where('name', '=', 'My copied test page')->first(); $movePageResp->assertRedirect($pageCopy->getUrl()); $this->assertTrue($pageCopy->book->id == $newBook->id, 'Page was copied to correct book'); $this->assertStringContainsString('This is some test content', $pageCopy->html); } public function test_page_copy_with_markdown_has_both_html_and_markdown() { $page = $this->entities->page(); $page->html = '<h1>This is some test content</h1>'; $page->markdown = '# This is some test content'; $page->save(); $newBook = Book::where('id', '!=', $page->book->id)->first(); $this->asEditor()->post($page->getUrl('/copy'), [ 'entity_selection' => 'book:' . $newBook->id, 'name' => 'My copied test page', ]); $pageCopy = Page::where('name', '=', 'My copied test page')->first(); $this->assertStringContainsString('This is some test content', $pageCopy->html); $this->assertEquals('# This is some test content', $pageCopy->markdown); } public function test_page_copy_with_no_destination() { $page = $this->entities->page(); $currentBook = $page->book; $resp = $this->asEditor()->get($page->getUrl('/copy')); $resp->assertSee('Copy Page'); $movePageResp = $this->post($page->getUrl('/copy'), [ 'name' => 'My copied test page', ]); $pageCopy = Page::where('name', '=', 'My copied test page')->first(); $movePageResp->assertRedirect($pageCopy->getUrl()); $this->assertTrue($pageCopy->book->id == $currentBook->id, 'Page was copied to correct book'); $this->assertTrue($pageCopy->id !== $page->id, 'Page copy is not the same instance'); } public function test_page_can_be_copied_without_edit_permission() { $page = $this->entities->page(); $currentBook = $page->book; $newBook = Book::where('id', '!=', $currentBook->id)->first(); $viewer = $this->users->viewer(); $resp = $this->actingAs($viewer)->get($page->getUrl()); $resp->assertDontSee($page->getUrl('/copy')); $newBook->owned_by = $viewer->id; $newBook->save(); $this->permissions->grantUserRolePermissions($viewer, ['page-create-own']); $this->permissions->regenerateForEntity($newBook); $resp = $this->actingAs($viewer)->get($page->getUrl()); $resp->assertSee($page->getUrl('/copy')); $movePageResp = $this->post($page->getUrl('/copy'), [ 'entity_selection' => 'book:' . $newBook->id, 'name' => 'My copied test page', ]); $movePageResp->assertRedirect(); $this->assertDatabaseHasEntityData('page', [ 'name' => 'My copied test page', 'created_by' => $viewer->id, 'book_id' => $newBook->id, ]); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Entity/EntityQueryTest.php
tests/Entity/EntityQueryTest.php
<?php namespace Tests\Entity; use BookStack\Entities\Models\Book; use Illuminate\Database\Eloquent\Builder; use Tests\TestCase; class EntityQueryTest extends TestCase { public function test_basic_entity_query_has_join_and_type_applied() { $query = Book::query(); $expected = 'select * from `entities` left join `entity_container_data` on `entity_container_data`.`entity_id` = `entities`.`id` and `entity_container_data`.`entity_type` = ? where `type` = ? and `entities`.`deleted_at` is null'; $this->assertEquals($expected, $query->toSql()); $this->assertEquals(['book', 'book'], $query->getBindings()); } public function test_joins_in_sub_queries_use_alias_names() { $query = Book::query()->whereHas('chapters', function (Builder $query) { $query->where('name', '=', 'a'); }); // Probably from type limits on relation where not needed? $expected = 'select * from `entities` left join `entity_container_data` on `entity_container_data`.`entity_id` = `entities`.`id` and `entity_container_data`.`entity_type` = ? where exists (select * from `entities` as `laravel_reserved_%d` left join `entity_container_data` on `entity_container_data`.`entity_id` = `laravel_reserved_%d`.`id` and `entity_container_data`.`entity_type` = ? where `entities`.`id` = `laravel_reserved_%d`.`book_id` and `name` = ? and `type` = ? and `laravel_reserved_%d`.`deleted_at` is null) and `type` = ? and `entities`.`deleted_at` is null'; $this->assertStringMatchesFormat($expected, $query->toSql()); $this->assertEquals(['book', 'chapter', 'a', 'chapter', 'book'], $query->getBindings()); } public function test_book_chapter_relation_applies_type_condition() { $book = $this->entities->book(); $query = $book->chapters(); $expected = 'select * from `entities` left join `entity_container_data` on `entity_container_data`.`entity_id` = `entities`.`id` and `entity_container_data`.`entity_type` = ? where `entities`.`book_id` = ? and `entities`.`book_id` is not null and `type` = ? and `entities`.`deleted_at` is null'; $this->assertEquals($expected, $query->toSql()); $this->assertEquals(['chapter', $book->id, 'chapter'], $query->getBindings()); $query = Book::query()->whereHas('chapters'); $expected = 'select * from `entities` left join `entity_container_data` on `entity_container_data`.`entity_id` = `entities`.`id` and `entity_container_data`.`entity_type` = ? where exists (select * from `entities` as `laravel_reserved_%d` left join `entity_container_data` on `entity_container_data`.`entity_id` = `laravel_reserved_%d`.`id` and `entity_container_data`.`entity_type` = ? where `entities`.`id` = `laravel_reserved_%d`.`book_id` and `type` = ? and `laravel_reserved_%d`.`deleted_at` is null) and `type` = ? and `entities`.`deleted_at` is null'; $this->assertStringMatchesFormat($expected, $query->toSql()); $this->assertEquals(['book', 'chapter', 'chapter', 'book'], $query->getBindings()); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Entity/PageTest.php
tests/Entity/PageTest.php
<?php namespace Tests\Entity; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Page; use BookStack\Uploads\Image; use Carbon\Carbon; use Tests\TestCase; class PageTest extends TestCase { public function test_create() { $chapter = $this->entities->chapter(); $page = Page::factory()->make([ 'name' => 'My First Page', ]); $resp = $this->asEditor()->get($chapter->getUrl()); $this->withHtml($resp)->assertElementContains('a[href="' . $chapter->getUrl('/create-page') . '"]', 'New Page'); $resp = $this->get($chapter->getUrl('/create-page')); /** @var Page $draftPage */ $draftPage = Page::query() ->where('draft', '=', true) ->orderBy('created_at', 'desc') ->first(); $resp->assertRedirect($draftPage->getUrl()); $resp = $this->get($draftPage->getUrl()); $this->withHtml($resp)->assertElementContains('form[action="' . $draftPage->getUrl() . '"][method="POST"]', 'Save Page'); $resp = $this->post($draftPage->getUrl(), $draftPage->only('name', 'html')); $draftPage->refresh(); $resp->assertRedirect($draftPage->getUrl()); } public function test_page_view_when_creator_is_deleted_but_owner_exists() { $page = $this->entities->page(); $user = $this->users->viewer(); $owner = $this->users->editor(); $page->created_by = $user->id; $page->owned_by = $owner->id; $page->save(); $user->delete(); $resp = $this->asAdmin()->get($page->getUrl()); $resp->assertStatus(200); $resp->assertSeeText('Owned by ' . $owner->name); } public function test_page_show_includes_pointer_section_select_mode_button() { $page = $this->entities->page(); $resp = $this->asEditor()->get($page->getUrl()); $this->withHtml($resp)->assertElementContains('.content-wrap button.screen-reader-only', 'Enter section select mode'); } public function test_page_creation_with_markdown_content() { $this->setSettings(['app-editor' => 'markdown']); $book = $this->entities->book(); $this->asEditor()->get($book->getUrl('/create-page')); $draft = Page::query()->where('book_id', '=', $book->id) ->where('draft', '=', true)->first(); $details = [ 'markdown' => '# a title', 'html' => '<h1>a title</h1>', 'name' => 'my page', ]; $resp = $this->post($book->getUrl("/draft/{$draft->id}"), $details); $resp->assertRedirect(); $this->assertDatabaseHasEntityData('page', [ 'markdown' => $details['markdown'], 'name' => $details['name'], 'id' => $draft->id, 'draft' => false, ]); $draft->refresh(); $resp = $this->get($draft->getUrl('/edit')); $resp->assertSee('# a title'); } public function test_page_creation_allows_summary_to_be_set() { $book = $this->entities->book(); $this->asEditor()->get($book->getUrl('/create-page')); $draft = Page::query()->where('book_id', '=', $book->id) ->where('draft', '=', true)->first(); $details = [ 'html' => '<h1>a title</h1>', 'name' => 'My page with summary', 'summary' => 'Here is my changelog message for a new page!', ]; $resp = $this->post($book->getUrl("/draft/{$draft->id}"), $details); $resp->assertRedirect(); $this->assertDatabaseHas('page_revisions', [ 'page_id' => $draft->id, 'summary' => 'Here is my changelog message for a new page!', ]); $draft->refresh(); $resp = $this->get($draft->getUrl('/revisions')); $resp->assertSee('Here is my changelog message for a new page!'); } public function test_page_delete() { $page = $this->entities->page(); $this->assertNull($page->deleted_at); $deleteViewReq = $this->asEditor()->get($page->getUrl('/delete')); $deleteViewReq->assertSeeText('Are you sure you want to delete this page?'); $deleteReq = $this->delete($page->getUrl()); $deleteReq->assertRedirect($page->getParent()->getUrl()); $this->assertActivityExists('page_delete', $page); $page->refresh(); $this->assertNotNull($page->deleted_at); $this->assertTrue($page->deletions()->count() === 1); $redirectReq = $this->get($deleteReq->baseResponse->headers->get('location')); $this->assertNotificationContains($redirectReq, 'Page Successfully Deleted'); } public function test_page_full_delete_removes_all_revisions() { $page = $this->entities->page(); $page->revisions()->create([ 'html' => '<p>ducks</p>', 'name' => 'my page revision', 'type' => 'draft', ]); $page->revisions()->create([ 'html' => '<p>ducks</p>', 'name' => 'my page revision', 'type' => 'revision', ]); $this->assertDatabaseHas('page_revisions', [ 'page_id' => $page->id, ]); $this->asEditor()->delete($page->getUrl()); $this->asAdmin()->post('/settings/recycle-bin/empty'); $this->assertDatabaseMissing('page_revisions', [ 'page_id' => $page->id, ]); } public function test_page_full_delete_nulls_related_images() { $page = $this->entities->page(); $image = Image::factory()->create(['type' => 'gallery', 'uploaded_to' => $page->id]); $this->asEditor()->delete($page->getUrl()); $this->asAdmin()->post('/settings/recycle-bin/empty'); $this->assertDatabaseMissing('images', [ 'type' => 'gallery', 'uploaded_to' => $page->id, ]); $this->assertDatabaseHas('images', [ 'id' => $image->id, 'uploaded_to' => null, ]); } public function test_page_within_chapter_deletion_returns_to_chapter() { $chapter = $this->entities->chapter(); $page = $chapter->pages()->first(); $this->asEditor()->delete($page->getUrl()) ->assertRedirect($chapter->getUrl()); } public function test_recently_updated_pages_view() { $user = $this->users->editor(); $content = $this->entities->createChainBelongingToUser($user); $resp = $this->asAdmin()->get('/pages/recently-updated'); $this->withHtml($resp)->assertElementContains('.entity-list .page:nth-child(1)', $content['page']->name); } public function test_recently_updated_pages_view_shows_updated_by_details() { $user = $this->users->editor(); $page = $this->entities->page(); $this->actingAs($user)->put($page->getUrl(), [ 'name' => 'Updated title', 'html' => '<p>Updated content</p>', ]); $resp = $this->asAdmin()->get('/pages/recently-updated'); $this->withHtml($resp)->assertElementContains('.entity-list .page:nth-child(1) small', 'by ' . $user->name); } public function test_recently_updated_pages_view_shows_parent_chain() { $user = $this->users->editor(); $page = $this->entities->pageWithinChapter(); $this->actingAs($user)->put($page->getUrl(), [ 'name' => 'Updated title', 'html' => '<p>Updated content</p>', ]); $resp = $this->asAdmin()->get('/pages/recently-updated'); $this->withHtml($resp)->assertElementContains('.entity-list .page:nth-child(1)', $page->chapter->getShortName(42)); $this->withHtml($resp)->assertElementContains('.entity-list .page:nth-child(1)', $page->book->getShortName(42)); } public function test_recently_updated_pages_view_does_not_show_parent_if_not_visible() { $user = $this->users->editor(); $page = $this->entities->pageWithinChapter(); $this->actingAs($user)->put($page->getUrl(), [ 'name' => 'Updated title', 'html' => '<p>Updated content</p>', ]); $this->permissions->setEntityPermissions($page->book); $this->permissions->setEntityPermissions($page, ['view'], [$user->roles->first()]); $resp = $this->get('/pages/recently-updated'); $resp->assertDontSee($page->book->getShortName(42)); $resp->assertDontSee($page->chapter->getShortName(42)); $this->withHtml($resp)->assertElementContains('.entity-list .page:nth-child(1)', 'Updated title'); } public function test_recently_updated_pages_on_home() { /** @var Page $page */ $page = Page::query()->orderBy('updated_at', 'asc')->first(); Page::query()->where('id', '!=', $page->id)->update([ 'updated_at' => Carbon::now()->subSecond(1), ]); $resp = $this->asAdmin()->get('/'); $this->withHtml($resp)->assertElementNotContains('#recently-updated-pages', $page->name); $this->put($page->getUrl(), [ 'name' => $page->name, 'html' => $page->html, ]); $resp = $this->get('/'); $this->withHtml($resp)->assertElementContains('#recently-updated-pages', $page->name); } public function test_page_edit_without_update_permissions_but_with_view_redirects_to_page() { $page = $this->entities->page(); $resp = $this->asViewer()->get($page->getUrl('/edit')); $resp->assertRedirect($page->getUrl()); $resp->assertSessionHas('error', 'You do not have permission to access the requested page.'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Entity/DefaultTemplateTest.php
tests/Entity/DefaultTemplateTest.php
<?php namespace Tests\Entity; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Chapter; use BookStack\Entities\Models\Page; use Tests\TestCase; class DefaultTemplateTest extends TestCase { public function test_creating_book_with_default_template() { $templatePage = $this->entities->templatePage(); $details = [ 'name' => 'My book with default template', 'default_template_id' => $templatePage->id, ]; $this->asEditor()->post('/books', $details); $this->assertDatabaseHasEntityData('book', $details); } public function test_creating_chapter_with_default_template() { $templatePage = $this->entities->templatePage(); $book = $this->entities->book(); $details = [ 'name' => 'My chapter with default template', 'default_template_id' => $templatePage->id, ]; $this->asEditor()->post($book->getUrl('/create-chapter'), $details); $this->assertDatabaseHasEntityData('chapter', $details); } public function test_updating_book_with_default_template() { $book = $this->entities->book(); $templatePage = $this->entities->templatePage(); $this->asEditor()->put($book->getUrl(), ['name' => $book->name, 'default_template_id' => strval($templatePage->id)]); $this->assertDatabaseHasEntityData('book', ['id' => $book->id, 'default_template_id' => $templatePage->id]); $this->asEditor()->put($book->getUrl(), ['name' => $book->name, 'default_template_id' => '']); $this->assertDatabaseHasEntityData('book', ['id' => $book->id, 'default_template_id' => null]); } public function test_updating_chapter_with_default_template() { $chapter = $this->entities->chapter(); $templatePage = $this->entities->templatePage(); $this->asEditor()->put($chapter->getUrl(), ['name' => $chapter->name, 'default_template_id' => strval($templatePage->id)]); $this->assertDatabaseHasEntityData('chapter', ['id' => $chapter->id, 'default_template_id' => $templatePage->id]); $this->asEditor()->put($chapter->getUrl(), ['name' => $chapter->name, 'default_template_id' => '']); $this->assertDatabaseHasEntityData('chapter', ['id' => $chapter->id, 'default_template_id' => null]); } public function test_default_book_template_cannot_be_set_if_not_a_template() { $book = $this->entities->book(); $page = $this->entities->page(); $this->assertFalse($page->template); $this->asEditor()->put("/books/{$book->slug}", ['name' => $book->name, 'default_template_id' => $page->id]); $this->assertDatabaseHasEntityData('book', ['id' => $book->id, 'default_template_id' => null]); } public function test_default_chapter_template_cannot_be_set_if_not_a_template() { $chapter = $this->entities->chapter(); $page = $this->entities->page(); $this->assertFalse($page->template); $this->asEditor()->put("/chapters/{$chapter->slug}", ['name' => $chapter->name, 'default_template_id' => $page->id]); $this->assertDatabaseHasEntityData('chapter', ['id' => $chapter->id, 'default_template_id' => null]); } public function test_default_book_template_cannot_be_set_if_not_have_access() { $book = $this->entities->book(); $templatePage = $this->entities->templatePage(); $this->permissions->disableEntityInheritedPermissions($templatePage); $this->asEditor()->put("/books/{$book->slug}", ['name' => $book->name, 'default_template_id' => $templatePage->id]); $this->assertDatabaseHasEntityData('book', ['id' => $book->id, 'default_template_id' => null]); } public function test_default_chapter_template_cannot_be_set_if_not_have_access() { $chapter = $this->entities->chapter(); $templatePage = $this->entities->templatePage(); $this->permissions->disableEntityInheritedPermissions($templatePage); $this->asEditor()->put("/chapters/{$chapter->slug}", ['name' => $chapter->name, 'default_template_id' => $templatePage->id]); $this->assertDatabaseHasEntityData('chapter', ['id' => $chapter->id, 'default_template_id' => null]); } public function test_inaccessible_book_default_template_can_be_set_if_unchanged() { $templatePage = $this->entities->templatePage(); $book = $this->bookUsingDefaultTemplate($templatePage); $this->permissions->disableEntityInheritedPermissions($templatePage); $this->asEditor()->put("/books/{$book->slug}", ['name' => $book->name, 'default_template_id' => $templatePage->id]); $this->assertDatabaseHasEntityData('book', ['id' => $book->id, 'default_template_id' => $templatePage->id]); } public function test_inaccessible_chapter_default_template_can_be_set_if_unchanged() { $templatePage = $this->entities->templatePage(); $chapter = $this->chapterUsingDefaultTemplate($templatePage); $this->permissions->disableEntityInheritedPermissions($templatePage); $this->asEditor()->put("/chapters/{$chapter->slug}", ['name' => $chapter->name, 'default_template_id' => $templatePage->id]); $this->assertDatabaseHasEntityData('chapter', ['id' => $chapter->id, 'default_template_id' => $templatePage->id]); } public function test_default_page_template_option_shows_on_book_form() { $templatePage = $this->entities->templatePage(); $book = $this->bookUsingDefaultTemplate($templatePage); $resp = $this->asEditor()->get($book->getUrl('/edit')); $this->withHtml($resp)->assertElementExists('input[name="default_template_id"][value="' . $templatePage->id . '"]'); } public function test_default_page_template_option_shows_on_chapter_form() { $templatePage = $this->entities->templatePage(); $chapter = $this->chapterUsingDefaultTemplate($templatePage); $resp = $this->asEditor()->get($chapter->getUrl('/edit')); $this->withHtml($resp)->assertElementExists('input[name="default_template_id"][value="' . $templatePage->id . '"]'); } public function test_book_default_page_template_option_only_shows_template_name_if_visible() { $templatePage = $this->entities->templatePage(); $book = $this->bookUsingDefaultTemplate($templatePage); $resp = $this->asEditor()->get($book->getUrl('/edit')); $this->withHtml($resp)->assertElementContains('#template-control a.text-page', "#{$templatePage->id}, {$templatePage->name}"); $this->permissions->disableEntityInheritedPermissions($templatePage); $resp = $this->asEditor()->get($book->getUrl('/edit')); $this->withHtml($resp)->assertElementNotContains('#template-control a.text-page', "#{$templatePage->id}, {$templatePage->name}"); $this->withHtml($resp)->assertElementContains('#template-control a.text-page', "#{$templatePage->id}"); } public function test_chapter_default_page_template_option_only_shows_template_name_if_visible() { $templatePage = $this->entities->templatePage(); $chapter = $this->chapterUsingDefaultTemplate($templatePage); $resp = $this->asEditor()->get($chapter->getUrl('/edit')); $this->withHtml($resp)->assertElementContains('#template-control a.text-page', "#{$templatePage->id}, {$templatePage->name}"); $this->permissions->disableEntityInheritedPermissions($templatePage); $resp = $this->asEditor()->get($chapter->getUrl('/edit')); $this->withHtml($resp)->assertElementNotContains('#template-control a.text-page', "#{$templatePage->id}, {$templatePage->name}"); $this->withHtml($resp)->assertElementContains('#template-control a.text-page', "#{$templatePage->id}"); } public function test_creating_book_page_uses_book_default_template() { $templatePage = $this->entities->templatePage(); $templatePage->forceFill(['html' => '<p>My template page</p>', 'markdown' => '# My template page'])->save(); $book = $this->bookUsingDefaultTemplate($templatePage); $this->asEditor()->get($book->getUrl('/create-page'))->assertRedirect(); $latestPage = $book->pages() ->where('draft', '=', true) ->where('template', '=', false) ->latest()->first(); $this->assertEquals('<p>My template page</p>', $latestPage->html); $this->assertEquals('# My template page', $latestPage->markdown); } public function test_creating_chapter_page_uses_chapter_default_template() { $templatePage = $this->entities->templatePage(); $templatePage->forceFill(['html' => '<p>My chapter template page</p>', 'markdown' => '# My chapter template page'])->save(); $chapter = $this->chapterUsingDefaultTemplate($templatePage); $this->asEditor()->get($chapter->getUrl('/create-page')); $latestPage = $chapter->pages() ->where('draft', '=', true) ->where('template', '=', false) ->latest()->first(); $this->assertEquals('<p>My chapter template page</p>', $latestPage->html); $this->assertEquals('# My chapter template page', $latestPage->markdown); } public function test_creating_chapter_page_uses_book_default_template_if_no_chapter_template_set() { $templatePage = $this->entities->templatePage(); $templatePage->forceFill(['html' => '<p>My template page in chapter</p>', 'markdown' => '# My template page in chapter'])->save(); $book = $this->bookUsingDefaultTemplate($templatePage); $chapter = $book->chapters()->first(); $this->asEditor()->get($chapter->getUrl('/create-page')); $latestPage = $chapter->pages() ->where('draft', '=', true) ->where('template', '=', false) ->latest()->first(); $this->assertEquals('<p>My template page in chapter</p>', $latestPage->html); $this->assertEquals('# My template page in chapter', $latestPage->markdown); } public function test_creating_chapter_page_uses_chapter_template_instead_of_book_template() { $bookTemplatePage = $this->entities->templatePage(); $bookTemplatePage->forceFill(['html' => '<p>My book template</p>', 'markdown' => '# My book template'])->save(); $book = $this->bookUsingDefaultTemplate($bookTemplatePage); $chapterTemplatePage = $this->entities->templatePage(); $chapterTemplatePage->forceFill(['html' => '<p>My chapter template</p>', 'markdown' => '# My chapter template'])->save(); $chapter = $book->chapters()->first(); $chapter->default_template_id = $chapterTemplatePage->id; $chapter->save(); $this->asEditor()->get($chapter->getUrl('/create-page')); $latestPage = $chapter->pages() ->where('draft', '=', true) ->where('template', '=', false) ->latest()->first(); $this->assertEquals('<p>My chapter template</p>', $latestPage->html); $this->assertEquals('# My chapter template', $latestPage->markdown); } public function test_creating_page_as_guest_uses_default_template() { $templatePage = $this->entities->templatePage(); $templatePage->forceFill(['html' => '<p>My template page</p>', 'markdown' => '# My template page'])->save(); $book = $this->bookUsingDefaultTemplate($templatePage); $chapter = $this->chapterUsingDefaultTemplate($templatePage); $guest = $this->users->guest(); $this->permissions->makeAppPublic(); $this->permissions->grantUserRolePermissions($guest, ['page-create-all', 'page-update-all']); $this->post($book->getUrl('/create-guest-page'), [ 'name' => 'My guest page with template' ])->assertRedirect(); $latestBookPage = $book->pages() ->where('draft', '=', false) ->where('template', '=', false) ->where('created_by', '=', $guest->id) ->latest()->first(); $this->assertEquals('<p>My template page</p>', $latestBookPage->html); $this->assertEquals('# My template page', $latestBookPage->markdown); $this->post($chapter->getUrl('/create-guest-page'), [ 'name' => 'My guest page with template' ]); $latestChapterPage = $chapter->pages() ->where('draft', '=', false) ->where('template', '=', false) ->where('created_by', '=', $guest->id) ->latest()->first(); $this->assertEquals('<p>My template page</p>', $latestChapterPage->html); $this->assertEquals('# My template page', $latestChapterPage->markdown); } public function test_templates_not_used_if_not_visible() { $templatePage = $this->entities->templatePage(); $templatePage->forceFill(['html' => '<p>My template page</p>', 'markdown' => '# My template page'])->save(); $book = $this->bookUsingDefaultTemplate($templatePage); $chapter = $this->chapterUsingDefaultTemplate($templatePage); $this->permissions->disableEntityInheritedPermissions($templatePage); $this->asEditor()->get($book->getUrl('/create-page')); $latestBookPage = $book->pages() ->where('draft', '=', true) ->where('template', '=', false) ->latest()->first(); $this->assertEquals('', $latestBookPage->html); $this->assertEquals('', $latestBookPage->markdown); $this->asEditor()->get($chapter->getUrl('/create-page')); $latestChapterPage = $chapter->pages() ->where('draft', '=', true) ->where('template', '=', false) ->latest()->first(); $this->assertEquals('', $latestChapterPage->html); $this->assertEquals('', $latestChapterPage->markdown); } public function test_template_page_delete_removes_template_usage() { $templatePage = $this->entities->templatePage(); $book = $this->bookUsingDefaultTemplate($templatePage); $chapter = $this->chapterUsingDefaultTemplate($templatePage); $book->refresh(); $this->assertEquals($templatePage->id, $book->default_template_id); $this->assertEquals($templatePage->id, $chapter->default_template_id); $this->asEditor()->delete($templatePage->getUrl()); $this->asAdmin()->post('/settings/recycle-bin/empty'); $book->refresh(); $chapter->refresh(); $this->assertEquals(null, $book->default_template_id); $this->assertEquals(null, $chapter->default_template_id); } protected function bookUsingDefaultTemplate(Page $page): Book { $book = $this->entities->book(); $book->default_template_id = $page->id; $book->save(); return $book; } protected function chapterUsingDefaultTemplate(Page $page): Chapter { $chapter = $this->entities->chapter(); $chapter->default_template_id = $page->id; $chapter->save(); return $chapter; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Activity/CommentMentionTest.php
tests/Activity/CommentMentionTest.php
<?php namespace Tests\Activity; use BookStack\Activity\Notifications\Messages\CommentMentionNotification; use BookStack\Permissions\Permission; use Illuminate\Support\Facades\Notification; use Tests\TestCase; class CommentMentionTest extends TestCase { public function test_mentions_are_notified() { $userToMention = $this->users->viewer(); $this->permissions->grantUserRolePermissions($userToMention, [Permission::ReceiveNotifications]); $editor = $this->users->editor(); $page = $this->entities->pageWithinChapter(); $notifications = Notification::fake(); $this->actingAs($editor)->post("/comment/{$page->id}", [ 'html' => '<p>Hello <a data-mention-user-id="' . $userToMention->id . '">@user</a></p>' ])->assertOk(); $notifications->assertSentTo($userToMention, function (CommentMentionNotification $notification) use ($userToMention, $editor, $page) { $mail = $notification->toMail($userToMention); $mailContent = html_entity_decode(strip_tags($mail->render()), ENT_QUOTES); $subjectPrefix = 'You have been mentioned in a comment on page: ' . mb_substr($page->name, 0, 20); return str_starts_with($mail->subject, $subjectPrefix) && str_contains($mailContent, 'View Comment') && str_contains($mailContent, 'Page Name: ' . $page->name) && str_contains($mailContent, 'Page Path: ' . $page->book->getShortName(24) . ' > ' . $page->chapter->getShortName(24)) && str_contains($mailContent, 'Commenter: ' . $editor->name) && str_contains($mailContent, 'Comment: Hello @user'); }); } public function test_mentions_are_not_notified_if_mentioned_by_same_user() { $editor = $this->users->editor(); $this->permissions->grantUserRolePermissions($editor, [Permission::ReceiveNotifications]); $page = $this->entities->page(); $notifications = Notification::fake(); $this->actingAs($editor)->post("/comment/{$page->id}", [ 'html' => '<p>Hello <a data-mention-user-id="' . $editor->id . '"></a></p>' ])->assertOk(); $notifications->assertNothingSent(); } public function test_mentions_are_logged_to_the_database_even_if_not_notified() { $editor = $this->users->editor(); $otherUser = $this->users->viewer(); $this->permissions->grantUserRolePermissions($editor, [Permission::ReceiveNotifications]); $page = $this->entities->page(); $notifications = Notification::fake(); $this->actingAs($editor)->post("/comment/{$page->id}", [ 'html' => '<p>Hello <a data-mention-user-id="' . $editor->id . '"></a> and <a data-mention-user-id="' . $otherUser->id . '"></a></p>' ])->assertOk(); $notifications->assertNothingSent(); $comment = $page->comments()->latest()->first(); $this->assertDatabaseHas('mention_history', [ 'mentionable_id' => $comment->id, 'mentionable_type' => 'comment', 'from_user_id' => $editor->id, 'to_user_id' => $otherUser->id, ]); $this->assertDatabaseHas('mention_history', [ 'mentionable_id' => $comment->id, 'mentionable_type' => 'comment', 'from_user_id' => $editor->id, 'to_user_id' => $editor->id, ]); } public function test_comment_updates_will_send_notifications_only_if_mention_is_new() { $userToMention = $this->users->viewer(); $this->permissions->grantUserRolePermissions($userToMention, [Permission::ReceiveNotifications]); $editor = $this->users->editor(); $this->permissions->grantUserRolePermissions($editor, [Permission::CommentUpdateOwn]); $page = $this->entities->page(); $notifications = Notification::fake(); $this->actingAs($editor)->post("/comment/{$page->id}", [ 'html' => '<p>Hello there</p>' ])->assertOk(); $comment = $page->comments()->latest()->first(); $notifications->assertNothingSent(); $this->put("/comment/{$comment->id}", [ 'html' => '<p>Hello <a data-mention-user-id="' . $userToMention->id . '"></a></p>' ])->assertOk(); $notifications->assertSentTo($userToMention, CommentMentionNotification::class); $notifications->assertCount(1); $this->put("/comment/{$comment->id}", [ 'html' => '<p>Hello again<a data-mention-user-id="' . $userToMention->id . '"></a></p>' ])->assertOk(); $notifications->assertCount(1); } public function test_notification_limited_to_those_with_view_permissions() { $userA = $this->users->newUser(); $userB = $this->users->newUser(); $this->permissions->grantUserRolePermissions($userA, [Permission::ReceiveNotifications]); $this->permissions->grantUserRolePermissions($userB, [Permission::ReceiveNotifications]); $notifications = Notification::fake(); $page = $this->entities->page(); $this->permissions->disableEntityInheritedPermissions($page); $this->permissions->addEntityPermission($page, ['view'], $userA->roles()->first()); $this->asAdmin()->post("/comment/{$page->id}", [ 'html' => '<p>Hello <a data-mention-user-id="' . $userA->id . '"></a> and <a data-mention-user-id="' . $userB->id . '"></a></p>' ])->assertOk(); $notifications->assertCount(1); $notifications->assertSentTo($userA, CommentMentionNotification::class); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Activity/MentionParserTest.php
tests/Activity/MentionParserTest.php
<?php namespace Tests\Activity; use BookStack\Activity\Tools\MentionParser; use Tests\TestCase; class MentionParserTest extends TestCase { public function test_it_extracts_mentions() { $parser = new MentionParser(); // Test basic mention extraction $html = '<p>Hello <a href="/user/5" data-mention-user-id="5">@User</a></p>'; $result = $parser->parseUserIdsFromHtml($html); $this->assertEquals([5], $result); // Test multiple mentions $html = '<p><a data-mention-user-id="1">@Alice</a> and <a data-mention-user-id="2">@Bob</a></p>'; $result = $parser->parseUserIdsFromHtml($html); $this->assertEquals([1, 2], $result); // Test filtering out invalid IDs (zero and negative) $html = '<p><a data-mention-user-id="0">@Invalid</a> <a data-mention-user-id="-5">@Negative</a> <a data-mention-user-id="3">@Valid</a></p>'; $result = $parser->parseUserIdsFromHtml($html); $this->assertEquals([3], $result); // Test non-mention links are ignored $html = '<p><a href="/page/1">Normal Link</a> <a data-mention-user-id="7">@User</a></p>'; $result = $parser->parseUserIdsFromHtml($html); $this->assertEquals([7], $result); // Test empty HTML $result = $parser->parseUserIdsFromHtml(''); $this->assertEquals([], $result); // Test duplicate user IDs $html = '<p><a data-mention-user-id="4">@User</a> mentioned <a data-mention-user-id="4">@User</a> again</p>'; $result = $parser->parseUserIdsFromHtml($html); $this->assertEquals([4], $result); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Activity/WebhookManagementTest.php
tests/Activity/WebhookManagementTest.php
<?php namespace Tests\Activity; use BookStack\Activity\ActivityType; use BookStack\Activity\Models\Webhook; use Tests\TestCase; class WebhookManagementTest extends TestCase { public function test_index_view() { $webhook = $this->newWebhook([ 'name' => 'My awesome webhook', 'endpoint' => 'https://example.com/donkey/webhook', ], ['all']); $resp = $this->asAdmin()->get('/settings/webhooks'); $resp->assertOk(); $this->withHtml($resp)->assertElementContains('a[href$="/settings/webhooks/create"]', 'Create New Webhook'); $this->withHtml($resp)->assertElementContains('a[href="' . $webhook->getUrl() . '"]', $webhook->name); $resp->assertSee($webhook->endpoint); $resp->assertSee('All system events'); $resp->assertSee('Active'); } public function test_create_view() { $resp = $this->asAdmin()->get('/settings/webhooks/create'); $resp->assertOk(); $resp->assertSee('Create New Webhook'); $this->withHtml($resp)->assertElementContains('form[action$="/settings/webhooks/create"] button', 'Save Webhook'); } public function test_store() { $resp = $this->asAdmin()->post('/settings/webhooks/create', [ 'name' => 'My first webhook', 'endpoint' => 'https://example.com/webhook', 'events' => ['all'], 'active' => 'true', 'timeout' => 4, ]); $resp->assertRedirect('/settings/webhooks'); $this->assertActivityExists(ActivityType::WEBHOOK_CREATE); $resp = $this->followRedirects($resp); $resp->assertSee('Webhook successfully created'); $this->assertDatabaseHas('webhooks', [ 'name' => 'My first webhook', 'endpoint' => 'https://example.com/webhook', 'active' => true, 'timeout' => 4, ]); /** @var Webhook $webhook */ $webhook = Webhook::query()->where('name', '=', 'My first webhook')->first(); $this->assertDatabaseHas('webhook_tracked_events', [ 'webhook_id' => $webhook->id, 'event' => 'all', ]); } public function test_edit_view() { $webhook = $this->newWebhook(); $resp = $this->asAdmin()->get('/settings/webhooks/' . $webhook->id); $resp->assertOk(); $resp->assertSee('Edit Webhook'); $this->withHtml($resp)->assertElementContains('form[action="' . $webhook->getUrl() . '"] button', 'Save Webhook'); $this->withHtml($resp)->assertElementContains('a[href="' . $webhook->getUrl('/delete') . '"]', 'Delete Webhook'); $this->withHtml($resp)->assertElementExists('input[type="checkbox"][value="all"][name="events[]"]'); } public function test_update() { $webhook = $this->newWebhook(); $resp = $this->asAdmin()->put('/settings/webhooks/' . $webhook->id, [ 'name' => 'My updated webhook', 'endpoint' => 'https://example.com/updated-webhook', 'events' => [ActivityType::PAGE_CREATE, ActivityType::PAGE_UPDATE], 'active' => 'true', 'timeout' => 5, ]); $resp->assertRedirect('/settings/webhooks'); $resp = $this->followRedirects($resp); $resp->assertSee('Webhook successfully updated'); $this->assertDatabaseHas('webhooks', [ 'id' => $webhook->id, 'name' => 'My updated webhook', 'endpoint' => 'https://example.com/updated-webhook', 'active' => true, 'timeout' => 5, ]); $trackedEvents = $webhook->trackedEvents()->get(); $this->assertCount(2, $trackedEvents); $this->assertEquals(['page_create', 'page_update'], $trackedEvents->pluck('event')->values()->all()); $this->assertActivityExists(ActivityType::WEBHOOK_UPDATE); } public function test_delete_view() { $webhook = $this->newWebhook(['name' => 'Webhook to delete']); $resp = $this->asAdmin()->get('/settings/webhooks/' . $webhook->id . '/delete'); $resp->assertOk(); $resp->assertSee('Delete Webhook'); $resp->assertSee('This will fully delete this webhook, with the name \'Webhook to delete\', from the system.'); $this->withHtml($resp)->assertElementContains('form[action$="/settings/webhooks/' . $webhook->id . '"]', 'Delete'); } public function test_destroy() { $webhook = $this->newWebhook(); $resp = $this->asAdmin()->delete('/settings/webhooks/' . $webhook->id); $resp->assertRedirect('/settings/webhooks'); $resp = $this->followRedirects($resp); $resp->assertSee('Webhook successfully deleted'); $this->assertDatabaseMissing('webhooks', ['id' => $webhook->id]); $this->assertDatabaseMissing('webhook_tracked_events', ['webhook_id' => $webhook->id]); $this->assertActivityExists(ActivityType::WEBHOOK_DELETE); } public function test_settings_manage_permission_required_for_webhook_routes() { $editor = $this->users->editor(); $this->actingAs($editor); $routes = [ ['GET', '/settings/webhooks'], ['GET', '/settings/webhooks/create'], ['POST', '/settings/webhooks/create'], ['GET', '/settings/webhooks/1'], ['PUT', '/settings/webhooks/1'], ['DELETE', '/settings/webhooks/1'], ['GET', '/settings/webhooks/1/delete'], ]; foreach ($routes as [$method, $endpoint]) { $resp = $this->call($method, $endpoint); $this->assertPermissionError($resp); } $this->permissions->grantUserRolePermissions($editor, ['settings-manage']); foreach ($routes as [$method, $endpoint]) { $resp = $this->call($method, $endpoint); $this->assertNotPermissionError($resp); } } protected function newWebhook(array $attrs = [], array $events = ['all']): Webhook { /** @var Webhook $webhook */ $webhook = Webhook::factory()->create($attrs); foreach ($events as $event) { $webhook->trackedEvents()->create(['event' => $event]); } return $webhook; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Activity/CommentSettingTest.php
tests/Activity/CommentSettingTest.php
<?php namespace Tests\Activity; use Tests\TestCase; class CommentSettingTest extends TestCase { public function test_comment_disable() { $page = $this->entities->page(); $this->setSettings(['app-disable-comments' => 'true']); $this->asAdmin(); $resp = $this->asAdmin()->get($page->getUrl()); $this->withHtml($resp)->assertElementNotExists('.comments-list'); } public function test_comment_enable() { $page = $this->entities->page(); $this->setSettings(['app-disable-comments' => 'false']); $this->asAdmin(); $resp = $this->asAdmin()->get($page->getUrl()); $this->withHtml($resp)->assertElementExists('.comments-list'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Activity/WebhookCallTest.php
tests/Activity/WebhookCallTest.php
<?php namespace Tests\Activity; use BookStack\Activity\ActivityType; use BookStack\Activity\DispatchWebhookJob; use BookStack\Activity\Models\Webhook; use BookStack\Activity\Tools\ActivityLogger; use BookStack\Api\ApiToken; use BookStack\Users\Models\User; use GuzzleHttp\Exception\ConnectException; use GuzzleHttp\Psr7\Response; use Illuminate\Support\Facades\Bus; use Tests\TestCase; class WebhookCallTest extends TestCase { public function test_webhook_listening_to_all_called_on_event() { $this->newWebhook([], ['all']); Bus::fake(); $this->runEvent(ActivityType::ROLE_CREATE); Bus::assertDispatched(DispatchWebhookJob::class); } public function test_webhook_listening_to_specific_event_called_on_event() { $this->newWebhook([], [ActivityType::ROLE_UPDATE]); Bus::fake(); $this->runEvent(ActivityType::ROLE_UPDATE); Bus::assertDispatched(DispatchWebhookJob::class); } public function test_webhook_listening_to_specific_event_not_called_on_other_event() { $this->newWebhook([], [ActivityType::ROLE_UPDATE]); Bus::fake(); $this->runEvent(ActivityType::ROLE_CREATE); Bus::assertNotDispatched(DispatchWebhookJob::class); } public function test_inactive_webhook_not_called_on_event() { $this->newWebhook(['active' => false], ['all']); Bus::fake(); $this->runEvent(ActivityType::ROLE_CREATE); Bus::assertNotDispatched(DispatchWebhookJob::class); } public function test_webhook_runs_for_delete_actions() { // This test must not fake the queue/bus since this covers an issue // around handling and serialization of items now deleted from the database. $webhook = $this->newWebhook(['active' => true, 'endpoint' => 'https://wh.example.com'], ['all']); $this->mockHttpClient([new Response(500)]); $user = $this->users->newUser(); $resp = $this->asAdmin()->delete($user->getEditUrl()); $resp->assertRedirect('/settings/users'); /** @var ApiToken $apiToken */ $editor = $this->users->editor(); $apiToken = ApiToken::factory()->create(['user_id' => $editor]); $this->delete($apiToken->getUrl())->assertRedirect(); $webhook->refresh(); $this->assertEquals('Response status from endpoint was 500', $webhook->last_error); } public function test_failed_webhook_call_logs_error() { $logger = $this->withTestLogger(); $this->mockHttpClient([new Response(500)]); $webhook = $this->newWebhook(['active' => true, 'endpoint' => 'https://wh.example.com'], ['all']); $this->assertNull($webhook->last_errored_at); $this->runEvent(ActivityType::ROLE_CREATE); $this->assertTrue($logger->hasError('Webhook call to endpoint https://wh.example.com failed with status 500')); $webhook->refresh(); $this->assertEquals('Response status from endpoint was 500', $webhook->last_error); $this->assertNotNull($webhook->last_errored_at); } public function test_webhook_call_exception_is_caught_and_logged() { $this->mockHttpClient([new ConnectException('Failed to perform request', new \GuzzleHttp\Psr7\Request('GET', ''))]); $logger = $this->withTestLogger(); $webhook = $this->newWebhook(['active' => true, 'endpoint' => 'https://wh.example.com'], ['all']); $this->assertNull($webhook->last_errored_at); $this->runEvent(ActivityType::ROLE_CREATE); $this->assertTrue($logger->hasError('Webhook call to endpoint https://wh.example.com failed with error "Failed to perform request"')); $webhook->refresh(); $this->assertEquals('Failed to perform request', $webhook->last_error); $this->assertNotNull($webhook->last_errored_at); } public function test_webhook_uses_ssr_hosts_option_if_set() { config()->set('app.ssr_hosts', 'https://*.example.com'); $responses = $this->mockHttpClient(); $webhook = $this->newWebhook(['active' => true, 'endpoint' => 'https://wh.example.co.uk'], ['all']); $this->runEvent(ActivityType::ROLE_CREATE); $this->assertEquals(0, $responses->requestCount()); $webhook->refresh(); $this->assertEquals('The URL does not match the configured allowed SSR hosts', $webhook->last_error); $this->assertNotNull($webhook->last_errored_at); } public function test_webhook_call_data_format() { $responses = $this->mockHttpClient([new Response(200, [], '')]); $webhook = $this->newWebhook(['active' => true, 'endpoint' => 'https://wh.example.com'], ['all']); $page = $this->entities->page(); $editor = $this->users->editor(); $this->runEvent(ActivityType::PAGE_UPDATE, $page, $editor); $request = $responses->latestRequest(); $reqData = json_decode($request->getBody(), true); $this->assertEquals('page_update', $reqData['event']); $this->assertEquals(($editor->name . ' updated page "' . $page->name . '"'), $reqData['text']); $this->assertIsString($reqData['triggered_at']); $this->assertEquals($editor->name, $reqData['triggered_by']['name']); $this->assertEquals($editor->getProfileUrl(), $reqData['triggered_by_profile_url']); $this->assertEquals($webhook->id, $reqData['webhook_id']); $this->assertEquals($webhook->name, $reqData['webhook_name']); $this->assertEquals($page->getUrl(), $reqData['url']); $this->assertEquals($page->name, $reqData['related_item']['name']); } protected function runEvent(string $event, $detail = '', ?User $user = null) { if (is_null($user)) { $user = $this->users->editor(); } $this->actingAs($user); $activityLogger = $this->app->make(ActivityLogger::class); $activityLogger->add($event, $detail); } protected function newWebhook(array $attrs, array $events): Webhook { /** @var Webhook $webhook */ $webhook = Webhook::factory()->create($attrs); foreach ($events as $event) { $webhook->trackedEvents()->create(['event' => $event]); } return $webhook; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Activity/CommentsApiTest.php
tests/Activity/CommentsApiTest.php
<?php namespace Tests\Activity; use BookStack\Activity\Models\Comment; use BookStack\Permissions\Permission; use Tests\Api\TestsApi; use Tests\TestCase; class CommentsApiTest extends TestCase { use TestsApi; public function test_endpoint_permission_controls() { $user = $this->users->editor(); $this->permissions->grantUserRolePermissions($user, [Permission::CommentDeleteAll, Permission::CommentUpdateAll]); $page = $this->entities->page(); $comment = Comment::factory()->make(); $page->comments()->save($comment); $this->actingAsForApi($user); $actions = [ ['GET', '/api/comments'], ['GET', "/api/comments/{$comment->id}"], ['POST', "/api/comments"], ['PUT', "/api/comments/{$comment->id}"], ['DELETE', "/api/comments/{$comment->id}"], ]; foreach ($actions as [$method, $endpoint]) { $resp = $this->call($method, $endpoint); $this->assertNotPermissionError($resp); } $comment = Comment::factory()->make(); $page->comments()->save($comment); $this->getJson("/api/comments")->assertSee(['id' => $comment->id]); $this->permissions->removeUserRolePermissions($user, [ Permission::CommentDeleteAll, Permission::CommentDeleteOwn, Permission::CommentUpdateAll, Permission::CommentUpdateOwn, Permission::CommentCreateAll ]); $this->assertPermissionError($this->json('delete', "/api/comments/{$comment->id}")); $this->assertPermissionError($this->json('put', "/api/comments/{$comment->id}")); $this->assertPermissionError($this->json('post', "/api/comments")); $this->assertNotPermissionError($this->json('get', "/api/comments/{$comment->id}")); $this->permissions->disableEntityInheritedPermissions($page); $this->json('get', "/api/comments/{$comment->id}")->assertStatus(404); $this->getJson("/api/comments")->assertDontSee(['id' => $comment->id]); } public function test_index() { $page = $this->entities->page(); Comment::query()->delete(); $comments = Comment::factory()->count(10)->make(); $page->comments()->saveMany($comments); $firstComment = $comments->first(); $resp = $this->actingAsApiEditor()->getJson('/api/comments'); $resp->assertJson([ 'data' => [ [ 'id' => $firstComment->id, 'commentable_id' => $page->id, 'commentable_type' => 'page', 'parent_id' => null, 'local_id' => $firstComment->local_id, ], ], ]); $resp->assertJsonCount(10, 'data'); $resp->assertJson(['total' => 10]); $filtered = $this->getJson("/api/comments?filter[id]={$firstComment->id}"); $filtered->assertJsonCount(1, 'data'); $filtered->assertJson(['total' => 1]); } public function test_create() { $page = $this->entities->page(); $resp = $this->actingAsApiEditor()->postJson('/api/comments', [ 'page_id' => $page->id, 'html' => '<p>My wonderful comment</p>', 'content_ref' => 'test-content-ref', ]); $resp->assertOk(); $id = $resp->json('id'); $this->assertDatabaseHas('comments', [ 'id' => $id, 'commentable_id' => $page->id, 'commentable_type' => 'page', 'html' => '<p>My wonderful comment</p>', ]); $comment = Comment::query()->findOrFail($id); $this->assertIsInt($comment->local_id); $reply = $this->actingAsApiEditor()->postJson('/api/comments', [ 'page_id' => $page->id, 'html' => '<p>My wonderful reply</p>', 'content_ref' => 'test-content-ref', 'reply_to' => $comment->local_id, ]); $reply->assertOk(); $this->assertDatabaseHas('comments', [ 'id' => $reply->json('id'), 'commentable_id' => $page->id, 'commentable_type' => 'page', 'html' => '<p>My wonderful reply</p>', 'parent_id' => $comment->local_id, ]); } public function test_read() { $page = $this->entities->page(); $user = $this->users->viewer(); $comment = Comment::factory()->make([ 'html' => '<p>A lovely comment <script>hello</script></p>', 'created_by' => $user->id, 'updated_by' => $user->id, ]); $page->comments()->save($comment); $comment->refresh(); $reply = Comment::factory()->make([ 'parent_id' => $comment->local_id, 'html' => '<p>A lovely<script>angry</script>reply</p>', ]); $page->comments()->save($reply); $resp = $this->actingAsApiEditor()->getJson("/api/comments/{$comment->id}"); $resp->assertJson([ 'id' => $comment->id, 'commentable_id' => $page->id, 'commentable_type' => 'page', 'html' => '<p>A lovely comment </p>', 'archived' => false, 'created_by' => [ 'id' => $user->id, 'name' => $user->name, ], 'updated_by' => [ 'id' => $user->id, 'name' => $user->name, ], 'replies' => [ [ 'id' => $reply->id, 'html' => '<p>A lovelyreply</p>' ] ] ]); } public function test_update() { $page = $this->entities->page(); $user = $this->users->editor(); $this->permissions->grantUserRolePermissions($user, [Permission::CommentUpdateAll]); $comment = Comment::factory()->make([ 'html' => '<p>A lovely comment</p>', 'created_by' => $this->users->viewer()->id, 'updated_by' => $this->users->viewer()->id, 'parent_id' => null, ]); $page->comments()->save($comment); $this->actingAsForApi($user)->putJson("/api/comments/{$comment->id}", [ 'html' => '<p>A lovely updated comment</p>', ])->assertOk(); $this->assertDatabaseHas('comments', [ 'id' => $comment->id, 'html' => '<p>A lovely updated comment</p>', 'archived' => 0, ]); $this->putJson("/api/comments/{$comment->id}", [ 'archived' => true, ]); $this->assertDatabaseHas('comments', [ 'id' => $comment->id, 'html' => '<p>A lovely updated comment</p>', 'archived' => 1, ]); $this->putJson("/api/comments/{$comment->id}", [ 'archived' => false, 'html' => '<p>A lovely updated again comment</p>', ]); $this->assertDatabaseHas('comments', [ 'id' => $comment->id, 'html' => '<p>A lovely updated again comment</p>', 'archived' => 0, ]); } public function test_update_cannot_archive_replies() { $page = $this->entities->page(); $user = $this->users->editor(); $this->permissions->grantUserRolePermissions($user, [Permission::CommentUpdateAll]); $comment = Comment::factory()->make([ 'html' => '<p>A lovely comment</p>', 'created_by' => $this->users->viewer()->id, 'updated_by' => $this->users->viewer()->id, 'parent_id' => 90, ]); $page->comments()->save($comment); $resp = $this->actingAsForApi($user)->putJson("/api/comments/{$comment->id}", [ 'archived' => true, ]); $this->assertEquals($this->errorResponse('Only top-level comments can be archived.', 400), $resp->json()); $this->assertDatabaseHas('comments', [ 'id' => $comment->id, 'archived' => 0, ]); } public function test_destroy() { $page = $this->entities->page(); $user = $this->users->editor(); $this->permissions->grantUserRolePermissions($user, [Permission::CommentDeleteAll]); $comment = Comment::factory()->make([ 'html' => '<p>A lovely comment</p>', ]); $page->comments()->save($comment); $this->actingAsForApi($user)->deleteJson("/api/comments/{$comment->id}")->assertStatus(204); $this->assertDatabaseMissing('comments', [ 'id' => $comment->id, ]); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Activity/AuditLogApiTest.php
tests/Activity/AuditLogApiTest.php
<?php namespace Tests\Activity; use BookStack\Activity\ActivityType; use BookStack\Facades\Activity; use Tests\Api\TestsApi; use Tests\TestCase; class AuditLogApiTest extends TestCase { use TestsApi; public function test_user_and_settings_manage_permissions_needed() { $editor = $this->users->editor(); $assertPermissionErrorOnCall = function () use ($editor) { $resp = $this->actingAsForApi($editor)->getJson('/api/audit-log'); $resp->assertStatus(403); $resp->assertJson($this->permissionErrorResponse()); }; $assertPermissionErrorOnCall(); $this->permissions->grantUserRolePermissions($editor, ['users-manage']); $assertPermissionErrorOnCall(); $this->permissions->removeUserRolePermissions($editor, ['users-manage']); $this->permissions->grantUserRolePermissions($editor, ['settings-manage']); $assertPermissionErrorOnCall(); $this->permissions->grantUserRolePermissions($editor, ['settings-manage', 'users-manage']); $resp = $this->actingAsForApi($editor)->getJson('/api/audit-log'); $resp->assertOk(); } public function test_index_endpoint_returns_expected_data() { $page = $this->entities->page(); $admin = $this->users->admin(); $this->actingAsForApi($admin); Activity::add(ActivityType::PAGE_UPDATE, $page); $resp = $this->get("/api/audit-log?filter[loggable_id]={$page->id}"); $resp->assertJson(['data' => [ [ 'type' => 'page_update', 'detail' => "({$page->id}) {$page->name}", 'user_id' => $admin->id, 'loggable_id' => $page->id, 'loggable_type' => 'page', 'ip' => '127.0.0.1', 'user' => [ 'id' => $admin->id, 'name' => $admin->name, 'slug' => $admin->slug, ], ] ]]); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Activity/CommentDisplayTest.php
tests/Activity/CommentDisplayTest.php
<?php namespace Tests\Activity; use BookStack\Activity\Models\Comment; use Tests\TestCase; class CommentDisplayTest extends TestCase { public function test_reply_comments_are_nested() { $this->asAdmin(); $page = $this->entities->page(); $this->postJson("/comment/$page->id", ['html' => '<p>My new comment</p>']); $this->postJson("/comment/$page->id", ['html' => '<p>My new comment</p>']); $respHtml = $this->withHtml($this->get($page->getUrl())); $respHtml->assertElementCount('.comment-branch', 3); $respHtml->assertElementNotExists('.comment-branch .comment-branch'); $comment = $page->comments()->first(); $resp = $this->postJson("/comment/$page->id", [ 'html' => '<p>My nested comment</p>', 'parent_id' => $comment->local_id ]); $resp->assertStatus(200); $respHtml = $this->withHtml($this->get($page->getUrl())); $respHtml->assertElementCount('.comment-branch', 4); $respHtml->assertElementContains('.comment-branch .comment-branch', 'My nested comment'); } public function test_comments_are_visible_in_the_page_editor() { $page = $this->entities->page(); $this->asAdmin()->postJson("/comment/$page->id", ['html' => '<p>My great comment to see in the editor</p>']); $respHtml = $this->withHtml($this->get($page->getUrl('/edit'))); $respHtml->assertElementContains('.comment-box .content', 'My great comment to see in the editor'); } public function test_comment_creator_name_truncated() { [$longNamedUser] = $this->users->newUserWithRole(['name' => 'Wolfeschlegelsteinhausenbergerdorff'], ['comment-create-all', 'page-view-all']); $page = $this->entities->page(); $comment = Comment::factory()->make(); $this->actingAs($longNamedUser)->postJson("/comment/$page->id", $comment->getAttributes()); $pageResp = $this->asAdmin()->get($page->getUrl()); $pageResp->assertSee('Wolfeschlegels…'); } public function test_comment_editor_js_loaded_with_create_or_edit_permissions() { $editor = $this->users->editor(); $page = $this->entities->page(); $resp = $this->actingAs($editor)->get($page->getUrl()); $resp->assertSee('window.editor_translations', false); $resp->assertSee('component="entity-selector"', false); $this->permissions->removeUserRolePermissions($editor, ['comment-create-all']); $this->permissions->grantUserRolePermissions($editor, ['comment-update-own']); $resp = $this->actingAs($editor)->get($page->getUrl()); $resp->assertDontSee('window.editor_translations', false); $resp->assertDontSee('component="entity-selector"', false); Comment::factory()->create([ 'created_by' => $editor->id, 'commentable_type' => 'page', 'commentable_id' => $page->id, ]); $resp = $this->actingAs($editor)->get($page->getUrl()); $resp->assertSee('window.editor_translations', false); $resp->assertSee('component="entity-selector"', false); } public function test_comment_displays_relative_times() { $page = $this->entities->page(); $comment = Comment::factory()->create(['commentable_id' => $page->id, 'commentable_type' => $page->getMorphClass()]); $comment->created_at = now()->subWeek(); $comment->updated_at = now()->subDay(); $comment->save(); $pageResp = $this->asAdmin()->get($page->getUrl()); $html = $this->withHtml($pageResp); // Create date shows relative time as text to user $html->assertElementContains('.comment-box', 'commented 1 week ago'); // Updated indicator has full time as title $html->assertElementContains('.comment-box span[title^="Updated ' . $comment->updated_at->format('Y-m-d') . '"]', 'Updated'); } public function test_comment_displays_reference_if_set() { $page = $this->entities->page(); $comment = Comment::factory()->make([ 'content_ref' => 'bkmrk-a:abc:4-1', 'local_id' => 10, ]); $page->comments()->save($comment); $html = $this->withHtml($this->asEditor()->get($page->getUrl())); $html->assertElementExists('#comment10 .comment-reference-indicator-wrap a'); } public function test_archived_comments_are_shown_in_their_own_container() { $page = $this->entities->page(); $comment = Comment::factory()->make(['local_id' => 44]); $page->comments()->save($comment); $html = $this->withHtml($this->asEditor()->get($page->getUrl())); $html->assertElementExists('#comment-tab-panel-active #comment44'); $html->assertElementNotExists('#comment-tab-panel-archived .comment-box'); $comment->archived = true; $comment->save(); $html = $this->withHtml($this->asEditor()->get($page->getUrl())); $html->assertElementExists('#comment-tab-panel-archived #comment44.comment-box'); $html->assertElementNotExists('#comment-tab-panel-active #comment44'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Activity/WatchTest.php
tests/Activity/WatchTest.php
<?php namespace Tests\Activity; use BookStack\Activity\ActivityType; use BookStack\Activity\Models\Comment; use BookStack\Activity\Notifications\Messages\BaseActivityNotification; use BookStack\Activity\Notifications\Messages\CommentCreationNotification; use BookStack\Activity\Notifications\Messages\PageCreationNotification; use BookStack\Activity\Notifications\Messages\PageUpdateNotification; use BookStack\Activity\Tools\ActivityLogger; use BookStack\Activity\Tools\UserEntityWatchOptions; use BookStack\Activity\WatchLevels; use BookStack\Entities\Models\Entity; use BookStack\Settings\UserNotificationPreferences; use Illuminate\Contracts\Notifications\Dispatcher; use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Notification; use Tests\TestCase; class WatchTest extends TestCase { public function test_watch_action_exists_on_entity_unless_active() { $editor = $this->users->editor(); $this->actingAs($editor); $entities = [$this->entities->book(), $this->entities->chapter(), $this->entities->page()]; /** @var Entity $entity */ foreach ($entities as $entity) { $resp = $this->get($entity->getUrl()); $this->withHtml($resp)->assertElementContains('form[action$="/watching/update"] button.icon-list-item', 'Watch'); $watchOptions = new UserEntityWatchOptions($editor, $entity); $watchOptions->updateLevelByValue(WatchLevels::COMMENTS); $resp = $this->get($entity->getUrl()); $this->withHtml($resp)->assertElementNotExists('form[action$="/watching/update"] button.icon-list-item'); } } public function test_watch_action_only_shows_with_permission() { $viewer = $this->users->viewer(); $this->actingAs($viewer); $entities = [$this->entities->book(), $this->entities->chapter(), $this->entities->page()]; /** @var Entity $entity */ foreach ($entities as $entity) { $resp = $this->get($entity->getUrl()); $this->withHtml($resp)->assertElementNotExists('form[action$="/watching/update"] button.icon-list-item'); } $this->permissions->grantUserRolePermissions($viewer, ['receive-notifications']); /** @var Entity $entity */ foreach ($entities as $entity) { $resp = $this->get($entity->getUrl()); $this->withHtml($resp)->assertElementExists('form[action$="/watching/update"] button.icon-list-item'); } } public function test_watch_update() { $editor = $this->users->editor(); $book = $this->entities->book(); $resp = $this->actingAs($editor)->put('/watching/update', [ 'type' => $book->getMorphClass(), 'id' => $book->id, 'level' => 'comments' ]); $resp->assertRedirect($book->getUrl()); $this->assertSessionHas('success'); $this->assertDatabaseHas('watches', [ 'watchable_id' => $book->id, 'watchable_type' => $book->getMorphClass(), 'user_id' => $editor->id, 'level' => WatchLevels::COMMENTS, ]); $resp = $this->put('/watching/update', [ 'type' => $book->getMorphClass(), 'id' => $book->id, 'level' => 'default' ]); $resp->assertRedirect($book->getUrl()); $this->assertDatabaseMissing('watches', [ 'watchable_id' => $book->id, 'watchable_type' => $book->getMorphClass(), 'user_id' => $editor->id, ]); } public function test_watch_update_fails_for_guest() { $this->setSettings(['app-public' => 'true']); $guest = $this->users->guest(); $this->permissions->grantUserRolePermissions($guest, ['receive-notifications']); $book = $this->entities->book(); $resp = $this->put('/watching/update', [ 'type' => $book->getMorphClass(), 'id' => $book->id, 'level' => 'comments' ]); $this->assertPermissionError($resp); $guest->unsetRelations(); } public function test_watch_detail_display_reflects_state() { $editor = $this->users->editor(); $book = $this->entities->bookHasChaptersAndPages(); $chapter = $book->chapters()->first(); $page = $chapter->pages()->first(); (new UserEntityWatchOptions($editor, $book))->updateLevelByValue(WatchLevels::UPDATES); $this->actingAs($editor)->get($book->getUrl())->assertSee('Watching new pages and updates'); $this->get($chapter->getUrl())->assertSee('Watching via parent book'); $this->get($page->getUrl())->assertSee('Watching via parent book'); (new UserEntityWatchOptions($editor, $chapter))->updateLevelByValue(WatchLevels::COMMENTS); $this->get($chapter->getUrl())->assertSee('Watching new pages, updates & comments'); $this->get($page->getUrl())->assertSee('Watching via parent chapter'); (new UserEntityWatchOptions($editor, $page))->updateLevelByValue(WatchLevels::UPDATES); $this->get($page->getUrl())->assertSee('Watching new pages and updates'); } public function test_watch_detail_ignore_indicator_cascades() { $editor = $this->users->editor(); $book = $this->entities->bookHasChaptersAndPages(); (new UserEntityWatchOptions($editor, $book))->updateLevelByValue(WatchLevels::IGNORE); $this->actingAs($editor)->get($book->getUrl())->assertSee('Ignoring notifications'); $this->get($book->chapters()->first()->getUrl())->assertSee('Ignoring via parent book'); $this->get($book->pages()->first()->getUrl())->assertSee('Ignoring via parent book'); } public function test_watch_option_menu_shows_current_active_state() { $editor = $this->users->editor(); $book = $this->entities->book(); $options = new UserEntityWatchOptions($editor, $book); $respHtml = $this->withHtml($this->actingAs($editor)->get($book->getUrl())); $respHtml->assertElementNotExists('form[action$="/watching/update"] svg[data-icon="check-circle"]'); $options->updateLevelByValue(WatchLevels::COMMENTS); $respHtml = $this->withHtml($this->actingAs($editor)->get($book->getUrl())); $respHtml->assertElementExists('form[action$="/watching/update"] button[value="comments"] svg[data-icon="check-circle"]'); $options->updateLevelByValue(WatchLevels::IGNORE); $respHtml = $this->withHtml($this->actingAs($editor)->get($book->getUrl())); $respHtml->assertElementExists('form[action$="/watching/update"] button[value="ignore"] svg[data-icon="check-circle"]'); } public function test_watch_option_menu_limits_options_for_pages() { $editor = $this->users->editor(); $book = $this->entities->bookHasChaptersAndPages(); (new UserEntityWatchOptions($editor, $book))->updateLevelByValue(WatchLevels::IGNORE); $respHtml = $this->withHtml($this->actingAs($editor)->get($book->getUrl())); $respHtml->assertElementExists('form[action$="/watching/update"] button[name="level"][value="new"]'); $respHtml = $this->withHtml($this->get($book->pages()->first()->getUrl())); $respHtml->assertElementExists('form[action$="/watching/update"] button[name="level"][value="updates"]'); $respHtml->assertElementNotExists('form[action$="/watching/update"] button[name="level"][value="new"]'); } public function test_notify_own_page_changes() { $editor = $this->users->editor(); $entities = $this->entities->createChainBelongingToUser($editor); $prefs = new UserNotificationPreferences($editor); $prefs->updateFromSettingsArray(['own-page-changes' => 'true']); $notifications = Notification::fake(); $this->asAdmin(); $this->entities->updatePage($entities['page'], ['name' => 'My updated page', 'html' => 'Hello']); $notifications->assertSentTo($editor, PageUpdateNotification::class); } public function test_notify_own_page_comments() { $editor = $this->users->editor(); $entities = $this->entities->createChainBelongingToUser($editor); $prefs = new UserNotificationPreferences($editor); $prefs->updateFromSettingsArray(['own-page-comments' => 'true']); $notifications = Notification::fake(); $this->asAdmin()->post("/comment/{$entities['page']->id}", [ 'html' => '<p>My new comment</p>' ]); $notifications->assertSentTo($editor, CommentCreationNotification::class); } public function test_notify_comment_replies() { $editor = $this->users->editor(); $entities = $this->entities->createChainBelongingToUser($editor); $prefs = new UserNotificationPreferences($editor); $prefs->updateFromSettingsArray(['comment-replies' => 'true']); // Create some existing comments to pad IDs to help potentially error // on mis-identification of parent via ids used. Comment::factory()->count(5) ->for($entities['page'], 'entity') ->create(['created_by' => $this->users->admin()->id]); $notifications = Notification::fake(); $this->actingAs($editor)->post("/comment/{$entities['page']->id}", [ 'html' => '<p>My new comment</p>' ]); $comment = $entities['page']->comments()->orderBy('id', 'desc')->first(); $this->asAdmin()->post("/comment/{$entities['page']->id}", [ 'html' => '<p>My new comment response</p>', 'parent_id' => $comment->local_id, ]); $notifications->assertSentTo($editor, CommentCreationNotification::class); } public function test_notify_watch_parent_book_ignore() { $editor = $this->users->editor(); $entities = $this->entities->createChainBelongingToUser($editor); $watches = new UserEntityWatchOptions($editor, $entities['book']); $prefs = new UserNotificationPreferences($editor); $watches->updateLevelByValue(WatchLevels::IGNORE); $prefs->updateFromSettingsArray(['own-page-changes' => 'true', 'own-page-comments' => true]); $notifications = Notification::fake(); $this->asAdmin()->post("/comment/{$entities['page']->id}", [ 'text' => 'My new comment response', ]); $this->entities->updatePage($entities['page'], ['name' => 'My updated page', 'html' => 'Hello']); $notifications->assertNothingSent(); } public function test_notify_watch_parent_book_comments() { $notifications = Notification::fake(); $editor = $this->users->editor(); $admin = $this->users->admin(); $entities = $this->entities->createChainBelongingToUser($editor); $watches = new UserEntityWatchOptions($editor, $entities['book']); $watches->updateLevelByValue(WatchLevels::COMMENTS); // Comment post $this->actingAs($admin)->post("/comment/{$entities['page']->id}", [ 'html' => '<p>My new comment response</p>', ]); $notifications->assertSentTo($editor, function (CommentCreationNotification $notification) use ($editor, $admin, $entities) { $mail = $notification->toMail($editor); $mailContent = html_entity_decode(strip_tags($mail->render()), ENT_QUOTES); return $mail->subject === 'New comment on page: ' . $entities['page']->getShortName() && str_contains($mailContent, 'View Comment') && str_contains($mailContent, 'Page Name: ' . $entities['page']->name) && str_contains($mailContent, 'Page Path: ' . $entities['book']->getShortName(24) . ' > ' . $entities['chapter']->getShortName(24)) && str_contains($mailContent, 'Commenter: ' . $admin->name) && str_contains($mailContent, 'Comment: My new comment response'); }); } public function test_notify_watch_parent_book_updates() { $notifications = Notification::fake(); $editor = $this->users->editor(); $admin = $this->users->admin(); $entities = $this->entities->createChainBelongingToUser($editor); $watches = new UserEntityWatchOptions($editor, $entities['book']); $watches->updateLevelByValue(WatchLevels::UPDATES); $this->actingAs($admin); $this->entities->updatePage($entities['page'], ['name' => 'Updated page', 'html' => 'new page content']); $notifications->assertSentTo($editor, function (PageUpdateNotification $notification) use ($editor, $admin, $entities) { $mail = $notification->toMail($editor); $mailContent = html_entity_decode(strip_tags($mail->render()), ENT_QUOTES); return $mail->subject === 'Updated page: Updated page' && str_contains($mailContent, 'View Page') && str_contains($mailContent, 'Page Name: Updated page') && str_contains($mailContent, 'Page Path: ' . $entities['book']->getShortName(24) . ' > ' . $entities['chapter']->getShortName(24)) && str_contains($mailContent, 'Updated By: ' . $admin->name) && str_contains($mailContent, 'you won\'t be sent notifications for further edits to this page by the same editor'); }); // Test debounce $notifications = Notification::fake(); $this->entities->updatePage($entities['page'], ['name' => 'Updated page', 'html' => 'new page content']); $notifications->assertNothingSentTo($editor); } public function test_notify_watch_parent_book_new() { $notifications = Notification::fake(); $editor = $this->users->editor(); $admin = $this->users->admin(); $entities = $this->entities->createChainBelongingToUser($editor); $watches = new UserEntityWatchOptions($editor, $entities['book']); $watches->updateLevelByValue(WatchLevels::NEW); $this->actingAs($admin)->get($entities['chapter']->getUrl('/create-page')); $page = $entities['chapter']->pages()->where('draft', '=', true)->first(); $this->post($page->getUrl(), ['name' => 'My new page', 'html' => 'My new page content']); $notifications->assertSentTo($editor, function (PageCreationNotification $notification) use ($editor, $admin, $entities) { $mail = $notification->toMail($editor); $mailContent = html_entity_decode(strip_tags($mail->render()), ENT_QUOTES); return $mail->subject === 'New page: My new page' && str_contains($mailContent, 'View Page') && str_contains($mailContent, 'Page Name: My new page') && str_contains($mailContent, 'Page Path: ' . $entities['book']->getShortName(24) . ' > ' . $entities['chapter']->getShortName(24)) && str_contains($mailContent, 'Created By: ' . $admin->name); }); } public function test_notify_watch_page_ignore_when_no_page_owner() { $editor = $this->users->editor(); $entities = $this->entities->createChainBelongingToUser($editor); $entities['page']->owned_by = null; $entities['page']->save(); $watches = new UserEntityWatchOptions($editor, $entities['page']); $watches->updateLevelByValue(WatchLevels::IGNORE); $notifications = Notification::fake(); $this->asAdmin(); $this->entities->updatePage($entities['page'], ['name' => 'My updated page', 'html' => 'Hello']); $notifications->assertNothingSent(); } public function test_notifications_sent_in_right_language() { $editor = $this->users->editor(); $admin = $this->users->admin(); setting()->putUser($editor, 'language', 'de'); $entities = $this->entities->createChainBelongingToUser($editor); $watches = new UserEntityWatchOptions($editor, $entities['book']); $watches->updateLevelByValue(WatchLevels::COMMENTS); $activities = [ ActivityType::PAGE_CREATE => $entities['page'], ActivityType::PAGE_UPDATE => $entities['page'], ActivityType::COMMENT_CREATE => Comment::factory()->make([ 'commentable_id' => $entities['page']->id, 'commentable_type' => $entities['page']->getMorphClass(), ]), ]; $notifications = Notification::fake(); $logger = app()->make(ActivityLogger::class); $this->actingAs($admin); foreach ($activities as $activityType => $detail) { $logger->add($activityType, $detail); } $sent = $notifications->sentNotifications()[get_class($editor)][$editor->id]; $this->assertCount(3, $sent); foreach ($sent as $notificationInfo) { $notification = $notificationInfo[0]['notification']; $this->assertInstanceOf(BaseActivityNotification::class, $notification); $mail = $notification->toMail($editor); $mailContent = html_entity_decode(strip_tags($mail->render()), ENT_QUOTES); $this->assertStringContainsString('Name der Seite:', $mailContent); $this->assertStringContainsString('Diese Benachrichtigung wurde', $mailContent); $this->assertStringContainsString('Sollte es beim Anklicken der Schaltfläche', $mailContent); } } public function test_failed_notifications_dont_block_and_log_errors() { $logger = $this->withTestLogger(); $editor = $this->users->editor(); $admin = $this->users->admin(); $page = $this->entities->page(); $book = $page->book; $activityLogger = app()->make(ActivityLogger::class); $watches = new UserEntityWatchOptions($editor, $book); $watches->updateLevelByValue(WatchLevels::UPDATES); $mockDispatcher = $this->mock(Dispatcher::class); $mockDispatcher->shouldReceive('send')->once() ->andThrow(\Exception::class, 'Failed to connect to mail server'); $this->actingAs($admin); $activityLogger->add(ActivityType::PAGE_UPDATE, $page); $this->assertTrue($logger->hasErrorThatContains("Failed to send email notification to user [id:{$editor->id}] with error: Failed to connect to mail server")); } public function test_notifications_not_sent_if_lacking_view_permission_for_related_item() { $notifications = Notification::fake(); $editor = $this->users->editor(); $page = $this->entities->page(); $watches = new UserEntityWatchOptions($editor, $page); $watches->updateLevelByValue(WatchLevels::COMMENTS); $this->permissions->disableEntityInheritedPermissions($page); $this->asAdmin()->post("/comment/{$page->id}", [ 'html' => '<p>My new comment response</p>', ])->assertOk(); $notifications->assertNothingSentTo($editor); } public function test_watches_deleted_on_user_delete() { $editor = $this->users->editor(); $page = $this->entities->page(); $watches = new UserEntityWatchOptions($editor, $page); $watches->updateLevelByValue(WatchLevels::COMMENTS); $this->assertDatabaseHas('watches', ['user_id' => $editor->id]); $this->asAdmin()->delete($editor->getEditUrl()); $this->assertDatabaseMissing('watches', ['user_id' => $editor->id]); } public function test_watches_deleted_on_item_delete() { $editor = $this->users->editor(); $page = $this->entities->page(); $watches = new UserEntityWatchOptions($editor, $page); $watches->updateLevelByValue(WatchLevels::COMMENTS); $this->assertDatabaseHas('watches', ['watchable_type' => 'page', 'watchable_id' => $page->id]); $this->entities->destroy($page); $this->assertDatabaseMissing('watches', ['watchable_type' => 'page', 'watchable_id' => $page->id]); } public function test_page_path_in_notifications_limited_by_permissions() { $chapter = $this->entities->chapterHasPages(); $page = $chapter->pages()->first(); $book = $chapter->book; $notification = new PageCreationNotification($page, $this->users->editor()); $viewer = $this->users->viewer(); $viewerRole = $viewer->roles()->first(); $content = html_entity_decode(strip_tags($notification->toMail($viewer)->render()), ENT_QUOTES); $this->assertStringContainsString('Page Path: ' . $book->getShortName(24) . ' > ' . $chapter->getShortName(24), $content); $this->permissions->setEntityPermissions($page, ['view'], [$viewerRole]); $this->permissions->setEntityPermissions($chapter, [], [$viewerRole]); $content = html_entity_decode(strip_tags($notification->toMail($viewer)->render()), ENT_QUOTES); $this->assertStringContainsString('Page Path: ' . $book->getShortName(24), $content); $this->assertStringNotContainsString(' > ' . $chapter->getShortName(24), $content); $this->permissions->setEntityPermissions($book, [], [$viewerRole]); $content = html_entity_decode(strip_tags($notification->toMail($viewer)->render()), ENT_QUOTES); $this->assertStringNotContainsString('Page Path:', $content); $this->assertStringNotContainsString($book->getShortName(24), $content); $this->assertStringNotContainsString($chapter->getShortName(24), $content); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Activity/CommentStoreTest.php
tests/Activity/CommentStoreTest.php
<?php namespace Tests\Activity; use BookStack\Activity\ActivityType; use BookStack\Activity\Models\Comment; use Tests\TestCase; class CommentStoreTest extends TestCase { public function test_add_comment() { $this->asAdmin(); $page = $this->entities->page(); Comment::factory()->create(['commentable_id' => $page->id, 'commentable_type' => 'page', 'local_id' => 2]); $comment = Comment::factory()->make(['parent_id' => 2]); $resp = $this->postJson("/comment/$page->id", $comment->getAttributes()); $resp->assertStatus(200); $resp->assertSee($comment->html, false); $pageResp = $this->get($page->getUrl()); $pageResp->assertSee($comment->html, false); $this->assertDatabaseHas('comments', [ 'local_id' => 3, 'commentable_id' => $page->id, 'commentable_type' => 'page', 'parent_id' => 2, ]); $this->assertActivityExists(ActivityType::COMMENT_CREATE); } public function test_add_comment_stores_content_reference_only_if_format_valid() { $validityByRefs = [ 'bkmrk-my-title:4589284922:4-3' => true, 'bkmrk-my-title:4589284922:' => true, 'bkmrk-my-title:4589284922:abc' => false, 'my-title:4589284922:' => false, 'bkmrk-my-title-4589284922:' => false, ]; $page = $this->entities->page(); foreach ($validityByRefs as $ref => $valid) { $this->asAdmin()->postJson("/comment/$page->id", [ 'html' => '<p>My comment</p>', 'parent_id' => null, 'content_ref' => $ref, ]); if ($valid) { $this->assertDatabaseHas('comments', ['commentable_id' => $page->id, 'content_ref' => $ref]); } else { $this->assertDatabaseMissing('comments', ['commentable_id' => $page->id, 'content_ref' => $ref]); } } } public function test_comment_edit() { $this->asAdmin(); $page = $this->entities->page(); $comment = Comment::factory()->make(); $this->postJson("/comment/$page->id", $comment->getAttributes()); $comment = $page->comments()->first(); $newHtml = '<p>updated text content</p>'; $resp = $this->putJson("/comment/$comment->id", [ 'html' => $newHtml, ]); $resp->assertStatus(200); $resp->assertSee($newHtml, false); $resp->assertDontSee($comment->html, false); $this->assertDatabaseHas('comments', [ 'html' => $newHtml, 'commentable_id' => $page->id, ]); $this->assertActivityExists(ActivityType::COMMENT_UPDATE); } public function test_comment_delete() { $this->asAdmin(); $page = $this->entities->page(); $comment = Comment::factory()->make(); $this->postJson("/comment/$page->id", $comment->getAttributes()); $comment = $page->comments()->first(); $resp = $this->delete("/comment/$comment->id"); $resp->assertStatus(200); $this->assertDatabaseMissing('comments', [ 'id' => $comment->id, ]); $this->assertActivityExists(ActivityType::COMMENT_DELETE); } public function test_comment_archive_and_unarchive() { $this->asAdmin(); $page = $this->entities->page(); $comment = Comment::factory()->make(); $page->comments()->save($comment); $comment->refresh(); $this->put("/comment/$comment->id/archive"); $this->assertDatabaseHas('comments', [ 'id' => $comment->id, 'archived' => true, ]); $this->assertActivityExists(ActivityType::COMMENT_UPDATE); $this->put("/comment/$comment->id/unarchive"); $this->assertDatabaseHas('comments', [ 'id' => $comment->id, 'archived' => false, ]); $this->assertActivityExists(ActivityType::COMMENT_UPDATE); } public function test_archive_endpoints_require_delete_or_edit_permissions() { $viewer = $this->users->viewer(); $page = $this->entities->page(); $comment = Comment::factory()->make(); $page->comments()->save($comment); $comment->refresh(); $endpoints = ["/comment/$comment->id/archive", "/comment/$comment->id/unarchive"]; foreach ($endpoints as $endpoint) { $resp = $this->actingAs($viewer)->put($endpoint); $this->assertPermissionError($resp); } $this->permissions->grantUserRolePermissions($viewer, ['comment-delete-all']); foreach ($endpoints as $endpoint) { $resp = $this->actingAs($viewer)->put($endpoint); $resp->assertOk(); } $this->permissions->removeUserRolePermissions($viewer, ['comment-delete-all']); $this->permissions->grantUserRolePermissions($viewer, ['comment-update-all']); foreach ($endpoints as $endpoint) { $resp = $this->actingAs($viewer)->put($endpoint); $resp->assertOk(); } } public function test_non_top_level_comments_cant_be_archived_or_unarchived() { $this->asAdmin(); $page = $this->entities->page(); $comment = Comment::factory()->make(); $page->comments()->save($comment); $subComment = Comment::factory()->make(['parent_id' => $comment->id]); $page->comments()->save($subComment); $subComment->refresh(); $resp = $this->putJson("/comment/$subComment->id/archive"); $resp->assertStatus(400); $this->assertDatabaseHas('comments', [ 'id' => $subComment->id, 'archived' => false, ]); $resp = $this->putJson("/comment/$subComment->id/unarchive"); $resp->assertStatus(400); } public function test_scripts_cannot_be_injected_via_comment_html() { $page = $this->entities->page(); $script = '<script>const a = "script";</script><script>const b = "sneakyscript";</script><p onclick="1">My lovely comment</p>'; $this->asAdmin()->postJson("/comment/$page->id", [ 'html' => $script, ]); $pageView = $this->get($page->getUrl()); $pageView->assertDontSee($script, false); $pageView->assertDontSee('sneakyscript', false); $pageView->assertSee('<p>My lovely comment</p>', false); $comment = $page->comments()->first(); $this->putJson("/comment/$comment->id", [ 'html' => $script . '<p>updated</p>', ]); $pageView = $this->get($page->getUrl()); $pageView->assertDontSee($script, false); $pageView->assertDontSee('sneakyscript', false); $pageView->assertSee('<p>My lovely comment</p><p>updated</p>'); } public function test_scripts_are_removed_even_if_already_in_db() { $page = $this->entities->page(); Comment::factory()->create([ 'html' => '<script>superbadscript</script><script>superbadscript</script><p onclick="superbadonclick">scriptincommentest</p>', 'commentable_type' => 'page', 'commentable_id' => $page ]); $resp = $this->asAdmin()->get($page->getUrl()); $resp->assertSee('scriptincommentest', false); $resp->assertDontSee('superbadscript', false); $resp->assertDontSee('superbadonclick', false); } public function test_comment_html_is_limited() { $page = $this->entities->page(); $input = '<h1>Test</h1><p id="abc" href="beans">Content<a href="#cat" data-a="b">a</a><section>Hello</section><section>there</section></p>'; $expected = '<p>Content<a href="#cat">a</a></p>'; $resp = $this->asAdmin()->post("/comment/{$page->id}", ['html' => $input]); $resp->assertOk(); $this->assertDatabaseHas('comments', [ 'commentable_type' => 'page', 'commentable_id' => $page->id, 'html' => $expected, ]); $comment = $page->comments()->first(); $resp = $this->put("/comment/{$comment->id}", ['html' => $input]); $resp->assertOk(); $this->assertDatabaseHas('comments', [ 'id' => $comment->id, 'html' => $expected, ]); } public function test_comment_html_spans_are_cleaned() { $page = $this->entities->page(); $input = '<p><span class="beans">Hello</span> do you have <span style="white-space: discard;">biscuits</span>?</p>'; $expected = '<p><span>Hello</span> do you have <span>biscuits</span>?</p>'; $resp = $this->asAdmin()->post("/comment/{$page->id}", ['html' => $input]); $resp->assertOk(); $this->assertDatabaseHas('comments', [ 'commentable_type' => 'page', 'commentable_id' => $page->id, 'html' => $expected, ]); $comment = $page->comments()->first(); $resp = $this->put("/comment/{$comment->id}", ['html' => $input]); $resp->assertOk(); $this->assertDatabaseHas('comments', [ 'id' => $comment->id, 'html' => $expected, ]); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Activity/WebhookFormatTesting.php
tests/Activity/WebhookFormatTesting.php
<?php namespace Tests\Activity; use BookStack\Activity\ActivityType; use BookStack\Activity\Models\Webhook; use BookStack\Activity\Tools\WebhookFormatter; use Illuminate\Support\Arr; use Tests\TestCase; class WebhookFormatTesting extends TestCase { public function test_entity_events_show_related_user_info() { $events = [ ActivityType::BOOK_UPDATE => $this->entities->book(), ActivityType::CHAPTER_CREATE => $this->entities->chapter(), ActivityType::PAGE_MOVE => $this->entities->page(), ]; foreach ($events as $event => $entity) { $data = $this->getWebhookData($event, $entity); $this->assertEquals($entity->createdBy->name, Arr::get($data, 'related_item.created_by.name')); $this->assertEquals($entity->updatedBy->id, Arr::get($data, 'related_item.updated_by.id')); $this->assertEquals($entity->ownedBy->slug, Arr::get($data, 'related_item.owned_by.slug')); } } public function test_page_create_and_update_events_show_revision_info() { $page = $this->entities->page(); $this->asEditor()->put($page->getUrl(), ['name' => 'Updated page', 'html' => 'new page html', 'summary' => 'Update a']); $data = $this->getWebhookData(ActivityType::PAGE_UPDATE, $page); $this->assertEquals($page->currentRevision->id, Arr::get($data, 'related_item.current_revision.id')); $this->assertEquals($page->currentRevision->type, Arr::get($data, 'related_item.current_revision.type')); $this->assertEquals('Update a', Arr::get($data, 'related_item.current_revision.summary')); } protected function getWebhookData(string $event, $detail): array { $webhook = Webhook::factory()->make(); $user = $this->users->editor(); $formatter = WebhookFormatter::getDefault($event, $webhook, $detail, $user, time()); return $formatter->format(); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Activity/AuditLogTest.php
tests/Activity/AuditLogTest.php
<?php namespace Tests\Activity; use BookStack\Activity\ActivityType; use BookStack\Activity\Models\Activity; use BookStack\Activity\Tools\ActivityLogger; use BookStack\Entities\Repos\PageRepo; use BookStack\Entities\Tools\TrashCan; use BookStack\Users\UserRepo; use Carbon\Carbon; use Tests\TestCase; class AuditLogTest extends TestCase { protected ActivityLogger $activityService; protected function setUp(): void { parent::setUp(); $this->activityService = app(ActivityLogger::class); } public function test_only_accessible_with_right_permissions() { $viewer = $this->users->viewer(); $this->actingAs($viewer); $resp = $this->get('/settings/audit'); $this->assertPermissionError($resp); $this->permissions->grantUserRolePermissions($viewer, ['settings-manage']); $resp = $this->get('/settings/audit'); $this->assertPermissionError($resp); $this->permissions->grantUserRolePermissions($viewer, ['users-manage']); $resp = $this->get('/settings/audit'); $resp->assertStatus(200); $resp->assertSeeText('Audit Log'); } public function test_shows_activity() { $admin = $this->users->admin(); $this->actingAs($admin); $page = $this->entities->page(); $this->activityService->add(ActivityType::PAGE_CREATE, $page); $activity = Activity::query()->orderBy('id', 'desc')->first(); $resp = $this->get('settings/audit'); $resp->assertSeeText($page->name); $resp->assertSeeText('page_create'); $resp->assertSeeText($activity->created_at->toDateTimeString()); $this->withHtml($resp)->assertElementContains('a[href*="users/' . $admin->id . '"]', $admin->name); } public function test_shows_name_for_deleted_items() { $this->actingAs($this->users->admin()); $page = $this->entities->page(); $pageName = $page->name; $this->activityService->add(ActivityType::PAGE_CREATE, $page); app(PageRepo::class)->destroy($page); app(TrashCan::class)->empty(); $resp = $this->get('settings/audit'); $resp->assertSeeText('Deleted Item'); $resp->assertSeeText('Name: ' . $pageName); } public function test_shows_activity_for_deleted_users() { $viewer = $this->users->viewer(); $this->actingAs($viewer); $page = $this->entities->page(); $this->activityService->add(ActivityType::PAGE_CREATE, $page); $this->actingAs($this->users->admin()); app(UserRepo::class)->destroy($viewer); $resp = $this->get('settings/audit'); $resp->assertSeeText("[ID: {$viewer->id}] Deleted User"); } public function test_deleted_user_shows_if_user_created_date_is_later_than_activity() { $viewer = $this->users->viewer(); $this->actingAs($viewer); $page = $this->entities->page(); $this->activityService->add(ActivityType::PAGE_CREATE, $page); $viewer->created_at = Carbon::now()->addDay(); $viewer->save(); $this->actingAs($this->users->admin()); $resp = $this->get('settings/audit'); $resp->assertSeeText("[ID: {$viewer->id}] Deleted User"); $resp->assertDontSee($viewer->name); } public function test_filters_by_key() { $this->actingAs($this->users->admin()); $page = $this->entities->page(); $this->activityService->add(ActivityType::PAGE_CREATE, $page); $resp = $this->get('settings/audit'); $resp->assertSeeText($page->name); $resp = $this->get('settings/audit?event=page_delete'); $resp->assertDontSeeText($page->name); } public function test_date_filters() { $this->actingAs($this->users->admin()); $page = $this->entities->page(); $this->activityService->add(ActivityType::PAGE_CREATE, $page); $yesterday = (Carbon::now()->subDay()->format('Y-m-d')); $tomorrow = (Carbon::now()->addDay()->format('Y-m-d')); $resp = $this->get('settings/audit?date_from=' . $yesterday); $resp->assertSeeText($page->name); $resp = $this->get('settings/audit?date_from=' . $tomorrow); $resp->assertDontSeeText($page->name); $resp = $this->get('settings/audit?date_to=' . $tomorrow); $resp->assertSeeText($page->name); $resp = $this->get('settings/audit?date_to=' . $yesterday); $resp->assertDontSeeText($page->name); } public function test_user_filter() { $admin = $this->users->admin(); $editor = $this->users->editor(); $this->actingAs($admin); $page = $this->entities->page(); $this->activityService->add(ActivityType::PAGE_CREATE, $page); $this->actingAs($editor); $chapter = $this->entities->chapter(); $this->activityService->add(ActivityType::CHAPTER_UPDATE, $chapter); $resp = $this->actingAs($admin)->get('settings/audit?user=' . $admin->id); $resp->assertSeeText($page->name); $resp->assertDontSeeText($chapter->name); $resp = $this->actingAs($admin)->get('settings/audit?user=' . $editor->id); $resp->assertSeeText($chapter->name); $resp->assertDontSeeText($page->name); } public function test_ip_address_logged_and_visible() { config()->set('app.proxies', '*'); $editor = $this->users->editor(); $page = $this->entities->page(); $this->actingAs($editor)->put($page->getUrl(), [ 'name' => 'Updated page', 'html' => '<p>Updated content</p>', ], [ 'X-Forwarded-For' => '192.123.45.1', ])->assertRedirect($page->refresh()->getUrl()); $this->assertDatabaseHas('activities', [ 'type' => ActivityType::PAGE_UPDATE, 'ip' => '192.123.45.1', 'user_id' => $editor->id, 'loggable_id' => $page->id, ]); $resp = $this->asAdmin()->get('/settings/audit'); $resp->assertSee('192.123.45.1'); } public function test_ip_address_is_searchable() { config()->set('app.proxies', '*'); $editor = $this->users->editor(); $page = $this->entities->page(); $this->actingAs($editor)->put($page->getUrl(), [ 'name' => 'Updated page', 'html' => '<p>Updated content</p>', ], [ 'X-Forwarded-For' => '192.123.45.1', ])->assertRedirect($page->refresh()->getUrl()); $this->actingAs($editor)->put($page->getUrl(), [ 'name' => 'Updated page', 'html' => '<p>Updated content</p>', ], [ 'X-Forwarded-For' => '192.122.45.1', ])->assertRedirect($page->refresh()->getUrl()); $resp = $this->asAdmin()->get('/settings/audit?&ip=192.123'); $resp->assertSee('192.123.45.1'); $resp->assertDontSee('192.122.45.1'); } public function test_ip_address_not_logged_in_demo_mode() { config()->set('app.proxies', '*'); config()->set('app.env', 'demo'); $editor = $this->users->editor(); $page = $this->entities->page(); $this->actingAs($editor)->put($page->getUrl(), [ 'name' => 'Updated page', 'html' => '<p>Updated content</p>', ], [ 'X-Forwarded-For' => '192.123.45.1', 'REMOTE_ADDR' => '192.123.45.2', ])->assertRedirect($page->refresh()->getUrl()); $this->assertDatabaseHas('activities', [ 'type' => ActivityType::PAGE_UPDATE, 'ip' => '127.0.0.1', 'user_id' => $editor->id, 'loggable_id' => $page->id, ]); } public function test_ip_address_respects_precision_setting() { config()->set('app.proxies', '*'); config()->set('app.ip_address_precision', 2); $editor = $this->users->editor(); $page = $this->entities->page(); $this->actingAs($editor)->put($page->getUrl(), [ 'name' => 'Updated page', 'html' => '<p>Updated content</p>', ], [ 'X-Forwarded-For' => '192.123.45.1', ])->assertRedirect($page->refresh()->getUrl()); $this->assertDatabaseHas('activities', [ 'type' => ActivityType::PAGE_UPDATE, 'ip' => '192.123.x.x', 'user_id' => $editor->id, 'loggable_id' => $page->id, ]); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Uploads/ImageTest.php
tests/Uploads/ImageTest.php
<?php namespace Tests\Uploads; use BookStack\Entities\Repos\PageRepo; use BookStack\Uploads\Image; use BookStack\Uploads\ImageService; use BookStack\Uploads\UserAvatars; use BookStack\Users\Models\Role; use Illuminate\Support\Str; use Tests\TestCase; class ImageTest extends TestCase { public function test_image_upload() { $page = $this->entities->page(); $admin = $this->users->admin(); $this->actingAs($admin); $imgDetails = $this->files->uploadGalleryImageToPage($this, $page); $relPath = $imgDetails['path']; $this->assertTrue(file_exists(public_path($relPath)), 'Uploaded image found at path: ' . public_path($relPath)); $this->files->deleteAtRelativePath($relPath); $this->assertDatabaseHas('images', [ 'url' => $this->baseUrl . $relPath, 'type' => 'gallery', 'uploaded_to' => $page->id, 'path' => $relPath, 'created_by' => $admin->id, 'updated_by' => $admin->id, 'name' => $imgDetails['name'], ]); } public function test_image_display_thumbnail_generation_does_not_increase_image_size() { $page = $this->entities->page(); $admin = $this->users->admin(); $this->actingAs($admin); $originalFile = $this->files->testFilePath('compressed.png'); $originalFileSize = filesize($originalFile); $imgDetails = $this->files->uploadGalleryImageToPage($this, $page, 'compressed.png'); $relPath = $imgDetails['path']; $this->assertTrue(file_exists(public_path($relPath)), 'Uploaded image found at path: ' . public_path($relPath)); $displayImage = $imgDetails['response']->thumbs->display; $displayImageRelPath = implode('/', array_slice(explode('/', $displayImage), 3)); $displayImagePath = public_path($displayImageRelPath); $displayFileSize = filesize($displayImagePath); $this->files->deleteAtRelativePath($relPath); $this->files->deleteAtRelativePath($displayImageRelPath); $this->assertEquals($originalFileSize, $displayFileSize, 'Display thumbnail generation should not increase image size'); } public function test_image_display_thumbnail_generation_for_apng_images_uses_original_file() { $page = $this->entities->page(); $admin = $this->users->admin(); $this->actingAs($admin); $imgDetails = $this->files->uploadGalleryImageToPage($this, $page, 'animated.png'); $this->files->deleteAtRelativePath($imgDetails['path']); $this->assertStringContainsString('thumbs-', $imgDetails['response']->thumbs->gallery); $this->assertStringNotContainsString('scaled-', $imgDetails['response']->thumbs->display); } public function test_image_display_thumbnail_generation_for_animated_avif_images_uses_original_file() { if (! function_exists('imageavif')) { $this->markTestSkipped('imageavif() is not available'); } $page = $this->entities->page(); $admin = $this->users->admin(); $this->actingAs($admin); $imgDetails = $this->files->uploadGalleryImageToPage($this, $page, 'animated.avif'); $this->files->deleteAtRelativePath($imgDetails['path']); $this->assertStringContainsString('thumbs-', $imgDetails['response']->thumbs->gallery); $this->assertStringNotContainsString('scaled-', $imgDetails['response']->thumbs->display); } public function test_image_edit() { $editor = $this->users->editor(); $this->actingAs($editor); $imgDetails = $this->files->uploadGalleryImageToPage($this, $this->entities->page()); $image = Image::query()->first(); $newName = Str::random(); $update = $this->put('/images/' . $image->id, ['name' => $newName]); $update->assertSuccessful(); $update->assertSee($newName); $this->files->deleteAtRelativePath($imgDetails['path']); $this->assertDatabaseHas('images', [ 'type' => 'gallery', 'name' => $newName, ]); } public function test_image_file_update() { $page = $this->entities->page(); $this->asEditor(); $imgDetails = $this->files->uploadGalleryImageToPage($this, $page); $relPath = $imgDetails['path']; $newUpload = $this->files->uploadedImage('updated-image.png', 'compressed.png'); $this->assertFileEquals($this->files->testFilePath('test-image.png'), public_path($relPath)); $imageId = $imgDetails['response']->id; $image = Image::findOrFail($imageId); $image->updated_at = now()->subMonth(); $image->save(); $this->call('PUT', "/images/{$imageId}/file", [], [], ['file' => $newUpload]) ->assertOk(); $this->assertFileEquals($this->files->testFilePath('compressed.png'), public_path($relPath)); $image->refresh(); $this->assertTrue($image->updated_at->gt(now()->subMinute())); $this->files->deleteAtRelativePath($relPath); } public function test_image_file_update_allows_case_differences() { $page = $this->entities->page(); $this->asEditor(); $imgDetails = $this->files->uploadGalleryImageToPage($this, $page); $relPath = $imgDetails['path']; $newUpload = $this->files->uploadedImage('updated-image.PNG', 'compressed.png'); $this->assertFileEquals($this->files->testFilePath('test-image.png'), public_path($relPath)); $imageId = $imgDetails['response']->id; $image = Image::findOrFail($imageId); $image->updated_at = now()->subMonth(); $image->save(); $this->call('PUT', "/images/{$imageId}/file", [], [], ['file' => $newUpload]) ->assertOk(); $this->assertFileEquals($this->files->testFilePath('compressed.png'), public_path($relPath)); $image->refresh(); $this->assertTrue($image->updated_at->gt(now()->subMinute())); $this->files->deleteAtRelativePath($relPath); } public function test_image_file_update_does_not_allow_change_in_image_extension() { $page = $this->entities->page(); $this->asEditor(); $imgDetails = $this->files->uploadGalleryImageToPage($this, $page); $relPath = $imgDetails['path']; $newUpload = $this->files->uploadedImage('updated-image.jpg', 'compressed.png'); $imageId = $imgDetails['response']->id; $this->call('PUT', "/images/{$imageId}/file", [], [], ['file' => $newUpload]) ->assertJson([ "message" => "Image file replacements must be of the same type", "status" => "error", ]); $this->files->deleteAtRelativePath($relPath); } public function test_gallery_get_list_format() { $this->asEditor(); $imgDetails = $this->files->uploadGalleryImageToPage($this, $this->entities->page()); $image = Image::query()->first(); $pageId = $imgDetails['page']->id; $firstPageRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}"); $firstPageRequest->assertSuccessful(); $this->withHtml($firstPageRequest)->assertElementExists('div'); $firstPageRequest->assertSuccessful()->assertSeeText($image->name); $secondPageRequest = $this->get("/images/gallery?page=2&uploaded_to={$pageId}"); $secondPageRequest->assertSuccessful(); $this->withHtml($secondPageRequest)->assertElementNotExists('div'); $namePartial = substr($imgDetails['name'], 0, 3); $searchHitRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}&search={$namePartial}"); $searchHitRequest->assertSuccessful()->assertSee($imgDetails['name']); $namePartial = Str::random(16); $searchFailRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}&search={$namePartial}"); $searchFailRequest->assertSuccessful()->assertDontSee($imgDetails['name']); $searchFailRequest->assertSuccessful(); $this->withHtml($searchFailRequest)->assertElementNotExists('div'); } public function test_image_gallery_lists_for_draft_page() { $this->actingAs($this->users->editor()); $draft = $this->entities->newDraftPage(); $this->files->uploadGalleryImageToPage($this, $draft); $image = Image::query()->where('uploaded_to', '=', $draft->id)->firstOrFail(); $resp = $this->get("/images/gallery?page=1&uploaded_to={$draft->id}"); $resp->assertSee($image->getThumb(150, 150)); } public function test_image_usage() { $page = $this->entities->page(); $editor = $this->users->editor(); $this->actingAs($editor); $imgDetails = $this->files->uploadGalleryImageToPage($this, $page); $image = Image::query()->first(); $page->html = '<img src="' . $image->url . '">'; $page->save(); $usage = $this->get('/images/edit/' . $image->id . '?delete=true'); $usage->assertSuccessful(); $usage->assertSeeText($page->name); $usage->assertSee($page->getUrl()); $this->files->deleteAtRelativePath($imgDetails['path']); } public function test_php_files_cannot_be_uploaded() { $page = $this->entities->page(); $admin = $this->users->admin(); $this->actingAs($admin); $fileName = 'bad.php'; $relPath = $this->files->expectedImagePath('gallery', $fileName); $this->files->deleteAtRelativePath($relPath); $file = $this->files->imageFromBase64File('bad-php.base64', $fileName); $upload = $this->withHeader('Content-Type', 'image/jpeg')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []); $upload->assertStatus(500); $this->assertStringContainsString('The file must have a valid & supported image extension', $upload->json('message')); $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded php file was uploaded but should have been stopped'); $this->assertDatabaseMissing('images', [ 'type' => 'gallery', 'name' => $fileName, ]); } public function test_php_like_files_cannot_be_uploaded() { $page = $this->entities->page(); $admin = $this->users->admin(); $this->actingAs($admin); $fileName = 'bad.phtml'; $relPath = $this->files->expectedImagePath('gallery', $fileName); $this->files->deleteAtRelativePath($relPath); $file = $this->files->imageFromBase64File('bad-phtml.base64', $fileName); $upload = $this->withHeader('Content-Type', 'image/jpeg')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []); $upload->assertStatus(500); $this->assertStringContainsString('The file must have a valid & supported image extension', $upload->json('message')); $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded php file was uploaded but should have been stopped'); } public function test_files_with_double_extensions_will_get_sanitized() { $page = $this->entities->page(); $admin = $this->users->admin(); $this->actingAs($admin); $fileName = 'bad.phtml.png'; $relPath = $this->files->expectedImagePath('gallery', $fileName); $expectedRelPath = dirname($relPath) . '/bad-phtml.png'; $this->files->deleteAtRelativePath($expectedRelPath); $file = $this->files->imageFromBase64File('bad-phtml-png.base64', $fileName); $upload = $this->withHeader('Content-Type', 'image/png')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []); $upload->assertStatus(200); $lastImage = Image::query()->latest('id')->first(); $this->assertEquals('bad.phtml.png', $lastImage->name); $this->assertEquals('bad-phtml.png', basename($lastImage->path)); $this->assertFileDoesNotExist(public_path($relPath), 'Uploaded image file name was not stripped of dots'); $this->assertFileExists(public_path($expectedRelPath)); $this->files->deleteAtRelativePath($lastImage->path); } public function test_url_entities_removed_from_filenames() { $this->asEditor(); $badNames = [ 'bad-char-#-image.png', 'bad-char-?-image.png', '?#.png', '?.png', '#.png', ]; foreach ($badNames as $name) { $galleryFile = $this->files->uploadedImage($name); $page = $this->entities->page(); $badPath = $this->files->expectedImagePath('gallery', $name); $this->files->deleteAtRelativePath($badPath); $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []); $upload->assertStatus(200); $lastImage = Image::query()->latest('id')->first(); $newFileName = explode('.', basename($lastImage->path))[0]; $this->assertEquals($lastImage->name, $name); $this->assertFalse(strpos($lastImage->path, $name), 'Path contains original image name'); $this->assertFalse(file_exists(public_path($badPath)), 'Uploaded image file name was not stripped of url entities'); $this->assertTrue(strlen($newFileName) > 0, 'File name was reduced to nothing'); $this->files->deleteAtRelativePath($lastImage->path); } } public function test_secure_images_uploads_to_correct_place() { config()->set('filesystems.images', 'local_secure'); $this->asEditor(); $galleryFile = $this->files->uploadedImage('my-secure-test-upload.png'); $page = $this->entities->page(); $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-test-upload.png'); $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []); $upload->assertStatus(200); $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath); if (file_exists($expectedPath)) { unlink($expectedPath); } } public function test_secure_image_paths_traversal_causes_500() { config()->set('filesystems.images', 'local_secure'); $this->asEditor(); $resp = $this->get('/uploads/images/../../logs/laravel.log'); $resp->assertStatus(500); } public function test_secure_image_paths_traversal_on_non_secure_images_causes_404() { config()->set('filesystems.images', 'local'); $this->asEditor(); $resp = $this->get('/uploads/images/../../logs/laravel.log'); $resp->assertStatus(404); } public function test_secure_image_paths_dont_serve_non_images() { config()->set('filesystems.images', 'local_secure'); $this->asEditor(); $testFilePath = storage_path('/uploads/images/testing.txt'); file_put_contents($testFilePath, 'hello from test_secure_image_paths_dont_serve_non_images'); $resp = $this->get('/uploads/images/testing.txt'); $resp->assertStatus(404); } public function test_secure_images_included_in_exports() { config()->set('filesystems.images', 'local_secure'); $this->asEditor(); $galleryFile = $this->files->uploadedImage('my-secure-test-upload.png'); $page = $this->entities->page(); $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-test-upload.png'); $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []); $imageUrl = json_decode($upload->getContent(), true)['url']; $page->html .= "<img src=\"{$imageUrl}\">"; $page->save(); $upload->assertStatus(200); $encodedImageContent = base64_encode(file_get_contents($expectedPath)); $export = $this->get($page->getUrl('/export/html')); $this->assertTrue(strpos($export->getContent(), $encodedImageContent) !== false, 'Uploaded image in export content'); if (file_exists($expectedPath)) { unlink($expectedPath); } } public function test_system_images_remain_public_with_local_secure() { config()->set('filesystems.images', 'local_secure'); $this->asAdmin(); $galleryFile = $this->files->uploadedImage('my-system-test-upload.png'); $expectedPath = public_path('uploads/images/system/' . date('Y-m') . '/my-system-test-upload.png'); $upload = $this->call('POST', '/settings/customization', [], [], ['app_logo' => $galleryFile], []); $upload->assertRedirect('/settings/customization'); $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath); if (file_exists($expectedPath)) { unlink($expectedPath); } } public function test_system_images_remain_public_with_local_secure_restricted() { config()->set('filesystems.images', 'local_secure_restricted'); $this->asAdmin(); $galleryFile = $this->files->uploadedImage('my-system-test-restricted-upload.png'); $expectedPath = public_path('uploads/images/system/' . date('Y-m') . '/my-system-test-restricted-upload.png'); $upload = $this->call('POST', '/settings/customization', [], [], ['app_logo' => $galleryFile], []); $upload->assertRedirect('/settings/customization'); $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath); if (file_exists($expectedPath)) { unlink($expectedPath); } } public function test_avatar_images_visible_only_when_public_access_enabled_with_local_secure_restricted() { config()->set('filesystems.images', 'local_secure_restricted'); $user = $this->users->admin(); $avatars = $this->app->make(UserAvatars::class); $avatars->assignToUserFromExistingData($user, $this->files->pngImageData(), 'png'); $avatarUrl = $user->getAvatar(); $resp = $this->get($avatarUrl); $resp->assertRedirect('/login'); $this->permissions->makeAppPublic(); $resp = $this->get($avatarUrl); $resp->assertOk(); $this->files->deleteAtRelativePath($user->avatar->path); } public function test_secure_restricted_images_inaccessible_without_relation_permission() { config()->set('filesystems.images', 'local_secure_restricted'); $this->asEditor(); $galleryFile = $this->files->uploadedImage('my-secure-restricted-test-upload.png'); $page = $this->entities->page(); $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []); $upload->assertStatus(200); $expectedUrl = url('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-test-upload.png'); $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-test-upload.png'); $this->get($expectedUrl)->assertOk(); $this->permissions->setEntityPermissions($page, [], []); $resp = $this->get($expectedUrl); $resp->assertNotFound(); if (file_exists($expectedPath)) { unlink($expectedPath); } } public function test_secure_restricted_images_accessible_with_public_guest_access() { config()->set('filesystems.images', 'local_secure_restricted'); $this->permissions->makeAppPublic(); $this->asEditor(); $page = $this->entities->page(); $this->files->uploadGalleryImageToPage($this, $page); $image = Image::query()->where('type', '=', 'gallery') ->where('uploaded_to', '=', $page->id) ->first(); $expectedUrl = url($image->path); $expectedPath = storage_path($image->path); auth()->logout(); $this->get($expectedUrl)->assertOk(); $this->permissions->setEntityPermissions($page, [], []); $resp = $this->get($expectedUrl); $resp->assertNotFound(); $this->permissions->setEntityPermissions($page, ['view'], [Role::getSystemRole('public')]); $this->get($expectedUrl)->assertOk(); if (file_exists($expectedPath)) { unlink($expectedPath); } } public function test_thumbnail_path_handled_by_secure_restricted_images() { config()->set('filesystems.images', 'local_secure_restricted'); $this->asEditor(); $galleryFile = $this->files->uploadedImage('my-secure-restricted-thumb-test-test.png'); $page = $this->entities->page(); $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []); $upload->assertStatus(200); $expectedUrl = url('uploads/images/gallery/' . date('Y-m') . '/thumbs-150-150/my-secure-restricted-thumb-test-test.png'); $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-thumb-test-test.png'); $this->get($expectedUrl)->assertOk(); $this->permissions->setEntityPermissions($page, [], []); $resp = $this->get($expectedUrl); $resp->assertNotFound(); if (file_exists($expectedPath)) { unlink($expectedPath); } } public function test_secure_restricted_image_access_controlled_in_exports() { config()->set('filesystems.images', 'local_secure_restricted'); $this->asEditor(); $galleryFile = $this->files->uploadedImage('my-secure-restricted-export-test.png'); $pageA = $this->entities->page(); $pageB = $this->entities->page(); $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-export-test.png'); $upload = $this->asEditor()->call('POST', '/images/gallery', ['uploaded_to' => $pageA->id], [], ['file' => $galleryFile], []); $upload->assertOk(); $imageUrl = json_decode($upload->getContent(), true)['url']; $pageB->html .= "<img src=\"{$imageUrl}\">"; $pageB->save(); $encodedImageContent = base64_encode(file_get_contents($expectedPath)); $export = $this->get($pageB->getUrl('/export/html')); $this->assertStringContainsString($encodedImageContent, $export->getContent()); $this->permissions->setEntityPermissions($pageA, [], []); $export = $this->get($pageB->getUrl('/export/html')); $this->assertStringNotContainsString($encodedImageContent, $export->getContent()); if (file_exists($expectedPath)) { unlink($expectedPath); } } public function test_image_delete() { $page = $this->entities->page(); $this->asAdmin(); $imageName = 'first-image.png'; $relPath = $this->files->expectedImagePath('gallery', $imageName); $this->files->deleteAtRelativePath($relPath); $this->files->uploadGalleryImage($this, $imageName, $page->id); $image = Image::first(); $delete = $this->delete('/images/' . $image->id); $delete->assertStatus(200); $this->assertDatabaseMissing('images', [ 'url' => $this->baseUrl . $relPath, 'type' => 'gallery', ]); $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected'); } public function test_image_delete_does_not_delete_similar_images() { $page = $this->entities->page(); $this->asAdmin(); $imageName = 'first-image.png'; $relPath = $this->files->expectedImagePath('gallery', $imageName); $this->files->deleteAtRelativePath($relPath); $this->files->uploadGalleryImage($this, $imageName, $page->id); $this->files->uploadGalleryImage($this, $imageName, $page->id); $this->files->uploadGalleryImage($this, $imageName, $page->id); $image = Image::first(); $folder = public_path(dirname($relPath)); $imageCount = count(glob($folder . '/*')); $delete = $this->delete('/images/' . $image->id); $delete->assertStatus(200); $newCount = count(glob($folder . '/*')); $this->assertEquals($imageCount - 1, $newCount, 'More files than expected have been deleted'); $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected'); } public function test_image_manager_delete_button_only_shows_with_permission() { $page = $this->entities->page(); $this->asAdmin(); $imageName = 'first-image.png'; $relPath = $this->files->expectedImagePath('gallery', $imageName); $this->files->deleteAtRelativePath($relPath); $viewer = $this->users->viewer(); $this->files->uploadGalleryImage($this, $imageName, $page->id); $image = Image::first(); $resp = $this->get("/images/edit/{$image->id}"); $this->withHtml($resp)->assertElementExists('button#image-manager-delete'); $resp = $this->actingAs($viewer)->get("/images/edit/{$image->id}"); $this->withHtml($resp)->assertElementNotExists('button#image-manager-delete'); $this->permissions->grantUserRolePermissions($viewer, ['image-delete-all']); $resp = $this->actingAs($viewer)->get("/images/edit/{$image->id}"); $this->withHtml($resp)->assertElementExists('button#image-manager-delete'); $this->files->deleteAtRelativePath($relPath); } public function test_image_manager_regen_thumbnails() { $this->asEditor(); $imageName = 'first-image.png'; $relPath = $this->files->expectedImagePath('gallery', $imageName); $this->files->deleteAtRelativePath($relPath); $this->files->uploadGalleryImage($this, $imageName, $this->entities->page()->id); $image = Image::first(); $resp = $this->get("/images/edit/{$image->id}"); $this->withHtml($resp)->assertElementExists('button#image-manager-rebuild-thumbs'); $expectedThumbPath = dirname($relPath) . '/scaled-1680-/' . basename($relPath); $this->files->deleteAtRelativePath($expectedThumbPath); $this->assertFileDoesNotExist($this->files->relativeToFullPath($expectedThumbPath)); $resp = $this->put("/images/{$image->id}/rebuild-thumbnails"); $resp->assertOk(); $this->assertFileExists($this->files->relativeToFullPath($expectedThumbPath)); $this->files->deleteAtRelativePath($relPath); } public function test_gif_thumbnail_generation() { $this->asAdmin(); $originalFile = $this->files->testFilePath('animated.gif'); $originalFileSize = filesize($originalFile); $imgDetails = $this->files->uploadGalleryImageToPage($this, $this->entities->page(), 'animated.gif'); $relPath = $imgDetails['path']; $this->assertTrue(file_exists(public_path($relPath)), 'Uploaded image found at path: ' . public_path($relPath)); $galleryThumb = $imgDetails['response']->thumbs->gallery; $displayThumb = $imgDetails['response']->thumbs->display; // Ensure display thumbnail is original image $this->assertStringEndsWith($imgDetails['path'], $displayThumb); $this->assertStringNotContainsString('thumbs', $displayThumb); // Ensure gallery thumbnail is reduced image (single frame) $galleryThumbRelPath = implode('/', array_slice(explode('/', $galleryThumb), 3)); $galleryThumbPath = public_path($galleryThumbRelPath); $galleryFileSize = filesize($galleryThumbPath); // Basic scan of GIF content to check frame count $originalFrameCount = count(explode("\x00\x21\xF9", file_get_contents($originalFile))) - 1; $galleryFrameCount = count(explode("\x00\x21\xF9", file_get_contents($galleryThumbPath))) - 1; $this->files->deleteAtRelativePath($relPath); $this->files->deleteAtRelativePath($galleryThumbRelPath); $this->assertNotEquals($originalFileSize, $galleryFileSize); $this->assertEquals(2, $originalFrameCount); $this->assertLessThan(2, $galleryFrameCount); } protected function getTestProfileImage() { $imageName = 'profile.png'; $relPath = $this->files->expectedImagePath('user', $imageName); $this->files->deleteAtRelativePath($relPath); return $this->files->uploadedImage($imageName); } public function test_user_image_upload() { $editor = $this->users->editor(); $admin = $this->users->admin(); $this->actingAs($admin); $file = $this->getTestProfileImage(); $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []); $this->assertDatabaseHas('images', [ 'type' => 'user', 'uploaded_to' => $editor->id, 'created_by' => $admin->id, ]); } public function test_user_images_deleted_on_user_deletion() { $editor = $this->users->editor(); $this->actingAs($editor); $file = $this->getTestProfileImage(); $this->call('PUT', '/my-account/profile', [], [], ['profile_image' => $file], []); $profileImages = Image::where('type', '=', 'user')->where('created_by', '=', $editor->id)->get(); $this->assertTrue($profileImages->count() === 1, 'Found profile images does not match upload count'); $imagePath = public_path($profileImages->first()->path); $this->assertTrue(file_exists($imagePath)); $userDelete = $this->asAdmin()->delete($editor->getEditUrl()); $userDelete->assertStatus(302); $this->assertDatabaseMissing('images', [ 'type' => 'user', 'created_by' => $editor->id, ]); $this->assertDatabaseMissing('images', [ 'type' => 'user', 'uploaded_to' => $editor->id, ]); $this->assertFalse(file_exists($imagePath)); } public function test_deleted_unused_images() { $page = $this->entities->page(); $admin = $this->users->admin(); $this->actingAs($admin); $imageName = 'unused-image.png'; $relPath = $this->files->expectedImagePath('gallery', $imageName); $this->files->deleteAtRelativePath($relPath); $upload = $this->files->uploadGalleryImage($this, $imageName, $page->id); $upload->assertStatus(200); $image = Image::where('type', '=', 'gallery')->first(); $pageRepo = app(PageRepo::class); $pageRepo->update($page, [ 'name' => $page->name, 'html' => $page->html . "<img src=\"{$image->url}\">", 'summary' => '', ]); // Ensure no images are reported as deletable $imageService = app(ImageService::class); $toDelete = $imageService->deleteUnusedImages(true, true); $this->assertCount(0, $toDelete); // Save a revision of our page without the image; $pageRepo->update($page, [ 'name' => $page->name, 'html' => '<p>Hello</p>', 'summary' => '', ]); // Ensure revision images are picked up okay $imageService = app(ImageService::class); $toDelete = $imageService->deleteUnusedImages(true, true); $this->assertCount(0, $toDelete); $toDelete = $imageService->deleteUnusedImages(false, true); $this->assertCount(1, $toDelete); // Check image is found when revisions are destroyed $page->revisions()->delete(); $toDelete = $imageService->deleteUnusedImages(true, true); $this->assertCount(1, $toDelete); // Check the image is deleted $absPath = public_path($relPath); $this->assertTrue(file_exists($absPath), "Existing uploaded file at path {$absPath} exists"); $toDelete = $imageService->deleteUnusedImages(true, false); $this->assertCount(1, $toDelete); $this->assertFalse(file_exists($absPath)); $this->files->deleteAtRelativePath($relPath); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Uploads/ImageStorageTest.php
tests/Uploads/ImageStorageTest.php
<?php namespace Tests\Uploads; use BookStack\Uploads\ImageStorage; use Tests\TestCase; class ImageStorageTest extends TestCase { public function test_local_image_storage_sets_755_directory_permissions() { if (PHP_OS_FAMILY !== 'Linux') { $this->markTestSkipped('Test only works on Linux'); } config()->set('filesystems.default', 'local'); $storage = $this->app->make(ImageStorage::class); $dirToCheck = 'test-dir-perms-' . substr(md5(random_bytes(16)), 0, 6); $disk = $storage->getDisk('gallery'); $disk->put("{$dirToCheck}/image.png", 'abc', true); $expectedPath = public_path("uploads/images/{$dirToCheck}"); $permissionsApplied = substr(sprintf('%o', fileperms($expectedPath)), -4); $this->assertEquals('0755', $permissionsApplied); @unlink("{$expectedPath}/image.png"); @rmdir($expectedPath); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Uploads/AttachmentTest.php
tests/Uploads/AttachmentTest.php
<?php namespace Tests\Uploads; use BookStack\Entities\Models\Page; use BookStack\Entities\Repos\PageRepo; use BookStack\Entities\Tools\TrashCan; use BookStack\Uploads\Attachment; use Tests\TestCase; class AttachmentTest extends TestCase { public function test_file_upload() { $page = $this->entities->page(); $this->asAdmin(); $admin = $this->users->admin(); $fileName = 'upload_test_file.txt'; $expectedResp = [ 'name' => $fileName, 'uploaded_to' => $page->id, 'extension' => 'txt', 'order' => 1, 'created_by' => $admin->id, 'updated_by' => $admin->id, ]; $upload = $this->files->uploadAttachmentFile($this, $fileName, $page->id); $upload->assertStatus(200); $attachment = Attachment::query()->orderBy('id', 'desc')->first(); $upload->assertJson($expectedResp); $expectedResp['path'] = $attachment->path; $this->assertDatabaseHas('attachments', $expectedResp); $this->files->deleteAllAttachmentFiles(); } public function test_file_upload_does_not_use_filename() { $page = $this->entities->page(); $fileName = 'upload_test_file.txt'; $this->asAdmin(); $upload = $this->files->uploadAttachmentFile($this, $fileName, $page->id); $upload->assertStatus(200); $attachment = Attachment::query()->orderBy('id', 'desc')->first(); $this->assertStringNotContainsString($fileName, $attachment->path); $this->assertStringEndsWith('-txt', $attachment->path); $this->files->deleteAllAttachmentFiles(); } public function test_file_display_and_access() { $page = $this->entities->page(); $this->asAdmin(); $fileName = 'upload_test_file.txt'; $upload = $this->files->uploadAttachmentFile($this, $fileName, $page->id); $upload->assertStatus(200); $attachment = Attachment::orderBy('id', 'desc')->take(1)->first(); $pageGet = $this->get($page->getUrl()); $pageGet->assertSeeText($fileName); $pageGet->assertSee($attachment->getUrl()); $attachmentGet = $this->get($attachment->getUrl()); $content = $attachmentGet->streamedContent(); $this->assertStringContainsString('Hi, This is a test file for testing the upload process.', $content); $this->files->deleteAllAttachmentFiles(); } public function test_attaching_link_to_page() { $page = $this->entities->page(); $admin = $this->users->admin(); $this->asAdmin(); $linkReq = $this->call('POST', 'attachments/link', [ 'attachment_link_url' => 'https://example.com', 'attachment_link_name' => 'Example Attachment Link', 'attachment_link_uploaded_to' => $page->id, ]); $expectedData = [ 'path' => 'https://example.com', 'name' => 'Example Attachment Link', 'uploaded_to' => $page->id, 'created_by' => $admin->id, 'updated_by' => $admin->id, 'external' => true, 'order' => 1, 'extension' => '', ]; $linkReq->assertStatus(200); $this->assertDatabaseHas('attachments', $expectedData); $attachment = Attachment::orderBy('id', 'desc')->take(1)->first(); $pageGet = $this->get($page->getUrl()); $pageGet->assertSeeText('Example Attachment Link'); $pageGet->assertSee($attachment->getUrl()); $attachmentGet = $this->get($attachment->getUrl()); $attachmentGet->assertRedirect('https://example.com'); $this->files->deleteAllAttachmentFiles(); } public function test_attaching_long_links_to_a_page() { $page = $this->entities->page(); $link = 'https://example.com?query=' . str_repeat('catsIScool', 195); $linkReq = $this->asAdmin()->post('attachments/link', [ 'attachment_link_url' => $link, 'attachment_link_name' => 'Example Attachment Link', 'attachment_link_uploaded_to' => $page->id, ]); $linkReq->assertStatus(200); $this->assertDatabaseHas('attachments', [ 'uploaded_to' => $page->id, 'path' => $link, 'external' => true, ]); $attachment = $page->attachments()->where('external', '=', true)->first(); $resp = $this->get($attachment->getUrl()); $resp->assertRedirect($link); } public function test_attachment_updating() { $page = $this->entities->page(); $this->asAdmin(); $attachment = Attachment::factory()->create(['uploaded_to' => $page->id]); $update = $this->call('PUT', 'attachments/' . $attachment->id, [ 'attachment_edit_name' => 'My new attachment name', 'attachment_edit_url' => 'https://test.example.com', ]); $expectedData = [ 'id' => $attachment->id, 'path' => 'https://test.example.com', 'name' => 'My new attachment name', 'uploaded_to' => $page->id, ]; $update->assertStatus(200); $this->assertDatabaseHas('attachments', $expectedData); $this->files->deleteAllAttachmentFiles(); } public function test_file_deletion() { $page = $this->entities->page(); $this->asAdmin(); $fileName = 'deletion_test.txt'; $this->files->uploadAttachmentFile($this, $fileName, $page->id); $attachment = Attachment::query()->orderBy('id', 'desc')->first(); $filePath = storage_path($attachment->path); $this->assertTrue(file_exists($filePath), 'File at path ' . $filePath . ' does not exist'); $attachment = Attachment::first(); $this->delete($attachment->getUrl()); $this->assertDatabaseMissing('attachments', [ 'name' => $fileName, ]); $this->assertFalse(file_exists($filePath), 'File at path ' . $filePath . ' was not deleted as expected'); $this->files->deleteAllAttachmentFiles(); } public function test_attachment_deletion_on_page_deletion() { $page = $this->entities->page(); $this->asAdmin(); $fileName = 'deletion_test.txt'; $this->files->uploadAttachmentFile($this, $fileName, $page->id); $attachment = Attachment::query()->orderBy('id', 'desc')->first(); $filePath = storage_path($attachment->path); $this->assertTrue(file_exists($filePath), 'File at path ' . $filePath . ' does not exist'); $this->assertDatabaseHas('attachments', [ 'name' => $fileName, ]); app(PageRepo::class)->destroy($page); app(TrashCan::class)->empty(); $this->assertDatabaseMissing('attachments', [ 'name' => $fileName, ]); $this->assertFalse(file_exists($filePath), 'File at path ' . $filePath . ' was not deleted as expected'); $this->files->deleteAllAttachmentFiles(); } public function test_attachment_access_without_permission_shows_404() { $admin = $this->users->admin(); $viewer = $this->users->viewer(); $page = $this->entities->page(); /** @var Page $page */ $this->actingAs($admin); $fileName = 'permission_test.txt'; $this->files->uploadAttachmentFile($this, $fileName, $page->id); $attachment = Attachment::orderBy('id', 'desc')->take(1)->first(); $this->permissions->setEntityPermissions($page, [], []); $this->actingAs($viewer); $attachmentGet = $this->get($attachment->getUrl()); $attachmentGet->assertStatus(404); $attachmentGet->assertSee('Attachment not found'); $this->files->deleteAllAttachmentFiles(); } public function test_data_and_js_links_cannot_be_attached_to_a_page() { $page = $this->entities->page(); $this->asAdmin(); $badLinks = [ 'javascript:alert("bunny")', ' javascript:alert("bunny")', 'JavaScript:alert("bunny")', "\t\n\t\nJavaScript:alert(\"bunny\")", 'data:text/html;<a></a>', 'Data:text/html;<a></a>', 'Data:text/html;<a></a>', ]; foreach ($badLinks as $badLink) { $linkReq = $this->post('attachments/link', [ 'attachment_link_url' => $badLink, 'attachment_link_name' => 'Example Attachment Link', 'attachment_link_uploaded_to' => $page->id, ]); $linkReq->assertStatus(422); $this->assertDatabaseMissing('attachments', [ 'path' => $badLink, ]); } $attachment = Attachment::factory()->create(['uploaded_to' => $page->id]); foreach ($badLinks as $badLink) { $linkReq = $this->put('attachments/' . $attachment->id, [ 'attachment_edit_url' => $badLink, 'attachment_edit_name' => 'Example Attachment Link', ]); $linkReq->assertStatus(422); $this->assertDatabaseMissing('attachments', [ 'path' => $badLink, ]); } } public function test_attachment_delete_only_shows_with_permission() { $this->asAdmin(); $page = $this->entities->page(); $this->files->uploadAttachmentFile($this, 'upload_test.txt', $page->id); $attachment = $page->attachments()->first(); $viewer = $this->users->viewer(); $this->permissions->grantUserRolePermissions($viewer, ['page-update-all', 'attachment-create-all']); $resp = $this->actingAs($viewer)->get($page->getUrl('/edit')); $html = $this->withHtml($resp); $html->assertElementExists(".card[data-id=\"{$attachment->id}\"]"); $html->assertElementNotExists(".card[data-id=\"{$attachment->id}\"] button[title=\"Delete\"]"); $this->permissions->grantUserRolePermissions($viewer, ['attachment-delete-all']); $resp = $this->actingAs($viewer)->get($page->getUrl('/edit')); $html = $this->withHtml($resp); $html->assertElementExists(".card[data-id=\"{$attachment->id}\"] button[title=\"Delete\"]"); } public function test_attachment_edit_only_shows_with_permission() { $this->asAdmin(); $page = $this->entities->page(); $this->files->uploadAttachmentFile($this, 'upload_test.txt', $page->id); $attachment = $page->attachments()->first(); $viewer = $this->users->viewer(); $this->permissions->grantUserRolePermissions($viewer, ['page-update-all', 'attachment-create-all']); $resp = $this->actingAs($viewer)->get($page->getUrl('/edit')); $html = $this->withHtml($resp); $html->assertElementExists(".card[data-id=\"{$attachment->id}\"]"); $html->assertElementNotExists(".card[data-id=\"{$attachment->id}\"] button[title=\"Edit\"]"); $this->permissions->grantUserRolePermissions($viewer, ['attachment-update-all']); $resp = $this->actingAs($viewer)->get($page->getUrl('/edit')); $html = $this->withHtml($resp); $html->assertElementExists(".card[data-id=\"{$attachment->id}\"] button[title=\"Edit\"]"); } public function test_file_access_with_open_query_param_provides_inline_response_with_correct_content_type() { $page = $this->entities->page(); $this->asAdmin(); $fileName = 'upload_test_file.txt'; $upload = $this->files->uploadAttachmentFile($this, $fileName, $page->id); $upload->assertStatus(200); $attachment = Attachment::query()->orderBy('id', 'desc')->take(1)->first(); $attachmentGet = $this->get($attachment->getUrl(true)); // http-foundation/Response does some 'fixing' of responses to add charsets to text responses. $attachmentGet->assertHeader('Content-Type', 'text/plain; charset=utf-8'); $attachmentGet->assertHeader('Content-Disposition', 'inline; filename="upload_test_file.txt"'); $attachmentGet->assertHeader('X-Content-Type-Options', 'nosniff'); $this->files->deleteAllAttachmentFiles(); } public function test_html_file_access_with_open_forces_plain_content_type() { $page = $this->entities->page(); $this->asAdmin(); $attachment = $this->files->uploadAttachmentDataToPage($this, $page, 'test_file.html', '<html></html><p>testing</p>', 'text/html'); $attachmentGet = $this->get($attachment->getUrl(true)); // http-foundation/Response does some 'fixing' of responses to add charsets to text responses. $attachmentGet->assertHeader('Content-Type', 'text/plain; charset=utf-8'); $attachmentGet->assertHeader('Content-Disposition', 'inline; filename="test_file.html"'); $this->files->deleteAllAttachmentFiles(); } public function test_file_upload_works_when_local_secure_restricted_is_in_use() { config()->set('filesystems.attachments', 'local_secure_restricted'); $page = $this->entities->page(); $fileName = 'upload_test_file.txt'; $this->asAdmin(); $upload = $this->files->uploadAttachmentFile($this, $fileName, $page->id); $upload->assertStatus(200); $attachment = Attachment::query()->orderBy('id', 'desc')->where('uploaded_to', '=', $page->id)->first(); $this->assertFileExists(storage_path($attachment->path)); $this->files->deleteAllAttachmentFiles(); } public function test_file_get_range_access() { $page = $this->entities->page(); $this->asAdmin(); $attachment = $this->files->uploadAttachmentDataToPage($this, $page, 'my_text.txt', 'abc123456', 'text/plain'); // Download access $resp = $this->get($attachment->getUrl(), ['Range' => 'bytes=3-5']); $resp->assertStatus(206); $resp->assertStreamedContent('123'); $resp->assertHeader('Content-Length', '3'); $resp->assertHeader('Content-Range', 'bytes 3-5/9'); // Inline access $resp = $this->get($attachment->getUrl(true), ['Range' => 'bytes=5-7']); $resp->assertStatus(206); $resp->assertStreamedContent('345'); $resp->assertHeader('Content-Length', '3'); $resp->assertHeader('Content-Range', 'bytes 5-7/9'); $this->files->deleteAllAttachmentFiles(); } public function test_file_head_range_returns_no_content() { $page = $this->entities->page(); $this->asAdmin(); $attachment = $this->files->uploadAttachmentDataToPage($this, $page, 'my_text.txt', 'abc123456', 'text/plain'); $resp = $this->head($attachment->getUrl(), ['Range' => 'bytes=0-9']); $resp->assertStreamedContent(''); $resp->assertHeader('Content-Length', '9'); $resp->assertStatus(200); $this->files->deleteAllAttachmentFiles(); } public function test_file_head_range_edge_cases() { $page = $this->entities->page(); $this->asAdmin(); // Mime-type "sniffing" happens on first 2k bytes, hence this content (2005 bytes) $content = '01234' . str_repeat('a', 1990) . '0123456789'; $attachment = $this->files->uploadAttachmentDataToPage($this, $page, 'my_text.txt', $content, 'text/plain'); // Test for both inline and download attachment serving foreach ([true, false] as $isInline) { // No end range $resp = $this->get($attachment->getUrl($isInline), ['Range' => 'bytes=5-']); $resp->assertStreamedContent(substr($content, 5)); $resp->assertHeader('Content-Length', '2000'); $resp->assertHeader('Content-Range', 'bytes 5-2004/2005'); $resp->assertStatus(206); // End only range $resp = $this->get($attachment->getUrl($isInline), ['Range' => 'bytes=-10']); $resp->assertStreamedContent('0123456789'); $resp->assertHeader('Content-Length', '10'); $resp->assertHeader('Content-Range', 'bytes 1995-2004/2005'); $resp->assertStatus(206); // Range across sniff point $resp = $this->get($attachment->getUrl($isInline), ['Range' => 'bytes=1997-2002']); $resp->assertStreamedContent('234567'); $resp->assertHeader('Content-Length', '6'); $resp->assertHeader('Content-Range', 'bytes 1997-2002/2005'); $resp->assertStatus(206); // Range up to sniff point $resp = $this->get($attachment->getUrl($isInline), ['Range' => 'bytes=0-1997']); $resp->assertHeader('Content-Length', '1998'); $resp->assertHeader('Content-Range', 'bytes 0-1997/2005'); $resp->assertStreamedContent(substr($content, 0, 1998)); $resp->assertStatus(206); // Range beyond sniff point $resp = $this->get($attachment->getUrl($isInline), ['Range' => 'bytes=2001-2003']); $resp->assertStreamedContent('678'); $resp->assertHeader('Content-Length', '3'); $resp->assertHeader('Content-Range', 'bytes 2001-2003/2005'); $resp->assertStatus(206); // Range beyond content $resp = $this->get($attachment->getUrl($isInline), ['Range' => 'bytes=0-2010']); $resp->assertStreamedContent($content); $resp->assertHeader('Content-Length', '2005'); $resp->assertHeader('Content-Range', 'bytes 0-2004/2005'); $resp->assertStatus(206); // Range start before end $resp = $this->get($attachment->getUrl($isInline), ['Range' => 'bytes=50-10']); $resp->assertStreamedContent($content); $resp->assertHeader('Content-Length', '2005'); $resp->assertHeader('Content-Range', 'bytes */2005'); $resp->assertStatus(416); // Full range request $resp = $this->get($attachment->getUrl($isInline), ['Range' => 'bytes=0-']); $resp->assertStreamedContent($content); $resp->assertHeader('Content-Length', '2005'); $resp->assertHeader('Content-Range', 'bytes 0-2004/2005'); $resp->assertStatus(206); } $this->files->deleteAllAttachmentFiles(); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Uploads/AvatarTest.php
tests/Uploads/AvatarTest.php
<?php namespace Tests\Uploads; use BookStack\Exceptions\HttpFetchException; use BookStack\Uploads\UserAvatars; use BookStack\Users\Models\User; use GuzzleHttp\Exception\ConnectException; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Response; use Tests\TestCase; class AvatarTest extends TestCase { protected function createUserRequest($user): User { $this->asAdmin()->post('/settings/users/create', [ 'name' => $user->name, 'email' => $user->email, 'password' => 'testing101', 'password-confirm' => 'testing101', ]); return User::query()->where('email', '=', $user->email)->first(); } protected function deleteUserImage(User $user): void { $this->files->deleteAtRelativePath($user->avatar->path); } public function test_gravatar_fetched_on_user_create() { $requests = $this->mockHttpClient([new Response(200, ['Content-Type' => 'image/png'], $this->files->pngImageData())]); config()->set(['services.disable_services' => false]); $user = User::factory()->make(); $user = $this->createUserRequest($user); $this->assertDatabaseHas('images', [ 'type' => 'user', 'created_by' => $user->id, ]); $this->deleteUserImage($user); $expectedUri = 'https://www.gravatar.com/avatar/' . md5(strtolower($user->email)) . '?s=500&d=identicon'; $this->assertEquals($expectedUri, $requests->latestRequest()->getUri()); } public function test_custom_url_used_if_set() { config()->set([ 'services.disable_services' => false, 'services.avatar_url' => 'https://example.com/${email}/${hash}/${size}', ]); $user = User::factory()->make(); $url = 'https://example.com/' . urlencode(strtolower($user->email)) . '/' . md5(strtolower($user->email)) . '/500'; $requests = $this->mockHttpClient([new Response(200, ['Content-Type' => 'image/png'], $this->files->pngImageData())]); $user = $this->createUserRequest($user); $this->assertEquals($url, $requests->latestRequest()->getUri()); $this->deleteUserImage($user); } public function test_avatar_not_fetched_if_no_custom_url_and_services_disabled() { config()->set(['services.disable_services' => true]); $user = User::factory()->make(); $requests = $this->mockHttpClient([new Response()]); $this->createUserRequest($user); $this->assertEquals(0, $requests->requestCount()); } public function test_avatar_not_fetched_if_avatar_url_option_set_to_false() { config()->set([ 'services.disable_services' => false, 'services.avatar_url' => false, ]); $user = User::factory()->make(); $requests = $this->mockHttpClient([new Response()]); $this->createUserRequest($user); $this->assertEquals(0, $requests->requestCount()); } public function test_no_failure_but_error_logged_on_failed_avatar_fetch() { config()->set(['services.disable_services' => false]); $this->mockHttpClient([new ConnectException('Failed to connect', new Request('GET', ''))]); $logger = $this->withTestLogger(); $user = User::factory()->make(); $this->createUserRequest($user); $this->assertTrue($logger->hasError('Failed to save user avatar image')); } public function test_exception_message_on_failed_fetch() { // set wrong url config()->set([ 'services.disable_services' => false, 'services.avatar_url' => 'http_malformed_url/${email}/${hash}/${size}', ]); $user = User::factory()->make(); $avatar = app()->make(UserAvatars::class); $logger = $this->withTestLogger(); $this->mockHttpClient([new ConnectException('Could not resolve host http_malformed_url', new Request('GET', ''))]); $avatar->fetchAndAssignToUser($user); $url = 'http_malformed_url/' . urlencode(strtolower($user->email)) . '/' . md5(strtolower($user->email)) . '/500'; $this->assertTrue($logger->hasError('Failed to save user avatar image')); $exception = $logger->getRecords()[0]['context']['exception']; $this->assertInstanceOf(HttpFetchException::class, $exception); $this->assertEquals('Cannot get image from ' . $url, $exception->getMessage()); $this->assertEquals('Could not resolve host http_malformed_url', $exception->getPrevious()->getMessage()); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Uploads/DrawioTest.php
tests/Uploads/DrawioTest.php
<?php namespace Tests\Uploads; use BookStack\Uploads\Image; use Tests\TestCase; class DrawioTest extends TestCase { public function test_get_image_as_base64() { $page = $this->entities->page(); $this->asAdmin(); $imageName = 'first-image.png'; $this->files->uploadGalleryImage($this, $imageName, $page->id); /** @var Image $image */ $image = Image::query()->first(); $image->type = 'drawio'; $image->save(); $imageGet = $this->getJson("/images/drawio/base64/{$image->id}"); $imageGet->assertJson([ 'content' => 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEcDCo5iYNs+gAAAB1pVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVBkLmUHAAAAFElEQVQI12O0jN/KgASYGFABqXwAZtoBV6Sl3hIAAAAASUVORK5CYII=', ]); } public function test_non_accessible_image_returns_404_error_and_message() { $page = $this->entities->page(); $this->asEditor(); $imageName = 'non-accessible-image.png'; $this->files->uploadGalleryImage($this, $imageName, $page->id); /** @var Image $image */ $image = Image::query()->first(); $image->type = 'drawio'; $image->save(); $this->permissions->disableEntityInheritedPermissions($page); $imageGet = $this->getJson("/images/drawio/base64/{$image->id}"); $imageGet->assertNotFound(); $imageGet->assertJson([ 'message' => 'Drawing data could not be loaded. The drawing file might no longer exist or you may not have permission to access it.', ]); } public function test_drawing_base64_upload() { $page = $this->entities->page(); $editor = $this->users->editor(); $this->actingAs($editor); $upload = $this->postJson('images/drawio', [ 'uploaded_to' => $page->id, 'image' => 'image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEcDCo5iYNs+gAAAB1pVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVBkLmUHAAAAFElEQVQI12O0jN/KgASYGFABqXwAZtoBV6Sl3hIAAAAASUVORK5CYII=', ]); $upload->assertStatus(200); $upload->assertJson([ 'type' => 'drawio', 'uploaded_to' => $page->id, 'created_by' => $editor->id, 'updated_by' => $editor->id, ]); $image = Image::where('type', '=', 'drawio')->first(); $this->assertTrue(file_exists(public_path($image->path)), 'Uploaded image not found at path: ' . public_path($image->path)); $testImageData = $this->files->pngImageData(); $uploadedImageData = file_get_contents(public_path($image->path)); $this->assertTrue($testImageData === $uploadedImageData, 'Uploaded image file data does not match our test image as expected'); } public function test_drawio_url_can_be_configured() { config()->set('services.drawio', 'http://cats.com?dog=tree'); $page = $this->entities->page(); $editor = $this->users->editor(); $resp = $this->actingAs($editor)->get($page->getUrl('/edit')); $resp->assertSee('drawio-url="http://cats.com?dog=tree"', false); } public function test_drawio_url_can_be_disabled() { config()->set('services.drawio', true); $page = $this->entities->page(); $editor = $this->users->editor(); $resp = $this->actingAs($editor)->get($page->getUrl('/edit')); $resp->assertSee('drawio-url="https://embed.diagrams.net/?embed=1&amp;proto=json&amp;spin=1&amp;configure=1"', false); config()->set('services.drawio', false); $resp = $this->actingAs($editor)->get($page->getUrl('/edit')); $resp->assertDontSee('drawio-url', false); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/User/RoleManagementTest.php
tests/User/RoleManagementTest.php
<?php namespace Tests\User; use BookStack\Activity\ActivityType; use BookStack\Users\Models\Role; use BookStack\Users\Models\User; use Tests\TestCase; class RoleManagementTest extends TestCase { public function test_cannot_delete_admin_role() { $adminRole = Role::getRole('admin'); $deletePageUrl = '/settings/roles/delete/' . $adminRole->id; $this->asAdmin()->get($deletePageUrl); $this->delete($deletePageUrl)->assertRedirect($deletePageUrl); $this->get($deletePageUrl)->assertSee('cannot be deleted'); } public function test_role_cannot_be_deleted_if_default() { $newRole = $this->users->createRole(); $this->setSettings(['registration-role' => $newRole->id]); $deletePageUrl = '/settings/roles/delete/' . $newRole->id; $this->asAdmin()->get($deletePageUrl); $this->delete($deletePageUrl)->assertRedirect($deletePageUrl); $this->get($deletePageUrl)->assertSee('cannot be deleted'); } public function test_role_create_update_delete_flow() { $testRoleName = 'Test Role'; $testRoleDesc = 'a little test description'; $testRoleUpdateName = 'An Super Updated role'; // Creation $resp = $this->asAdmin()->get('/settings/features'); $this->withHtml($resp)->assertElementContains('a[href="' . url('/settings/roles') . '"]', 'Roles'); $resp = $this->get('/settings/roles'); $this->withHtml($resp)->assertElementContains('a[href="' . url('/settings/roles/new') . '"]', 'Create New Role'); $resp = $this->get('/settings/roles/new'); $this->withHtml($resp)->assertElementContains('form[action="' . url('/settings/roles/new') . '"]', 'Save Role'); $resp = $this->post('/settings/roles/new', [ 'display_name' => $testRoleName, 'description' => $testRoleDesc, ]); $resp->assertRedirect('/settings/roles'); $resp = $this->get('/settings/roles'); $resp->assertSee($testRoleName); $resp->assertSee($testRoleDesc); $this->assertDatabaseHas('roles', [ 'display_name' => $testRoleName, 'description' => $testRoleDesc, 'mfa_enforced' => false, ]); /** @var Role $role */ $role = Role::query()->where('display_name', '=', $testRoleName)->first(); // Updating $resp = $this->get('/settings/roles/' . $role->id); $resp->assertSee($testRoleName); $resp->assertSee($testRoleDesc); $this->withHtml($resp)->assertElementContains('form[action="' . url('/settings/roles/' . $role->id) . '"]', 'Save Role'); $resp = $this->put('/settings/roles/' . $role->id, [ 'display_name' => $testRoleUpdateName, 'description' => $testRoleDesc, 'mfa_enforced' => 'true', ]); $resp->assertRedirect('/settings/roles'); $this->assertDatabaseHas('roles', [ 'display_name' => $testRoleUpdateName, 'description' => $testRoleDesc, 'mfa_enforced' => true, ]); // Deleting $resp = $this->get('/settings/roles/' . $role->id); $this->withHtml($resp)->assertElementContains('a[href="' . url("/settings/roles/delete/$role->id") . '"]', 'Delete Role'); $resp = $this->get("/settings/roles/delete/$role->id"); $resp->assertSee($testRoleUpdateName); $this->withHtml($resp)->assertElementContains('form[action="' . url("/settings/roles/delete/$role->id") . '"]', 'Confirm'); $resp = $this->delete("/settings/roles/delete/$role->id"); $resp->assertRedirect('/settings/roles'); $this->get('/settings/roles')->assertSee('Role successfully deleted'); $this->assertActivityExists(ActivityType::ROLE_DELETE); } public function test_role_external_auth_id_validation() { config()->set('auth.method', 'oidc'); $role = Role::query()->first(); $routeByMethod = [ 'post' => '/settings/roles/new', 'put' => "/settings/roles/{$role->id}", ]; foreach ($routeByMethod as $method => $route) { $resp = $this->asAdmin()->get($route); $resp->assertDontSee('The external auth id'); $resp = $this->asAdmin()->call($method, $route, [ 'display_name' => 'Test role for auth id validation', 'description' => '', 'external_auth_id' => str_repeat('a', 181), ]); $resp->assertRedirect($route); $resp = $this->followRedirects($resp); $resp->assertSee('The external auth id may not be greater than 180 characters.'); } } public function test_admin_role_cannot_be_removed_if_user_last_admin() { /** @var Role $adminRole */ $adminRole = Role::query()->where('system_name', '=', 'admin')->first(); $adminUser = $this->users->admin(); $adminRole->users()->where('id', '!=', $adminUser->id)->delete(); $this->assertEquals(1, $adminRole->users()->count()); $viewerRole = $this->users->viewer()->roles()->first(); $editUrl = '/settings/users/' . $adminUser->id; $resp = $this->actingAs($adminUser)->put($editUrl, [ 'name' => $adminUser->name, 'email' => $adminUser->email, 'roles' => [ 'viewer' => strval($viewerRole->id), ], ]); $resp->assertRedirect($editUrl); $resp = $this->get($editUrl); $resp->assertSee('This user is the only user assigned to the administrator role'); } public function test_migrate_users_on_delete_works() { $roleA = $this->users->createRole(); $roleB = $this->users->createRole(); $user = $this->users->viewer(); $user->attachRole($roleB); $this->assertCount(0, $roleA->users()->get()); $this->assertCount(1, $roleB->users()->get()); $deletePage = $this->asAdmin()->get("/settings/roles/delete/$roleB->id"); $this->withHtml($deletePage)->assertElementExists('select[name=migrate_role_id]'); $this->asAdmin()->delete("/settings/roles/delete/$roleB->id", [ 'migrate_role_id' => $roleA->id, ]); $this->assertCount(1, $roleA->users()->get()); $this->assertEquals($user->id, $roleA->users()->first()->id); } public function test_delete_with_empty_migrate_option_works() { $role = $this->users->attachNewRole($this->users->viewer()); $this->assertCount(1, $role->users()->get()); $deletePage = $this->asAdmin()->get("/settings/roles/delete/$role->id"); $this->withHtml($deletePage)->assertElementExists('select[name=migrate_role_id]'); $resp = $this->asAdmin()->delete("/settings/roles/delete/$role->id", [ 'migrate_role_id' => '', ]); $resp->assertRedirect('/settings/roles'); $this->assertDatabaseMissing('roles', ['id' => $role->id]); } public function test_entity_permissions_are_removed_on_delete() { /** @var Role $roleA */ $roleA = Role::query()->create(['display_name' => 'Entity Permissions Delete Test']); $page = $this->entities->page(); $this->permissions->setEntityPermissions($page, ['view'], [$roleA]); $this->assertDatabaseHas('entity_permissions', [ 'role_id' => $roleA->id, 'entity_id' => $page->id, 'entity_type' => $page->getMorphClass(), ]); $this->asAdmin()->delete("/settings/roles/delete/$roleA->id"); $this->assertDatabaseMissing('entity_permissions', [ 'role_id' => $roleA->id, 'entity_id' => $page->id, 'entity_type' => $page->getMorphClass(), ]); } public function test_image_view_notice_shown_on_role_form() { /** @var Role $role */ $role = Role::query()->first(); $this->asAdmin()->get("/settings/roles/{$role->id}") ->assertSee('Actual access of uploaded image files will be dependant upon system image storage option'); } public function test_copy_role_button_shown() { /** @var Role $role */ $role = Role::query()->first(); $resp = $this->asAdmin()->get("/settings/roles/{$role->id}"); $this->withHtml($resp)->assertElementContains('a[href$="/roles/new?copy_from=' . $role->id . '"]', 'Copy'); } public function test_copy_from_param_on_create_prefills_with_other_role_data() { /** @var Role $role */ $role = Role::query()->first(); $resp = $this->asAdmin()->get("/settings/roles/new?copy_from={$role->id}"); $resp->assertOk(); $this->withHtml($resp)->assertElementExists('input[name="display_name"][value="' . ($role->display_name . ' (Copy)') . '"]'); } public function test_public_role_visible_in_user_edit_screen() { /** @var User $user */ $user = User::query()->first(); $adminRole = Role::getSystemRole('admin'); $publicRole = Role::getSystemRole('public'); $resp = $this->asAdmin()->get('/settings/users/' . $user->id); $this->withHtml($resp)->assertElementExists('[name="roles[' . $adminRole->id . ']"]') ->assertElementExists('[name="roles[' . $publicRole->id . ']"]'); } public function test_public_role_visible_in_role_listing() { $this->asAdmin()->get('/settings/roles') ->assertSee('Admin') ->assertSee('Public'); } public function test_public_role_visible_in_default_role_setting() { $resp = $this->asAdmin()->get('/settings/registration'); $this->withHtml($resp)->assertElementExists('[data-system-role-name="admin"]') ->assertElementExists('[data-system-role-name="public"]'); } public function test_public_role_not_deletable() { /** @var Role $publicRole */ $publicRole = Role::getSystemRole('public'); $resp = $this->asAdmin()->delete('/settings/roles/delete/' . $publicRole->id); $resp->assertRedirect('/settings/roles/delete/' . $publicRole->id); $this->get('/settings/roles/delete/' . $publicRole->id); $resp = $this->delete('/settings/roles/delete/' . $publicRole->id); $resp->assertRedirect('/settings/roles/delete/' . $publicRole->id); $resp = $this->get('/settings/roles/delete/' . $publicRole->id); $resp->assertSee('This role is a system role and cannot be deleted'); } public function test_role_permission_removal() { // To cover issue fixed in f99c8ff99aee9beb8c692f36d4b84dc6e651e50a. $page = $this->entities->page(); $viewerRole = Role::getRole('viewer'); $viewer = $this->users->viewer(); $this->actingAs($viewer)->get($page->getUrl())->assertOk(); $this->asAdmin()->put('/settings/roles/' . $viewerRole->id, [ 'display_name' => $viewerRole->display_name, 'description' => $viewerRole->description, 'permissions' => [], ])->assertStatus(302); $this->actingAs($viewer)->get($page->getUrl())->assertStatus(404); } public function test_index_listing_sorting() { $this->asAdmin(); $role = $this->users->createRole(); $role->display_name = 'zz test role'; $role->created_at = now()->addDays(1); $role->save(); $runTest = function (string $order, string $direction, bool $expectFirstResult) use ($role) { setting()->putForCurrentUser('roles_sort', $order); setting()->putForCurrentUser('roles_sort_order', $direction); $html = $this->withHtml($this->get('/settings/roles')); $selector = ".item-list-row:first-child a[href$=\"/roles/{$role->id}\"]"; if ($expectFirstResult) { $html->assertElementExists($selector); } else { $html->assertElementNotExists($selector); } }; $runTest('name', 'asc', false); $runTest('name', 'desc', true); $runTest('created_at', 'desc', true); $runTest('created_at', 'asc', false); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/User/UserApiTokenTest.php
tests/User/UserApiTokenTest.php
<?php namespace Tests\User; use BookStack\Activity\ActivityType; use BookStack\Api\ApiToken; use Carbon\Carbon; use Illuminate\Support\Facades\Hash; use Tests\TestCase; class UserApiTokenTest extends TestCase { protected array $testTokenData = [ 'name' => 'My test API token', 'expires_at' => '2050-04-01', ]; public function test_tokens_section_not_visible_in_my_account_without_access_api_permission() { $user = $this->users->viewer(); $resp = $this->actingAs($user)->get('/my-account/auth'); $resp->assertDontSeeText('API Tokens'); $this->permissions->grantUserRolePermissions($user, ['access-api']); $resp = $this->actingAs($user)->get('/my-account/auth'); $resp->assertSeeText('API Tokens'); $resp->assertSeeText('Create Token'); } public function test_those_with_manage_users_can_view_other_user_tokens_but_not_create() { $viewer = $this->users->viewer(); $editor = $this->users->editor(); $this->permissions->grantUserRolePermissions($viewer, ['users-manage']); $resp = $this->actingAs($viewer)->get($editor->getEditUrl()); $resp->assertSeeText('API Tokens'); $resp->assertDontSeeText('Create Token'); } public function test_create_api_token() { $editor = $this->users->editor(); $resp = $this->asAdmin()->get("/api-tokens/{$editor->id}/create"); $resp->assertStatus(200); $resp->assertSee('Create API Token'); $resp->assertSee('Token Secret'); $resp = $this->post("/api-tokens/{$editor->id}/create", $this->testTokenData); $token = ApiToken::query()->latest()->first(); $resp->assertRedirect("/api-tokens/{$editor->id}/{$token->id}"); $this->assertDatabaseHas('api_tokens', [ 'user_id' => $editor->id, 'name' => $this->testTokenData['name'], 'expires_at' => $this->testTokenData['expires_at'], ]); // Check secret token $this->assertSessionHas('api-token-secret:' . $token->id); $secret = session('api-token-secret:' . $token->id); $this->assertDatabaseMissing('api_tokens', [ 'secret' => $secret, ]); $this->assertTrue(Hash::check($secret, $token->secret)); $this->assertTrue(strlen($token->token_id) === 32); $this->assertTrue(strlen($secret) === 32); $this->assertSessionHas('success'); $this->assertActivityExists(ActivityType::API_TOKEN_CREATE); } public function test_create_with_no_expiry_sets_expiry_hundred_years_away() { $editor = $this->users->editor(); $resp = $this->asAdmin()->post("/api-tokens/{$editor->id}/create", ['name' => 'No expiry token', 'expires_at' => '']); $resp->assertRedirect(); $token = ApiToken::query()->latest()->first(); $over = Carbon::now()->addYears(101); $under = Carbon::now()->addYears(99); $this->assertTrue( ($token->expires_at < $over && $token->expires_at > $under), 'Token expiry set at 100 years in future' ); } public function test_created_token_displays_on_profile_page() { $editor = $this->users->editor(); $resp = $this->asAdmin()->post("/api-tokens/{$editor->id}/create", $this->testTokenData); $resp->assertRedirect(); $token = ApiToken::query()->latest()->first(); $resp = $this->get($editor->getEditUrl()); $this->withHtml($resp)->assertElementExists('#api_tokens'); $this->withHtml($resp)->assertElementContains('#api_tokens', $token->name); $this->withHtml($resp)->assertElementContains('#api_tokens', $token->token_id); $this->withHtml($resp)->assertElementContains('#api_tokens', $token->expires_at->format('Y-m-d')); } public function test_secret_shown_once_after_creation() { $editor = $this->users->editor(); $resp = $this->asAdmin()->followingRedirects()->post("/api-tokens/{$editor->id}/create", $this->testTokenData); $resp->assertSeeText('Token Secret'); $token = ApiToken::query()->latest()->first(); $this->assertNull(session('api-token-secret:' . $token->id)); $resp = $this->get("/api-tokens/{$editor->id}/{$token->id}"); $resp->assertOk(); $resp->assertDontSeeText('Client Secret'); } public function test_token_update() { $editor = $this->users->editor(); $this->asAdmin()->post("/api-tokens/{$editor->id}/create", $this->testTokenData); $token = ApiToken::query()->latest()->first(); $updateData = [ 'name' => 'My updated token', 'expires_at' => '2011-01-01', ]; $resp = $this->put("/api-tokens/{$editor->id}/{$token->id}", $updateData); $resp->assertRedirect("/api-tokens/{$editor->id}/{$token->id}"); $this->assertDatabaseHas('api_tokens', array_merge($updateData, ['id' => $token->id])); $this->assertSessionHas('success'); $this->assertActivityExists(ActivityType::API_TOKEN_UPDATE); } public function test_token_update_with_blank_expiry_sets_to_hundred_years_away() { $editor = $this->users->editor(); $this->asAdmin()->post("/api-tokens/{$editor->id}/create", $this->testTokenData); $token = ApiToken::query()->latest()->first(); $this->put("/api-tokens/{$editor->id}/{$token->id}", [ 'name' => 'My updated token', 'expires_at' => '', ])->assertRedirect(); $token->refresh(); $over = Carbon::now()->addYears(101); $under = Carbon::now()->addYears(99); $this->assertTrue( ($token->expires_at < $over && $token->expires_at > $under), 'Token expiry set at 100 years in future' ); } public function test_token_delete() { $editor = $this->users->editor(); $this->asAdmin()->post("/api-tokens/{$editor->id}/create", $this->testTokenData); $token = ApiToken::query()->latest()->first(); $tokenUrl = "/api-tokens/{$editor->id}/{$token->id}"; $resp = $this->get($tokenUrl . '/delete'); $resp->assertSeeText('Delete Token'); $resp->assertSeeText($token->name); $this->withHtml($resp)->assertElementExists('form[action$="' . $tokenUrl . '"]'); $resp = $this->delete($tokenUrl); $resp->assertRedirect($editor->getEditUrl('#api_tokens')); $this->assertDatabaseMissing('api_tokens', ['id' => $token->id]); $this->assertActivityExists(ActivityType::API_TOKEN_DELETE); } public function test_user_manage_can_delete_token_without_api_permission_themselves() { $viewer = $this->users->viewer(); $editor = $this->users->editor(); $this->permissions->grantUserRolePermissions($editor, ['users-manage']); $this->asAdmin()->post("/api-tokens/{$viewer->id}/create", $this->testTokenData); $token = ApiToken::query()->latest()->first(); $resp = $this->actingAs($editor)->get("/api-tokens/{$viewer->id}/{$token->id}"); $resp->assertStatus(200); $resp->assertSeeText('Delete Token'); $resp = $this->actingAs($editor)->delete("/api-tokens/{$viewer->id}/{$token->id}"); $resp->assertRedirect($viewer->getEditUrl('#api_tokens')); $this->assertDatabaseMissing('api_tokens', ['id' => $token->id]); } public function test_return_routes_change_depending_on_entry_context() { $user = $this->users->admin(); $returnByContext = [ 'settings' => url("/settings/users/{$user->id}/#api_tokens"), 'my-account' => url('/my-account/auth#api_tokens'), ]; foreach ($returnByContext as $context => $returnUrl) { $resp = $this->actingAs($user)->get("/api-tokens/{$user->id}/create?context={$context}"); $this->withHtml($resp)->assertLinkExists($returnUrl, 'Cancel'); $this->post("/api-tokens/{$user->id}/create", $this->testTokenData); $token = $user->apiTokens()->latest()->first(); $resp = $this->get($token->getUrl()); $this->withHtml($resp)->assertLinkExists($returnUrl, 'Back'); $resp = $this->delete($token->getUrl()); $resp->assertRedirect($returnUrl); } } public function test_context_assumed_for_editing_tokens_of_another_user() { $user = $this->users->viewer(); $resp = $this->asAdmin()->get("/api-tokens/{$user->id}/create?context=my-account"); $this->withHtml($resp)->assertLinkExists($user->getEditUrl('#api_tokens'), 'Cancel'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/User/UserMyAccountTest.php
tests/User/UserMyAccountTest.php
<?php namespace Tests\User; use BookStack\Access\Mfa\MfaValue; use BookStack\Activity\Tools\UserEntityWatchOptions; use BookStack\Activity\WatchLevels; use BookStack\Api\ApiToken; use BookStack\Uploads\Image; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Str; use Tests\TestCase; class UserMyAccountTest extends TestCase { public function test_index_view() { $resp = $this->asEditor()->get('/my-account'); $resp->assertRedirect('/my-account/profile'); } public function test_views_not_accessible_to_guest_user() { $categories = ['profile', 'auth', 'shortcuts', 'notifications', '']; $this->setSettings(['app-public' => 'true']); $this->permissions->grantUserRolePermissions($this->users->guest(), ['receive-notifications']); foreach ($categories as $category) { $resp = $this->get('/my-account/' . $category); $resp->assertRedirect('/'); } } public function test_profile_updating() { $editor = $this->users->editor(); $resp = $this->actingAs($editor)->get('/my-account/profile'); $resp->assertSee('Profile Details'); $html = $this->withHtml($resp); $html->assertFieldHasValue('name', $editor->name); $html->assertFieldHasValue('email', $editor->email); $resp = $this->put('/my-account/profile', [ 'name' => 'Barryius', 'email' => 'barryius@example.com', 'language' => 'fr', ]); $resp->assertRedirect('/my-account/profile'); $this->assertDatabaseHas('users', [ 'name' => 'Barryius', 'email' => $editor->email, // No email change due to not having permissions ]); $this->assertEquals(setting()->getUser($editor, 'language'), 'fr'); } public function test_profile_user_avatar_update_and_reset() { $user = $this->users->viewer(); $avatarFile = $this->files->uploadedImage('avatar-icon.png'); $this->assertEquals(0, $user->image_id); $upload = $this->actingAs($user)->call('PUT', "/my-account/profile", [ 'name' => 'Barry Scott', ], [], ['profile_image' => $avatarFile], []); $upload->assertRedirect('/my-account/profile'); $user->refresh(); $this->assertNotEquals(0, $user->image_id); /** @var Image $image */ $image = Image::query()->findOrFail($user->image_id); $this->assertFileExists(public_path($image->path)); $reset = $this->put("/my-account/profile", [ 'name' => 'Barry Scott', 'profile_image_reset' => 'true', ]); $upload->assertRedirect('/my-account/profile'); $user->refresh(); $this->assertFileDoesNotExist(public_path($image->path)); $this->assertEquals(0, $user->image_id); } public function test_profile_admin_options_link_shows_if_permissions_allow() { $editor = $this->users->editor(); $resp = $this->actingAs($editor)->get('/my-account/profile'); $resp->assertDontSee('Administrator Options'); $this->withHtml($resp)->assertLinkNotExists(url("/settings/users/{$editor->id}")); $this->permissions->grantUserRolePermissions($editor, ['users-manage']); $resp = $this->actingAs($editor)->get('/my-account/profile'); $resp->assertSee('Administrator Options'); $this->withHtml($resp)->assertLinkExists(url("/settings/users/{$editor->id}")); } public function test_profile_self_delete() { $editor = $this->users->editor(); $resp = $this->actingAs($editor)->get('/my-account/profile'); $this->withHtml($resp)->assertLinkExists(url('/my-account/delete'), 'Delete Account'); $resp = $this->get('/my-account/delete'); $resp->assertSee('Delete My Account'); $this->withHtml($resp)->assertElementContains('form[action$="/my-account"] button', 'Confirm'); $resp = $this->delete('/my-account'); $resp->assertRedirect('/'); $this->assertDatabaseMissing('users', ['id' => $editor->id]); } public function test_profile_self_delete_shows_ownership_migration_if_can_manage_users() { $editor = $this->users->editor(); $resp = $this->actingAs($editor)->get('/my-account/delete'); $resp->assertDontSee('Migrate Ownership'); $this->permissions->grantUserRolePermissions($editor, ['users-manage']); $resp = $this->actingAs($editor)->get('/my-account/delete'); $resp->assertSee('Migrate Ownership'); } public function test_auth_password_change() { $editor = $this->users->editor(); $resp = $this->actingAs($editor)->get('/my-account/auth'); $resp->assertSee('Change Password'); $this->withHtml($resp)->assertElementExists('form[action$="/my-account/auth/password"]'); $password = Str::random(); $resp = $this->put('/my-account/auth/password', [ 'password' => $password, 'password-confirm' => $password, ]); $resp->assertRedirect('/my-account/auth'); $editor->refresh(); $this->assertTrue(Hash::check($password, $editor->password)); } public function test_auth_password_change_hides_if_not_using_email_auth() { $editor = $this->users->editor(); $resp = $this->actingAs($editor)->get('/my-account/auth'); $resp->assertSee('Change Password'); config()->set('auth.method', 'oidc'); $resp = $this->actingAs($editor)->get('/my-account/auth'); $resp->assertDontSee('Change Password'); } public function test_auth_page_has_mfa_links() { $editor = $this->users->editor(); $resp = $this->actingAs($editor)->get('/my-account/auth'); $resp->assertSee('0 methods configured'); $this->withHtml($resp)->assertLinkExists(url('/mfa/setup')); MfaValue::upsertWithValue($editor, 'totp', 'testval'); $resp = $this->get('/my-account/auth'); $resp->assertSee('1 method configured'); } public function test_auth_page_api_tokens() { $editor = $this->users->editor(); $resp = $this->actingAs($editor)->get('/my-account/auth'); $resp->assertSee('API Tokens'); $this->withHtml($resp)->assertLinkExists(url("/api-tokens/{$editor->id}/create?context=my-account")); ApiToken::factory()->create(['user_id' => $editor->id, 'name' => 'My great token']); $editor->unsetRelations(); $resp = $this->get('/my-account/auth'); $resp->assertSee('My great token'); } public function test_interface_shortcuts_updating() { $this->asEditor(); // View preferences with defaults $resp = $this->get('/my-account/shortcuts'); $resp->assertSee('UI Shortcut Preferences'); $html = $this->withHtml($resp); $html->assertFieldHasValue('enabled', 'false'); $html->assertFieldHasValue('shortcut[home_view]', '1'); // Update preferences $resp = $this->put('/my-account/shortcuts', [ 'enabled' => 'true', 'shortcut' => ['home_view' => 'Ctrl + 1'], ]); $resp->assertRedirect('/my-account/shortcuts'); $resp->assertSessionHas('success', 'Shortcut preferences have been updated!'); // View updates to preferences page $resp = $this->get('/my-account/shortcuts'); $html = $this->withHtml($resp); $html->assertFieldHasValue('enabled', 'true'); $html->assertFieldHasValue('shortcut[home_view]', 'Ctrl + 1'); } public function test_body_has_shortcuts_component_when_active() { $editor = $this->users->editor(); $this->actingAs($editor); $this->withHtml($this->get('/'))->assertElementNotExists('body[component="shortcuts"]'); setting()->putUser($editor, 'ui-shortcuts-enabled', 'true'); $this->withHtml($this->get('/'))->assertElementExists('body[component="shortcuts"]'); } public function test_notification_routes_requires_notification_permission() { $viewer = $this->users->viewer(); $resp = $this->actingAs($viewer)->get('/my-account/notifications'); $this->assertPermissionError($resp); $resp = $this->actingAs($viewer)->get('/my-account/profile'); $resp->assertDontSeeText('Notification Preferences'); $resp = $this->put('/my-account/notifications'); $this->assertPermissionError($resp); $this->permissions->grantUserRolePermissions($viewer, ['receive-notifications']); $resp = $this->get('/my-account/notifications'); $resp->assertOk(); $resp->assertSee('Notification Preferences'); } public function test_notification_preferences_updating() { $editor = $this->users->editor(); // View preferences with defaults $resp = $this->actingAs($editor)->get('/my-account/notifications'); $resp->assertSee('Notification Preferences'); $html = $this->withHtml($resp); $html->assertFieldHasValue('preferences[comment-replies]', 'false'); // Update preferences $resp = $this->put('/my-account/notifications', [ 'preferences' => ['comment-replies' => 'true'], ]); $resp->assertRedirect('/my-account/notifications'); $resp->assertSessionHas('success', 'Notification preferences have been updated!'); // View updates to preferences page $resp = $this->get('/my-account/notifications'); $html = $this->withHtml($resp); $html->assertFieldHasValue('preferences[comment-replies]', 'true'); } public function test_notification_preferences_show_watches() { $editor = $this->users->editor(); $book = $this->entities->book(); $options = new UserEntityWatchOptions($editor, $book); $options->updateLevelByValue(WatchLevels::COMMENTS); $resp = $this->actingAs($editor)->get('/my-account/notifications'); $resp->assertSee($book->name); $resp->assertSee('All Page Updates & Comments'); $options->updateLevelByValue(WatchLevels::DEFAULT); $resp = $this->actingAs($editor)->get('/my-account/notifications'); $resp->assertDontSee($book->name); $resp->assertDontSee('All Page Updates & Comments'); } public function test_notification_preferences_dont_error_on_deleted_items() { $editor = $this->users->editor(); $book = $this->entities->book(); $options = new UserEntityWatchOptions($editor, $book); $options->updateLevelByValue(WatchLevels::COMMENTS); $this->actingAs($editor)->delete($book->getUrl()); $book->refresh(); $this->assertNotNull($book->deleted_at); $resp = $this->actingAs($editor)->get('/my-account/notifications'); $resp->assertOk(); $resp->assertDontSee($book->name); } public function test_notification_preferences_not_accessible_to_guest() { $this->setSettings(['app-public' => 'true']); $guest = $this->users->guest(); $this->permissions->grantUserRolePermissions($guest, ['receive-notifications']); $resp = $this->get('/my-account/notifications'); $this->assertPermissionError($resp); $resp = $this->put('/my-account/notifications', [ 'preferences' => ['comment-replies' => 'true'], ]); $this->assertPermissionError($resp); } public function test_notification_comment_options_only_exist_if_comments_active() { $resp = $this->asEditor()->get('/my-account/notifications'); $resp->assertSee('Notify upon comments'); $resp->assertSee('Notify upon replies'); $resp->assertSee('Notify when I\'m mentioned in a comment'); setting()->put('app-disable-comments', true); $resp = $this->get('/my-account/notifications'); $resp->assertDontSee('Notify upon comments'); $resp->assertDontSee('Notify upon replies'); $resp->assertDontSee('Notify when I\'m mentioned in a comment'); } public function test_notification_comment_mention_option_enabled_by_default() { $resp = $this->asEditor()->get('/my-account/notifications'); $this->withHtml($resp)->assertElementExists('input[name="preferences[comment-mentions]"][value="true"]'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/User/UserPreferencesTest.php
tests/User/UserPreferencesTest.php
<?php namespace Tests\User; use Tests\TestCase; class UserPreferencesTest extends TestCase { public function test_update_sort_preference() { $editor = $this->users->editor(); $this->actingAs($editor); $updateRequest = $this->patch('/preferences/change-sort/books', [ 'sort' => 'created_at', 'order' => 'desc', ]); $updateRequest->assertStatus(302); $this->assertDatabaseHas('settings', [ 'setting_key' => 'user:' . $editor->id . ':books_sort', 'value' => 'created_at', ]); $this->assertDatabaseHas('settings', [ 'setting_key' => 'user:' . $editor->id . ':books_sort_order', 'value' => 'desc', ]); $this->assertEquals('created_at', setting()->getForCurrentUser('books_sort')); $this->assertEquals('desc', setting()->getForCurrentUser('books_sort_order')); } public function test_update_sort_bad_entity_type_handled() { $editor = $this->users->editor(); $this->actingAs($editor); $updateRequest = $this->patch('/preferences/change-sort/dogs', [ 'sort' => 'name', 'order' => 'asc', ]); $updateRequest->assertRedirect(); $this->assertNotEmpty('name', setting()->getForCurrentUser('bookshelves_sort')); $this->assertNotEmpty('asc', setting()->getForCurrentUser('bookshelves_sort_order')); } public function test_update_expansion_preference() { $editor = $this->users->editor(); $this->actingAs($editor); $updateRequest = $this->patch('/preferences/change-expansion/home-details', ['expand' => 'true']); $updateRequest->assertStatus(204); $this->assertDatabaseHas('settings', [ 'setting_key' => 'user:' . $editor->id . ':section_expansion#home-details', 'value' => 'true', ]); $this->assertEquals(true, setting()->getForCurrentUser('section_expansion#home-details')); $invalidKeyRequest = $this->patch('/preferences/change-expansion/my-home-details', ['expand' => 'true']); $invalidKeyRequest->assertStatus(500); } public function test_toggle_dark_mode() { $home = $this->actingAs($this->users->editor())->get('/'); $home->assertSee('Dark Mode'); $this->withHtml($home)->assertElementNotExists('.dark-mode'); $this->assertEquals(false, setting()->getForCurrentUser('dark-mode-enabled', false)); $prefChange = $this->patch('/preferences/toggle-dark-mode'); $prefChange->assertRedirect(); $this->assertEquals(true, setting()->getForCurrentUser('dark-mode-enabled')); $home = $this->actingAs($this->users->editor())->get('/'); $this->withHtml($home)->assertElementExists('.dark-mode'); $home->assertDontSee('Dark Mode'); $home->assertSee('Light Mode'); } public function test_dark_mode_defaults_to_config_option() { config()->set('setting-defaults.user.dark-mode-enabled', false); $this->assertEquals(false, setting()->getForCurrentUser('dark-mode-enabled')); $home = $this->get('/login'); $this->withHtml($home)->assertElementNotExists('.dark-mode'); config()->set('setting-defaults.user.dark-mode-enabled', true); $this->assertEquals(true, setting()->getForCurrentUser('dark-mode-enabled')); $home = $this->get('/login'); $this->withHtml($home)->assertElementExists('.dark-mode'); } public function test_dark_mode_toggle_endpoint_changes_to_light_when_dark_by_default() { config()->set('setting-defaults.user.dark-mode-enabled', true); $editor = $this->users->editor(); $this->assertEquals(true, setting()->getUser($editor, 'dark-mode-enabled')); $prefChange = $this->actingAs($editor)->patch('/preferences/toggle-dark-mode'); $prefChange->assertRedirect(); $this->assertEquals(false, setting()->getUser($editor, 'dark-mode-enabled')); $home = $this->get('/'); $this->withHtml($home)->assertElementNotExists('.dark-mode'); $home->assertDontSee('Light Mode'); $home->assertSee('Dark Mode'); } public function test_books_view_type_preferences_when_list() { $editor = $this->users->editor(); setting()->putUser($editor, 'books_view_type', 'list'); $resp = $this->actingAs($editor)->get('/books'); $this->withHtml($resp) ->assertElementNotExists('.featured-image-container') ->assertElementExists('.content-wrap .entity-list-item'); } public function test_books_view_type_preferences_when_grid() { $editor = $this->users->editor(); setting()->putUser($editor, 'books_view_type', 'grid'); $resp = $this->actingAs($editor)->get('/books'); $this->withHtml($resp)->assertElementExists('.featured-image-container'); } public function test_shelf_view_type_change() { $editor = $this->users->editor(); $shelf = $this->entities->shelf(); setting()->putUser($editor, 'bookshelf_view_type', 'list'); $resp = $this->actingAs($editor)->get($shelf->getUrl())->assertSee('Grid View'); $this->withHtml($resp) ->assertElementNotExists('.featured-image-container') ->assertElementExists('.content-wrap .entity-list-item'); $req = $this->patch("/preferences/change-view/bookshelf", [ 'view' => 'grid', '_return' => $shelf->getUrl(), ]); $req->assertRedirect($shelf->getUrl()); $resp = $this->actingAs($editor)->get($shelf->getUrl()) ->assertSee('List View'); $this->withHtml($resp) ->assertElementExists('.featured-image-container') ->assertElementNotExists('.content-wrap .entity-list-item'); } public function test_update_code_language_favourite() { $editor = $this->users->editor(); $page = $this->entities->page(); $this->actingAs($editor); $this->patch('/preferences/update-code-language-favourite', ['language' => 'php', 'active' => true]); $this->patch('/preferences/update-code-language-favourite', ['language' => 'javascript', 'active' => true]); $resp = $this->get($page->getUrl('/edit')); $resp->assertSee('option:code-editor:favourites="php,javascript"', false); $this->patch('/preferences/update-code-language-favourite', ['language' => 'ruby', 'active' => true]); $this->patch('/preferences/update-code-language-favourite', ['language' => 'php', 'active' => false]); $resp = $this->get($page->getUrl('/edit')); $resp->assertSee('option:code-editor:favourites="javascript,ruby"', false); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/User/UserSearchTest.php
tests/User/UserSearchTest.php
<?php namespace Tests\User; use BookStack\Permissions\Permission; use BookStack\Users\Models\User; use Tests\TestCase; class UserSearchTest extends TestCase { public function test_select_search_matches_by_name() { $viewer = $this->users->viewer(); $admin = $this->users->admin(); $resp = $this->actingAs($admin)->get('/search/users/select?search=' . urlencode($viewer->name)); $resp->assertOk(); $resp->assertSee($viewer->name); $resp->assertDontSee($admin->name); } public function test_select_search_shows_first_by_name_without_search() { /** @var User $firstUser */ $firstUser = User::query()->orderBy('name', 'desc')->first(); $resp = $this->asAdmin()->get('/search/users/select'); $resp->assertOk(); $resp->assertSee($firstUser->name); } public function test_select_search_does_not_match_by_email() { $viewer = $this->users->viewer(); $editor = $this->users->editor(); $resp = $this->actingAs($editor)->get('/search/users/select?search=' . urlencode($viewer->email)); $resp->assertDontSee($viewer->name); } public function test_select_requires_right_permission() { $permissions = ['users-manage', 'restrictions-manage-own', 'restrictions-manage-all']; $user = $this->users->viewer(); foreach ($permissions as $permission) { $resp = $this->actingAs($user)->get('/search/users/select?search=a'); $this->assertPermissionError($resp); $this->permissions->grantUserRolePermissions($user, [$permission]); $resp = $this->actingAs($user)->get('/search/users/select?search=a'); $resp->assertOk(); $user->roles()->delete(); $user->clearPermissionCache(); } } public function test_select_requires_logged_in_user() { $this->setSettings(['app-public' => true]); $this->permissions->grantUserRolePermissions($this->users->guest(), ['users-manage']); $resp = $this->get('/search/users/select?search=a'); $this->assertPermissionError($resp); } public function test_mentions_search_matches_by_name() { $viewer = $this->users->viewer(); $editor = $this->users->editor(); $resp = $this->actingAs($editor)->get('/search/users/mention?search=' . urlencode($viewer->name)); $resp->assertOk(); $resp->assertSee($viewer->name); $resp->assertDontSee($editor->name); } public function test_mentions_search_does_not_match_by_email() { $viewer = $this->users->viewer(); $resp = $this->asEditor()->get('/search/users/mention?search=' . urlencode($viewer->email)); $resp->assertDontSee($viewer->name); } public function test_mentions_search_requires_logged_in_user() { $this->setSettings(['app-public' => true]); $guest = $this->users->guest(); $this->permissions->grantUserRolePermissions($guest, [Permission::CommentCreateAll, Permission::CommentUpdateAll]); $resp = $this->get('/search/users/mention?search=a'); $this->assertPermissionError($resp); } public function test_mentions_search_requires_comment_create_or_update_permission() { $viewer = $this->users->viewer(); $editor = $this->users->editor(); $resp = $this->actingAs($viewer)->get('/search/users/mention?search=' . urlencode($editor->name)); $this->assertPermissionError($resp); $this->permissions->grantUserRolePermissions($viewer, [Permission::CommentCreateAll]); $resp = $this->actingAs($editor)->get('/search/users/mention?search=' . urlencode($viewer->name)); $resp->assertOk(); $resp->assertSee($viewer->name); $this->permissions->removeUserRolePermissions($viewer, [Permission::CommentCreateAll]); $this->permissions->grantUserRolePermissions($viewer, [Permission::CommentUpdateAll]); $resp = $this->actingAs($editor)->get('/search/users/mention?search=' . urlencode($viewer->name)); $resp->assertOk(); $resp->assertSee($viewer->name); } public function test_mentions_search_shows_first_by_name_without_search() { /** @var User $firstUser */ $firstUser = User::query() ->orderBy('name', 'asc') ->first(); $resp = $this->asEditor()->get('/search/users/mention'); $resp->assertOk(); $this->withHtml($resp)->assertElementContains('a[data-id]:first-child', $firstUser->name); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/User/UserProfileTest.php
tests/User/UserProfileTest.php
<?php namespace Tests\User; use BookStack\Activity\ActivityType; use BookStack\Facades\Activity; use BookStack\Users\Models\User; use Tests\TestCase; class UserProfileTest extends TestCase { /** * @var User */ protected $user; protected function setUp(): void { parent::setUp(); $this->user = User::all()->last(); } public function test_profile_page_shows_name() { $this->asAdmin() ->get('/user/' . $this->user->slug) ->assertSee($this->user->name); } public function test_profile_page_shows_recent_entities() { $content = $this->entities->createChainBelongingToUser($this->user, $this->user); $resp = $this->asAdmin()->get('/user/' . $this->user->slug); // Check the recently created page is shown $resp->assertSee($content['page']->name); // Check the recently created chapter is shown $resp->assertSee($content['chapter']->name); // Check the recently created book is shown $resp->assertSee($content['book']->name); } public function test_profile_page_shows_created_content_counts() { $newUser = User::factory()->create(); $resp = $this->asAdmin()->get('/user/' . $newUser->slug) ->assertSee($newUser->name); $this->withHtml($resp)->assertElementContains('#content-counts', '0 Books') ->assertElementContains('#content-counts', '0 Chapters') ->assertElementContains('#content-counts', '0 Pages'); $this->entities->createChainBelongingToUser($newUser, $newUser); $resp = $this->asAdmin()->get('/user/' . $newUser->slug) ->assertSee($newUser->name); $this->withHtml($resp)->assertElementContains('#content-counts', '1 Book') ->assertElementContains('#content-counts', '1 Chapter') ->assertElementContains('#content-counts', '1 Page'); } public function test_profile_page_shows_recent_activity() { $newUser = User::factory()->create(); $this->actingAs($newUser); $entities = $this->entities->createChainBelongingToUser($newUser, $newUser); Activity::add(ActivityType::BOOK_UPDATE, $entities['book']); Activity::add(ActivityType::PAGE_CREATE, $entities['page']); $resp = $this->asAdmin()->get('/user/' . $newUser->slug); $this->withHtml($resp)->assertElementContains('#recent-user-activity', 'updated book') ->assertElementContains('#recent-user-activity', 'created page') ->assertElementContains('#recent-user-activity', $entities['page']->name); } public function test_user_activity_has_link_leading_to_profile() { $newUser = User::factory()->create(); $this->actingAs($newUser); $entities = $this->entities->createChainBelongingToUser($newUser, $newUser); Activity::add(ActivityType::BOOK_UPDATE, $entities['book']); Activity::add(ActivityType::PAGE_CREATE, $entities['page']); $linkSelector = '#recent-activity a[href$="/user/' . $newUser->slug . '"]'; $resp = $this->asAdmin()->get('/'); $this->withHtml($resp)->assertElementContains($linkSelector, $newUser->name); } public function test_profile_has_search_links_in_created_entity_lists() { $user = $this->users->editor(); $resp = $this->actingAs($this->users->admin())->get('/user/' . $user->slug); $expectedLinks = [ '/search?term=%7Bcreated_by%3A' . $user->slug . '%7D+%7Btype%3Apage%7D', '/search?term=%7Bcreated_by%3A' . $user->slug . '%7D+%7Btype%3Achapter%7D', '/search?term=%7Bcreated_by%3A' . $user->slug . '%7D+%7Btype%3Abook%7D', '/search?term=%7Bcreated_by%3A' . $user->slug . '%7D+%7Btype%3Abookshelf%7D', ]; foreach ($expectedLinks as $link) { $this->withHtml($resp)->assertElementContains('[href$="' . $link . '"]', 'View All'); } } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/User/UserManagementTest.php
tests/User/UserManagementTest.php
<?php namespace Tests\User; use BookStack\Access\Mfa\MfaValue; use BookStack\Access\SocialAccount; use BookStack\Access\UserInviteException; use BookStack\Access\UserInviteService; use BookStack\Activity\ActivityType; use BookStack\Activity\Models\Activity; use BookStack\Activity\Models\Comment; use BookStack\Activity\Models\Favourite; use BookStack\Activity\Models\View; use BookStack\Activity\Models\Watch; use BookStack\Api\ApiToken; use BookStack\Entities\Models\Deletion; use BookStack\Entities\Models\PageRevision; use BookStack\Exports\Import; use BookStack\Uploads\Attachment; use BookStack\Uploads\Image; use BookStack\Users\Models\Role; use BookStack\Users\Models\User; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Str; use Mockery\MockInterface; use Tests\TestCase; class UserManagementTest extends TestCase { public function test_user_creation() { /** @var User $user */ $user = User::factory()->make(); $adminRole = Role::getRole('admin'); $resp = $this->asAdmin()->get('/settings/users'); $this->withHtml($resp)->assertElementContains('a[href="' . url('/settings/users/create') . '"]', 'Add New User'); $resp = $this->get('/settings/users/create'); $this->withHtml($resp)->assertElementContains('form[action="' . url('/settings/users/create') . '"]', 'Save'); $resp = $this->post('/settings/users/create', [ 'name' => $user->name, 'email' => $user->email, 'password' => $user->password, 'password-confirm' => $user->password, 'roles[' . $adminRole->id . ']' => 'true', ]); $resp->assertRedirect('/settings/users'); $resp = $this->get('/settings/users'); $resp->assertSee($user->name); $this->assertDatabaseHas('users', $user->only('name', 'email')); $user->refresh(); $this->assertStringStartsWith(Str::slug($user->name), $user->slug); } public function test_user_updating() { $user = $this->users->viewer(); $password = $user->password; $resp = $this->asAdmin()->get('/settings/users/' . $user->id); $resp->assertSee($user->email); $this->put($user->getEditUrl(), [ 'name' => 'Barry Scott', ])->assertRedirect('/settings/users'); $this->assertDatabaseHas('users', ['id' => $user->id, 'name' => 'Barry Scott', 'password' => $password]); $this->assertDatabaseMissing('users', ['name' => $user->name]); $user->refresh(); $this->assertStringStartsWith(Str::slug($user->name), $user->slug); } public function test_user_password_update() { $user = $this->users->viewer(); $userProfilePage = '/settings/users/' . $user->id; $this->asAdmin()->get($userProfilePage); $this->put($userProfilePage, [ 'password' => 'newpassword', ])->assertRedirect($userProfilePage); $this->get($userProfilePage)->assertSee('Password confirmation required'); $this->put($userProfilePage, [ 'password' => 'newpassword', 'password-confirm' => 'newpassword', ])->assertRedirect('/settings/users'); $userPassword = User::query()->find($user->id)->password; $this->assertTrue(Hash::check('newpassword', $userPassword)); } public function test_user_can_be_updated_with_single_char_name() { $user = $this->users->viewer(); $this->asAdmin()->put("/settings/users/{$user->id}", [ 'name' => 'b' ])->assertRedirect('/settings/users'); $this->assertEquals('b', $user->refresh()->name); } public function test_user_cannot_be_deleted_if_last_admin() { $adminRole = Role::getRole('admin'); // Delete all but one admin user if there are more than one $adminUsers = $adminRole->users; if (count($adminUsers) > 1) { /** @var User $user */ foreach ($adminUsers->splice(1) as $user) { $user->delete(); } } // Ensure we currently only have 1 admin user $this->assertEquals(1, $adminRole->users()->count()); /** @var User $user */ $user = $adminRole->users->first(); $resp = $this->asAdmin()->delete('/settings/users/' . $user->id); $resp->assertRedirect('/settings/users/' . $user->id); $resp = $this->get('/settings/users/' . $user->id); $resp->assertSee('You cannot delete the only admin'); $this->assertDatabaseHas('users', ['id' => $user->id]); } public function test_delete() { $editor = $this->users->editor(); $resp = $this->asAdmin()->delete("settings/users/{$editor->id}"); $resp->assertRedirect('/settings/users'); $resp = $this->followRedirects($resp); $resp->assertSee('User successfully removed'); $this->assertActivityExists(ActivityType::USER_DELETE); $this->assertDatabaseMissing('users', ['id' => $editor->id]); } public function test_delete_offers_migrate_option() { $editor = $this->users->editor(); $resp = $this->asAdmin()->get("settings/users/{$editor->id}/delete"); $resp->assertSee('Migrate Ownership'); $resp->assertSee('new_owner_id'); } public function test_migrate_option_hidden_if_user_cannot_manage_users() { $editor = $this->users->editor(); $resp = $this->asEditor()->get("settings/users/{$editor->id}/delete"); $resp->assertDontSee('Migrate Ownership'); $resp->assertDontSee('new_owner_id'); $this->permissions->grantUserRolePermissions($editor, ['users-manage']); $resp = $this->asEditor()->get("settings/users/{$editor->id}/delete"); $resp->assertSee('Migrate Ownership'); $this->withHtml($resp)->assertElementExists('form input[name="new_owner_id"]'); $resp->assertSee('new_owner_id'); } public function test_delete_with_new_owner_id_changes_ownership() { $page = $this->entities->page(); $owner = $page->ownedBy; $newOwner = User::query()->where('id', '!=', $owner->id)->first(); $this->asAdmin()->delete("settings/users/{$owner->id}", ['new_owner_id' => $newOwner->id])->assertRedirect(); $this->assertDatabaseHasEntityData('page', [ 'id' => $page->id, 'owned_by' => $newOwner->id, ]); } public function test_delete_with_empty_owner_migration_id_works() { $user = $this->users->editor(); $resp = $this->asAdmin()->delete("settings/users/{$user->id}", ['new_owner_id' => '']); $resp->assertRedirect('/settings/users'); $this->assertActivityExists(ActivityType::USER_DELETE); $this->assertSessionHas('success'); } public function test_delete_with_empty_owner_migration_id_clears_relevant_id_uses() { $user = $this->users->editor(); $page = $this->entities->page(); $this->actingAs($user); // Create relations $activity = Activity::factory()->create(['user_id' => $user->id]); $attachment = Attachment::factory()->create(['created_by' => $user->id, 'updated_by' => $user->id]); $comment = Comment::factory()->create(['created_by' => $user->id, 'updated_by' => $user->id]); $deletion = Deletion::factory()->create(['deleted_by' => $user->id]); $page->forceFill(['owned_by' => $user->id, 'created_by' => $user->id, 'updated_by' => $user->id])->save(); $page->rebuildPermissions(); $image = Image::factory()->create(['created_by' => $user->id, 'updated_by' => $user->id]); $import = Import::factory()->create(['created_by' => $user->id]); $revision = PageRevision::factory()->create(['created_by' => $user->id]); $apiToken = ApiToken::factory()->create(['user_id' => $user->id]); \DB::table('email_confirmations')->insert(['user_id' => $user->id, 'token' => 'abc123']); $favourite = Favourite::factory()->create(['user_id' => $user->id]); $mfaValue = MfaValue::factory()->create(['user_id' => $user->id]); $socialAccount = SocialAccount::factory()->create(['user_id' => $user->id]); \DB::table('user_invites')->insert(['user_id' => $user->id, 'token' => 'abc123']); View::incrementFor($page); $watch = Watch::factory()->create(['user_id' => $user->id]); $userColumnsByTable = [ 'api_tokens' => ['user_id'], 'attachments' => ['created_by', 'updated_by'], 'comments' => ['created_by', 'updated_by'], 'deletions' => ['deleted_by'], 'email_confirmations' => ['user_id'], 'entities' => ['created_by', 'updated_by', 'owned_by'], 'favourites' => ['user_id'], 'images' => ['created_by', 'updated_by'], 'imports' => ['created_by'], 'joint_permissions' => ['owner_id'], 'mfa_values' => ['user_id'], 'page_revisions' => ['created_by'], 'role_user' => ['user_id'], 'social_accounts' => ['user_id'], 'user_invites' => ['user_id'], 'views' => ['user_id'], 'watches' => ['user_id'], ]; // Ensure columns have user id before deletion foreach ($userColumnsByTable as $table => $columns) { foreach ($columns as $column) { $this->assertDatabaseHas($table, [$column => $user->id]); } } $resp = $this->asAdmin()->delete("settings/users/{$user->id}", ['new_owner_id' => '']); $resp->assertRedirect('/settings/users'); // Ensure columns missing user id after deletion foreach ($userColumnsByTable as $table => $columns) { foreach ($columns as $column) { $this->assertDatabaseMissing($table, [$column => $user->id]); } } // Check models exist where should be retained $this->assertDatabaseHas('attachments', ['id' => $attachment->id, 'created_by' => null, 'updated_by' => null]); $this->assertDatabaseHas('comments', ['id' => $comment->id, 'created_by' => null, 'updated_by' => null]); $this->assertDatabaseHas('deletions', ['id' => $deletion->id, 'deleted_by' => null]); $this->assertDatabaseHas('entities', ['id' => $page->id, 'created_by' => null, 'updated_by' => null, 'owned_by' => null]); $this->assertDatabaseHas('images', ['id' => $image->id, 'created_by' => null, 'updated_by' => null]); $this->assertDatabaseHas('imports', ['id' => $import->id, 'created_by' => null]); $this->assertDatabaseHas('page_revisions', ['id' => $revision->id, 'created_by' => null]); // Check models no longer exist where should have been deleted with the user $this->assertDatabaseMissing('api_tokens', ['id' => $apiToken->id]); $this->assertDatabaseMissing('email_confirmations', ['token' => 'abc123']); $this->assertDatabaseMissing('favourites', ['id' => $favourite->id]); $this->assertDatabaseMissing('mfa_values', ['id' => $mfaValue->id]); $this->assertDatabaseMissing('social_accounts', ['id' => $socialAccount->id]); $this->assertDatabaseMissing('user_invites', ['token' => 'abc123']); $this->assertDatabaseMissing('watches', ['id' => $watch->id]); // Ensure activity remains using the old ID (Special case for auditing changes) $this->assertDatabaseHas('activities', ['id' => $activity->id, 'user_id' => $user->id]); } public function test_delete_removes_user_preferences() { $editor = $this->users->editor(); setting()->putUser($editor, 'dark-mode-enabled', 'true'); $this->assertDatabaseHas('settings', [ 'setting_key' => 'user:' . $editor->id . ':dark-mode-enabled', 'value' => 'true', ]); $this->asAdmin()->delete("settings/users/{$editor->id}"); $this->assertDatabaseMissing('settings', [ 'setting_key' => 'user:' . $editor->id . ':dark-mode-enabled', ]); } public function test_guest_profile_shows_limited_form() { $guest = $this->users->guest(); $resp = $this->asAdmin()->get('/settings/users/' . $guest->id); $resp->assertSee('Guest'); $html = $this->withHtml($resp); $html->assertElementNotExists('#password'); $html->assertElementNotExists('[name="language"]'); } public function test_guest_profile_cannot_be_deleted() { $guestUser = $this->users->guest(); $resp = $this->asAdmin()->get('/settings/users/' . $guestUser->id . '/delete'); $resp->assertSee('Delete User'); $resp->assertSee('Guest'); $this->withHtml($resp)->assertElementContains('form[action$="/settings/users/' . $guestUser->id . '"] button', 'Confirm'); $resp = $this->delete('/settings/users/' . $guestUser->id); $resp->assertRedirect('/settings/users/' . $guestUser->id); $resp = $this->followRedirects($resp); $resp->assertSee('cannot delete the guest user'); } public function test_user_create_language_reflects_default_system_locale() { $langs = ['en', 'fr', 'hr']; foreach ($langs as $lang) { config()->set('app.default_locale', $lang); $resp = $this->asAdmin()->get('/settings/users/create'); $this->withHtml($resp)->assertElementExists('select[name="language"] option[value="' . $lang . '"][selected]'); } } public function test_user_creation_is_not_performed_if_the_invitation_sending_fails() { /** @var User $user */ $user = User::factory()->make(); $adminRole = Role::getRole('admin'); // Simulate an invitation sending failure $this->mock(UserInviteService::class, function (MockInterface $mock) { $mock->shouldReceive('sendInvitation')->once()->andThrow(UserInviteException::class); }); $this->asAdmin()->post('/settings/users/create', [ 'name' => $user->name, 'email' => $user->email, 'send_invite' => 'true', 'roles[' . $adminRole->id . ']' => 'true', ]); // Since the invitation failed, the user should not exist in the database $this->assertDatabaseMissing('users', $user->only('name', 'email')); } public function test_user_create_activity_is_not_persisted_if_the_invitation_sending_fails() { /** @var User $user */ $user = User::factory()->make(); $this->mock(UserInviteService::class, function (MockInterface $mock) { $mock->shouldReceive('sendInvitation')->once()->andThrow(UserInviteException::class); }); $this->asAdmin()->post('/settings/users/create', [ 'name' => $user->name, 'email' => $user->email, 'send_invite' => 'true', ]); $this->assertDatabaseMissing('activities', ['type' => 'USER_CREATE']); } public function test_return_to_form_with_warning_if_the_invitation_sending_fails() { $logger = $this->withTestLogger(); /** @var User $user */ $user = User::factory()->make(); $this->mock(UserInviteService::class, function (MockInterface $mock) { $mock->shouldReceive('sendInvitation')->once()->andThrow(UserInviteException::class); }); $resp = $this->asAdmin()->post('/settings/users/create', [ 'name' => $user->name, 'email' => $user->email, 'send_invite' => 'true', ]); $resp->assertRedirect('/settings/users/create'); $this->assertSessionError('Could not create user since invite email failed to send'); $this->assertEquals($user->email, session()->getOldInput('email')); $this->assertTrue($logger->hasErrorThatContains('Failed to send user invite with error:')); } public function test_user_create_update_fails_if_locale_is_invalid() { $user = $this->users->editor(); // Too long $resp = $this->asAdmin()->put($user->getEditUrl(), ['language' => 'this_is_too_long']); $resp->assertSessionHasErrors(['language' => 'The language may not be greater than 15 characters.']); session()->flush(); // Invalid characters $resp = $this->put($user->getEditUrl(), ['language' => 'en<GB']); $resp->assertSessionHasErrors(['language' => 'The language may only contain letters, numbers, dashes and underscores.']); session()->flush(); // Both on create $resp = $this->post('/settings/users/create', [ 'language' => 'en<GB_and_this_is_longer', 'name' => 'My name', 'email' => 'jimmy@example.com', ]); $resp->assertSessionHasErrors(['language' => 'The language may not be greater than 15 characters.']); $resp->assertSessionHasErrors(['language' => 'The language may only contain letters, numbers, dashes and underscores.']); } public function test_user_avatar_update_and_reset() { $user = $this->users->viewer(); $avatarFile = $this->files->uploadedImage('avatar-icon.png'); $this->assertEquals(0, $user->image_id); $upload = $this->asAdmin()->call('PUT', "/settings/users/{$user->id}", [ 'name' => 'Barry Scott', ], [], ['profile_image' => $avatarFile], []); $upload->assertRedirect('/settings/users'); $user->refresh(); $this->assertNotEquals(0, $user->image_id); /** @var Image $image */ $image = Image::query()->findOrFail($user->image_id); $this->assertFileExists(public_path($image->path)); $reset = $this->put("/settings/users/{$user->id}", [ 'name' => 'Barry Scott', 'profile_image_reset' => 'true', ]); $upload->assertRedirect('/settings/users'); $user->refresh(); $this->assertFileDoesNotExist(public_path($image->path)); $this->assertEquals(0, $user->image_id); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Auth/UserInviteTest.php
tests/Auth/UserInviteTest.php
<?php namespace Tests\Auth; use BookStack\Access\Notifications\UserInviteNotification; use BookStack\Access\UserInviteService; use BookStack\Users\Models\User; use Carbon\Carbon; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Notification; use Illuminate\Support\Str; use Tests\TestCase; class UserInviteTest extends TestCase { public function test_user_creation_creates_invite() { Notification::fake(); $admin = $this->users->admin(); $email = Str::random(16) . '@example.com'; $resp = $this->actingAs($admin)->post('/settings/users/create', [ 'name' => 'Barry', 'email' => $email, 'send_invite' => 'true', ]); $resp->assertRedirect('/settings/users'); $newUser = User::query()->where('email', '=', $email)->orderBy('id', 'desc')->first(); Notification::assertSentTo($newUser, UserInviteNotification::class); $this->assertDatabaseHas('user_invites', [ 'user_id' => $newUser->id, ]); } public function test_user_invite_sent_in_selected_language() { Notification::fake(); $admin = $this->users->admin(); $email = Str::random(16) . '@example.com'; $resp = $this->actingAs($admin)->post('/settings/users/create', [ 'name' => 'Barry', 'email' => $email, 'send_invite' => 'true', 'language' => 'de', ]); $resp->assertRedirect('/settings/users'); $newUser = User::query()->where('email', '=', $email)->orderBy('id', 'desc')->first(); Notification::assertSentTo($newUser, UserInviteNotification::class, function ($notification, $channels, $notifiable) { /** @var MailMessage $mail */ $mail = $notification->toMail($notifiable); return 'Sie wurden eingeladen, BookStack beizutreten!' === $mail->subject && 'Ein Konto wurde für Sie auf BookStack erstellt.' === $mail->greeting; }); } public function test_invite_set_password() { Notification::fake(); $user = $this->users->viewer(); $inviteService = app(UserInviteService::class); $inviteService->sendInvitation($user); $token = DB::table('user_invites')->where('user_id', '=', $user->id)->first()->token; $setPasswordPageResp = $this->get('/register/invite/' . $token); $setPasswordPageResp->assertSuccessful(); $setPasswordPageResp->assertSee('Welcome to BookStack!'); $setPasswordPageResp->assertSee('Password'); $setPasswordPageResp->assertSee('Confirm Password'); $setPasswordResp = $this->followingRedirects()->post('/register/invite/' . $token, [ 'password' => 'my test password', ]); $setPasswordResp->assertSee('Password set, you should now be able to login using your set password to access BookStack!'); $newPasswordValid = auth()->validate([ 'email' => $user->email, 'password' => 'my test password', ]); $this->assertTrue($newPasswordValid); $this->assertDatabaseMissing('user_invites', [ 'user_id' => $user->id, ]); } public function test_invite_set_has_password_validation() { Notification::fake(); $user = $this->users->viewer(); $inviteService = app(UserInviteService::class); $inviteService->sendInvitation($user); $token = DB::table('user_invites')->where('user_id', '=', $user->id)->first()->token; $this->get('/register/invite/' . $token); $shortPassword = $this->followingRedirects()->post('/register/invite/' . $token, [ 'password' => 'mypassw', ]); $shortPassword->assertSee('The password must be at least 8 characters.'); $this->get('/register/invite/' . $token); $noPassword = $this->followingRedirects()->post('/register/invite/' . $token, [ 'password' => '', ]); $noPassword->assertSee('The password field is required.'); $this->assertDatabaseHas('user_invites', [ 'user_id' => $user->id, ]); } public function test_non_existent_invite_token_redirects_to_home() { $setPasswordPageResp = $this->get('/register/invite/' . Str::random(12)); $setPasswordPageResp->assertRedirect('/'); $setPasswordResp = $this->post('/register/invite/' . Str::random(12), ['password' => 'Password Test']); $setPasswordResp->assertRedirect('/'); } public function test_token_expires_after_two_weeks() { Notification::fake(); $user = $this->users->viewer(); $inviteService = app(UserInviteService::class); $inviteService->sendInvitation($user); $tokenEntry = DB::table('user_invites')->where('user_id', '=', $user->id)->first(); DB::table('user_invites')->update(['created_at' => Carbon::now()->subDays(14)->subHour(1)]); $setPasswordPageResp = $this->get('/register/invite/' . $tokenEntry->token); $setPasswordPageResp->assertRedirect('/password/email'); $setPasswordPageResp->assertSessionHas('error', 'This invitation link has expired. You can instead try to reset your account password.'); } public function test_set_password_view_is_throttled() { for ($i = 0; $i < 11; $i++) { $response = $this->get("/register/invite/tokenhere{$i}"); } $response->assertStatus(429); } public function test_set_password_post_is_throttled() { for ($i = 0; $i < 11; $i++) { $response = $this->post("/register/invite/tokenhere{$i}", [ 'password' => 'my test password', ]); } $response->assertStatus(429); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Auth/SocialAuthTest.php
tests/Auth/SocialAuthTest.php
<?php namespace Tests\Auth; use BookStack\Access\SocialAccount; use BookStack\Activity\ActivityType; use BookStack\Users\Models\User; use Illuminate\Support\Facades\DB; use Laravel\Socialite\Contracts\Factory; use Laravel\Socialite\Contracts\Provider; use Mockery; use Tests\TestCase; class SocialAuthTest extends TestCase { public function test_social_registration() { $user = User::factory()->make(); $this->setSettings(['registration-enabled' => 'true']); config(['GOOGLE_APP_ID' => 'abc123', 'GOOGLE_APP_SECRET' => '123abc']); $mockSocialite = $this->mock(Factory::class); $mockSocialDriver = Mockery::mock(Provider::class); $mockSocialUser = Mockery::mock(\Laravel\Socialite\Contracts\User::class); $mockSocialite->shouldReceive('driver')->twice()->with('google')->andReturn($mockSocialDriver); $mockSocialDriver->shouldReceive('redirect')->once()->andReturn(redirect('/')); $mockSocialDriver->shouldReceive('user')->once()->andReturn($mockSocialUser); $mockSocialUser->shouldReceive('getId')->twice()->andReturn(1); $mockSocialUser->shouldReceive('getEmail')->twice()->andReturn($user->email); $mockSocialUser->shouldReceive('getName')->once()->andReturn($user->name); $mockSocialUser->shouldReceive('getAvatar')->once()->andReturn('avatar_placeholder'); $this->get('/register/service/google'); $this->get('/login/service/google/callback'); $this->assertDatabaseHas('users', ['name' => $user->name, 'email' => $user->email]); $user = $user->whereEmail($user->email)->first(); $this->assertDatabaseHas('social_accounts', ['user_id' => $user->id]); } public function test_social_login() { config([ 'GOOGLE_APP_ID' => 'abc123', 'GOOGLE_APP_SECRET' => '123abc', 'GITHUB_APP_ID' => 'abc123', 'GITHUB_APP_SECRET' => '123abc', ]); $mockSocialite = $this->mock(Factory::class); $mockSocialDriver = Mockery::mock(Provider::class); $mockSocialUser = Mockery::mock(\Laravel\Socialite\Contracts\User::class); $mockSocialUser->shouldReceive('getId')->twice()->andReturn('logintest123'); $mockSocialDriver->shouldReceive('user')->twice()->andReturn($mockSocialUser); $mockSocialite->shouldReceive('driver')->twice()->with('google')->andReturn($mockSocialDriver); $mockSocialite->shouldReceive('driver')->twice()->with('github')->andReturn($mockSocialDriver); $mockSocialDriver->shouldReceive('redirect')->twice()->andReturn(redirect('/')); // Test login routes $resp = $this->get('/login'); $this->withHtml($resp)->assertElementExists('a#social-login-google[href$="/login/service/google"]'); $resp = $this->followingRedirects()->get('/login/service/google'); $resp->assertSee('login-form'); // Test social callback $resp = $this->followingRedirects()->get('/login/service/google/callback'); $resp->assertSee('login-form'); $resp->assertSee(trans('errors.social_account_not_used', ['socialAccount' => 'Google'])); $resp = $this->get('/login'); $this->withHtml($resp)->assertElementExists('a#social-login-github[href$="/login/service/github"]'); $resp = $this->followingRedirects()->get('/login/service/github'); $resp->assertSee('login-form'); // Test social callback with matching social account DB::table('social_accounts')->insert([ 'user_id' => $this->users->admin()->id, 'driver' => 'github', 'driver_id' => 'logintest123', ]); $resp = $this->followingRedirects()->get('/login/service/github/callback'); $resp->assertDontSee('login-form'); $this->assertActivityExists(ActivityType::AUTH_LOGIN, null, 'github; (' . $this->users->admin()->id . ') ' . $this->users->admin()->name); } public function test_social_account_attach() { config([ 'GOOGLE_APP_ID' => 'abc123', 'GOOGLE_APP_SECRET' => '123abc', ]); $editor = $this->users->editor(); $mockSocialite = $this->mock(Factory::class); $mockSocialDriver = Mockery::mock(Provider::class); $mockSocialUser = Mockery::mock(\Laravel\Socialite\Contracts\User::class); $mockSocialUser->shouldReceive('getId')->twice()->andReturn('logintest123'); $mockSocialUser->shouldReceive('getAvatar')->andReturn(null); $mockSocialite->shouldReceive('driver')->twice()->with('google')->andReturn($mockSocialDriver); $mockSocialDriver->shouldReceive('redirect')->once()->andReturn(redirect('/login/service/google/callback')); $mockSocialDriver->shouldReceive('user')->once()->andReturn($mockSocialUser); // Test login routes $resp = $this->actingAs($editor)->followingRedirects()->get('/login/service/google'); $resp->assertSee('Access & Security'); // Test social callback with matching social account $this->assertDatabaseHas('social_accounts', [ 'user_id' => $editor->id, 'driver' => 'google', 'driver_id' => 'logintest123', ]); } public function test_social_account_detach() { $editor = $this->users->editor(); config([ 'GITHUB_APP_ID' => 'abc123', 'GITHUB_APP_SECRET' => '123abc', ]); $socialAccount = SocialAccount::query()->forceCreate([ 'user_id' => $editor->id, 'driver' => 'github', 'driver_id' => 'logintest123', ]); $resp = $this->actingAs($editor)->get('/my-account/auth'); $this->withHtml($resp)->assertElementContains('form[action$="/login/service/github/detach"]', 'Disconnect Account'); $resp = $this->post('/login/service/github/detach'); $resp->assertRedirect('/my-account/auth#social-accounts'); $resp = $this->followRedirects($resp); $resp->assertSee('Github account was successfully disconnected from your profile.'); $this->assertDatabaseMissing('social_accounts', ['id' => $socialAccount->id]); } public function test_social_autoregister() { config([ 'services.google.client_id' => 'abc123', 'services.google.client_secret' => '123abc', ]); $user = User::factory()->make(); $mockSocialite = $this->mock(Factory::class); $mockSocialDriver = Mockery::mock(Provider::class); $mockSocialUser = Mockery::mock(\Laravel\Socialite\Contracts\User::class); $mockSocialUser->shouldReceive('getId')->times(4)->andReturn(1); $mockSocialUser->shouldReceive('getEmail')->times(2)->andReturn($user->email); $mockSocialUser->shouldReceive('getName')->once()->andReturn($user->name); $mockSocialUser->shouldReceive('getAvatar')->once()->andReturn('avatar_placeholder'); $mockSocialDriver->shouldReceive('user')->times(2)->andReturn($mockSocialUser); $mockSocialite->shouldReceive('driver')->times(4)->with('google')->andReturn($mockSocialDriver); $mockSocialDriver->shouldReceive('redirect')->twice()->andReturn(redirect('/')); $googleAccountNotUsedMessage = trans('errors.social_account_not_used', ['socialAccount' => 'Google']); $this->get('/login/service/google'); $resp = $this->followingRedirects()->get('/login/service/google/callback'); $resp->assertSee($googleAccountNotUsedMessage); config(['services.google.auto_register' => true]); $this->get('/login/service/google'); $resp = $this->followingRedirects()->get('/login/service/google/callback'); $resp->assertDontSee($googleAccountNotUsedMessage); $this->assertDatabaseHas('users', ['name' => $user->name, 'email' => $user->email, 'email_confirmed' => false]); $user = $user->whereEmail($user->email)->first(); $this->assertDatabaseHas('social_accounts', ['user_id' => $user->id]); } public function test_social_auto_email_confirm() { config([ 'services.google.client_id' => 'abc123', 'services.google.client_secret' => '123abc', 'services.google.auto_register' => true, 'services.google.auto_confirm' => true, ]); $user = User::factory()->make(); $mockSocialite = $this->mock(Factory::class); $mockSocialDriver = Mockery::mock(Provider::class); $mockSocialUser = Mockery::mock(\Laravel\Socialite\Contracts\User::class); $mockSocialUser->shouldReceive('getId')->times(3)->andReturn(1); $mockSocialUser->shouldReceive('getEmail')->times(2)->andReturn($user->email); $mockSocialUser->shouldReceive('getName')->once()->andReturn($user->name); $mockSocialUser->shouldReceive('getAvatar')->once()->andReturn('avatar_placeholder'); $mockSocialDriver->shouldReceive('user')->times(1)->andReturn($mockSocialUser); $mockSocialite->shouldReceive('driver')->times(2)->with('google')->andReturn($mockSocialDriver); $mockSocialDriver->shouldReceive('redirect')->once()->andReturn(redirect('/')); $this->get('/login/service/google'); $this->get('/login/service/google/callback'); $this->assertDatabaseHas('users', ['name' => $user->name, 'email' => $user->email, 'email_confirmed' => true]); $user = $user->whereEmail($user->email)->first(); $this->assertDatabaseHas('social_accounts', ['user_id' => $user->id]); } public function test_google_select_account_option_changes_redirect_url() { config()->set('services.google.select_account', 'true'); $resp = $this->get('/login/service/google'); $this->assertStringContainsString('prompt=select_account', $resp->headers->get('Location')); } public function test_social_registration_with_no_name_uses_email_as_name() { $user = User::factory()->make(['email' => 'nonameuser@example.com']); $this->setSettings(['registration-enabled' => 'true']); config(['GITHUB_APP_ID' => 'abc123', 'GITHUB_APP_SECRET' => '123abc']); $mockSocialite = $this->mock(Factory::class); $mockSocialDriver = Mockery::mock(Provider::class); $mockSocialUser = Mockery::mock(\Laravel\Socialite\Contracts\User::class); $mockSocialite->shouldReceive('driver')->twice()->with('github')->andReturn($mockSocialDriver); $mockSocialDriver->shouldReceive('redirect')->once()->andReturn(redirect('/')); $mockSocialDriver->shouldReceive('user')->once()->andReturn($mockSocialUser); $mockSocialUser->shouldReceive('getId')->twice()->andReturn(1); $mockSocialUser->shouldReceive('getEmail')->twice()->andReturn($user->email); $mockSocialUser->shouldReceive('getName')->once()->andReturn(''); $mockSocialUser->shouldReceive('getAvatar')->once()->andReturn('avatar_placeholder'); $this->get('/register/service/github'); $this->get('/login/service/github/callback'); $this->assertDatabaseHas('users', ['name' => 'nonameuser', 'email' => $user->email]); $user = $user->whereEmail($user->email)->first(); $this->assertDatabaseHas('social_accounts', ['user_id' => $user->id]); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Auth/MfaVerificationTest.php
tests/Auth/MfaVerificationTest.php
<?php namespace Tests\Auth; use BookStack\Access\LoginService; use BookStack\Access\Mfa\MfaValue; use BookStack\Access\Mfa\TotpService; use BookStack\Exceptions\StoppedAuthenticationException; use BookStack\Users\Models\Role; use BookStack\Users\Models\User; use Illuminate\Support\Facades\Hash; use PragmaRX\Google2FA\Google2FA; use Tests\TestCase; use Tests\TestResponse; class MfaVerificationTest extends TestCase { public function test_totp_verification() { [$user, $secret, $loginResp] = $this->startTotpLogin(); $loginResp->assertRedirect('/mfa/verify'); $resp = $this->get('/mfa/verify'); $resp->assertSee('Verify Access'); $resp->assertSee('Enter the code, generated using your mobile app, below:'); $this->withHtml($resp)->assertElementExists('form[action$="/mfa/totp/verify"] input[name="code"][autofocus]'); $google2fa = new Google2FA(); $resp = $this->post('/mfa/totp/verify', [ 'code' => $google2fa->getCurrentOtp($secret), ]); $resp->assertRedirect('/'); $this->assertEquals($user->id, auth()->user()->id); } public function test_totp_verification_fails_on_missing_invalid_code() { [$user, $secret, $loginResp] = $this->startTotpLogin(); $resp = $this->get('/mfa/verify'); $resp = $this->post('/mfa/totp/verify', [ 'code' => '', ]); $resp->assertRedirect('/mfa/verify'); $resp = $this->get('/mfa/verify'); $resp->assertSeeText('The code field is required.'); $this->assertNull(auth()->user()); $resp = $this->post('/mfa/totp/verify', [ 'code' => '123321', ]); $resp->assertRedirect('/mfa/verify'); $resp = $this->get('/mfa/verify'); $resp->assertSeeText('The provided code is not valid or has expired.'); $this->assertNull(auth()->user()); } public function test_totp_form_has_autofill_configured() { [$user, $secret, $loginResp] = $this->startTotpLogin(); $html = $this->withHtml($this->get('/mfa/verify')); $html->assertElementExists('form[autocomplete="off"][action$="/verify"]'); $html->assertElementExists('input[autocomplete="one-time-code"][name="code"]'); } public function test_backup_code_verification() { [$user, $codes, $loginResp] = $this->startBackupCodeLogin(); $loginResp->assertRedirect('/mfa/verify'); $resp = $this->get('/mfa/verify'); $resp->assertSee('Verify Access'); $resp->assertSee('Backup Code'); $resp->assertSee('Enter one of your remaining backup codes below:'); $this->withHtml($resp)->assertElementExists('form[action$="/mfa/backup_codes/verify"] input[name="code"]'); $resp = $this->post('/mfa/backup_codes/verify', [ 'code' => $codes[1], ]); $resp->assertRedirect('/'); $this->assertEquals($user->id, auth()->user()->id); // Ensure code no longer exists in available set $userCodes = MfaValue::getValueForUser($user, MfaValue::METHOD_BACKUP_CODES); $this->assertStringNotContainsString($codes[1], $userCodes); $this->assertStringContainsString($codes[0], $userCodes); } public function test_backup_code_verification_fails_on_missing_or_invalid_code() { [$user, $codes, $loginResp] = $this->startBackupCodeLogin(); $resp = $this->get('/mfa/verify'); $resp = $this->post('/mfa/backup_codes/verify', [ 'code' => '', ]); $resp->assertRedirect('/mfa/verify'); $resp = $this->get('/mfa/verify'); $resp->assertSeeText('The code field is required.'); $this->assertNull(auth()->user()); $resp = $this->post('/mfa/backup_codes/verify', [ 'code' => 'ab123-ab456', ]); $resp->assertRedirect('/mfa/verify'); $resp = $this->get('/mfa/verify'); $resp->assertSeeText('The provided code is not valid or has already been used.'); $this->assertNull(auth()->user()); } public function test_backup_code_verification_fails_on_attempted_code_reuse() { [$user, $codes, $loginResp] = $this->startBackupCodeLogin(); $this->post('/mfa/backup_codes/verify', [ 'code' => $codes[0], ]); $this->assertNotNull(auth()->user()); auth()->logout(); session()->flush(); $this->post('/login', ['email' => $user->email, 'password' => 'password']); $this->get('/mfa/verify'); $resp = $this->post('/mfa/backup_codes/verify', [ 'code' => $codes[0], ]); $resp->assertRedirect('/mfa/verify'); $this->assertNull(auth()->user()); $resp = $this->get('/mfa/verify'); $resp->assertSeeText('The provided code is not valid or has already been used.'); } public function test_backup_code_verification_shows_warning_when_limited_codes_remain() { [$user, $codes, $loginResp] = $this->startBackupCodeLogin(['abc12-def45', 'abc12-def46']); $resp = $this->post('/mfa/backup_codes/verify', [ 'code' => $codes[0], ]); $resp = $this->followRedirects($resp); $resp->assertSeeText('You have less than 5 backup codes remaining, Please generate and store a new set before you run out of codes to prevent being locked out of your account.'); } public function test_backup_code_form_has_autofill_configured() { [$user, $codes, $loginResp] = $this->startBackupCodeLogin(); $html = $this->withHtml($this->get('/mfa/verify')); $html->assertElementExists('form[autocomplete="off"][action$="/verify"]'); $html->assertElementExists('input[autocomplete="one-time-code"][name="code"]'); } public function test_both_mfa_options_available_if_set_on_profile() { $user = $this->users->editor(); $user->password = Hash::make('password'); $user->save(); MfaValue::upsertWithValue($user, MfaValue::METHOD_TOTP, 'abc123'); MfaValue::upsertWithValue($user, MfaValue::METHOD_BACKUP_CODES, '["abc12-def456"]'); /** @var TestResponse $mfaView */ $mfaView = $this->followingRedirects()->post('/login', [ 'email' => $user->email, 'password' => 'password', ]); // Totp shown by default $this->withHtml($mfaView)->assertElementExists('form[action$="/mfa/totp/verify"] input[name="code"]'); $this->withHtml($mfaView)->assertElementContains('a[href$="/mfa/verify?method=backup_codes"]', 'Verify using a backup code'); // Ensure can view backup_codes view $resp = $this->get('/mfa/verify?method=backup_codes'); $this->withHtml($resp)->assertElementExists('form[action$="/mfa/backup_codes/verify"] input[name="code"]'); $this->withHtml($resp)->assertElementContains('a[href$="/mfa/verify?method=totp"]', 'Verify using a mobile app'); } public function test_mfa_required_with_no_methods_leads_to_setup() { $user = $this->users->editor(); $user->password = Hash::make('password'); $user->save(); /** @var Role $role */ $role = $user->roles->first(); $role->mfa_enforced = true; $role->save(); $this->assertDatabaseMissing('mfa_values', [ 'user_id' => $user->id, ]); /** @var TestResponse $resp */ $resp = $this->followingRedirects()->post('/login', [ 'email' => $user->email, 'password' => 'password', ]); $resp->assertSeeText('No Methods Configured'); $this->withHtml($resp)->assertElementContains('a[href$="/mfa/setup"]', 'Configure'); $this->get('/mfa/backup_codes/generate'); $resp = $this->post('/mfa/backup_codes/confirm'); $resp->assertRedirect('/login'); $this->assertDatabaseHas('mfa_values', [ 'user_id' => $user->id, ]); $resp = $this->get('/login'); $resp->assertSeeText('Multi-factor method configured, Please now login again using the configured method.'); $resp = $this->followingRedirects()->post('/login', [ 'email' => $user->email, 'password' => 'password', ]); $resp->assertSeeText('Enter one of your remaining backup codes below:'); } public function test_mfa_setup_route_access() { $routes = [ ['get', '/mfa/setup'], ['get', '/mfa/totp/generate'], ['post', '/mfa/totp/confirm'], ['get', '/mfa/backup_codes/generate'], ['post', '/mfa/backup_codes/confirm'], ]; // Non-auth access foreach ($routes as [$method, $path]) { $resp = $this->call($method, $path); $resp->assertRedirect('/login'); } // Attempted login user, who has configured mfa, access // Sets up user that has MFA required after attempted login. $loginService = $this->app->make(LoginService::class); $user = $this->users->editor(); /** @var Role $role */ $role = $user->roles->first(); $role->mfa_enforced = true; $role->save(); try { $loginService->login($user, 'testing'); } catch (StoppedAuthenticationException $e) { } $this->assertNotNull($loginService->getLastLoginAttemptUser()); MfaValue::upsertWithValue($user, MfaValue::METHOD_BACKUP_CODES, '[]'); foreach ($routes as [$method, $path]) { $resp = $this->call($method, $path); $resp->assertRedirect('/login'); } } public function test_login_mfa_interception_does_not_log_error() { $logHandler = $this->withTestLogger(); [$user, $secret, $loginResp] = $this->startTotpLogin(); $loginResp->assertRedirect('/mfa/verify'); $this->assertFalse($logHandler->hasErrorRecords()); } /** * @return array<User, string, TestResponse> */ protected function startTotpLogin(): array { $secret = $this->app->make(TotpService::class)->generateSecret(); $user = $this->users->editor(); $user->password = Hash::make('password'); $user->save(); MfaValue::upsertWithValue($user, MfaValue::METHOD_TOTP, $secret); $loginResp = $this->post('/login', [ 'email' => $user->email, 'password' => 'password', ]); return [$user, $secret, $loginResp]; } /** * @return array<User, string, TestResponse> */ protected function startBackupCodeLogin($codes = ['kzzu6-1pgll', 'bzxnf-plygd', 'bwdsp-ysl51', '1vo93-ioy7n', 'lf7nw-wdyka', 'xmtrd-oplac']): array { $user = $this->users->editor(); $user->password = Hash::make('password'); $user->save(); MfaValue::upsertWithValue($user, MfaValue::METHOD_BACKUP_CODES, json_encode($codes)); $loginResp = $this->post('/login', [ 'email' => $user->email, 'password' => 'password', ]); return [$user, $codes, $loginResp]; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Auth/MfaConfigurationTest.php
tests/Auth/MfaConfigurationTest.php
<?php namespace Tests\Auth; use BookStack\Access\Mfa\MfaValue; use BookStack\Activity\ActivityType; use BookStack\Users\Models\Role; use BookStack\Users\Models\User; use Illuminate\Support\Facades\Hash; use PragmaRX\Google2FA\Google2FA; use Tests\TestCase; class MfaConfigurationTest extends TestCase { public function test_totp_setup() { $editor = $this->users->editor(); $this->assertDatabaseMissing('mfa_values', ['user_id' => $editor->id]); // Setup page state $resp = $this->actingAs($editor)->get('/mfa/setup'); $this->withHtml($resp)->assertElementContains('a[href$="/mfa/totp/generate"]', 'Setup'); // Generate page access $resp = $this->get('/mfa/totp/generate'); $resp->assertSee('Mobile App Setup'); $resp->assertSee('Verify Setup'); $this->withHtml($resp)->assertElementExists('form[action$="/mfa/totp/confirm"] button'); $this->assertSessionHas('mfa-setup-totp-secret'); $svg = $this->withHtml($resp)->getOuterHtml('#main-content .card svg'); // Validation error, code should remain the same $resp = $this->post('/mfa/totp/confirm', [ 'code' => 'abc123', ]); $resp->assertRedirect('/mfa/totp/generate'); $resp = $this->followRedirects($resp); $resp->assertSee('The provided code is not valid or has expired.'); $revisitSvg = $this->withHtml($resp)->getOuterHtml('#main-content .card svg'); $this->assertTrue($svg === $revisitSvg); $secret = decrypt(session()->get('mfa-setup-totp-secret')); $resp->assertSee("?secret={$secret}&issuer=BookStack&algorithm=SHA1&digits=6&period=30"); // Successful confirmation $google2fa = new Google2FA(); $otp = $google2fa->getCurrentOtp($secret); $resp = $this->post('/mfa/totp/confirm', [ 'code' => $otp, ]); $resp->assertRedirect('/mfa/setup'); // Confirmation of setup $resp = $this->followRedirects($resp); $resp->assertSee('Multi-factor method successfully configured'); $this->withHtml($resp)->assertElementContains('a[href$="/mfa/totp/generate"]', 'Reconfigure'); $this->assertDatabaseHas('mfa_values', [ 'user_id' => $editor->id, 'method' => 'totp', ]); $this->assertFalse(session()->has('mfa-setup-totp-secret')); $value = MfaValue::query()->where('user_id', '=', $editor->id) ->where('method', '=', 'totp')->first(); $this->assertEquals($secret, decrypt($value->value)); } public function test_backup_codes_setup() { $editor = $this->users->editor(); $this->assertDatabaseMissing('mfa_values', ['user_id' => $editor->id]); // Setup page state $resp = $this->actingAs($editor)->get('/mfa/setup'); $this->withHtml($resp)->assertElementContains('a[href$="/mfa/backup_codes/generate"]', 'Setup'); // Generate page access $resp = $this->get('/mfa/backup_codes/generate'); $resp->assertSee('Backup Codes'); $this->withHtml($resp)->assertElementContains('form[action$="/mfa/backup_codes/confirm"]', 'Confirm and Enable'); $this->assertSessionHas('mfa-setup-backup-codes'); $codes = decrypt(session()->get('mfa-setup-backup-codes')); // Check code format $this->assertCount(16, $codes); $this->assertEquals(16 * 11, strlen(implode('', $codes))); // Check download link $resp->assertSee(base64_encode(implode("\n\n", $codes))); // Confirm submit $resp = $this->post('/mfa/backup_codes/confirm'); $resp->assertRedirect('/mfa/setup'); // Confirmation of setup $resp = $this->followRedirects($resp); $resp->assertSee('Multi-factor method successfully configured'); $this->withHtml($resp)->assertElementContains('a[href$="/mfa/backup_codes/generate"]', 'Reconfigure'); $this->assertDatabaseHas('mfa_values', [ 'user_id' => $editor->id, 'method' => 'backup_codes', ]); $this->assertFalse(session()->has('mfa-setup-backup-codes')); $value = MfaValue::query()->where('user_id', '=', $editor->id) ->where('method', '=', 'backup_codes')->first(); $this->assertEquals($codes, json_decode(decrypt($value->value))); } public function test_backup_codes_cannot_be_confirmed_if_not_previously_generated() { $resp = $this->asEditor()->post('/mfa/backup_codes/confirm'); $resp->assertStatus(500); } public function test_mfa_method_count_is_visible_on_user_edit_page() { $user = $this->users->editor(); $resp = $this->actingAs($this->users->admin())->get($user->getEditUrl()); $resp->assertSee('0 methods configured'); MfaValue::upsertWithValue($user, MfaValue::METHOD_TOTP, 'test'); $resp = $this->get($user->getEditUrl()); $resp->assertSee('1 method configured'); MfaValue::upsertWithValue($user, MfaValue::METHOD_BACKUP_CODES, 'test'); $resp = $this->get($user->getEditUrl()); $resp->assertSee('2 methods configured'); } public function test_mfa_setup_link_only_shown_when_viewing_own_user_edit_page() { $admin = $this->users->admin(); $resp = $this->actingAs($admin)->get($admin->getEditUrl()); $this->withHtml($resp)->assertElementExists('a[href$="/mfa/setup"]'); $resp = $this->actingAs($admin)->get($this->users->editor()->getEditUrl()); $this->withHtml($resp)->assertElementNotExists('a[href$="/mfa/setup"]'); } public function test_mfa_indicator_shows_in_user_list() { $admin = $this->users->admin(); User::query()->where('id', '!=', $admin->id)->delete(); $resp = $this->actingAs($admin)->get('/settings/users'); $this->withHtml($resp)->assertElementNotExists('[title="MFA Configured"] svg'); MfaValue::upsertWithValue($admin, MfaValue::METHOD_TOTP, 'test'); $resp = $this->actingAs($admin)->get('/settings/users'); $this->withHtml($resp)->assertElementExists('[title="MFA Configured"] svg'); } public function test_remove_mfa_method() { $admin = $this->users->admin(); MfaValue::upsertWithValue($admin, MfaValue::METHOD_TOTP, 'test'); $this->assertEquals(1, $admin->mfaValues()->count()); $resp = $this->actingAs($admin)->get('/mfa/setup'); $this->withHtml($resp)->assertElementExists('form[action$="/mfa/totp/remove"]'); $resp = $this->delete('/mfa/totp/remove'); $resp->assertRedirect('/mfa/setup'); $resp = $this->followRedirects($resp); $resp->assertSee('Multi-factor method successfully removed'); $this->assertActivityExists(ActivityType::MFA_REMOVE_METHOD); $this->assertEquals(0, $admin->mfaValues()->count()); } public function test_mfa_required_if_set_on_role() { $user = $this->users->viewer(); $user->password = Hash::make('password'); $user->save(); /** @var Role $role */ $role = $user->roles()->first(); $role->mfa_enforced = true; $role->save(); $resp = $this->post('/login', ['email' => $user->email, 'password' => 'password']); $this->assertFalse(auth()->check()); $resp->assertRedirect('/mfa/verify'); } public function test_mfa_required_if_mfa_option_configured() { $user = $this->users->viewer(); $user->password = Hash::make('password'); $user->save(); $user->mfaValues()->create([ 'method' => MfaValue::METHOD_TOTP, 'value' => 'test', ]); $resp = $this->post('/login', ['email' => $user->email, 'password' => 'password']); $this->assertFalse(auth()->check()); $resp->assertRedirect('/mfa/verify'); } public function test_totp_setup_url_shows_correct_user_when_setup_forced_upon_login() { $admin = $this->users->admin(); /** @var Role $role */ $role = $admin->roles()->first(); $role->mfa_enforced = true; $role->save(); $resp = $this->post('/login', ['email' => $admin->email, 'password' => 'password']); $this->assertFalse(auth()->check()); $resp->assertRedirect('/mfa/verify'); $resp = $this->get('/mfa/totp/generate'); $resp->assertSeeText('Mobile App Setup'); $resp->assertDontSee('otpauth://totp/BookStack:guest%40example.com', false); $resp->assertSee('otpauth://totp/BookStack:admin%40admin.com', false); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Auth/Saml2Test.php
tests/Auth/Saml2Test.php
<?php namespace Tests\Auth; use BookStack\Users\Models\Role; use BookStack\Users\Models\User; use Tests\TestCase; class Saml2Test extends TestCase { protected function setUp(): void { parent::setUp(); // Set default config for SAML2 config()->set([ 'auth.method' => 'saml2', 'auth.defaults.guard' => 'saml2', 'saml2.name' => 'SingleSignOn-Testing', 'saml2.email_attribute' => 'email', 'saml2.display_name_attributes' => ['first_name', 'last_name'], 'saml2.external_id_attribute' => 'uid', 'saml2.user_to_groups' => false, 'saml2.group_attribute' => 'user_groups', 'saml2.remove_from_groups' => false, 'saml2.onelogin_overrides' => null, 'saml2.onelogin.idp.entityId' => 'http://saml.local/saml2/idp/metadata.php', 'saml2.onelogin.idp.singleSignOnService.url' => 'http://saml.local/saml2/idp/SSOService.php', 'saml2.onelogin.idp.singleLogoutService.url' => 'http://saml.local/saml2/idp/SingleLogoutService.php', 'saml2.autoload_from_metadata' => false, 'saml2.onelogin.idp.x509cert' => $this->testCert, 'saml2.onelogin.debug' => false, 'saml2.onelogin.security.requestedAuthnContext' => true, ]); } public function test_metadata_endpoint_displays_xml_as_expected() { $req = $this->get('/saml2/metadata'); $req->assertHeader('Content-Type', 'text/xml; charset=utf-8'); $req->assertSee('md:EntityDescriptor'); $req->assertSee(url('/saml2/acs')); } public function test_metadata_endpoint_loads_when_autoloading_with_bad_url_set() { config()->set([ 'saml2.autoload_from_metadata' => true, 'saml2.onelogin.idp.entityId' => 'http://192.168.1.1:9292', 'saml2.onelogin.idp.singleSignOnService.url' => null, ]); $req = $this->get('/saml2/metadata'); $req->assertOk(); $req->assertHeader('Content-Type', 'text/xml; charset=utf-8'); $req->assertSee('md:EntityDescriptor'); } public function test_onelogin_overrides_functions_as_expected() { $json = '{"sp": {"assertionConsumerService": {"url": "https://example.com/super-cats"}}, "contactPerson": {"technical": {"givenName": "Barry Scott", "emailAddress": "barry@example.com"}}}'; config()->set(['saml2.onelogin_overrides' => $json]); $req = $this->get('/saml2/metadata'); $req->assertSee('https://example.com/super-cats'); $req->assertSee('md:ContactPerson'); $req->assertSee('<md:GivenName>Barry Scott</md:GivenName>', false); } public function test_login_option_shows_on_login_page() { $req = $this->get('/login'); $req->assertSeeText('SingleSignOn-Testing'); $this->withHtml($req)->assertElementExists('form[action$="/saml2/login"][method=POST] button'); } public function test_login() { $req = $this->post('/saml2/login'); $redirect = $req->headers->get('location'); $this->assertStringStartsWith('http://saml.local/saml2/idp/SSOService.php', $redirect, 'Login redirects to SSO location'); config()->set(['saml2.onelogin.strict' => false]); $this->assertFalse($this->isAuthenticated()); $acsPost = $this->post('/saml2/acs', ['SAMLResponse' => $this->acsPostData]); $redirect = $acsPost->headers->get('Location'); $acsId = explode('?id=', $redirect)[1]; $this->assertTrue(strlen($acsId) > 12); $this->assertStringContainsString('/saml2/acs?id=', $redirect); $this->assertTrue(cache()->has('saml2_acs:' . $acsId)); $acsGet = $this->get($redirect); $acsGet->assertRedirect('/'); $this->assertFalse(cache()->has('saml2_acs:' . $acsId)); $this->assertTrue($this->isAuthenticated()); $this->assertDatabaseHas('users', [ 'email' => 'user@example.com', 'external_auth_id' => 'user', 'email_confirmed' => false, 'name' => 'Barry Scott', ]); } public function test_acs_process_id_randomly_generated() { $acsPost = $this->post('/saml2/acs', ['SAMLResponse' => $this->acsPostData]); $redirectA = $acsPost->headers->get('Location'); $acsPost = $this->post('/saml2/acs', ['SAMLResponse' => $this->acsPostData]); $redirectB = $acsPost->headers->get('Location'); $this->assertFalse($redirectA === $redirectB); } public function test_process_acs_endpoint_cant_be_called_with_invalid_id() { $resp = $this->get('/saml2/acs'); $resp->assertRedirect('/login'); $this->followRedirects($resp)->assertSeeText('Login using SingleSignOn-Testing failed, system did not provide successful authorization'); $resp = $this->get('/saml2/acs?id=abc123'); $resp->assertRedirect('/login'); $this->followRedirects($resp)->assertSeeText('Login using SingleSignOn-Testing failed, system did not provide successful authorization'); } public function test_group_role_sync_on_login() { config()->set([ 'saml2.onelogin.strict' => false, 'saml2.user_to_groups' => true, 'saml2.remove_from_groups' => false, ]); $memberRole = Role::factory()->create(['external_auth_id' => 'member']); $adminRole = Role::getSystemRole('admin'); $this->followingRedirects()->post('/saml2/acs', ['SAMLResponse' => $this->acsPostData]); $user = User::query()->where('external_auth_id', '=', 'user')->first(); $userRoleIds = $user->roles()->pluck('id'); $this->assertContains($memberRole->id, $userRoleIds, 'User was assigned to member role'); $this->assertContains($adminRole->id, $userRoleIds, 'User was assigned to admin role'); } public function test_group_role_sync_removal_option_works_as_expected() { config()->set([ 'saml2.onelogin.strict' => false, 'saml2.user_to_groups' => true, 'saml2.remove_from_groups' => true, ]); $acsPost = $this->followingRedirects()->post('/saml2/acs', ['SAMLResponse' => $this->acsPostData]); $user = User::query()->where('external_auth_id', '=', 'user')->first(); $randomRole = Role::factory()->create(['external_auth_id' => 'random']); $user->attachRole($randomRole); $this->assertContains($randomRole->id, $user->roles()->pluck('id')); auth()->logout(); $acsPost = $this->followingRedirects()->post('/saml2/acs', ['SAMLResponse' => $this->acsPostData]); $this->assertNotContains($randomRole->id, $user->roles()->pluck('id')); } public function test_logout_link_directs_to_saml_path() { config()->set([ 'saml2.onelogin.strict' => false, ]); $resp = $this->actingAs($this->users->editor())->get('/'); $this->withHtml($resp)->assertElementContains('form[action$="/saml2/logout"] button', 'Logout'); } public function test_logout_sls_flow() { config()->set([ 'saml2.onelogin.strict' => false, ]); $handleLogoutResponse = function () { $this->assertFalse($this->isAuthenticated()); $req = $this->get('/saml2/sls'); $req->assertRedirect('/'); $this->assertFalse($this->isAuthenticated()); }; $this->followingRedirects()->post('/saml2/acs', ['SAMLResponse' => $this->acsPostData]); $req = $this->post('/saml2/logout'); $redirect = $req->headers->get('location'); $this->assertStringStartsWith('http://saml.local/saml2/idp/SingleLogoutService.php', $redirect); $sloData = $this->parseSamlDataFromUrl($redirect, 'SAMLRequest'); $this->assertStringContainsString('<samlp:SessionIndex>_4fe7c0d1572d64b27f930aa6f236a6f42e930901cc</samlp:SessionIndex>', $sloData); $this->withGet(['SAMLResponse' => $this->sloResponseData], $handleLogoutResponse); } public function test_logout_sls_flow_when_sls_not_configured() { config()->set([ 'saml2.onelogin.strict' => false, 'saml2.onelogin.idp.singleLogoutService.url' => null, ]); $this->followingRedirects()->post('/saml2/acs', ['SAMLResponse' => $this->acsPostData]); $this->assertTrue($this->isAuthenticated()); $req = $this->post('/saml2/logout'); $req->assertRedirect('/'); $this->assertFalse($this->isAuthenticated()); } public function test_logout_sls_flow_logs_user_out_before_redirect() { config()->set([ 'saml2.onelogin.strict' => false, ]); $this->followingRedirects()->post('/saml2/acs', ['SAMLResponse' => $this->acsPostData]); $this->assertTrue($this->isAuthenticated()); $req = $this->post('/saml2/logout'); $redirect = $req->headers->get('location'); $this->assertStringStartsWith('http://saml.local/saml2/idp/SingleLogoutService.php', $redirect); $this->assertFalse($this->isAuthenticated()); } public function test_logout_sls_request_redirect_prevents_auto_login_when_enabled() { config()->set([ 'saml2.onelogin.strict' => false, 'auth.auto_initiate' => true, 'services.google.client_id' => false, 'services.github.client_id' => false, ]); $this->followingRedirects()->post('/saml2/acs', ['SAMLResponse' => $this->acsPostData]); $req = $this->post('/saml2/logout'); $redirect = $req->headers->get('location'); $this->assertStringContainsString(urlencode(url('/login?prevent_auto_init=true')), $redirect); } public function test_logout_sls_response_endpoint_redirect_prevents_auto_login_when_enabled() { config()->set([ 'saml2.onelogin.strict' => false, 'auth.auto_initiate' => true, 'services.google.client_id' => false, 'services.github.client_id' => false, ]); $this->followingRedirects()->post('/saml2/acs', ['SAMLResponse' => $this->acsPostData]); $this->withGet(['SAMLResponse' => $this->sloResponseData], function () { $req = $this->get('/saml2/sls'); $redirect = $req->headers->get('location'); $this->assertEquals(url('/login?prevent_auto_init=true'), $redirect); }); } public function test_dump_user_details_option_works() { config()->set([ 'saml2.onelogin.strict' => false, 'saml2.dump_user_details' => true, ]); $acsPost = $this->followingRedirects()->post('/saml2/acs', ['SAMLResponse' => $this->acsPostData]); $acsPost->assertJsonStructure([ 'id_from_idp', 'attrs_from_idp' => [], 'attrs_after_parsing' => [], ]); } public function test_dump_user_details_response_contains_parsed_group_data_if_groups_enabled() { config()->set([ 'saml2.onelogin.strict' => false, 'saml2.dump_user_details' => true, 'saml2.user_to_groups' => true, ]); $acsPost = $this->followingRedirects()->post('/saml2/acs', ['SAMLResponse' => $this->acsPostData]); $acsPost->assertJson([ 'attrs_after_parsing' => [ 'groups' => ['member', 'admin'], ] ]); } public function test_saml_routes_are_only_active_if_saml_enabled() { config()->set(['auth.method' => 'standard']); $getRoutes = ['/metadata', '/sls']; foreach ($getRoutes as $route) { $req = $this->get('/saml2' . $route); $this->assertPermissionError($req); } $postRoutes = ['/login', '/acs', '/logout']; foreach ($postRoutes as $route) { $req = $this->post('/saml2' . $route); $this->assertPermissionError($req); } } public function test_forgot_password_routes_inaccessible() { $resp = $this->get('/password/email'); $this->assertPermissionError($resp); $resp = $this->post('/password/email'); $this->assertPermissionError($resp); $resp = $this->get('/password/reset/abc123'); $this->assertPermissionError($resp); $resp = $this->post('/password/reset'); $this->assertPermissionError($resp); } public function test_standard_login_routes_inaccessible() { $resp = $this->post('/login'); $this->assertPermissionError($resp); $resp = $this->post('/logout'); $this->assertPermissionError($resp); } public function test_user_invite_routes_inaccessible() { $resp = $this->get('/register/invite/abc123'); $this->assertPermissionError($resp); $resp = $this->post('/register/invite/abc123'); $this->assertPermissionError($resp); } public function test_user_register_routes_inaccessible() { $resp = $this->get('/register'); $this->assertPermissionError($resp); $resp = $this->post('/register'); $this->assertPermissionError($resp); } public function test_email_domain_restriction_active_on_new_saml_login() { $this->setSettings([ 'registration-restrict' => 'testing.com', ]); config()->set([ 'saml2.onelogin.strict' => false, ]); $acsPost = $this->followingRedirects()->post('/saml2/acs', ['SAMLResponse' => $this->acsPostData]); $acsPost->assertSeeText('That email domain does not have access to this application'); $this->assertFalse(auth()->check()); $this->assertDatabaseMissing('users', ['email' => 'user@example.com']); } public function test_group_sync_functions_when_email_confirmation_required() { setting()->put('registration-confirmation', 'true'); config()->set([ 'saml2.onelogin.strict' => false, 'saml2.user_to_groups' => true, 'saml2.remove_from_groups' => false, ]); $memberRole = Role::factory()->create(['external_auth_id' => 'member']); $adminRole = Role::getSystemRole('admin'); $acsPost = $this->followingRedirects()->post('/saml2/acs', ['SAMLResponse' => $this->acsPostData]); $this->assertEquals('http://localhost/register/confirm', url()->current()); $acsPost->assertSee('Please check your email and click the confirmation button to access BookStack.'); /** @var User $user */ $user = User::query()->where('external_auth_id', '=', 'user')->first(); $userRoleIds = $user->roles()->pluck('id'); $this->assertContains($memberRole->id, $userRoleIds, 'User was assigned to member role'); $this->assertContains($adminRole->id, $userRoleIds, 'User was assigned to admin role'); $this->assertFalse(boolval($user->email_confirmed), 'User email remains unconfirmed'); $this->assertNull(auth()->user()); $homeGet = $this->get('/'); $homeGet->assertRedirect('/login'); } public function test_login_where_existing_non_saml_user_shows_warning() { $this->post('/saml2/login'); config()->set(['saml2.onelogin.strict' => false]); // Make the user pre-existing in DB with different auth_id User::query()->forceCreate([ 'email' => 'user@example.com', 'external_auth_id' => 'old_system_user_id', 'email_confirmed' => false, 'name' => 'Barry Scott', ]); $acsPost = $this->followingRedirects()->post('/saml2/acs', ['SAMLResponse' => $this->acsPostData]); $this->assertFalse($this->isAuthenticated()); $this->assertDatabaseHas('users', [ 'email' => 'user@example.com', 'external_auth_id' => 'old_system_user_id', ]); $acsPost->assertSee('A user with the email user@example.com already exists but with different credentials'); } public function test_login_request_contains_expected_default_authncontext() { $authReq = $this->getAuthnRequest(); $this->assertStringContainsString('samlp:RequestedAuthnContext Comparison="exact"', $authReq); $this->assertStringContainsString('<saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</saml:AuthnContextClassRef>', $authReq); } public function test_false_idp_authncontext_option_does_not_pass_authncontext_in_saml_request() { config()->set(['saml2.onelogin.security.requestedAuthnContext' => false]); $authReq = $this->getAuthnRequest(); $this->assertStringNotContainsString('samlp:RequestedAuthnContext', $authReq); $this->assertStringNotContainsString('<saml:AuthnContextClassRef>', $authReq); } public function test_array_idp_authncontext_option_passes_value_as_authncontextclassref_in_request() { config()->set(['saml2.onelogin.security.requestedAuthnContext' => ['urn:federation:authentication:windows', 'urn:federation:authentication:linux']]); $authReq = $this->getAuthnRequest(); $this->assertStringContainsString('samlp:RequestedAuthnContext', $authReq); $this->assertStringContainsString('<saml:AuthnContextClassRef>urn:federation:authentication:windows</saml:AuthnContextClassRef>', $authReq); $this->assertStringContainsString('<saml:AuthnContextClassRef>urn:federation:authentication:linux</saml:AuthnContextClassRef>', $authReq); } protected function getAuthnRequest(): string { $req = $this->post('/saml2/login'); $location = $req->headers->get('Location'); return $this->parseSamlDataFromUrl($location, 'SAMLRequest'); } protected function parseSamlDataFromUrl(string $url, string $paramName): string { $query = explode('?', $url)[1]; $params = []; parse_str($query, $params); return gzinflate(base64_decode($params[$paramName])); } protected function withGet(array $options, callable $callback) { return $this->withGlobal($_GET, $options, $callback); } protected function withGlobal(array &$global, array $options, callable $callback) { $original = []; foreach ($options as $key => $val) { $original[$key] = $global[$key] ?? null; $global[$key] = $val; } $callback(); foreach ($options as $key => $val) { $val = $original[$key]; if ($val) { $global[$key] = $val; } else { unset($global[$key]); } } } /** * The post data for a callback for single-sign-in. * Provides the following attributes: * array:5 [ * "uid" => array:1 [ * 0 => "user" * ] * "first_name" => array:1 [ * 0 => "Barry" * ] * "last_name" => array:1 [ * 0 => "Scott" * ] * "email" => array:1 [ * 0 => "user@example.com" * ] * "user_groups" => array:2 [ * 0 => "member" * 1 => "admin" * ] * ]. */ protected string $acsPostData = 'PHNhbWxwOlJlc3BvbnNlIHhtbG5zOnNhbWxwPSJ1cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6cHJvdG9jb2wiIHhtbG5zOnNhbWw9InVybjpvYXNpczpuYW1lczp0YzpTQU1MOjIuMDphc3NlcnRpb24iIElEPSJfNGRkNDU2NGRjNzk0MDYxZWYxYmFhMDQ2N2Q3OTAyOGNlZDNjZTU0YmVlIiBWZXJzaW9uPSIyLjAiIElzc3VlSW5zdGFudD0iMjAxOS0xMS0xN1QxNzo1MzozOVoiIERlc3RpbmF0aW9uPSJodHRwOi8vYm9va3N0YWNrLmxvY2FsL3NhbWwyL2FjcyIgSW5SZXNwb25zZVRvPSJPTkVMT0dJTl82YTBmNGYzOTkzMDQwZjE5ODdmZDM3MDY4YjUyOTYyMjlhZDUzNjFjIj48c2FtbDpJc3N1ZXI+aHR0cDovL3NhbWwubG9jYWwvc2FtbDIvaWRwL21ldGFkYXRhLnBocDwvc2FtbDpJc3N1ZXI+PGRzOlNpZ25hdHVyZSB4bWxuczpkcz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC8wOS94bWxkc2lnIyI+CiAgPGRzOlNpZ25lZEluZm8+PGRzOkNhbm9uaWNhbGl6YXRpb25NZXRob2QgQWxnb3JpdGhtPSJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzEwL3htbC1leGMtYzE0biMiLz4KICAgIDxkczpTaWduYXR1cmVNZXRob2QgQWxnb3JpdGhtPSJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNyc2Etc2hhMjU2Ii8+CiAgPGRzOlJlZmVyZW5jZSBVUkk9IiNfNGRkNDU2NGRjNzk0MDYxZWYxYmFhMDQ2N2Q3OTAyOGNlZDNjZTU0YmVlIj48ZHM6VHJhbnNmb3Jtcz48ZHM6VHJhbnNmb3JtIEFsZ29yaXRobT0iaHR0cDovL3d3dy53My5vcmcvMjAwMC8wOS94bWxkc2lnI2VudmVsb3BlZC1zaWduYXR1cmUiLz48ZHM6VHJhbnNmb3JtIEFsZ29yaXRobT0iaHR0cDovL3d3dy53My5vcmcvMjAwMS8xMC94bWwtZXhjLWMxNG4jIi8+PC9kczpUcmFuc2Zvcm1zPjxkczpEaWdlc3RNZXRob2QgQWxnb3JpdGhtPSJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGVuYyNzaGEyNTYiLz48ZHM6RGlnZXN0VmFsdWU+dm1oL1M3NU5mK2crZWNESkN6QWJaV0tKVmx1ZzdCZnNDKzlhV05lSXJlUT08L2RzOkRpZ2VzdFZhbHVlPjwvZHM6UmVmZXJlbmNlPjwvZHM6U2lnbmVkSW5mbz48ZHM6U2lnbmF0dXJlVmFsdWU+dnJhZ0tKWHNjVm5UNjJFaEk3bGk4MERUWHNOTGJOc3lwNWZ2QnU4WjFYSEtFUVA3QWpPNkcxcVBwaGpWQ2dRMzd6TldVVTZvUytQeFA3UDlHeG5xL3hKejRUT3lHcHJ5N1RoK2pIcHc0YWVzQTdrTmp6VU51UmU2c1ltWTlrRXh2VjMvTmJRZjROMlM2Y2RhRHIzWFRodllVVDcxYzQwNVVHOFJpQjJaY3liWHIxZU1yWCtXUDBnU2Qrc0F2RExqTjBJc3pVWlVUNThadFpEVE1ya1ZGL0pIbFBFQ04vVW1sYVBBeitTcUJ4c25xTndZK1oxYUt3MnlqeFRlNnUxM09Kb29OOVN1REowNE0rK2F3RlY3NkI4cXEyTzMxa3FBbDJibm1wTGxtTWdRNFEraUlnL3dCc09abTV1clphOWJObDNLVEhtTVBXbFpkbWhsLzgvMy9IT1RxN2thWGs3cnlWRHRLcFlsZ3FUajNhRUpuL0dwM2o4SFp5MUVialRiOTRRT1ZQMG5IQzB1V2hCaE13TjdzVjFrUSsxU2NjUlpUZXJKSGlSVUQvR0srTVg3M0YrbzJVTFRIL1Z6Tm9SM2o4N2hOLzZ1UC9JeG5aM1RudGR1MFZPZS9ucEdVWjBSMG9SWFhwa2JTL2poNWk1ZjU0RXN4eXZ1VEM5NHdKaEM8L2RzOlNpZ25hdHVyZVZhbHVlPgo8ZHM6S2V5SW5mbz48ZHM6WDUwOURhdGE+PGRzOlg1MDlDZXJ0aWZpY2F0ZT5NSUlFYXpDQ0F0T2dBd0lCQWdJVWU3YTA4OENucjRpem1ybkJFbng1cTNIVE12WXdEUVlKS29aSWh2Y05BUUVMQlFBd1JURUxNQWtHQTFVRUJoTUNSMEl4RXpBUkJnTlZCQWdNQ2xOdmJXVXRVM1JoZEdVeElUQWZCZ05WQkFvTUdFbHVkR1Z5Ym1WMElGZHBaR2RwZEhNZ1VIUjVJRXgwWkRBZUZ3MHhPVEV4TVRZeE1qRTNNVFZhRncweU9URXhNVFV4TWpFM01UVmFNRVV4Q3pBSkJnTlZCQVlUQWtkQ01STXdFUVlEVlFRSURBcFRiMjFsTFZOMFlYUmxNU0V3SHdZRFZRUUtEQmhKYm5SbGNtNWxkQ0JYYVdSbmFYUnpJRkIwZVNCTWRHUXdnZ0dpTUEwR0NTcUdTSWIzRFFFQkFRVUFBNElCandBd2dnR0tBb0lCZ1FEekxlOUZmZHlwbFR4SHA0U3VROWdRdFpUM3QrU0RmdkVMNzJwcENmRlp3NytCNXM1Qi9UNzNhWHBvUTNTNTNwR0kxUklXQ2dlMmlDVVEydHptMjdhU05IMGl1OWFKWWNVUVovUklUcWQwYXl5RGtzMU5BMlBUM1RXNnQzbTdLVjVyZTRQME5iK1lEZXV5SGRreitqY010cG44Q21Cb1QwSCtza2hhMGhpcUlOa2prUlBpSHZMSFZHcCt0SFVFQS9JNm1ONGFCL1VFeFNUTHM3OU5zTFVmdGVxcXhlOSt0dmRVYVRveURQcmhQRmpPTnMrOU5LQ2t6SUM2dmN2N0o2QXR1S0c2bkVUK3pCOXlPV2d0R1lRaWZYcVFBMnk1ZEw4MUJCMHE1dU1hQkxTMnBxM2FQUGp6VTJGMytFeXNqeVNXVG5Da2ZrN0M1U3NDWFJ1OFErVTk1dHVucE5md2Y1b2xFNldhczQ4Tk1NK1B3VjdpQ05NUGtOemxscTZQQ2lNK1A4RHJNU2N6elVaWlFVU3Y2ZFN3UENvK1lTVmltRU0wT2czWEpUaU5oUTVBTmxhSW42Nkt3NWdmb0JmdWlYbXlJS2lTRHlBaURZbUZhZjQzOTV3V3dMa1RSK2N3OFdmamFIc3dLWlRvbW4xTVIzT0pzWTJVSjBlUkJZTStZU3NDQXdFQUFhTlRNRkV3SFFZRFZSME9CQllFRkltcDJDWUNHZmNiN3c5MUgvY1NoVENrWHdSL01COEdBMVVkSXdRWU1CYUFGSW1wMkNZQ0dmY2I3dzkxSC9jU2hUQ2tYd1IvTUE4R0ExVWRFd0VCL3dRRk1BTUJBZjh3RFFZSktvWklodmNOQVFFTEJRQURnZ0dCQUErZy9DN3VMOWxuK1crcUJrbkxXODFrb2pZZmxnUEsxSTFNSEl3bk12bC9aVEhYNGRSWEtEcms3S2NVcTFLanFhak5WNjZmMWNha3AwM0lpakJpTzBYaTFnWFVaWUxvQ2lOR1V5eXA5WGxvaUl5OVh3MlBpV25ydzAreVp5dlZzc2JlaFhYWUpsNFJpaEJqQld1bDlSNHdNWUxPVVNKRGUyV3hjVUJoSm54eU5ScytQMHhMU1FYNkIybjZueG9Ea280cDA3czhaS1hRa2VpWjJpd0ZkVHh6UmtHanRoTVV2NzA0bnpzVkdCVDBEQ1B0ZlNhTzVLSlpXMXJDczN5aU10aG5CeHE0cUVET1FKRklsKy9MRDcxS2JCOXZaY1c1SnVhdnpCRm1rS0dOcm8vNkcxSTdlbDQ2SVI0d2lqVHlORkNZVXVEOWR0aWduTm1wV3ROOE9XK3B0aUwvanRUeVNXdWtqeXMwcyt2TG44M0NWdmpCMGRKdFZBSVlPZ1hGZEl1aWk2Nmdjend3TS9MR2lPRXhKbjBkVE56c0ovSVlocHhMNEZCRXVQMHBza1kwbzBhVWxKMkxTMmord1NRVFJLc0JnTWp5clVyZWtsZTJPRFN0U3RuM2VhYmpJeDAvRkhscEZyMGpOSW0vb01QN2t3anRVWDR6YU5lNDdRSTRHZz09PC9kczpYNTA5Q2VydGlmaWNhdGU+PC9kczpYNTA5RGF0YT48L2RzOktleUluZm8+PC9kczpTaWduYXR1cmU+PHNhbWxwOlN0YXR1cz48c2FtbHA6U3RhdHVzQ29kZSBWYWx1ZT0idXJuOm9hc2lzOm5hbWVzOnRjOlNBTUw6Mi4wOnN0YXR1czpTdWNjZXNzIi8+PC9zYW1scDpTdGF0dXM+PHNhbWw6QXNzZXJ0aW9uIHhtbG5zOnhzaT0iaHR0cDovL3d3dy53My5vcmcvMjAwMS9YTUxTY2hlbWEtaW5zdGFuY2UiIHhtbG5zOnhzPSJodHRwOi8vd3d3LnczLm9yZy8yMDAxL1hNTFNjaGVtYSIgSUQ9Il82ODQyZGY5YzY1OWYxM2ZlNTE5NmNkOWVmNmMyZjAyODM2NGFlOTQzYjEiIFZlcnNpb249IjIuMCIgSXNzdWVJbnN0YW50PSIyMDE5LTExLTE3VDE3OjUzOjM5WiI+PHNhbWw6SXNzdWVyPmh0dHA6Ly9zYW1sLmxvY2FsL3NhbWwyL2lkcC9tZXRhZGF0YS5waHA8L3NhbWw6SXNzdWVyPjxkczpTaWduYXR1cmUgeG1sbnM6ZHM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDkveG1sZHNpZyMiPgogIDxkczpTaWduZWRJbmZvPjxkczpDYW5vbmljYWxpemF0aW9uTWV0aG9kIEFsZ29yaXRobT0iaHR0cDovL3d3dy53My5vcmcvMjAwMS8xMC94bWwtZXhjLWMxNG4jIi8+CiAgICA8ZHM6U2lnbmF0dXJlTWV0aG9kIEFsZ29yaXRobT0iaHR0cDovL3d3dy53My5vcmcvMjAwMS8wNC94bWxkc2lnLW1vcmUjcnNhLXNoYTI1NiIvPgogIDxkczpSZWZlcmVuY2UgVVJJPSIjXzY4NDJkZjljNjU5ZjEzZmU1MTk2Y2Q5ZWY2YzJmMDI4MzY0YWU5NDNiMSI+PGRzOlRyYW5zZm9ybXM+PGRzOlRyYW5zZm9ybSBBbGdvcml0aG09Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDkveG1sZHNpZyNlbnZlbG9wZWQtc2lnbmF0dXJlIi8+PGRzOlRyYW5zZm9ybSBBbGdvcml0aG09Imh0dHA6Ly93d3cudzMub3JnLzIwMDEvMTAveG1sLWV4Yy1jMTRuIyIvPjwvZHM6VHJhbnNmb3Jtcz48ZHM6RGlnZXN0TWV0aG9kIEFsZ29yaXRobT0iaHR0cDovL3d3dy53My5vcmcvMjAwMS8wNC94bWxlbmMjc2hhMjU2Ii8+PGRzOkRpZ2VzdFZhbHVlPmtyYjV3NlM4dG9YYy9lU3daUFVPQnZRem4zb3M0SkFDdXh4ckpreHBnRnc9PC9kczpEaWdlc3RWYWx1ZT48L2RzOlJlZmVyZW5jZT48L2RzOlNpZ25lZEluZm8+PGRzOlNpZ25hdHVyZVZhbHVlPjJxcW1Ba3hucXhOa3N5eXh5dnFTVDUxTDg5VS9ZdHpja2t1ekF4ci9hQ1JTK1NPRzg1YkFNWm8vU3puc3d0TVlBYlFRQ0VGb0R1amdNdlpzSFl3NlR2dmFHanlXWUpRNVZyYWhlemZaSWlCVUU0NHBtWGFrOCswV0l0WTVndnBGSXhxWFZaRmdFUkt2VExmZVFCMzhkMVZQc0ZVZ0RYdXQ4VS9Qdm43dXZwdXZjVXorMUUyOUVKR2FZL0dndnhUN0tyWU9SQTh3SitNdVRzUVZtanNlUnhveVJTejA4TmJ3ZTJIOGpXQnpFWWNxWWwyK0ZnK2hwNWd0S216VmhLRnBkNXZBNjdBSXo1NXN0QmNHNSswNHJVaWpFSzRzci9xa0x5QmtKQjdLdkwzanZKcG8zQjhxYkxYeXhLb1dSSmRnazhKNHMvTVp1QWk3QWUxUXNTTjl2Z3ZTdVRlc0VCUjVpSHJuS1lrbEpRWXNrbUQzbSsremE4U1NRbnBlM0UzYUZBY3p6cElUdUQ4YkFCWmRqcUk2TkhrSmFRQXBmb0hWNVQrZ244ejdUTWsrSStUU2JlQURubUxCS3lnMHRabW10L0ZKbDV6eWowVmxwc1dzTVM2OVE2bUZJVStqcEhSanpOb2FLMVM1dlQ3ZW1HbUhKSUp0cWlOdXJRN0tkQlBJPC9kczpTaWduYXR1cmVWYWx1ZT4KPGRzOktleUluZm8+PGRzOlg1MDlEYXRhPjxkczpYNTA5Q2VydGlmaWNhdGU+TUlJRWF6Q0NBdE9nQXdJQkFnSVVlN2EwODhDbnI0aXptcm5CRW54NXEzSFRNdll3RFFZSktvWklodmNOQVFFTEJRQXdSVEVMTUFrR0ExVUVCaE1DUjBJeEV6QVJCZ05WQkFnTUNsTnZiV1V0VTNSaGRHVXhJVEFmQmdOVkJBb01HRWx1ZEdWeWJtVjBJRmRwWkdkcGRITWdVSFI1SUV4MFpEQWVGdzB4T1RFeE1UWXhNakUzTVRWYUZ3MHlPVEV4TVRVeE1qRTNNVFZhTUVVeEN6QUpCZ05WQkFZVEFrZENNUk13RVFZRFZRUUlEQXBUYjIxbExWTjBZWFJsTVNFd0h3WURWUVFLREJoSmJuUmxjbTVsZENCWGFXUm5hWFJ6SUZCMGVTQk1kR1F3Z2dHaU1BMEdDU3FHU0liM0RRRUJBUVVBQTRJQmp3QXdnZ0dLQW9JQmdRRHpMZTlGZmR5cGxUeEhwNFN1UTlnUXRaVDN0K1NEZnZFTDcycHBDZkZadzcrQjVzNUIvVDczYVhwb1EzUzUzcEdJMVJJV0NnZTJpQ1VRMnR6bTI3YVNOSDBpdTlhSlljVVFaL1JJVHFkMGF5eURrczFOQTJQVDNUVzZ0M203S1Y1cmU0UDBOYitZRGV1eUhka3oramNNdHBuOENtQm9UMEgrc2toYTBoaXFJTmtqa1JQaUh2TEhWR3ArdEhVRUEvSTZtTjRhQi9VRXhTVExzNzlOc0xVZnRlcXF4ZTkrdHZkVWFUb3lEUHJoUEZqT05zKzlOS0NreklDNnZjdjdKNkF0dUtHNm5FVCt6Qjl5T1dndEdZUWlmWHFRQTJ5NWRMODFCQjBxNXVNYUJMUzJwcTNhUFBqelUyRjMrRXlzanlTV1RuQ2tmazdDNVNzQ1hSdThRK1U5NXR1bnBOZndmNW9sRTZXYXM0OE5NTStQd1Y3aUNOTVBrTnpsbHE2UENpTStQOERyTVNjenpVWlpRVVN2NmRTd1BDbytZU1ZpbUVNME9nM1hKVGlOaFE1QU5sYUluNjZLdzVnZm9CZnVpWG15SUtpU0R5QWlEWW1GYWY0Mzk1d1d3TGtUUitjdzhXZmphSHN3S1pUb21uMU1SM09Kc1kyVUowZVJCWU0rWVNzQ0F3RUFBYU5UTUZFd0hRWURWUjBPQkJZRUZJbXAyQ1lDR2ZjYjd3OTFIL2NTaFRDa1h3Ui9NQjhHQTFVZEl3UVlNQmFBRkltcDJDWUNHZmNiN3c5MUgvY1NoVENrWHdSL01BOEdBMVVkRXdFQi93UUZNQU1CQWY4d0RRWUpLb1pJaHZjTkFRRUxCUUFEZ2dHQkFBK2cvQzd1TDlsbitXK3FCa25MVzgxa29qWWZsZ1BLMUkxTUhJd25NdmwvWlRIWDRkUlhLRHJrN0tjVXExS2pxYWpOVjY2ZjFjYWtwMDNJaWpCaU8wWGkxZ1hVWllMb0NpTkdVeXlwOVhsb2lJeTlYdzJQaVducncwK3laeXZWc3NiZWhYWFlKbDRSaWhCakJXdWw5UjR3TVlMT1VTSkRlMld4Y1VCaEpueHlOUnMrUDB4TFNRWDZCMm42bnhvRGtvNHAwN3M4WktYUWtlaVoyaXdGZFR4elJrR2p0aE1VdjcwNG56c1ZHQlQwRENQdGZTYU81S0paVzFyQ3MzeWlNdGhuQnhxNHFFRE9RSkZJbCsvTEQ3MUtiQjl2WmNXNUp1YXZ6QkZta0tHTnJvLzZHMUk3ZWw0NklSNHdpalR5TkZDWVV1RDlkdGlnbk5tcFd0TjhPVytwdGlML2p0VHlTV3VranlzMHMrdkxuODNDVnZqQjBkSnRWQUlZT2dYRmRJdWlpNjZnY3p3d00vTEdpT0V4Sm4wZFROenNKL0lZaHB4TDRGQkV1UDBwc2tZMG8wYVVsSjJMUzJqK3dTUVRSS3NCZ01qeXJVcmVrbGUyT0RTdFN0bjNlYWJqSXgwL0ZIbHBGcjBqTkltL29NUDdrd2p0VVg0emFOZTQ3UUk0R2c9PTwvZHM6WDUwOUNlcnRpZmljYXRlPjwvZHM6WDUwOURhdGE+PC9kczpLZXlJbmZvPjwvZHM6U2lnbmF0dXJlPjxzYW1sOlN1YmplY3Q+PHNhbWw6TmFtZUlEIFNQTmFtZVF1YWxpZmllcj0iaHR0cDovL2Jvb2tzdGFjay5sb2NhbC9zYW1sMi9tZXRhZGF0YSIgRm9ybWF0PSJ1cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6bmFtZWlkLWZvcm1hdDp0cmFuc2llbnQiPl8yYzdhYjg2ZWI4ZjFkMTA2MzQ0M2YyMTljYzU4NjhmZjY2NzA4OTEyZTM8L3NhbWw6TmFtZUlEPjxzYW1sOlN1YmplY3RDb25maXJtYXRpb24gTWV0aG9kPSJ1cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6Y206YmVhcmVyIj48c2FtbDpTdWJqZWN0Q29uZmlybWF0aW9uRGF0YSBOb3RPbk9yQWZ0ZXI9IjIwMTktMTEtMTdUMTc6NTg6MzlaIiBSZWNpcGllbnQ9Imh0dHA6Ly9ib29rc3RhY2subG9jYWwvc2FtbDIvYWNzIiBJblJlc3BvbnNlVG89Ik9ORUxPR0lOXzZhMGY0ZjM5OTMwNDBmMTk4N2ZkMzcwNjhiNTI5NjIyOWFkNTM2MWMiLz48L3NhbWw6U3ViamVjdENvbmZpcm1hdGlvbj48L3NhbWw6U3ViamVjdD48c2FtbDpDb25kaXRpb25zIE5vdEJlZm9yZT0iMjAxOS0xMS0xN1QxNzo1MzowOVoiIE5vdE9uT3JBZnRlcj0iMjAxOS0xMS0xN1QxNzo1ODozOVoiPjxzYW1sOkF1ZGllbmNlUmVzdHJpY3Rpb24+PHNhbWw6QXVkaWVuY2U+aHR0cDovL2Jvb2tzdGFjay5sb2NhbC9zYW1sMi9tZXRhZGF0YTwvc2FtbDpBdWRpZW5jZT48L3NhbWw6QXVkaWVuY2VSZXN0cmljdGlvbj48L3NhbWw6Q29uZGl0aW9ucz48c2FtbDpBdXRoblN0YXRlbWVudCBBdXRobkluc3RhbnQ9IjIwMTktMTEtMTdUMTc6NTM6MzlaIiBTZXNzaW9uTm90T25PckFmdGVyPSIyMDE5LTExLTE4VDAxOjUzOjM5WiIgU2Vzc2lvbkluZGV4PSJfNGZlN2MwZDE1NzJkNjRiMjdmOTMwYWE2ZjIzNmE2ZjQyZTkzMDkwMWNjIj48c2FtbDpBdXRobkNvbnRleHQ+PHNhbWw6QXV0aG5Db250ZXh0Q2xhc3NSZWY+dXJuOm9hc2lzOm5hbWVzOnRjOlNBTUw6Mi4wOmFjOmNsYXNzZXM6UGFzc3dvcmQ8L3NhbWw6QXV0aG5Db250ZXh0Q2xhc3NSZWY+PC9zYW1sOkF1dGhuQ29udGV4dD48L3NhbWw6QXV0aG5TdGF0ZW1lbnQ+PHNhbWw6QXR0cmlidXRlU3RhdGVtZW50PjxzYW1sOkF0dHJpYnV0ZSBOYW1lPSJ1aWQiIE5hbWVGb3JtYXQ9InVybjpvYXNpczpuYW1lczp0YzpTQU1MOjIuMDphdHRybmFtZS1mb3JtYXQ6YmFzaWMiPjxzYW1sOkF0dHJpYnV0ZVZhbHVlIHhzaTp0eXBlPSJ4czpzdHJpbmciPnVzZXI8L3NhbWw6QXR0cmlidXRlVmFsdWU+PC9zYW1sOkF0dHJpYnV0ZT48c2FtbDpBdHRyaWJ1dGUgTmFtZT0iZmlyc3RfbmFtZSIgTmFtZUZvcm1hdD0idXJuOm9hc2lzOm5hbWVzOnRjOlNBTUw6Mi4wOmF0dHJuYW1lLWZvcm1hdDpiYXNpYyI+PHNhbWw6QXR0cmlidXRlVmFsdWUgeHNpOnR5cGU9InhzOnN0cmluZyI+QmFycnk8L3NhbWw6QXR0cmlidXRlVmFsdWU+PC9zYW1sOkF0dHJpYnV0ZT48c2FtbDpBdHRyaWJ1dGUgTmFtZT0ibGFzdF9uYW1lIiBOYW1lRm9ybWF0PSJ1cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6YXR0cm5hbWUtZm9ybWF0OmJhc2ljIj48c2FtbDpBdHRyaWJ1dGVWYWx1ZSB4c2k6dHlwZT0ieHM6c3RyaW5nIj5TY290dDwvc2FtbDpBdHRyaWJ1dGVWYWx1ZT48L3NhbWw6QXR0cmlidXRlPjxzYW1sOkF0dHJpYnV0ZSBOYW1lPSJlbWFpbCIgTmFtZUZvcm1hdD0idXJuOm9hc2lzOm5hbWVzOnRjOlNBTUw6Mi4wOmF0dHJuYW1lLWZvcm1hdDpiYXNpYyI+PHNhbWw6QXR0cmlidXRlVmFsdWUgeHNpOnR5cGU9InhzOnN0cmluZyI+dXNlckBleGFtcGxlLmNvbTwvc2FtbDpBdHRyaWJ1dGVWYWx1ZT48L3NhbWw6QXR0cmlidXRlPjxzYW1sOkF0dHJpYnV0ZSBOYW1lPSJ1c2VyX2dyb3VwcyIgTmFtZUZvcm1hdD0idXJuOm9hc2lzOm5hbWVzOnRjOlNBTUw6Mi4wOmF0dHJuYW1lLWZvcm1hdDpiYXNpYyI+PHNhbWw6QXR0cmlidXRlVmFsdWUgeHNpOnR5cGU9InhzOnN0cmluZyI+bWVtYmVyPC9zYW1sOkF0dHJpYnV0ZVZhbHVlPjxzYW1sOkF0dHJpYnV0ZVZhbHVlIHhzaTp0eXBlPSJ4czpzdHJpbmciPmFkbWluPC9zYW1sOkF0dHJpYnV0ZVZhbHVlPjwvc2FtbDpBdHRyaWJ1dGU+PC9zYW1sOkF0dHJpYnV0ZVN0YXRlbWVudD48L3NhbWw6QXNzZXJ0aW9uPjwvc2FtbHA6UmVzcG9uc2U+'; protected string $sloResponseData = 'fZHRa8IwEMb/lZJ3bdJa04a2MOYYglOY4sNe5JKms9gmpZfC/vxF3ZjC8OXgLvl938ddjtC1vVjZTzu6d429NaiDr641KC5PBRkHIyxgg8JAp1E4JbZPbysRTanoB+ussi25QR4TgKgH11hDguWiIIeawTxOaK1iPYt5XcczHUlJeVRlMklBJjOuM1qDVCTY6wE9WRAv5HHEUS8NOjDOjyjLJoxNGN+xVESpSNgHCRYaXWPAXaijc70IQ2ntyUPqNG2tgjY8Z45CbNFLmt8V7GxBNuuX1eZ1uT7EcZJKAE4TJhXPaMxlVlFffPKKJnXE5ryusoiU+VlMXJIN5Y/feXRn1VR92GkHFTiY9sc+D2+p/HqRrQM34n33bCsd7KEd9eMd4+W32I5KaUQSlleHP9Hwv6uX3w==';
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
true
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Auth/ResetPasswordTest.php
tests/Auth/ResetPasswordTest.php
<?php namespace Tests\Auth; use BookStack\Access\Notifications\ResetPasswordNotification; use BookStack\Users\Models\User; use Carbon\CarbonInterval; use Illuminate\Support\Facades\Notification; use Illuminate\Support\Sleep; use Tests\TestCase; class ResetPasswordTest extends TestCase { protected function setUp(): void { parent::setUp(); Sleep::fake(); } public function test_reset_flow() { Notification::fake(); $resp = $this->get('/login'); $this->withHtml($resp)->assertElementContains('a[href="' . url('/password/email') . '"]', 'Forgot Password?'); $resp = $this->get('/password/email'); $this->withHtml($resp)->assertElementContains('form[action="' . url('/password/email') . '"]', 'Send Reset Link'); $resp = $this->post('/password/email', [ 'email' => 'admin@admin.com', ]); $resp->assertRedirect('/password/email'); $resp = $this->get('/password/email'); $resp->assertSee('A password reset link will be sent to admin@admin.com if that email address is found in the system.'); $this->assertDatabaseHas('password_resets', [ 'email' => 'admin@admin.com', ]); /** @var User $user */ $user = User::query()->where('email', '=', 'admin@admin.com')->first(); Notification::assertSentTo($user, ResetPasswordNotification::class); $n = Notification::sent($user, ResetPasswordNotification::class); $this->get('/password/reset/' . $n->first()->token) ->assertOk() ->assertSee('Reset Password'); $resp = $this->post('/password/reset', [ 'email' => 'admin@admin.com', 'password' => 'randompass', 'password_confirmation' => 'randompass', 'token' => $n->first()->token, ]); $resp->assertRedirect('/'); $this->get('/')->assertSee('Your password has been successfully reset'); } public function test_reset_flow_shows_success_message_even_if_wrong_password_to_prevent_user_discovery() { $this->get('/password/email'); $resp = $this->followingRedirects()->post('/password/email', [ 'email' => 'barry@admin.com', ]); $resp->assertSee('A password reset link will be sent to barry@admin.com if that email address is found in the system.'); $resp->assertDontSee('We can\'t find a user'); $this->get('/password/reset/arandometokenvalue')->assertSee('Reset Password'); $resp = $this->post('/password/reset', [ 'email' => 'barry@admin.com', 'password' => 'randompass', 'password_confirmation' => 'randompass', 'token' => 'arandometokenvalue', ]); $resp->assertRedirect('/password/reset/arandometokenvalue'); $this->get('/password/reset/arandometokenvalue') ->assertDontSee('We can\'t find a user') ->assertSee('The password reset token is invalid for this email address.'); } public function test_reset_request_with_not_found_user_still_has_delay() { $this->followingRedirects()->post('/password/email', [ 'email' => 'barrynotfoundrandomuser@example.com', ]); Sleep::assertSlept(function (CarbonInterval $duration): bool { return $duration->totalMilliseconds > 999; }, 1); } public function test_reset_page_shows_sign_links() { $this->setSettings(['registration-enabled' => 'true']); $resp = $this->get('/password/email'); $this->withHtml($resp)->assertElementContains('a', 'Log in') ->assertElementContains('a', 'Sign up'); } public function test_reset_request_is_throttled() { $editor = $this->users->editor(); Notification::fake(); $this->get('/password/email'); $this->followingRedirects()->post('/password/email', [ 'email' => $editor->email, ]); $resp = $this->followingRedirects()->post('/password/email', [ 'email' => $editor->email, ]); Notification::assertSentTimes(ResetPasswordNotification::class, 1); $resp->assertSee('A password reset link will be sent to ' . $editor->email . ' if that email address is found in the system.'); } public function test_reset_request_with_not_found_user_is_throttled() { for ($i = 0; $i < 11; $i++) { $response = $this->post('/password/email', [ 'email' => 'barrynotfoundrandomuser@example.com', ]); } $response->assertStatus(429); } public function test_reset_call_is_throttled() { for ($i = 0; $i < 11; $i++) { $response = $this->post('/password/reset', [ 'email' => "arandomuser{$i}@example.com", 'token' => "randomtoken{$i}", ]); } $response->assertStatus(429); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Auth/GroupSyncServiceTest.php
tests/Auth/GroupSyncServiceTest.php
<?php namespace Tests\Auth; use BookStack\Access\GroupSyncService; use BookStack\Users\Models\Role; use BookStack\Users\Models\User; use Tests\TestCase; class GroupSyncServiceTest extends TestCase { public function test_user_is_assigned_to_matching_roles() { $user = $this->users->viewer(); $roleA = Role::factory()->create(['display_name' => 'Wizards']); $roleB = Role::factory()->create(['display_name' => 'Gremlins']); $roleC = Role::factory()->create(['display_name' => 'ABC123', 'external_auth_id' => 'sales']); $roleD = Role::factory()->create(['display_name' => 'DEF456', 'external_auth_id' => 'admin-team']); foreach ([$roleA, $roleB, $roleC, $roleD] as $role) { $this->assertFalse($user->hasRole($role->id)); } (new GroupSyncService())->syncUserWithFoundGroups($user, ['Wizards', 'Gremlinz', 'Sales', 'Admin Team'], false); $user = User::query()->find($user->id); $this->assertTrue($user->hasRole($roleA->id)); $this->assertFalse($user->hasRole($roleB->id)); $this->assertTrue($user->hasRole($roleC->id)); $this->assertTrue($user->hasRole($roleD->id)); } public function test_multiple_values_in_role_external_auth_id_handled() { $user = $this->users->viewer(); $role = Role::factory()->create(['display_name' => 'ABC123', 'external_auth_id' => 'sales, engineering, developers, marketers']); $this->assertFalse($user->hasRole($role->id)); (new GroupSyncService())->syncUserWithFoundGroups($user, ['Developers'], false); $user = User::query()->find($user->id); $this->assertTrue($user->hasRole($role->id)); } public function test_commas_can_be_used_in_external_auth_id_if_escaped() { $user = $this->users->viewer(); $role = Role::factory()->create(['display_name' => 'ABC123', 'external_auth_id' => 'sales\,-developers, marketers']); $this->assertFalse($user->hasRole($role->id)); (new GroupSyncService())->syncUserWithFoundGroups($user, ['Sales, Developers'], false); $user = User::query()->find($user->id); $this->assertTrue($user->hasRole($role->id)); } public function test_external_auth_id_matches_ignoring_case() { $user = $this->users->viewer(); $role = Role::factory()->create(['display_name' => 'ABC123', 'external_auth_id' => 'WaRRioRs']); $this->assertFalse($user->hasRole($role->id)); (new GroupSyncService())->syncUserWithFoundGroups($user, ['wArriors', 'penguiNs'], false); $user = User::query()->find($user->id); $this->assertTrue($user->hasRole($role->id)); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Auth/LdapTest.php
tests/Auth/LdapTest.php
<?php namespace Tests\Auth; use BookStack\Access\Ldap; use BookStack\Access\LdapService; use BookStack\Exceptions\LdapException; use BookStack\Users\Models\Role; use BookStack\Users\Models\User; use Illuminate\Testing\TestResponse; use Mockery\MockInterface; use Tests\TestCase; class LdapTest extends TestCase { protected MockInterface $mockLdap; protected User $mockUser; protected string $resourceId = 'resource-test'; protected function setUp(): void { parent::setUp(); if (!defined('LDAP_OPT_REFERRALS')) { define('LDAP_OPT_REFERRALS', 1); } config()->set([ 'auth.method' => 'ldap', 'auth.defaults.guard' => 'ldap', 'services.ldap.base_dn' => 'dc=ldap,dc=local', 'services.ldap.email_attribute' => 'mail', 'services.ldap.display_name_attribute' => 'cn', 'services.ldap.id_attribute' => 'uid', 'services.ldap.user_to_groups' => false, 'services.ldap.version' => '3', 'services.ldap.user_filter' => '(&(uid={user}))', 'services.ldap.follow_referrals' => false, 'services.ldap.tls_insecure' => false, 'services.ldap.tls_ca_cert' => false, 'services.ldap.thumbnail_attribute' => null, ]); $this->mockLdap = $this->mock(Ldap::class); $this->mockUser = User::factory()->make(); } protected function runFailedAuthLogin() { $this->commonLdapMocks(1, 1, 1, 1, 1); $this->mockLdap->shouldReceive('searchAndGetEntries')->times(1) ->andReturn(['count' => 0]); $this->post('/login', ['username' => 'timmyjenkins', 'password' => 'cattreedog']); } protected function mockEscapes($times = 1) { $this->mockLdap->shouldReceive('escape')->times($times)->andReturnUsing(function ($val) { return ldap_escape($val); }); } protected function mockExplodes($times = 1) { $this->mockLdap->shouldReceive('explodeDn')->times($times)->andReturnUsing(function ($dn, $withAttrib) { return ldap_explode_dn($dn, $withAttrib); }); } protected function mockUserLogin(?string $email = null): TestResponse { return $this->post('/login', [ 'username' => $this->mockUser->name, 'password' => $this->mockUser->password, ] + ($email ? ['email' => $email] : [])); } /** * Set LDAP method mocks for things we commonly call without altering. */ protected function commonLdapMocks(int $connects = 1, int $versions = 1, int $options = 2, int $binds = 4, int $escapes = 2, int $explodes = 0, int $groups = 0) { $this->mockLdap->shouldReceive('connect')->times($connects)->andReturn($this->resourceId); $this->mockLdap->shouldReceive('setVersion')->times($versions); $this->mockLdap->shouldReceive('setOption')->times($options); $this->mockLdap->shouldReceive('bind')->times($binds)->andReturn(true); $this->mockEscapes($escapes); $this->mockExplodes($explodes); $this->mockGroupLookups($groups); } protected function mockGroupLookups(int $times = 1): void { $this->mockLdap->shouldReceive('read')->times($times)->andReturn(['count' => 0]); $this->mockLdap->shouldReceive('getEntries')->times($times)->andReturn(['count' => 0]); } public function test_login() { $this->commonLdapMocks(1, 1, 2, 4, 2); $this->mockLdap->shouldReceive('searchAndGetEntries')->times(2) ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array')) ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], 'dn' => 'dc=test' . config('services.ldap.base_dn'), ]]); $resp = $this->mockUserLogin(); $resp->assertRedirect('/login'); $resp = $this->followRedirects($resp); $resp->assertSee('Please enter an email to use for this account.'); $resp->assertSee($this->mockUser->name); $resp = $this->followingRedirects()->mockUserLogin($this->mockUser->email); $this->withHtml($resp)->assertElementExists('#home-default'); $resp->assertSee($this->mockUser->name); $this->assertDatabaseHas('users', [ 'email' => $this->mockUser->email, 'email_confirmed' => false, 'external_auth_id' => $this->mockUser->name, ]); } public function test_email_domain_restriction_active_on_new_ldap_login() { $this->setSettings([ 'registration-restrict' => 'testing.com', ]); $this->commonLdapMocks(1, 1, 2, 4, 2); $this->mockLdap->shouldReceive('searchAndGetEntries')->times(2) ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array')) ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], 'dn' => 'dc=test' . config('services.ldap.base_dn'), ]]); $resp = $this->mockUserLogin(); $resp->assertRedirect('/login'); $this->followRedirects($resp)->assertSee('Please enter an email to use for this account.'); $email = 'tester@invaliddomain.com'; $resp = $this->mockUserLogin($email); $resp->assertRedirect('/login'); $this->followRedirects($resp)->assertSee('That email domain does not have access to this application'); $this->assertDatabaseMissing('users', ['email' => $email]); } public function test_login_works_when_no_uid_provided_by_ldap_server() { $ldapDn = 'cn=test-user,dc=test' . config('services.ldap.base_dn'); $this->commonLdapMocks(1, 1, 1, 2, 1); $this->mockLdap->shouldReceive('searchAndGetEntries')->times(1) ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array')) ->andReturn(['count' => 1, 0 => [ 'cn' => [$this->mockUser->name], 'dn' => $ldapDn, 'mail' => [$this->mockUser->email], ]]); $resp = $this->mockUserLogin(); $resp->assertRedirect('/'); $this->followRedirects($resp)->assertSee($this->mockUser->name); $this->assertDatabaseHas('users', ['email' => $this->mockUser->email, 'email_confirmed' => false, 'external_auth_id' => $ldapDn]); } public function test_login_works_when_ldap_server_does_not_provide_a_cn_value() { $ldapDn = 'cn=test-user,dc=test' . config('services.ldap.base_dn'); $this->commonLdapMocks(1, 1, 1, 2, 1); $this->mockLdap->shouldReceive('searchAndGetEntries')->times(1) ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array')) ->andReturn(['count' => 1, 0 => [ 'dn' => $ldapDn, 'mail' => [$this->mockUser->email], ]]); $resp = $this->mockUserLogin(); $resp->assertRedirect('/'); $this->assertDatabaseHas('users', [ 'name' => 'test-user', 'email' => $this->mockUser->email, ]); } public function test_a_custom_uid_attribute_can_be_specified_and_is_used_properly() { config()->set(['services.ldap.id_attribute' => 'my_custom_id']); $this->commonLdapMocks(1, 1, 1, 2, 1); $ldapDn = 'cn=test-user,dc=test' . config('services.ldap.base_dn'); $this->mockLdap->shouldReceive('searchAndGetEntries')->times(1) ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array')) ->andReturn(['count' => 1, 0 => [ 'cn' => [$this->mockUser->name], 'dn' => $ldapDn, 'my_custom_id' => ['cooluser456'], 'mail' => [$this->mockUser->email], ]]); $resp = $this->mockUserLogin(); $resp->assertRedirect('/'); $this->followRedirects($resp)->assertSee($this->mockUser->name); $this->assertDatabaseHas('users', ['email' => $this->mockUser->email, 'email_confirmed' => false, 'external_auth_id' => 'cooluser456']); } public function test_user_filter_default_placeholder_format() { config()->set('services.ldap.user_filter', '(&(uid={user}))'); $this->mockUser->name = 'barryldapuser'; $expectedFilter = '(&(uid=\62\61\72\72\79\6c\64\61\70\75\73\65\72))'; $this->commonLdapMocks(1, 1, 1, 1, 1); $this->mockLdap->shouldReceive('searchAndGetEntries') ->once() ->with($this->resourceId, config('services.ldap.base_dn'), $expectedFilter, \Mockery::type('array')) ->andReturn(['count' => 0, 0 => []]); $resp = $this->mockUserLogin(); $resp->assertRedirect('/login'); } public function test_user_filter_old_placeholder_format() { config()->set('services.ldap.user_filter', '(&(username=${user}))'); $this->mockUser->name = 'barryldapuser'; $expectedFilter = '(&(username=\62\61\72\72\79\6c\64\61\70\75\73\65\72))'; $this->commonLdapMocks(1, 1, 1, 1, 1); $this->mockLdap->shouldReceive('searchAndGetEntries') ->once() ->with($this->resourceId, config('services.ldap.base_dn'), $expectedFilter, \Mockery::type('array')) ->andReturn(['count' => 0, 0 => []]); $resp = $this->mockUserLogin(); $resp->assertRedirect('/login'); } public function test_initial_incorrect_credentials() { $this->commonLdapMocks(1, 1, 1, 0, 1); $this->mockLdap->shouldReceive('searchAndGetEntries')->times(1) ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array')) ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], 'dn' => 'dc=test' . config('services.ldap.base_dn'), ]]); $this->mockLdap->shouldReceive('bind')->times(2)->andReturn(true, false); $resp = $this->mockUserLogin(); $resp->assertRedirect('/login'); $this->followRedirects($resp)->assertSee('These credentials do not match our records.'); $this->assertDatabaseMissing('users', ['external_auth_id' => $this->mockUser->name]); } public function test_login_not_found_username() { $this->commonLdapMocks(1, 1, 1, 1, 1); $this->mockLdap->shouldReceive('searchAndGetEntries')->times(1) ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array')) ->andReturn(['count' => 0]); $resp = $this->mockUserLogin(); $resp->assertRedirect('/login'); $this->followRedirects($resp)->assertSee('These credentials do not match our records.'); $this->assertDatabaseMissing('users', ['external_auth_id' => $this->mockUser->name]); } public function test_create_user_form() { $userForm = $this->asAdmin()->get('/settings/users/create'); $userForm->assertDontSee('Password'); $save = $this->post('/settings/users/create', [ 'name' => $this->mockUser->name, 'email' => $this->mockUser->email, ]); $save->assertSessionHasErrors(['external_auth_id' => 'The external auth id field is required.']); $save = $this->post('/settings/users/create', [ 'name' => $this->mockUser->name, 'email' => $this->mockUser->email, 'external_auth_id' => $this->mockUser->name, ]); $save->assertRedirect('/settings/users'); $this->assertDatabaseHas('users', ['email' => $this->mockUser->email, 'external_auth_id' => $this->mockUser->name, 'email_confirmed' => true]); } public function test_user_edit_form() { $editUser = $this->users->viewer(); $editPage = $this->asAdmin()->get("/settings/users/{$editUser->id}"); $editPage->assertSee('Edit User'); $editPage->assertDontSee('Password'); $update = $this->put("/settings/users/{$editUser->id}", [ 'name' => $editUser->name, 'email' => $editUser->email, 'external_auth_id' => 'test_auth_id', ]); $update->assertRedirect('/settings/users'); $this->assertDatabaseHas('users', ['email' => $editUser->email, 'external_auth_id' => 'test_auth_id']); } public function test_registration_disabled() { $resp = $this->followingRedirects()->get('/register'); $this->withHtml($resp)->assertElementContains('#content', 'Log In'); } public function test_non_admins_cannot_change_auth_id() { $testUser = $this->users->viewer(); $this->actingAs($testUser) ->get('/settings/users/' . $testUser->id) ->assertDontSee('External Authentication'); } public function test_login_maps_roles_and_retains_existing_roles() { $roleToReceive = Role::factory()->create(['display_name' => 'LdapTester']); $roleToReceive2 = Role::factory()->create(['display_name' => 'LdapTester Second']); $existingRole = Role::factory()->create(['display_name' => 'ldaptester-existing']); $this->mockUser->forceFill(['external_auth_id' => $this->mockUser->name])->save(); $this->mockUser->attachRole($existingRole); app('config')->set([ 'services.ldap.user_to_groups' => true, 'services.ldap.group_attribute' => 'memberOf', 'services.ldap.remove_from_groups' => false, ]); $this->commonLdapMocks(1, 1, 4, 5, 2, 2, 2); $this->mockLdap->shouldReceive('searchAndGetEntries')->times(2) ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array')) ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], 'dn' => 'dc=test' . config('services.ldap.base_dn'), 'mail' => [$this->mockUser->email], 'memberof' => [ 'count' => 2, 0 => 'cn=ldaptester,ou=groups,dc=example,dc=com', 1 => 'cn=ldaptester-second,ou=groups,dc=example,dc=com', ], ]]); $this->mockUserLogin()->assertRedirect('/'); $user = User::where('email', $this->mockUser->email)->first(); $this->assertDatabaseHas('role_user', [ 'user_id' => $user->id, 'role_id' => $roleToReceive->id, ]); $this->assertDatabaseHas('role_user', [ 'user_id' => $user->id, 'role_id' => $roleToReceive2->id, ]); $this->assertDatabaseHas('role_user', [ 'user_id' => $user->id, 'role_id' => $existingRole->id, ]); } public function test_login_maps_roles_and_removes_old_roles_if_set() { $roleToReceive = Role::factory()->create(['display_name' => 'LdapTester']); $existingRole = Role::factory()->create(['display_name' => 'ldaptester-existing']); $this->mockUser->forceFill(['external_auth_id' => $this->mockUser->name])->save(); $this->mockUser->attachRole($existingRole); app('config')->set([ 'services.ldap.user_to_groups' => true, 'services.ldap.group_attribute' => 'memberOf', 'services.ldap.remove_from_groups' => true, ]); $this->commonLdapMocks(1, 1, 3, 4, 2, 1, 1); $this->mockLdap->shouldReceive('searchAndGetEntries')->times(2) ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array')) ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], 'dn' => 'dc=test' . config('services.ldap.base_dn'), 'mail' => [$this->mockUser->email], 'memberof' => [ 'count' => 1, 0 => 'cn=ldaptester,ou=groups,dc=example,dc=com', ], ]]); $this->mockUserLogin()->assertRedirect('/'); $user = User::query()->where('email', $this->mockUser->email)->first(); $this->assertDatabaseHas('role_user', [ 'user_id' => $user->id, 'role_id' => $roleToReceive->id, ]); $this->assertDatabaseMissing('role_user', [ 'user_id' => $user->id, 'role_id' => $existingRole->id, ]); } public function test_dump_user_groups_shows_group_related_details_as_json() { app('config')->set([ 'services.ldap.user_to_groups' => true, 'services.ldap.group_attribute' => 'memberOf', 'services.ldap.remove_from_groups' => true, 'services.ldap.dump_user_groups' => true, ]); $userResp = ['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], 'dn' => 'dc=test,' . config('services.ldap.base_dn'), 'mail' => [$this->mockUser->email], ]]; $this->commonLdapMocks(1, 1, 4, 5, 2, 2, 0); $this->mockLdap->shouldReceive('searchAndGetEntries')->times(2) ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array')) ->andReturn($userResp, ['count' => 1, 0 => [ 'dn' => 'dc=test,' . config('services.ldap.base_dn'), 'memberof' => [ 'count' => 1, 0 => 'cn=ldaptester,ou=groups,dc=example,dc=com', ], ], ]); $this->mockLdap->shouldReceive('read')->times(2); $this->mockLdap->shouldReceive('getEntries')->times(2) ->andReturn([ 'count' => 1, 0 => [ 'dn' => 'cn=ldaptester,ou=groups,dc=example,dc=com', 'memberof' => [ 'count' => 1, 0 => 'cn=monsters,ou=groups,dc=example,dc=com', ], ], ], ['count' => 0]); $resp = $this->mockUserLogin(); $resp->assertJson([ 'details_from_ldap' => [ 'dn' => 'dc=test,' . config('services.ldap.base_dn'), 'memberof' => [ 0 => 'cn=ldaptester,ou=groups,dc=example,dc=com', 'count' => 1, ], ], 'parsed_direct_user_groups' => [ 'cn=ldaptester,ou=groups,dc=example,dc=com', ], 'parsed_recursive_user_groups' => [ 'cn=ldaptester,ou=groups,dc=example,dc=com', 'cn=monsters,ou=groups,dc=example,dc=com', ], 'parsed_resulting_group_names' => [ 'ldaptester', 'monsters', ], ]); } public function test_recursive_group_search_queries_via_full_dn() { app('config')->set([ 'services.ldap.user_to_groups' => true, 'services.ldap.group_attribute' => 'memberOf', ]); $userResp = ['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], 'dn' => 'dc=test,' . config('services.ldap.base_dn'), 'mail' => [$this->mockUser->email], ]]; $groupResp = ['count' => 1, 0 => [ 'dn' => 'dc=test,' . config('services.ldap.base_dn'), 'memberof' => [ 'count' => 1, 0 => 'cn=ldaptester,ou=groups,dc=example,dc=com', ], ], ]; $this->commonLdapMocks(1, 1, 3, 4, 2, 1); $escapedName = ldap_escape($this->mockUser->name); $this->mockLdap->shouldReceive('searchAndGetEntries')->twice() ->with($this->resourceId, config('services.ldap.base_dn'), "(&(uid={$escapedName}))", \Mockery::type('array')) ->andReturn($userResp, $groupResp); $this->mockLdap->shouldReceive('read')->times(1) ->with($this->resourceId, 'cn=ldaptester,ou=groups,dc=example,dc=com', '(objectClass=*)', ['memberof']) ->andReturn(['count' => 0]); $this->mockLdap->shouldReceive('getEntries')->times(1) ->with($this->resourceId, ['count' => 0]) ->andReturn(['count' => 0]); $resp = $this->mockUserLogin(); $resp->assertRedirect('/'); } public function test_external_auth_id_visible_in_roles_page_when_ldap_active() { $role = Role::factory()->create(['display_name' => 'ldaptester', 'external_auth_id' => 'ex-auth-a, test-second-param']); $this->asAdmin()->get('/settings/roles/' . $role->id) ->assertSee('ex-auth-a'); } public function test_login_maps_roles_using_external_auth_ids_if_set() { $roleToReceive = Role::factory()->create(['display_name' => 'ldaptester', 'external_auth_id' => 'test-second-param, ex-auth-a']); $roleToNotReceive = Role::factory()->create(['display_name' => 'ex-auth-a', 'external_auth_id' => 'test-second-param']); app('config')->set([ 'services.ldap.user_to_groups' => true, 'services.ldap.group_attribute' => 'memberOf', 'services.ldap.remove_from_groups' => true, ]); $this->commonLdapMocks(1, 1, 3, 4, 2, 1, 1); $this->mockLdap->shouldReceive('searchAndGetEntries')->times(2) ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array')) ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], 'dn' => 'dc=test' . config('services.ldap.base_dn'), 'mail' => [$this->mockUser->email], 'memberof' => [ 'count' => 1, 0 => 'cn=ex-auth-a,ou=groups,dc=example,dc=com', ], ]]); $this->mockUserLogin()->assertRedirect('/'); $user = User::query()->where('email', $this->mockUser->email)->first(); $this->assertDatabaseHas('role_user', [ 'user_id' => $user->id, 'role_id' => $roleToReceive->id, ]); $this->assertDatabaseMissing('role_user', [ 'user_id' => $user->id, 'role_id' => $roleToNotReceive->id, ]); } public function test_login_group_mapping_does_not_conflict_with_default_role() { $roleToReceive = Role::factory()->create(['display_name' => 'LdapTester']); $roleToReceive2 = Role::factory()->create(['display_name' => 'LdapTester Second']); $this->mockUser->forceFill(['external_auth_id' => $this->mockUser->name])->save(); setting()->put('registration-role', $roleToReceive->id); app('config')->set([ 'services.ldap.user_to_groups' => true, 'services.ldap.group_attribute' => 'memberOf', 'services.ldap.remove_from_groups' => true, ]); $this->commonLdapMocks(1, 1, 4, 5, 2, 2, 2); $this->mockLdap->shouldReceive('searchAndGetEntries')->times(2) ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array')) ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], 'dn' => 'dc=test' . config('services.ldap.base_dn'), 'mail' => [$this->mockUser->email], 'memberof' => [ 'count' => 2, 0 => 'cn=ldaptester,ou=groups,dc=example,dc=com', 1 => 'cn=ldaptester-second,ou=groups,dc=example,dc=com', ], ]]); $this->mockUserLogin()->assertRedirect('/'); $user = User::query()->where('email', $this->mockUser->email)->first(); $this->assertDatabaseHas('role_user', [ 'user_id' => $user->id, 'role_id' => $roleToReceive->id, ]); $this->assertDatabaseHas('role_user', [ 'user_id' => $user->id, 'role_id' => $roleToReceive2->id, ]); } public function test_login_uses_specified_display_name_attribute() { app('config')->set([ 'services.ldap.display_name_attribute' => 'displayName', ]); $this->commonLdapMocks(1, 1, 2, 4, 2); $this->mockLdap->shouldReceive('searchAndGetEntries')->times(2) ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array')) ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], 'dn' => 'dc=test' . config('services.ldap.base_dn'), 'displayname' => 'displayNameAttribute', ]]); $this->mockUserLogin()->assertRedirect('/login'); $this->get('/login')->assertSee('Please enter an email to use for this account.'); $resp = $this->mockUserLogin($this->mockUser->email); $resp->assertRedirect('/'); $this->get('/')->assertSee('displayNameAttribute'); $this->assertDatabaseHas('users', ['email' => $this->mockUser->email, 'email_confirmed' => false, 'external_auth_id' => $this->mockUser->name, 'name' => 'displayNameAttribute']); } public function test_login_uses_multiple_display_properties_if_defined() { app('config')->set([ 'services.ldap.display_name_attribute' => 'firstname|middlename|noname|lastname', ]); $this->commonLdapMocks(1, 1, 1, 2, 1); $this->mockLdap->shouldReceive('searchAndGetEntries')->times(1) ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array')) ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], 'dn' => 'dc=test' . config('services.ldap.base_dn'), 'firstname' => ['Barry'], 'middlename' => ['Elliott'], 'lastname' => ['Chuckle'], 'mail' => [$this->mockUser->email], ]]); $this->mockUserLogin(); $this->assertDatabaseHas('users', [ 'email' => $this->mockUser->email, 'name' => 'Barry Elliott Chuckle', ]); } public function test_login_uses_default_display_name_attribute_if_specified_not_present() { app('config')->set([ 'services.ldap.display_name_attribute' => 'displayName', ]); $this->commonLdapMocks(1, 1, 2, 4, 2); $this->mockLdap->shouldReceive('searchAndGetEntries')->times(2) ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array')) ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], 'dn' => 'dc=test' . config('services.ldap.base_dn'), ]]); $this->mockUserLogin()->assertRedirect('/login'); $this->get('/login')->assertSee('Please enter an email to use for this account.'); $resp = $this->mockUserLogin($this->mockUser->email); $resp->assertRedirect('/'); $this->get('/')->assertSee($this->mockUser->name); $this->assertDatabaseHas('users', [ 'email' => $this->mockUser->email, 'email_confirmed' => false, 'external_auth_id' => $this->mockUser->name, 'name' => $this->mockUser->name, ]); } protected function checkLdapReceivesCorrectDetails($serverString, $expectedHostString): void { app('config')->set(['services.ldap.server' => $serverString]); $this->mockLdap->shouldReceive('connect') ->once() ->with($expectedHostString) ->andReturn(false); $this->mockUserLogin(); } public function test_ldap_receives_correct_connect_host_from_config() { $expectedResultByInput = [ 'ldaps://bookstack:8080' => 'ldaps://bookstack:8080', 'ldap.bookstack.com:8080' => 'ldap://ldap.bookstack.com:8080', 'ldap.bookstack.com' => 'ldap://ldap.bookstack.com', 'ldaps://ldap.bookstack.com' => 'ldaps://ldap.bookstack.com', 'ldaps://ldap.bookstack.com ldap://a.b.com' => 'ldaps://ldap.bookstack.com ldap://a.b.com', ]; foreach ($expectedResultByInput as $input => $expectedResult) { $this->checkLdapReceivesCorrectDetails($input, $expectedResult); $this->refreshApplication(); $this->setUp(); } } public function test_forgot_password_routes_inaccessible() { $resp = $this->get('/password/email'); $this->assertPermissionError($resp); $resp = $this->post('/password/email'); $this->assertPermissionError($resp); $resp = $this->get('/password/reset/abc123'); $this->assertPermissionError($resp); $resp = $this->post('/password/reset'); $this->assertPermissionError($resp); } public function test_user_invite_routes_inaccessible() { $resp = $this->get('/register/invite/abc123'); $this->assertPermissionError($resp); $resp = $this->post('/register/invite/abc123'); $this->assertPermissionError($resp); } public function test_user_register_routes_inaccessible() { $resp = $this->get('/register'); $this->assertPermissionError($resp); $resp = $this->post('/register'); $this->assertPermissionError($resp); } public function test_dump_user_details_option_works() { config()->set(['services.ldap.dump_user_details' => true, 'services.ldap.thumbnail_attribute' => 'jpegphoto']); $this->commonLdapMocks(1, 1, 1, 1, 1); $this->mockLdap->shouldReceive('searchAndGetEntries')->times(1) ->with($this->resourceId, config('services.ldap.base_dn'), \Mockery::type('string'), \Mockery::type('array')) ->andReturn(['count' => 1, 0 => [ 'uid' => [$this->mockUser->name], 'cn' => [$this->mockUser->name], // Test dumping binary data for avatar responses 'jpegphoto' => base64_decode('/9j/4AAQSkZJRg=='), 'dn' => 'dc=test' . config('services.ldap.base_dn'), ]]); $resp = $this->post('/login', [ 'username' => $this->mockUser->name, 'password' => $this->mockUser->password, ]); $resp->assertJsonStructure([ 'details_from_ldap' => [], 'details_bookstack_parsed' => [], ]); } public function test_start_tls_called_if_option_set() { config()->set(['services.ldap.start_tls' => true]); $this->mockLdap->shouldReceive('startTls')->once()->andReturn(true); $this->runFailedAuthLogin(); } public function test_connection_fails_if_tls_fails() { config()->set(['services.ldap.start_tls' => true]); $this->mockLdap->shouldReceive('startTls')->once()->andReturn(false); $this->commonLdapMocks(1, 1, 0, 0, 0);
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
true
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Auth/OidcTest.php
tests/Auth/OidcTest.php
<?php namespace Tests\Auth; use BookStack\Activity\ActivityType; use BookStack\Facades\Theme; use BookStack\Theming\ThemeEvents; use BookStack\Uploads\UserAvatars; use BookStack\Users\Models\Role; use BookStack\Users\Models\User; use GuzzleHttp\Psr7\Response; use Illuminate\Testing\TestResponse; use Tests\Helpers\OidcJwtHelper; use Tests\TestCase; class OidcTest extends TestCase { protected string $keyFilePath; protected $keyFile; protected function setUp(): void { parent::setUp(); // Set default config for OpenID Connect $this->keyFile = tmpfile(); $this->keyFilePath = 'file://' . stream_get_meta_data($this->keyFile)['uri']; file_put_contents($this->keyFilePath, OidcJwtHelper::publicPemKey()); config()->set([ 'auth.method' => 'oidc', 'auth.defaults.guard' => 'oidc', 'oidc.name' => 'SingleSignOn-Testing', 'oidc.display_name_claims' => 'name', 'oidc.client_id' => OidcJwtHelper::defaultClientId(), 'oidc.client_secret' => 'testpass', 'oidc.jwt_public_key' => $this->keyFilePath, 'oidc.issuer' => OidcJwtHelper::defaultIssuer(), 'oidc.authorization_endpoint' => 'https://oidc.local/auth', 'oidc.token_endpoint' => 'https://oidc.local/token', 'oidc.userinfo_endpoint' => 'https://oidc.local/userinfo', 'oidc.discover' => false, 'oidc.dump_user_details' => false, 'oidc.additional_scopes' => '', 'odic.fetch_avatar' => false, 'oidc.user_to_groups' => false, 'oidc.groups_claim' => 'group', 'oidc.remove_from_groups' => false, 'oidc.external_id_claim' => 'sub', 'oidc.end_session_endpoint' => false, ]); } protected function tearDown(): void { parent::tearDown(); if (file_exists($this->keyFilePath)) { unlink($this->keyFilePath); } } public function test_login_option_shows_on_login_page() { $req = $this->get('/login'); $req->assertSeeText('SingleSignOn-Testing'); $this->withHtml($req)->assertElementExists('form[action$="/oidc/login"][method=POST] button'); } public function test_oidc_routes_are_only_active_if_oidc_enabled() { config()->set(['auth.method' => 'standard']); $routes = ['/login' => 'post', '/callback' => 'get']; foreach ($routes as $uri => $method) { $req = $this->call($method, '/oidc' . $uri); $this->assertPermissionError($req); } } public function test_forgot_password_routes_inaccessible() { $resp = $this->get('/password/email'); $this->assertPermissionError($resp); $resp = $this->post('/password/email'); $this->assertPermissionError($resp); $resp = $this->get('/password/reset/abc123'); $this->assertPermissionError($resp); $resp = $this->post('/password/reset'); $this->assertPermissionError($resp); } public function test_standard_login_routes_inaccessible() { $resp = $this->post('/login'); $this->assertPermissionError($resp); } public function test_logout_route_functions() { $this->actingAs($this->users->editor()); $this->post('/logout'); $this->assertFalse(auth()->check()); } public function test_user_invite_routes_inaccessible() { $resp = $this->get('/register/invite/abc123'); $this->assertPermissionError($resp); $resp = $this->post('/register/invite/abc123'); $this->assertPermissionError($resp); } public function test_user_register_routes_inaccessible() { $resp = $this->get('/register'); $this->assertPermissionError($resp); $resp = $this->post('/register'); $this->assertPermissionError($resp); } public function test_login() { $req = $this->post('/oidc/login'); $redirect = $req->headers->get('location'); $this->assertStringStartsWith('https://oidc.local/auth', $redirect, 'Login redirects to SSO location'); $this->assertFalse($this->isAuthenticated()); $this->assertStringContainsString('scope=openid%20profile%20email', $redirect); $this->assertStringContainsString('client_id=' . OidcJwtHelper::defaultClientId(), $redirect); $this->assertStringContainsString('redirect_uri=' . urlencode(url('/oidc/callback')), $redirect); } public function test_login_success_flow() { // Start auth $this->post('/oidc/login'); $state = explode(':', session()->get('oidc_state'), 2)[1]; $transactions = $this->mockHttpClient([$this->getMockAuthorizationResponse([ 'email' => 'benny@example.com', 'sub' => 'benny1010101', ])]); // Callback from auth provider // App calls token endpoint to get id token $resp = $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state); $resp->assertRedirect('/'); $this->assertEquals(1, $transactions->requestCount()); $tokenRequest = $transactions->latestRequest(); $this->assertEquals('https://oidc.local/token', (string) $tokenRequest->getUri()); $this->assertEquals('POST', $tokenRequest->getMethod()); $this->assertEquals('Basic ' . base64_encode(OidcJwtHelper::defaultClientId() . ':testpass'), $tokenRequest->getHeader('Authorization')[0]); $this->assertStringContainsString('grant_type=authorization_code', $tokenRequest->getBody()); $this->assertStringContainsString('code=SplxlOBeZQQYbYS6WxSbIA', $tokenRequest->getBody()); $this->assertStringContainsString('redirect_uri=' . urlencode(url('/oidc/callback')), $tokenRequest->getBody()); $this->assertTrue(auth()->check()); $this->assertDatabaseHas('users', [ 'email' => 'benny@example.com', 'external_auth_id' => 'benny1010101', 'email_confirmed' => false, ]); $user = User::query()->where('email', '=', 'benny@example.com')->first(); $this->assertActivityExists(ActivityType::AUTH_LOGIN, null, "oidc; ({$user->id}) Barry Scott"); } public function test_login_uses_custom_additional_scopes_if_defined() { config()->set([ 'oidc.additional_scopes' => 'groups, badgers', ]); $redirect = $this->post('/oidc/login')->headers->get('location'); $this->assertStringContainsString('scope=openid%20profile%20email%20groups%20badgers', $redirect); } public function test_callback_fails_if_no_state_present_or_matching() { $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=abc124'); $this->assertSessionError('Login using SingleSignOn-Testing failed, system did not provide successful authorization'); $this->post('/oidc/login'); $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=abc124'); $this->assertSessionError('Login using SingleSignOn-Testing failed, system did not provide successful authorization'); } public function test_callback_works_even_if_other_request_made_by_session() { $this->mockHttpClient([$this->getMockAuthorizationResponse([ 'email' => 'benny@example.com', 'sub' => 'benny1010101', ])]); $this->post('/oidc/login'); $state = explode(':', session()->get('oidc_state'), 2)[1]; $this->get('/'); $resp = $this->get("/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state={$state}"); $resp->assertRedirect('/'); } public function test_callback_fails_if_state_timestamp_is_too_old() { $this->post('/oidc/login'); $state = explode(':', session()->get('oidc_state'), 2)[1]; session()->put('oidc_state', (time() - 60 * 4) . ':' . $state); $this->get('/'); $resp = $this->get("/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state={$state}"); $resp->assertRedirect('/login'); $this->assertSessionError('Login using SingleSignOn-Testing failed, system did not provide successful authorization'); } public function test_dump_user_details_option_outputs_as_expected() { config()->set('oidc.dump_user_details', true); $resp = $this->runLogin([ 'email' => 'benny@example.com', 'sub' => 'benny505', ]); $resp->assertStatus(200); $resp->assertJson([ 'email' => 'benny@example.com', 'sub' => 'benny505', 'iss' => OidcJwtHelper::defaultIssuer(), 'aud' => OidcJwtHelper::defaultClientId(), ]); $this->assertFalse(auth()->check()); } public function test_auth_fails_if_no_email_exists_in_user_data() { config()->set('oidc.userinfo_endpoint', null); $this->runLogin([ 'email' => '', 'sub' => 'benny505', ]); $this->assertSessionError('Could not find an email address, for this user, in the data provided by the external authentication system'); } public function test_auth_fails_if_already_logged_in() { $this->asEditor(); $this->runLogin([ 'email' => 'benny@example.com', 'sub' => 'benny505', ]); $this->assertSessionError('Already logged in'); } public function test_auth_login_as_existing_user() { $editor = $this->users->editor(); $editor->external_auth_id = 'benny505'; $editor->save(); $this->assertFalse(auth()->check()); $this->runLogin([ 'email' => 'benny@example.com', 'sub' => 'benny505', ]); $this->assertTrue(auth()->check()); $this->assertEquals($editor->id, auth()->user()->id); } public function test_auth_login_as_existing_user_email_with_different_auth_id_fails() { $editor = $this->users->editor(); $editor->external_auth_id = 'editor101'; $editor->save(); $this->assertFalse(auth()->check()); $resp = $this->runLogin([ 'email' => $editor->email, 'sub' => 'benny505', ]); $resp = $this->followRedirects($resp); $resp->assertSeeText('A user with the email ' . $editor->email . ' already exists but with different credentials.'); $this->assertFalse(auth()->check()); } public function test_auth_login_with_invalid_token_fails() { $resp = $this->runLogin([ 'sub' => null, ]); $resp = $this->followRedirects($resp); $resp->assertSeeText('ID token validation failed with error: Missing token subject value'); $this->assertFalse(auth()->check()); } public function test_auth_fails_if_endpoints_start_with_https() { $endpointConfigKeys = [ 'oidc.token_endpoint' => 'tokenEndpoint', 'oidc.authorization_endpoint' => 'authorizationEndpoint', 'oidc.userinfo_endpoint' => 'userinfoEndpoint', ]; foreach ($endpointConfigKeys as $endpointConfigKey => $endpointName) { $logger = $this->withTestLogger(); $original = config()->get($endpointConfigKey); $new = str_replace('https://', 'http://', $original); config()->set($endpointConfigKey, $new); $this->withoutExceptionHandling(); $err = null; try { $resp = $this->runLogin(); $resp->assertRedirect('/login'); } catch (\Exception $exception) { $err = $exception; } $this->assertEquals("Endpoint value for \"{$endpointName}\" must start with https://", $err->getMessage()); config()->set($endpointConfigKey, $original); } } public function test_auth_login_with_autodiscovery() { $this->withAutodiscovery(); $transactions = $this->mockHttpClient([ $this->getAutoDiscoveryResponse(), $this->getJwksResponse(), ]); $this->assertFalse(auth()->check()); $this->runLogin(); $this->assertTrue(auth()->check()); $discoverRequest = $transactions->requestAt(0); $keysRequest = $transactions->requestAt(1); $this->assertEquals('GET', $keysRequest->getMethod()); $this->assertEquals('GET', $discoverRequest->getMethod()); $this->assertEquals(OidcJwtHelper::defaultIssuer() . '/.well-known/openid-configuration', $discoverRequest->getUri()); $this->assertEquals(OidcJwtHelper::defaultIssuer() . '/oidc/keys', $keysRequest->getUri()); } public function test_auth_fails_if_autodiscovery_fails() { $this->withAutodiscovery(); $this->mockHttpClient([ new Response(404, [], 'Not found'), ]); $resp = $this->followRedirects($this->runLogin()); $this->assertFalse(auth()->check()); $resp->assertSeeText('Login using SingleSignOn-Testing failed, system did not provide successful authorization'); } public function test_autodiscovery_calls_are_cached() { $this->withAutodiscovery(); $transactions = $this->mockHttpClient([ $this->getAutoDiscoveryResponse(), $this->getJwksResponse(), $this->getAutoDiscoveryResponse([ 'issuer' => 'https://auto.example.com', ]), $this->getJwksResponse(), ]); // Initial run $this->post('/oidc/login'); $this->assertEquals(2, $transactions->requestCount()); // Second run, hits cache $this->post('/oidc/login'); $this->assertEquals(2, $transactions->requestCount()); // Third run, different issuer, new cache key config()->set(['oidc.issuer' => 'https://auto.example.com']); $this->post('/oidc/login'); $this->assertEquals(4, $transactions->requestCount()); } public function test_auth_login_with_autodiscovery_with_keys_that_do_not_have_alg_property() { $this->withAutodiscovery(); $keyArray = OidcJwtHelper::publicJwkKeyArray(); unset($keyArray['alg']); $this->mockHttpClient([ $this->getAutoDiscoveryResponse(), new Response(200, [ 'Content-Type' => 'application/json', 'Cache-Control' => 'no-cache, no-store', 'Pragma' => 'no-cache', ], json_encode([ 'keys' => [ $keyArray, ], ])), ]); $this->assertFalse(auth()->check()); $this->runLogin(); $this->assertTrue(auth()->check()); } public function test_auth_login_with_autodiscovery_with_keys_that_do_not_have_use_property() { // Based on reading the OIDC discovery spec: // > This contains the signing key(s) the RP uses to validate signatures from the OP. The JWK Set MAY also // > contain the Server's encryption key(s), which are used by RPs to encrypt requests to the Server. When // > both signing and encryption keys are made available, a use (Key Use) parameter value is REQUIRED for all // > keys in the referenced JWK Set to indicate each key's intended usage. // We can assume that keys without use are intended for signing. $this->withAutodiscovery(); $keyArray = OidcJwtHelper::publicJwkKeyArray(); unset($keyArray['use']); $this->mockHttpClient([ $this->getAutoDiscoveryResponse(), new Response(200, [ 'Content-Type' => 'application/json', 'Cache-Control' => 'no-cache, no-store', 'Pragma' => 'no-cache', ], json_encode([ 'keys' => [ $keyArray, ], ])), ]); $this->assertFalse(auth()->check()); $this->runLogin(); $this->assertTrue(auth()->check()); } public function test_auth_uses_configured_external_id_claim_option() { config()->set([ 'oidc.external_id_claim' => 'super_awesome_id', ]); $resp = $this->runLogin([ 'email' => 'benny@example.com', 'sub' => 'benny1010101', 'super_awesome_id' => 'xXBennyTheGeezXx', ]); $resp->assertRedirect('/'); /** @var User $user */ $user = User::query()->where('email', '=', 'benny@example.com')->first(); $this->assertEquals('xXBennyTheGeezXx', $user->external_auth_id); } public function test_auth_uses_mulitple_display_name_claims_if_configured() { config()->set(['oidc.display_name_claims' => 'first_name|last_name']); $this->runLogin([ 'email' => 'benny@example.com', 'sub' => 'benny1010101', 'first_name' => 'Benny', 'last_name' => 'Jenkins' ]); $this->assertDatabaseHas('users', [ 'name' => 'Benny Jenkins', 'email' => 'benny@example.com', ]); } public function test_user_avatar_fetched_from_picture_on_first_login_if_enabled() { config()->set(['oidc.fetch_avatar' => true]); $this->runLogin([ 'email' => 'avatar@example.com', 'picture' => 'https://example.com/my-avatar.jpg', ], [ new Response(200, ['Content-Type' => 'image/jpeg'], $this->files->jpegImageData()) ]); $user = User::query()->where('email', '=', 'avatar@example.com')->first(); $this->assertNotNull($user); $this->assertTrue($user->avatar()->exists()); } public function test_user_avatar_fetched_for_existing_user_when_no_avatar_already_assigned() { config()->set(['oidc.fetch_avatar' => true]); $editor = $this->users->editor(); $editor->external_auth_id = 'benny509'; $editor->save(); $this->assertFalse($editor->avatar()->exists()); $this->runLogin([ 'picture' => 'https://example.com/my-avatar.jpg', 'sub' => 'benny509', ], [ new Response(200, ['Content-Type' => 'image/jpeg'], $this->files->jpegImageData()) ]); $editor->refresh(); $this->assertTrue($editor->avatar()->exists()); } public function test_user_avatar_not_fetched_if_image_data_format_unknown() { config()->set(['oidc.fetch_avatar' => true]); $this->runLogin([ 'email' => 'avatar-format@example.com', 'picture' => 'https://example.com/my-avatar.jpg', ], [ new Response(200, ['Content-Type' => 'image/jpeg'], str_repeat('abc123', 5)) ]); $user = User::query()->where('email', '=', 'avatar-format@example.com')->first(); $this->assertNotNull($user); $this->assertFalse($user->avatar()->exists()); } public function test_user_avatar_not_fetched_when_avatar_already_assigned() { config()->set(['oidc.fetch_avatar' => true]); $editor = $this->users->editor(); $editor->external_auth_id = 'benny509'; $editor->save(); $avatars = $this->app->make(UserAvatars::class); $originalImageData = $this->files->pngImageData(); $avatars->assignToUserFromExistingData($editor, $originalImageData, 'png'); $this->runLogin([ 'picture' => 'https://example.com/my-avatar.jpg', 'sub' => 'benny509', ], [ new Response(200, ['Content-Type' => 'image/jpeg'], $this->files->jpegImageData()) ]); $editor->refresh(); $newAvatarData = file_get_contents($this->files->relativeToFullPath($editor->avatar->path)); $this->assertEquals($originalImageData, $newAvatarData); } public function test_user_avatar_fetch_follows_up_to_three_redirects() { config()->set(['oidc.fetch_avatar' => true]); $logger = $this->withTestLogger(); $this->runLogin([ 'email' => 'avatar@example.com', 'picture' => 'https://example.com/my-avatar.jpg', ], [ new Response(302, ['Location' => 'https://example.com/a']), new Response(302, ['Location' => 'https://example.com/b']), new Response(302, ['Location' => 'https://example.com/c']), new Response(302, ['Location' => 'https://example.com/d']), ]); $user = User::query()->where('email', '=', 'avatar@example.com')->first(); $this->assertFalse($user->avatar()->exists()); $this->assertStringContainsString('"Failed to fetch image, max redirect limit of 3 tries reached. Last fetched URL: https://example.com/c"', $logger->getRecords()[0]->formatted); } public function test_login_group_sync() { config()->set([ 'oidc.user_to_groups' => true, 'oidc.groups_claim' => 'groups', 'oidc.remove_from_groups' => false, ]); $roleA = Role::factory()->create(['display_name' => 'Wizards']); $roleB = Role::factory()->create(['display_name' => 'ZooFolks', 'external_auth_id' => 'zookeepers']); $roleC = Role::factory()->create(['display_name' => 'Another Role']); $resp = $this->runLogin([ 'email' => 'benny@example.com', 'sub' => 'benny1010101', 'groups' => ['Wizards', 'Zookeepers'], ]); $resp->assertRedirect('/'); /** @var User $user */ $user = User::query()->where('email', '=', 'benny@example.com')->first(); $this->assertTrue($user->hasRole($roleA->id)); $this->assertTrue($user->hasRole($roleB->id)); $this->assertFalse($user->hasRole($roleC->id)); } public function test_login_group_sync_with_nested_groups_in_token() { config()->set([ 'oidc.user_to_groups' => true, 'oidc.groups_claim' => 'my.custom.groups.attr', 'oidc.remove_from_groups' => false, ]); $roleA = Role::factory()->create(['display_name' => 'Wizards']); $resp = $this->runLogin([ 'email' => 'benny@example.com', 'sub' => 'benny1010101', 'my' => [ 'custom' => [ 'groups' => [ 'attr' => ['Wizards'], ], ], ], ]); $resp->assertRedirect('/'); /** @var User $user */ $user = User::query()->where('email', '=', 'benny@example.com')->first(); $this->assertTrue($user->hasRole($roleA->id)); } public function test_oidc_logout_form_active_when_oidc_active() { $this->runLogin(); $resp = $this->get('/'); $this->withHtml($resp)->assertElementExists('header form[action$="/oidc/logout"] button'); } public function test_logout_with_autodiscovery_with_oidc_logout_enabled() { config()->set(['oidc.end_session_endpoint' => true]); $this->withAutodiscovery(); $transactions = $this->mockHttpClient([ $this->getAutoDiscoveryResponse(), $this->getJwksResponse(), ]); $resp = $this->asEditor()->post('/oidc/logout'); $resp->assertRedirect('https://auth.example.com/oidc/logout?post_logout_redirect_uri=' . urlencode(url('/'))); $this->assertEquals(2, $transactions->requestCount()); $this->assertFalse(auth()->check()); } public function test_logout_with_autodiscovery_with_oidc_logout_disabled() { $this->withAutodiscovery(); config()->set(['oidc.end_session_endpoint' => false]); $this->mockHttpClient([ $this->getAutoDiscoveryResponse(), $this->getJwksResponse(), ]); $resp = $this->asEditor()->post('/oidc/logout'); $resp->assertRedirect('/'); $this->assertFalse(auth()->check()); } public function test_logout_without_autodiscovery_but_with_endpoint_configured() { config()->set(['oidc.end_session_endpoint' => 'https://example.com/logout']); $resp = $this->asEditor()->post('/oidc/logout'); $resp->assertRedirect('https://example.com/logout?post_logout_redirect_uri=' . urlencode(url('/'))); $this->assertFalse(auth()->check()); } public function test_logout_without_autodiscovery_with_configured_endpoint_adds_to_query_if_existing() { config()->set(['oidc.end_session_endpoint' => 'https://example.com/logout?a=b']); $resp = $this->asEditor()->post('/oidc/logout'); $resp->assertRedirect('https://example.com/logout?a=b&post_logout_redirect_uri=' . urlencode(url('/'))); $this->assertFalse(auth()->check()); } public function test_logout_with_autodiscovery_and_auto_initiate_returns_to_auto_prevented_login() { $this->withAutodiscovery(); config()->set([ 'auth.auto_initiate' => true, 'services.google.client_id' => false, 'services.github.client_id' => false, 'oidc.end_session_endpoint' => true, ]); $this->mockHttpClient([ $this->getAutoDiscoveryResponse(), $this->getJwksResponse(), ]); $resp = $this->asEditor()->post('/oidc/logout'); $redirectUrl = url('/login?prevent_auto_init=true'); $resp->assertRedirect('https://auth.example.com/oidc/logout?post_logout_redirect_uri=' . urlencode($redirectUrl)); $this->assertFalse(auth()->check()); } public function test_logout_endpoint_url_overrides_autodiscovery_endpoint() { config()->set(['oidc.end_session_endpoint' => 'https://a.example.com']); $this->withAutodiscovery(); $transactions = $this->mockHttpClient([ $this->getAutoDiscoveryResponse(), $this->getJwksResponse(), ]); $resp = $this->asEditor()->post('/oidc/logout'); $resp->assertRedirect('https://a.example.com?post_logout_redirect_uri=' . urlencode(url('/'))); $this->assertEquals(2, $transactions->requestCount()); $this->assertFalse(auth()->check()); } public function test_logout_with_autodiscovery_does_not_use_rp_logout_if_no_url_via_autodiscovery() { config()->set(['oidc.end_session_endpoint' => true]); $this->withAutodiscovery(); $this->mockHttpClient([ $this->getAutoDiscoveryResponse(['end_session_endpoint' => null]), $this->getJwksResponse(), ]); $resp = $this->asEditor()->post('/oidc/logout'); $resp->assertRedirect('/'); $this->assertFalse(auth()->check()); } public function test_logout_redirect_contains_id_token_hint_if_existing() { config()->set(['oidc.end_session_endpoint' => 'https://example.com/logout']); // Fix times so our token is predictable $claimOverrides = [ 'iat' => time(), 'exp' => time() + 720, 'auth_time' => time() ]; $this->runLogin($claimOverrides); $resp = $this->asEditor()->post('/oidc/logout'); $query = 'id_token_hint=' . urlencode(OidcJwtHelper::idToken($claimOverrides)) . '&post_logout_redirect_uri=' . urlencode(url('/')); $resp->assertRedirect('https://example.com/logout?' . $query); } public function test_oidc_id_token_pre_validate_theme_event_without_return() { $args = []; $callback = function (...$eventArgs) use (&$args) { $args = $eventArgs; }; Theme::listen(ThemeEvents::OIDC_ID_TOKEN_PRE_VALIDATE, $callback); $resp = $this->runLogin([ 'email' => 'benny@example.com', 'sub' => 'benny1010101', 'name' => 'Benny', ]); $resp->assertRedirect('/'); $this->assertDatabaseHas('users', [ 'external_auth_id' => 'benny1010101', ]); $this->assertArrayHasKey('iss', $args[0]); $this->assertArrayHasKey('sub', $args[0]); $this->assertEquals('Benny', $args[0]['name']); $this->assertEquals('benny1010101', $args[0]['sub']); $this->assertArrayHasKey('access_token', $args[1]); $this->assertArrayHasKey('expires_in', $args[1]); $this->assertArrayHasKey('refresh_token', $args[1]); } public function test_oidc_id_token_pre_validate_theme_event_with_return() { $callback = function (...$eventArgs) { return array_merge($eventArgs[0], [ 'email' => 'lenny@example.com', 'sub' => 'lenny1010101', 'name' => 'Lenny', ]); }; Theme::listen(ThemeEvents::OIDC_ID_TOKEN_PRE_VALIDATE, $callback); $resp = $this->runLogin([ 'email' => 'benny@example.com', 'sub' => 'benny1010101', 'name' => 'Benny', ]); $resp->assertRedirect('/'); $this->assertDatabaseHas('users', [ 'email' => 'lenny@example.com', 'external_auth_id' => 'lenny1010101', 'name' => 'Lenny', ]); } public function test_pkce_used_on_authorize_and_access() { // Start auth $resp = $this->post('/oidc/login'); $state = explode(':', session()->get('oidc_state'), 2)[1]; $pkceCode = session()->get('oidc_pkce_code'); $this->assertGreaterThan(30, strlen($pkceCode)); $expectedCodeChallenge = trim(strtr(base64_encode(hash('sha256', $pkceCode, true)), '+/', '-_'), '='); $redirect = $resp->headers->get('Location'); $redirectParams = []; parse_str(parse_url($redirect, PHP_URL_QUERY), $redirectParams); $this->assertEquals($expectedCodeChallenge, $redirectParams['code_challenge']); $this->assertEquals('S256', $redirectParams['code_challenge_method']); $transactions = $this->mockHttpClient([$this->getMockAuthorizationResponse([ 'email' => 'benny@example.com', 'sub' => 'benny1010101', ])]); $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state); $tokenRequest = $transactions->latestRequest(); $bodyParams = []; parse_str($tokenRequest->getBody(), $bodyParams); $this->assertEquals($pkceCode, $bodyParams['code_verifier']); } public function test_userinfo_endpoint_used_if_missing_claims_in_id_token() { config()->set('oidc.display_name_claims', 'first_name|last_name'); $this->post('/oidc/login'); $state = explode(':', session()->get('oidc_state'), 2)[1]; $client = $this->mockHttpClient([ $this->getMockAuthorizationResponse(['name' => null]), new Response(200, [ 'Content-Type' => 'application/json', ], json_encode([ 'sub' => OidcJwtHelper::defaultPayload()['sub'], 'first_name' => 'Barry', 'last_name' => 'Userinfo', ])) ]); $resp = $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state); $resp->assertRedirect('/'); $this->assertEquals(2, $client->requestCount()); $userinfoRequest = $client->requestAt(1); $this->assertEquals('GET', $userinfoRequest->getMethod()); $this->assertEquals('https://oidc.local/userinfo', (string) $userinfoRequest->getUri()); $this->assertEquals('Barry Userinfo', user()->name); } public function test_userinfo_endpoint_fetch_with_different_sub_throws_error() { $userinfoResponseData = ['sub' => 'dcba4321']; $userinfoResponse = new Response(200, ['Content-Type' => 'application/json'], json_encode($userinfoResponseData)); $resp = $this->runLogin(['name' => null], [$userinfoResponse]); $resp->assertRedirect('/login'); $this->assertSessionError('Userinfo endpoint response validation failed with error: Subject value provided in the userinfo endpoint does not match the provided ID token value'); } public function test_userinfo_endpoint_fetch_returning_no_sub_throws_error() { $userinfoResponseData = ['name' => 'testing'];
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
true
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Auth/LoginAutoInitiateTest.php
tests/Auth/LoginAutoInitiateTest.php
<?php namespace Tests\Auth; use Tests\TestCase; class LoginAutoInitiateTest extends TestCase { protected function setUp(): void { parent::setUp(); config()->set([ 'auth.auto_initiate' => true, 'services.google.client_id' => false, 'services.github.client_id' => false, ]); } public function test_with_oidc() { config()->set([ 'auth.method' => 'oidc', ]); $req = $this->get('/login'); $req->assertSeeText('Attempting Login'); $this->withHtml($req)->assertElementExists('form[action$="/oidc/login"][method=POST][id="login-form"] button'); $this->withHtml($req)->assertElementExists('button[form="login-form"]'); } public function test_with_saml2() { config()->set([ 'auth.method' => 'saml2', ]); $req = $this->get('/login'); $req->assertSeeText('Attempting Login'); $this->withHtml($req)->assertElementExists('form[action$="/saml2/login"][method=POST][id="login-form"] button'); $this->withHtml($req)->assertElementExists('button[form="login-form"]'); } public function test_it_does_not_run_if_social_provider_is_active() { config()->set([ 'auth.method' => 'oidc', 'services.google.client_id' => 'abc123a', 'services.google.client_secret' => 'def456', ]); $req = $this->get('/login'); $req->assertDontSeeText('Attempting Login'); $req->assertSee('Log In'); } public function test_it_does_not_run_if_prevent_query_string_exists() { config()->set([ 'auth.method' => 'oidc', ]); $req = $this->get('/login?prevent_auto_init=true'); $req->assertDontSeeText('Attempting Login'); $req->assertSee('Log In'); } public function test_logout_with_auto_init_leads_to_login_page_with_prevention_query() { config()->set([ 'auth.method' => 'oidc', ]); $this->actingAs($this->users->editor()); $req = $this->post('/logout'); $req->assertRedirect('/login?prevent_auto_init=true'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Auth/RegistrationTest.php
tests/Auth/RegistrationTest.php
<?php namespace Tests\Auth; use BookStack\Access\Notifications\ConfirmEmailNotification; use BookStack\Users\Models\Role; use BookStack\Users\Models\User; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Notification; use Tests\TestCase; class RegistrationTest extends TestCase { public function test_confirmed_registration() { // Fake notifications Notification::fake(); // Set settings and get user instance $this->setSettings(['registration-enabled' => 'true', 'registration-confirmation' => 'true']); $user = User::factory()->make(); // Go through registration process $resp = $this->post('/register', $user->only('name', 'email', 'password')); $resp->assertRedirect('/register/confirm'); $this->assertDatabaseHas('users', ['name' => $user->name, 'email' => $user->email, 'email_confirmed' => false]); $resp = $this->get('/register/confirm'); $resp->assertSee('Thanks for registering!'); // Ensure notification sent /** @var User $dbUser */ $dbUser = User::query()->where('email', '=', $user->email)->first(); Notification::assertSentTo($dbUser, ConfirmEmailNotification::class); // Test access and resend confirmation email $resp = $this->post('/login', ['email' => $user->email, 'password' => $user->password]); $resp->assertRedirect('/register/confirm/awaiting'); $resp = $this->get('/register/confirm/awaiting'); $this->withHtml($resp)->assertElementContains('form[action="' . url('/register/confirm/resend') . '"]', 'Resend'); $this->get('/books')->assertRedirect('/login'); $this->post('/register/confirm/resend', $user->only('email')); // Get confirmation and confirm notification matches $emailConfirmation = DB::table('email_confirmations')->where('user_id', '=', $dbUser->id)->first(); Notification::assertSentTo($dbUser, ConfirmEmailNotification::class, function ($notification, $channels) use ($emailConfirmation) { return $notification->token === $emailConfirmation->token; }); // Check confirmation email confirmation accept page. $resp = $this->get('/register/confirm/' . $emailConfirmation->token); $acceptPage = $this->withHtml($resp); $resp->assertOk(); $resp->assertSee('Thanks for confirming!'); $acceptPage->assertElementExists('form[method="post"][action$="/register/confirm/accept"][component="auto-submit"] button'); $acceptPage->assertFieldHasValue('token', $emailConfirmation->token); // Check acceptance confirm $this->post('/register/confirm/accept', ['token' => $emailConfirmation->token])->assertRedirect('/login'); // Check state on login redirect $this->get('/login')->assertSee('Your email has been confirmed! You should now be able to login using this email address.'); $this->assertDatabaseMissing('email_confirmations', ['token' => $emailConfirmation->token]); $this->assertDatabaseHas('users', ['name' => $dbUser->name, 'email' => $dbUser->email, 'email_confirmed' => true]); } public function test_restricted_registration() { $this->setSettings(['registration-enabled' => 'true', 'registration-confirmation' => 'true', 'registration-restrict' => 'example.com']); $user = User::factory()->make(); // Go through registration process $this->post('/register', $user->only('name', 'email', 'password')) ->assertRedirect('/register'); $resp = $this->get('/register'); $resp->assertSee('That email domain does not have access to this application'); $this->assertDatabaseMissing('users', $user->only('email')); $user->email = 'barry@example.com'; $this->post('/register', $user->only('name', 'email', 'password')) ->assertRedirect('/register/confirm'); $this->assertDatabaseHas('users', ['name' => $user->name, 'email' => $user->email, 'email_confirmed' => false]); $this->assertNull(auth()->user()); $this->get('/')->assertRedirect('/login'); $resp = $this->followingRedirects()->post('/login', $user->only('email', 'password')); $resp->assertSee('Email Address Not Confirmed'); $this->assertNull(auth()->user()); } public function test_restricted_registration_with_confirmation_disabled() { $this->setSettings(['registration-enabled' => 'true', 'registration-confirmation' => 'false', 'registration-restrict' => 'example.com']); $user = User::factory()->make(); // Go through registration process $this->post('/register', $user->only('name', 'email', 'password')) ->assertRedirect('/register'); $this->assertDatabaseMissing('users', $user->only('email')); $this->get('/register')->assertSee('That email domain does not have access to this application'); $user->email = 'barry@example.com'; $this->post('/register', $user->only('name', 'email', 'password')) ->assertRedirect('/register/confirm'); $this->assertDatabaseHas('users', ['name' => $user->name, 'email' => $user->email, 'email_confirmed' => false]); $this->assertNull(auth()->user()); $this->get('/')->assertRedirect('/login'); $resp = $this->post('/login', $user->only('email', 'password')); $resp->assertRedirect('/register/confirm/awaiting'); $this->get('/register/confirm/awaiting')->assertSee('Email Address Not Confirmed'); $this->assertNull(auth()->user()); } public function test_registration_role_unset_by_default() { $this->assertFalse(setting('registration-role')); $resp = $this->asAdmin()->get('/settings/registration'); $this->withHtml($resp)->assertElementContains('select[name="setting-registration-role"] option[value="0"][selected]', '-- None --'); } public function test_registration_showing() { // Ensure registration form is showing $this->setSettings(['registration-enabled' => 'true']); $resp = $this->get('/login'); $this->withHtml($resp)->assertElementContains('a[href="' . url('/register') . '"]', 'Sign up'); } public function test_normal_registration() { // Set settings and get user instance /** @var Role $registrationRole */ $registrationRole = Role::query()->first(); $this->setSettings(['registration-enabled' => 'true', 'registration-role' => $registrationRole->id]); /** @var User $user */ $user = User::factory()->make(); // Test form and ensure user is created $resp = $this->get('/register') ->assertSee('Sign Up'); $this->withHtml($resp)->assertElementContains('form[action="' . url('/register') . '"]', 'Create Account'); $resp = $this->post('/register', $user->only('password', 'name', 'email')); $resp->assertRedirect('/'); $resp = $this->get('/'); $resp->assertOk(); $resp->assertSee($user->name); $this->assertDatabaseHas('users', ['name' => $user->name, 'email' => $user->email]); $user = User::query()->where('email', '=', $user->email)->first(); $this->assertEquals(1, $user->roles()->count()); $this->assertEquals($registrationRole->id, $user->roles()->first()->id); } public function test_empty_registration_redirects_back_with_errors() { // Set settings and get user instance $this->setSettings(['registration-enabled' => 'true']); // Test form and ensure user is created $this->get('/register'); $this->post('/register', [])->assertRedirect('/register'); $this->get('/register')->assertSee('The name field is required'); } public function test_registration_validation() { $this->setSettings(['registration-enabled' => 'true']); $this->get('/register'); $resp = $this->followingRedirects()->post('/register', [ 'name' => '1', 'email' => '1', 'password' => '1', ]); $resp->assertSee('The name must be at least 2 characters.'); $resp->assertSee('The email must be a valid email address.'); $resp->assertSee('The password must be at least 8 characters.'); } public function test_registration_simple_honeypot_active() { $this->setSettings(['registration-enabled' => 'true']); $resp = $this->get('/register'); $this->withHtml($resp)->assertElementExists('form input[name="username"]'); $resp = $this->post('/register', [ 'name' => 'Barry', 'email' => 'barrybot@example.com', 'password' => 'barryIsTheBestBot', 'username' => 'MyUsername' ]); $resp->assertRedirect('/register'); $resp = $this->followRedirects($resp); $this->withHtml($resp)->assertElementExists('form input[name="username"].text-neg'); } public function test_registration_endpoint_throttled() { $this->setSettings(['registration-enabled' => 'true']); for ($i = 0; $i < 11; $i++) { $response = $this->post('/register/', [ 'name' => "Barry{$i}", 'email' => "barry{$i}@example.com", 'password' => "barryIsTheBest{$i}", ]); auth()->logout(); } $response->assertStatus(429); } public function test_registration_confirmation_throttled() { $this->setSettings(['registration-enabled' => 'true']); for ($i = 0; $i < 11; $i++) { $response = $this->post('/register/confirm/accept', [ 'token' => "token{$i}", ]); } $response->assertStatus(429); } public function test_registration_confirmation_resend() { Notification::fake(); $this->setSettings(['registration-enabled' => 'true', 'registration-confirmation' => 'true']); $user = User::factory()->make(); $resp = $this->post('/register', $user->only('name', 'email', 'password')); $resp->assertRedirect('/register/confirm'); $dbUser = User::query()->where('email', '=', $user->email)->first(); $resp = $this->post('/login', ['email' => $user->email, 'password' => $user->password]); $resp->assertRedirect('/register/confirm/awaiting'); $resp = $this->post('/register/confirm/resend'); $resp->assertRedirect('/register/confirm'); Notification::assertSentToTimes($dbUser, ConfirmEmailNotification::class, 2); } public function test_registration_confirmation_expired_resend() { Notification::fake(); $this->setSettings(['registration-enabled' => 'true', 'registration-confirmation' => 'true']); $user = User::factory()->make(); $resp = $this->post('/register', $user->only('name', 'email', 'password')); $resp->assertRedirect('/register/confirm'); $dbUser = User::query()->where('email', '=', $user->email)->first(); $resp = $this->post('/login', ['email' => $user->email, 'password' => $user->password]); $resp->assertRedirect('/register/confirm/awaiting'); $emailConfirmation = DB::table('email_confirmations')->where('user_id', '=', $dbUser->id)->first(); $this->travel(2)->days(); $resp = $this->post("/register/confirm/accept", [ 'token' => $emailConfirmation->token, ]); $resp->assertRedirect('/register/confirm'); $this->assertSessionError('The confirmation token has expired, A new confirmation email has been sent.'); Notification::assertSentToTimes($dbUser, ConfirmEmailNotification::class, 2); } public function test_registration_confirmation_awaiting_and_resend_returns_to_log_if_no_login_attempt_user_found() { $this->setSettings(['registration-enabled' => 'true', 'registration-confirmation' => 'true']); $this->get('/register/confirm/awaiting')->assertRedirect('/login'); $this->assertSessionError('A user for this action could not be found.'); $this->flushSession(); $this->post('/register/confirm/resend')->assertRedirect('/login'); $this->assertSessionError('A user for this action could not be found.'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Auth/AuthTest.php
tests/Auth/AuthTest.php
<?php namespace Tests\Auth; use BookStack\Access\Mfa\MfaSession; use Illuminate\Support\Facades\Hash; use Illuminate\Testing\TestResponse; use Tests\TestCase; class AuthTest extends TestCase { public function test_auth_working() { $this->get('/')->assertRedirect('/login'); } public function test_login() { $this->login('admin@admin.com', 'password')->assertRedirect('/'); } public function test_public_viewing() { $this->setSettings(['app-public' => 'true']); $this->get('/') ->assertOk() ->assertSee('Log in'); } public function test_sign_up_link_on_login() { $this->get('/login')->assertDontSee('Sign up'); $this->setSettings(['registration-enabled' => 'true']); $this->get('/login')->assertSee('Sign up'); } public function test_logout() { $this->asAdmin()->get('/')->assertOk(); $this->post('/logout')->assertRedirect('/'); $this->get('/')->assertRedirect('/login'); } public function test_mfa_session_cleared_on_logout() { $user = $this->users->editor(); $mfaSession = $this->app->make(MfaSession::class); $mfaSession->markVerifiedForUser($user); $this->assertTrue($mfaSession->isVerifiedForUser($user)); $this->asAdmin()->post('/logout'); $this->assertFalse($mfaSession->isVerifiedForUser($user)); } public function test_login_redirects_to_initially_requested_url_correctly() { config()->set('app.url', 'http://localhost'); $page = $this->entities->page(); $this->get($page->getUrl())->assertRedirect(url('/login')); $this->login('admin@admin.com', 'password') ->assertRedirect($page->getUrl()); } public function test_login_intended_redirect_does_not_redirect_to_external_pages() { config()->set('app.url', 'http://localhost'); $this->setSettings(['app-public' => true]); $this->get('/login', ['referer' => 'https://example.com']); $login = $this->post('/login', ['email' => 'admin@admin.com', 'password' => 'password']); $login->assertRedirect('http://localhost'); } public function test_login_intended_redirect_does_not_factor_mfa_routes() { $this->get('/books')->assertRedirect('/login'); $this->get('/mfa/setup')->assertRedirect('/login'); $login = $this->post('/login', ['email' => 'admin@admin.com', 'password' => 'password']); $login->assertRedirect('/books'); } public function test_login_authenticates_admins_on_all_guards() { $this->post('/login', ['email' => 'admin@admin.com', 'password' => 'password']); $this->assertTrue(auth()->check()); $this->assertTrue(auth('ldap')->check()); $this->assertTrue(auth('saml2')->check()); $this->assertTrue(auth('oidc')->check()); } public function test_login_authenticates_nonadmins_on_default_guard_only() { $editor = $this->users->editor(); $editor->password = bcrypt('password'); $editor->save(); $this->post('/login', ['email' => $editor->email, 'password' => 'password']); $this->assertTrue(auth()->check()); $this->assertFalse(auth('ldap')->check()); $this->assertFalse(auth('saml2')->check()); $this->assertFalse(auth('oidc')->check()); } public function test_failed_logins_are_logged_when_message_configured() { $log = $this->withTestLogger(); config()->set(['logging.failed_login.message' => 'Failed login for %u']); $this->post('/login', ['email' => 'admin@example.com', 'password' => 'cattreedog']); $this->assertTrue($log->hasWarningThatContains('Failed login for admin@example.com')); $this->post('/login', ['email' => 'admin@admin.com', 'password' => 'password']); $this->assertFalse($log->hasWarningThatContains('Failed login for admin@admin.com')); } public function test_logged_in_user_with_unconfirmed_email_is_logged_out() { $this->setSettings(['registration-confirmation' => 'true']); $user = $this->users->editor(); $user->email_confirmed = false; $user->save(); auth()->login($user); $this->assertTrue(auth()->check()); $this->get('/books')->assertRedirect('/'); $this->assertFalse(auth()->check()); } public function test_login_attempts_are_rate_limited() { for ($i = 0; $i < 5; $i++) { $resp = $this->login('bennynotexisting@example.com', 'pw123'); } $resp = $this->followRedirects($resp); $resp->assertSee('These credentials do not match our records.'); // Check the fifth attempt provides a lockout response $resp = $this->followRedirects($this->login('bennynotexisting@example.com', 'pw123')); $resp->assertSee('Too many login attempts. Please try again in'); } public function test_login_specifically_disabled_for_guest_account() { $guest = $this->users->guest(); $resp = $this->post('/login', ['email' => $guest->email, 'password' => 'password']); $resp->assertRedirect('/login'); $resp = $this->followRedirects($resp); $resp->assertSee('These credentials do not match our records.'); // Test login even with password somehow set $guest->password = Hash::make('password'); $guest->save(); $resp = $this->post('/login', ['email' => $guest->email, 'password' => 'password']); $resp->assertRedirect('/login'); $resp = $this->followRedirects($resp); $resp->assertSee('These credentials do not match our records.'); } /** * Perform a login. */ protected function login(string $email, string $password): TestResponse { return $this->post('/login', compact('email', 'password')); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Util/DateFormatterTest.php
tests/Util/DateFormatterTest.php
<?php namespace Tests\Util; use BookStack\Util\DateFormatter; use Carbon\Carbon; use Tests\TestCase; class DateFormatterTest extends TestCase { public function test_iso_with_timezone_alters_from_stored_to_display_timezone() { $formatter = new DateFormatter('Europe/London'); $dateTime = new Carbon('2020-06-01 12:00:00', 'UTC'); $result = $formatter->absolute($dateTime); $this->assertEquals('2020-06-01 13:00:00 BST', $result); } public function test_iso_with_timezone_works_from_non_utc_dates() { $formatter = new DateFormatter('Asia/Shanghai'); $dateTime = new Carbon('2025-06-10 15:25:00', 'America/New_York'); $result = $formatter->absolute($dateTime); $this->assertEquals('2025-06-11 03:25:00 CST', $result); } public function test_relative() { $formatter = new DateFormatter('Europe/London'); $dateTime = (new Carbon('now', 'UTC'))->subMinutes(50); $result = $formatter->relative($dateTime); $this->assertEquals('50 minutes ago', $result); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Unit/FrameworkAssumptionTest.php
tests/Unit/FrameworkAssumptionTest.php
<?php namespace Tests\Unit; use BadMethodCallException; use BookStack\Entities\Models\Page; use Tests\TestCase; /** * This class tests assumptions we're relying upon in the framework. * This is primarily to keep track of certain bits of functionality that * may be used in important areas such as to enforce permissions. */ class FrameworkAssumptionTest extends TestCase { public function test_scopes_error_if_not_existing() { $this->expectException(BadMethodCallException::class); $this->expectExceptionMessage('Call to undefined method BookStack\Entities\Models\Page::scopeNotfoundscope()'); Page::query()->scopes('notfoundscope'); } public function test_scopes_applies_upon_existing() { // Page has SoftDeletes trait by default, so we apply our custom scope and ensure // it stacks on the global scope to filter out deleted items. $query = Page::query()->scopes('visible')->toSql(); $this->assertStringContainsString('joint_permissions', $query); $this->assertStringContainsString('`deleted_at` is null', $query); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Unit/IpFormatterTest.php
tests/Unit/IpFormatterTest.php
<?php namespace Tests\Unit; use BookStack\Activity\Tools\IpFormatter; use Tests\TestCase; class IpFormatterTest extends TestCase { public function test_ips_formatted_as_expected() { $this->assertEquals('192.123.45.5', (new IpFormatter('192.123.45.5', 4))->format()); $this->assertEquals('192.123.45.x', (new IpFormatter('192.123.45.5', 3))->format()); $this->assertEquals('192.123.x.x', (new IpFormatter('192.123.45.5', 2))->format()); $this->assertEquals('192.x.x.x', (new IpFormatter('192.123.45.5', 1))->format()); $this->assertEquals('x.x.x.x', (new IpFormatter('192.123.45.5', 0))->format()); $ipv6 = '2001:db8:85a3:8d3:1319:8a2e:370:7348'; $this->assertEquals($ipv6, (new IpFormatter($ipv6, 4))->format()); $this->assertEquals('2001:db8:85a3:8d3:1319:8a2e:x:x', (new IpFormatter($ipv6, 3))->format()); $this->assertEquals('2001:db8:85a3:8d3:x:x:x:x', (new IpFormatter($ipv6, 2))->format()); $this->assertEquals('2001:db8:x:x:x:x:x:x', (new IpFormatter($ipv6, 1))->format()); $this->assertEquals('x:x:x:x:x:x:x:x', (new IpFormatter($ipv6, 0))->format()); } public function test_shortened_ipv6_addresses_expands_as_expected() { $this->assertEquals('2001:0:0:0:0:0:x:x', (new IpFormatter('2001::370:7348', 3))->format()); $this->assertEquals('2001:0:0:0:0:85a3:x:x', (new IpFormatter('2001::85a3:370:7348', 3))->format()); $this->assertEquals('2001:0:x:x:x:x:x:x', (new IpFormatter('2001::', 1))->format()); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Unit/OidcIdTokenTest.php
tests/Unit/OidcIdTokenTest.php
<?php namespace Tests\Unit; use BookStack\Access\Oidc\OidcIdToken; use BookStack\Access\Oidc\OidcInvalidTokenException; use Tests\Helpers\OidcJwtHelper; use Tests\TestCase; class OidcIdTokenTest extends TestCase { public function test_valid_token_passes_validation() { $token = new OidcIdToken(OidcJwtHelper::idToken(), OidcJwtHelper::defaultIssuer(), [ OidcJwtHelper::publicJwkKeyArray(), ]); $this->assertTrue($token->validate('xxyyzz.aaa.bbccdd.123')); } public function test_get_claim_returns_value_if_existing() { $token = new OidcIdToken(OidcJwtHelper::idToken(), OidcJwtHelper::defaultIssuer(), []); $this->assertEquals('bscott@example.com', $token->getClaim('email')); } public function test_get_claim_returns_null_if_not_existing() { $token = new OidcIdToken(OidcJwtHelper::idToken(), OidcJwtHelper::defaultIssuer(), []); $this->assertEquals(null, $token->getClaim('emails')); } public function test_get_all_claims_returns_all_payload_claims() { $defaultPayload = OidcJwtHelper::defaultPayload(); $token = new OidcIdToken(OidcJwtHelper::idToken($defaultPayload), OidcJwtHelper::defaultIssuer(), []); $this->assertEquals($defaultPayload, $token->getAllClaims()); } public function test_token_structure_error_cases() { $idToken = OidcJwtHelper::idToken(); $idTokenExploded = explode('.', $idToken); $messagesAndTokenValues = [ ['Could not parse out a valid header within the provided token', ''], ['Could not parse out a valid header within the provided token', 'cat'], ['Could not parse out a valid payload within the provided token', $idTokenExploded[0]], ['Could not parse out a valid payload within the provided token', $idTokenExploded[0] . '.' . 'dog'], ['Could not parse out a valid signature within the provided token', $idTokenExploded[0] . '.' . $idTokenExploded[1]], ['Could not parse out a valid signature within the provided token', $idTokenExploded[0] . '.' . $idTokenExploded[1] . '.' . '@$%'], ]; foreach ($messagesAndTokenValues as [$message, $tokenValue]) { $token = new OidcIdToken($tokenValue, OidcJwtHelper::defaultIssuer(), []); $err = null; try { $token->validate('abc'); } catch (\Exception $exception) { $err = $exception; } $this->assertInstanceOf(OidcInvalidTokenException::class, $err, $message); $this->assertEquals($message, $err->getMessage()); } } public function test_error_thrown_if_token_signature_not_validated_from_no_keys() { $token = new OidcIdToken(OidcJwtHelper::idToken(), OidcJwtHelper::defaultIssuer(), []); $this->expectException(OidcInvalidTokenException::class); $this->expectExceptionMessage('Token signature could not be validated using the provided keys'); $token->validate('abc'); } public function test_error_thrown_if_token_signature_not_validated_from_non_matching_key() { $token = new OidcIdToken(OidcJwtHelper::idToken(), OidcJwtHelper::defaultIssuer(), [ array_merge(OidcJwtHelper::publicJwkKeyArray(), [ 'n' => 'iqK-1QkICMf_cusNLpeNnN-bhT0-9WLBvzgwKLALRbrevhdi5ttrLHIQshaSL0DklzfyG2HWRmAnJ9Q7sweEjuRiiqRcSUZbYu8cIv2hLWYu7K_NH67D2WUjl0EnoHEuiVLsZhQe1CmdyLdx087j5nWkd64K49kXRSdxFQUlj8W3NeK3CjMEUdRQ3H4RZzJ4b7uuMiFA29S2ZhMNG20NPbkUVsFL-jiwTd10KSsPT8yBYipI9O7mWsUWt_8KZs1y_vpM_k3SyYihnWpssdzDm1uOZ8U3mzFr1xsLAO718GNUSXk6npSDzLl59HEqa6zs4O9awO2qnSHvcmyELNk31w', ]), ]); $this->expectException(OidcInvalidTokenException::class); $this->expectExceptionMessage('Token signature could not be validated using the provided keys'); $token->validate('abc'); } public function test_error_thrown_if_invalid_key_provided() { $token = new OidcIdToken(OidcJwtHelper::idToken(), OidcJwtHelper::defaultIssuer(), ['url://example.com']); $this->expectException(OidcInvalidTokenException::class); $this->expectExceptionMessage('Unexpected type of key value provided'); $token->validate('abc'); } public function test_error_thrown_if_token_algorithm_is_not_rs256() { $token = new OidcIdToken(OidcJwtHelper::idToken([], ['alg' => 'HS256']), OidcJwtHelper::defaultIssuer(), []); $this->expectException(OidcInvalidTokenException::class); $this->expectExceptionMessage('Only RS256 signature validation is supported. Token reports using HS256'); $token->validate('abc'); } public function test_token_claim_error_cases() { /** @var array<array{0: string: 1: array}> $claimOverridesByErrorMessage */ $claimOverridesByErrorMessage = [ // 1. iss claim present ['Missing or non-matching token issuer value', ['iss' => null]], // 1. iss claim matches provided issuer ['Missing or non-matching token issuer value', ['iss' => 'https://auth.example.co.uk']], // 2. aud claim present ['Missing token audience value', ['aud' => null]], // 2. aud claim validates all values against those expected (Only expect single) ['Token audience value has 2 values, Expected 1', ['aud' => ['xxyyzz.aaa.bbccdd.123', 'def']]], // 2. aud claim matches client id ['Token audience value did not match the expected client_id', ['aud' => 'xxyyzz.aaa.bbccdd.456']], // 4. azp claim matches client id if present ['Token authorized party exists but does not match the expected client_id', ['azp' => 'xxyyzz.aaa.bbccdd.456']], // 5. exp claim present ['Missing token expiration time value', ['exp' => null]], // 5. exp claim not expired ['Token has expired', ['exp' => time() - 360]], // 6. iat claim present ['Missing token issued at time value', ['iat' => null]], // 6. iat claim too far in the future ['Token issue at time is not recent or is invalid', ['iat' => time() + 600]], // 6. iat claim too far in the past ['Token issue at time is not recent or is invalid', ['iat' => time() - 172800]], // Custom: sub is present ['Missing token subject value', ['sub' => null]], ]; foreach ($claimOverridesByErrorMessage as [$message, $overrides]) { $token = new OidcIdToken(OidcJwtHelper::idToken($overrides), OidcJwtHelper::defaultIssuer(), [ OidcJwtHelper::publicJwkKeyArray(), ]); $err = null; try { $token->validate('xxyyzz.aaa.bbccdd.123'); } catch (\Exception $exception) { $err = $exception; } $this->assertInstanceOf(OidcInvalidTokenException::class, $err, $message); $this->assertEquals($message, $err->getMessage()); } } public function test_keys_can_be_a_local_file_reference_to_pem_key() { $file = tmpfile(); $testFilePath = 'file://' . stream_get_meta_data($file)['uri']; file_put_contents($testFilePath, OidcJwtHelper::publicPemKey()); $token = new OidcIdToken(OidcJwtHelper::idToken(), OidcJwtHelper::defaultIssuer(), [ $testFilePath, ]); $this->assertTrue($token->validate('xxyyzz.aaa.bbccdd.123')); unlink($testFilePath); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Unit/SsrUrlValidatorTest.php
tests/Unit/SsrUrlValidatorTest.php
<?php namespace Tests\Unit; use BookStack\Exceptions\HttpFetchException; use BookStack\Util\SsrUrlValidator; use Tests\TestCase; class SsrUrlValidatorTest extends TestCase { public function test_allowed() { $testMap = [ // Single values ['config' => '', 'url' => '', 'result' => false], ['config' => '', 'url' => 'https://example.com', 'result' => false], ['config' => ' ', 'url' => 'https://example.com', 'result' => false], ['config' => '*', 'url' => '', 'result' => false], ['config' => '*', 'url' => 'https://example.com', 'result' => true], ['config' => 'https://*', 'url' => 'https://example.com', 'result' => true], ['config' => 'http://*', 'url' => 'https://example.com', 'result' => false], ['config' => 'https://*example.com', 'url' => 'https://example.com', 'result' => true], ['config' => 'https://*ample.com', 'url' => 'https://example.com', 'result' => true], ['config' => 'https://*.example.com', 'url' => 'https://example.com', 'result' => false], ['config' => 'https://*.example.com', 'url' => 'https://test.example.com', 'result' => true], ['config' => '*//example.com', 'url' => 'https://example.com', 'result' => true], ['config' => '*//example.com', 'url' => 'http://example.com', 'result' => true], ['config' => '*//example.co', 'url' => 'http://example.co.uk', 'result' => false], ['config' => '*//example.co/bookstack', 'url' => 'https://example.co/bookstack/a/path', 'result' => true], ['config' => '*//example.co*', 'url' => 'https://example.co.uk/bookstack/a/path', 'result' => true], ['config' => 'https://example.com', 'url' => 'https://example.com/a/b/c?test=cat', 'result' => true], ['config' => 'https://example.com', 'url' => 'https://example.co.uk', 'result' => false], // Escapes ['config' => 'https://(.*?).com', 'url' => 'https://example.com', 'result' => false], ['config' => 'https://example.com', 'url' => 'https://example.co.uk#https://example.com', 'result' => false], // Multi values ['config' => '*//example.org *//example.com', 'url' => 'https://example.com', 'result' => true], ['config' => '*//example.org *//example.com', 'url' => 'https://example.com/a/b/c?test=cat#hello', 'result' => true], ['config' => '*.example.org *.example.com', 'url' => 'https://example.co.uk', 'result' => false], ['config' => ' *.example.org *.example.com ', 'url' => 'https://example.co.uk', 'result' => false], ['config' => '* *.example.com', 'url' => 'https://example.co.uk', 'result' => true], ['config' => '*//example.org *//example.com *//example.co.uk', 'url' => 'https://example.co.uk', 'result' => true], ['config' => '*//example.org *//example.com *//example.co.uk', 'url' => 'https://example.net', 'result' => false], ]; foreach ($testMap as $test) { $result = (new SsrUrlValidator($test['config']))->allowed($test['url']); $this->assertEquals($test['result'], $result, "Failed asserting url '{$test['url']}' with config '{$test['config']}' results " . ($test['result'] ? 'true' : 'false')); } } public function test_enssure_allowed() { $result = (new SsrUrlValidator('https://example.com'))->ensureAllowed('https://example.com'); $this->assertNull($result); $this->expectException(HttpFetchException::class); (new SsrUrlValidator('https://example.com'))->ensureAllowed('https://test.example.com'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Unit/PageIncludeParserTest.php
tests/Unit/PageIncludeParserTest.php
<?php namespace Tests\Unit; use BookStack\Entities\Tools\PageIncludeContent; use BookStack\Entities\Tools\PageIncludeParser; use BookStack\Entities\Tools\PageIncludeTag; use BookStack\Util\HtmlDocument; use Tests\TestCase; class PageIncludeParserTest extends TestCase { public function test_simple_inline_text() { $this->runParserTest( '<p>{{@45#content}}</p>', ['45' => '<p id="content">Testing</p>'], '<p>Testing</p>', ); } public function test_simple_inline_text_with_existing_siblings() { $this->runParserTest( '<p>{{@45#content}} <strong>Hi</strong>there!</p>', ['45' => '<p id="content">Testing</p>'], '<p>Testing <strong>Hi</strong>there!</p>', ); } public function test_simple_inline_text_within_other_text() { $this->runParserTest( '<p>Hello {{@45#content}}there!</p>', ['45' => '<p id="content">Testing</p>'], '<p>Hello Testingthere!</p>', ); } public function test_complex_inline_text_within_other_text() { $this->runParserTest( '<p>Hello {{@45#content}}there!</p>', ['45' => '<p id="content"><strong>Testing</strong> with<em>some</em><i>extra</i>tags</p>'], '<p>Hello <strong>Testing</strong> with<em>some</em><i>extra</i>tagsthere!</p>', ); } public function test_block_content_types() { $inputs = [ '<table id="content"><td>Text</td></table>', '<ul id="content"><li>Item A</li></ul>', '<ol id="content"><li>Item A</li></ol>', '<pre id="content">Code</pre>', ]; foreach ($inputs as $input) { $this->runParserTest( '<p>A{{@45#content}}B</p>', ['45' => $input], '<p>A</p>' . $input . '<p>B</p>', ); } } public function test_block_content_nested_origin_gets_placed_before() { $this->runParserTest( '<p><strong>A {{@45#content}} there!</strong></p>', ['45' => '<pre id="content">Testing</pre>'], '<pre id="content">Testing</pre><p><strong>A there!</strong></p>', ); } public function test_block_content_nested_origin_gets_placed_after() { $this->runParserTest( '<p><strong>Some really good {{@45#content}} there!</strong></p>', ['45' => '<pre id="content">Testing</pre>'], '<p><strong>Some really good there!</strong></p><pre id="content">Testing</pre>', ); } public function test_block_content_in_shallow_origin_gets_split() { $this->runParserTest( '<p>Some really good {{@45#content}} there!</p>', ['45' => '<pre id="content">doggos</pre>'], '<p>Some really good </p><pre id="content">doggos</pre><p> there!</p>', ); } public function test_block_content_in_shallow_origin_split_does_not_duplicate_id() { $this->runParserTest( '<p id="test" title="Hi">Some really good {{@45#content}} there!</p>', ['45' => '<pre id="content">doggos</pre>'], '<p title="Hi">Some really good </p><pre id="content">doggos</pre><p id="test" title="Hi"> there!</p>', ); } public function test_block_content_in_shallow_origin_does_not_leave_empty_nodes() { $this->runParserTest( '<p>{{@45#content}}</p>', ['45' => '<pre id="content">doggos</pre>'], '<pre id="content">doggos</pre>', ); } public function test_block_content_in_allowable_parent_element() { $this->runParserTest( '<div>{{@45#content}}</div>', ['45' => '<pre id="content">doggos</pre>'], '<div><pre id="content">doggos</pre></div>', ); } public function test_block_content_in_paragraph_origin_with_allowable_grandparent() { $this->runParserTest( '<div><p>{{@45#content}}</p></div>', ['45' => '<pre id="content">doggos</pre>'], '<div><pre id="content">doggos</pre></div>', ); } public function test_block_content_in_paragraph_origin_with_allowable_grandparent_with_adjacent_content() { $this->runParserTest( '<div><p>Cute {{@45#content}} over there!</p></div>', ['45' => '<pre id="content">doggos</pre>'], '<div><p>Cute </p><pre id="content">doggos</pre><p> over there!</p></div>', ); } public function test_block_content_in_child_within_paragraph_origin_with_allowable_grandparent_with_adjacent_content() { $this->runParserTest( '<div><p><strong>Cute {{@45#content}} over there!</strong></p></div>', ['45' => '<pre id="content">doggos</pre>'], '<div><pre id="content">doggos</pre><p><strong>Cute over there!</strong></p></div>', ); } public function test_block_content_in_paragraph_origin_within_details() { $this->runParserTest( '<details><p>{{@45#content}}</p></details>', ['45' => '<pre id="content">doggos</pre>'], '<details><pre id="content">doggos</pre></details>', ); } public function test_simple_whole_document() { $this->runParserTest( '<p>{{@45}}</p>', ['45' => '<p id="content">Testing</p>'], '<p id="content">Testing</p>', ); } public function test_multi_source_elem_whole_document() { $this->runParserTest( '<p>{{@45}}</p>', ['45' => '<p>Testing</p><blockquote>This</blockquote>'], '<p>Testing</p><blockquote>This</blockquote>', ); } public function test_multi_source_elem_whole_document_with_shared_content_origin() { $this->runParserTest( '<p>This is {{@45}} some text</p>', ['45' => '<p>Testing</p><blockquote>This</blockquote>'], '<p>This is </p><p>Testing</p><blockquote>This</blockquote><p> some text</p>', ); } public function test_multi_source_elem_whole_document_with_nested_content_origin() { $this->runParserTest( '<p><strong>{{@45}}</strong></p>', ['45' => '<p>Testing</p><blockquote>This</blockquote>'], '<p>Testing</p><blockquote>This</blockquote>', ); } public function test_multiple_tags_in_same_origin_with_inline_content() { $this->runParserTest( '<p>This {{@45#content}}{{@45#content}} content is {{@45#content}}</p>', ['45' => '<p id="content">inline</p>'], '<p>This inlineinline content is inline</p>', ); } public function test_multiple_tags_in_same_origin_with_block_content() { $this->runParserTest( '<p>This {{@45#content}}{{@45#content}} content is {{@45#content}}</p>', ['45' => '<pre id="content">block</pre>'], '<p>This </p><pre id="content">block</pre><pre id="content">block</pre><p> content is </p><pre id="content">block</pre>', ); } public function test_multiple_tags_in_differing_origin_levels_with_block_content() { $this->runParserTest( '<div><p>This <strong>{{@45#content}}</strong> content is {{@45#content}}</p>{{@45#content}}</div>', ['45' => '<pre id="content">block</pre>'], '<div><pre id="content">block</pre><p>This content is </p><pre id="content">block</pre><pre id="content">block</pre></div>', ); } public function test_multiple_tags_in_shallow_origin_with_multi_block_content() { $this->runParserTest( '<p>{{@45}}C{{@45}}</p><div>{{@45}}{{@45}}</div>', ['45' => '<p>A</p><p>B</p>'], '<p>A</p><p>B</p><p>C</p><p>A</p><p>B</p><div><p>A</p><p>B</p><p>A</p><p>B</p></div>', ); } protected function runParserTest(string $html, array $contentById, string $expected): void { $doc = new HtmlDocument($html); $parser = new PageIncludeParser($doc, function (PageIncludeTag $tag) use ($contentById): PageIncludeContent { $html = $contentById[strval($tag->getPageId())] ?? ''; return PageIncludeContent::fromHtmlAndTag($html, $tag); }); $parser->parse(); $this->assertEquals($expected, $doc->getBodyInnerHtml()); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Unit/ConfigTest.php
tests/Unit/ConfigTest.php
<?php namespace Tests\Unit; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Mail; use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport; use Tests\TestCase; /** * Class ConfigTest * Many of the tests here are to check on tweaks made * to maintain backwards compatibility. */ class ConfigTest extends TestCase { public function test_filesystem_images_falls_back_to_storage_type_var() { $this->runWithEnv(['STORAGE_TYPE' => 'local_secure'], function () { $this->checkEnvConfigResult('STORAGE_IMAGE_TYPE', 's3', 'filesystems.images', 's3'); $this->checkEnvConfigResult('STORAGE_IMAGE_TYPE', null, 'filesystems.images', 'local_secure'); }); } public function test_filesystem_attachments_falls_back_to_storage_type_var() { $this->runWithEnv(['STORAGE_TYPE' => 'local_secure'], function () { $this->checkEnvConfigResult('STORAGE_ATTACHMENT_TYPE', 's3', 'filesystems.attachments', 's3'); $this->checkEnvConfigResult('STORAGE_ATTACHMENT_TYPE', null, 'filesystems.attachments', 'local_secure'); }); } public function test_app_url_blank_if_old_default_value() { $initUrl = 'https://example.com/docs'; $oldDefault = 'http://bookstack.dev'; $this->checkEnvConfigResult('APP_URL', $initUrl, 'app.url', $initUrl); $this->checkEnvConfigResult('APP_URL', $oldDefault, 'app.url', ''); } public function test_errorlog_plain_webserver_channel() { // We can't full test this due to it being targeted for the SAPI logging handler // so we just overwrite that component so we can capture the error log output. config()->set([ 'logging.channels.errorlog_plain_webserver.handler_with' => [0], ]); $temp = tempnam(sys_get_temp_dir(), 'bs-test'); $original = ini_set('error_log', $temp); Log::channel('errorlog_plain_webserver')->info('Aww, look, a cute puppy'); ini_set('error_log', $original); $output = file_get_contents($temp); $this->assertStringContainsString('Aww, look, a cute puppy', $output); $this->assertStringNotContainsString('INFO', $output); $this->assertStringNotContainsString('info', $output); $this->assertStringNotContainsString('testing', $output); } public function test_session_cookie_uses_sub_path_from_app_url() { $this->checkEnvConfigResult('APP_URL', 'https://example.com', 'session.path', '/'); $this->checkEnvConfigResult('APP_URL', 'https://a.com/b', 'session.path', '/b'); $this->checkEnvConfigResult('APP_URL', 'https://a.com/b/d/e', 'session.path', '/b/d/e'); $this->checkEnvConfigResult('APP_URL', '', 'session.path', '/'); } public function test_saml2_idp_authn_context_string_parsed_as_space_separated_array() { $this->checkEnvConfigResult( 'SAML2_IDP_AUTHNCONTEXT', 'urn:federation:authentication:windows urn:federation:authentication:linux', 'saml2.onelogin.security.requestedAuthnContext', ['urn:federation:authentication:windows', 'urn:federation:authentication:linux'] ); } public function test_dompdf_remote_fetching_controlled_by_allow_untrusted_server_fetching_false() { $this->checkEnvConfigResult('ALLOW_UNTRUSTED_SERVER_FETCHING', 'false', 'exports.dompdf.enable_remote', false); $this->checkEnvConfigResult('ALLOW_UNTRUSTED_SERVER_FETCHING', 'true', 'exports.dompdf.enable_remote', true); } public function test_dompdf_paper_size_options_are_limited() { $this->checkEnvConfigResult('EXPORT_PAGE_SIZE', 'cat', 'exports.dompdf.default_paper_size', 'a4'); $this->checkEnvConfigResult('EXPORT_PAGE_SIZE', 'letter', 'exports.dompdf.default_paper_size', 'letter'); $this->checkEnvConfigResult('EXPORT_PAGE_SIZE', 'a4', 'exports.dompdf.default_paper_size', 'a4'); } public function test_snappy_paper_size_options_are_limited() { $this->checkEnvConfigResult('EXPORT_PAGE_SIZE', 'cat', 'exports.snappy.options.page-size', 'A4'); $this->checkEnvConfigResult('EXPORT_PAGE_SIZE', 'letter', 'exports.snappy.options.page-size', 'Letter'); $this->checkEnvConfigResult('EXPORT_PAGE_SIZE', 'a4', 'exports.snappy.options.page-size', 'A4'); } public function test_sendmail_command_is_configurable() { $this->checkEnvConfigResult('MAIL_SENDMAIL_COMMAND', '/var/sendmail -o', 'mail.mailers.sendmail.path', '/var/sendmail -o'); } public function test_mail_disable_ssl_verification_alters_mailer() { $getStreamOptions = function (): array { /** @var EsmtpTransport $transport */ $transport = Mail::mailer('smtp')->getSymfonyTransport(); return $transport->getStream()->getStreamOptions(); }; $this->assertEmpty($getStreamOptions()); $this->runWithEnv(['MAIL_VERIFY_SSL' => 'false'], function () use ($getStreamOptions) { $options = $getStreamOptions(); $this->assertArrayHasKey('ssl', $options); $this->assertFalse($options['ssl']['verify_peer']); $this->assertFalse($options['ssl']['verify_peer_name']); }); } public function test_non_null_mail_encryption_options_enforce_smtp_scheme() { $this->checkEnvConfigResult('MAIL_ENCRYPTION', 'tls', 'mail.mailers.smtp.require_tls', true); $this->checkEnvConfigResult('MAIL_ENCRYPTION', 'ssl', 'mail.mailers.smtp.require_tls', true); $this->checkEnvConfigResult('MAIL_ENCRYPTION', 'null', 'mail.mailers.smtp.require_tls', false); } public function test_smtp_scheme_and_certain_port_forces_tls_usage() { $isMailTlsRequired = function () { /** @var EsmtpTransport $transport */ $transport = Mail::mailer('smtp')->getSymfonyTransport(); Mail::purge('smtp'); return $transport->isTlsRequired(); }; $runTest = function (string $tlsOption, int $port, bool $expectedResult) use ($isMailTlsRequired) { $this->runWithEnv(['MAIL_ENCRYPTION' => $tlsOption, 'MAIL_PORT' => $port], function () use ($isMailTlsRequired, $port, $expectedResult) { $this->assertEquals($expectedResult, $isMailTlsRequired()); }); }; $runTest('null', 587, false); $runTest('tls', 587, true); $runTest('null', 465, true); } public function test_mysql_host_parsed_as_expected() { $cases = [ '127.0.0.1' => ['127.0.0.1', 3306], '127.0.0.1:3307' => ['127.0.0.1', 3307], 'a.example.com' => ['a.example.com', 3306], 'a.example.com:3307' => ['a.example.com', 3307], '[::1]' => ['[::1]', 3306], '[::1]:123' => ['[::1]', 123], '[2001:db8:3c4d:0015:0000:0000:1a2f]' => ['[2001:db8:3c4d:0015:0000:0000:1a2f]', 3306], '[2001:db8:3c4d:0015:0000:0000:1a2f]:4567' => ['[2001:db8:3c4d:0015:0000:0000:1a2f]', 4567], ]; foreach ($cases as $host => [$expectedHost, $expectedPort]) { $this->runWithEnv(["DB_HOST" => $host], function () use ($expectedHost, $expectedPort) { $this->assertEquals($expectedHost, config("database.connections.mysql.host")); $this->assertEquals($expectedPort, config("database.connections.mysql.port")); }, false); } } /** * Set an environment variable of the given name and value * then check the given config key to see if it matches the given result. * Providing a null $envVal clears the variable. */ protected function checkEnvConfigResult(string $envName, ?string $envVal, string $configKey, mixed $expectedResult): void { $this->runWithEnv([$envName => $envVal], function () use ($configKey, $expectedResult) { $this->assertEquals($expectedResult, config($configKey)); }); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Api/BooksApiTest.php
tests/Api/BooksApiTest.php
<?php namespace Tests\Api; use BookStack\Entities\Models\Book; use BookStack\Entities\Repos\BaseRepo; use Carbon\Carbon; use Tests\TestCase; class BooksApiTest extends TestCase { use TestsApi; protected string $baseEndpoint = '/api/books'; public function test_index_endpoint_returns_expected_book() { $this->actingAsApiEditor(); $firstBook = Book::query()->orderBy('id', 'asc')->first(); $resp = $this->getJson($this->baseEndpoint . '?count=1&sort=+id'); $resp->assertJson(['data' => [ [ 'id' => $firstBook->id, 'name' => $firstBook->name, 'slug' => $firstBook->slug, 'owned_by' => $firstBook->owned_by, 'created_by' => $firstBook->created_by, 'updated_by' => $firstBook->updated_by, 'cover' => null, ], ]]); } public function test_index_endpoint_includes_cover_if_set() { $this->actingAsApiEditor(); $book = $this->entities->book(); $baseRepo = $this->app->make(BaseRepo::class); $image = $this->files->uploadedImage('book_cover'); $baseRepo->updateCoverImage($book, $image); $resp = $this->getJson($this->baseEndpoint . '?filter[id]=' . $book->id); $resp->assertJson(['data' => [ [ 'id' => $book->id, 'cover' => [ 'id' => $book->coverInfo()->getImage()->id, 'url' => $book->coverInfo()->getImage()->url, ], ], ]]); } public function test_create_endpoint() { $this->actingAsApiEditor(); $templatePage = $this->entities->templatePage(); $details = [ 'name' => 'My API book', 'description' => 'A book created via the API', 'default_template_id' => $templatePage->id, ]; $resp = $this->postJson($this->baseEndpoint, $details); $resp->assertStatus(200); $newItem = Book::query()->orderByDesc('id')->where('name', '=', $details['name'])->first(); $resp->assertJson(array_merge($details, [ 'id' => $newItem->id, 'slug' => $newItem->slug, 'description_html' => '<p>A book created via the API</p>', ])); $this->assertActivityExists('book_create', $newItem); } public function test_create_endpoint_with_html() { $this->actingAsApiEditor(); $details = [ 'name' => 'My API book', 'description_html' => '<p>A book <em>created</em> <strong>via</strong> the API</p>', ]; $resp = $this->postJson($this->baseEndpoint, $details); $resp->assertStatus(200); $newItem = Book::query()->orderByDesc('id')->where('name', '=', $details['name'])->first(); $expectedDetails = array_merge($details, [ 'id' => $newItem->id, 'description' => 'A book created via the API', ]); $resp->assertJson($expectedDetails); $this->assertDatabaseHasEntityData('book', $expectedDetails); } public function test_book_name_needed_to_create() { $this->actingAsApiEditor(); $details = [ 'description' => 'A book created via the API', ]; $resp = $this->postJson($this->baseEndpoint, $details); $resp->assertStatus(422); $resp->assertJson([ 'error' => [ 'message' => 'The given data was invalid.', 'validation' => [ 'name' => ['The name field is required.'], ], 'code' => 422, ], ]); } public function test_read_endpoint() { $this->actingAsApiEditor(); $book = $this->entities->book(); $resp = $this->getJson($this->baseEndpoint . "/{$book->id}"); $resp->assertStatus(200); $resp->assertJson([ 'id' => $book->id, 'slug' => $book->slug, 'created_by' => [ 'name' => $book->createdBy->name, ], 'updated_by' => [ 'name' => $book->createdBy->name, ], 'owned_by' => [ 'name' => $book->ownedBy->name, ], 'default_template_id' => null, ]); } public function test_read_endpoint_includes_chapter_and_page_contents() { $this->actingAsApiEditor(); $book = $this->entities->bookHasChaptersAndPages(); $chapter = $book->chapters()->first(); $chapterPage = $chapter->pages()->first(); $resp = $this->getJson($this->baseEndpoint . "/{$book->id}"); $directChildCount = $book->directPages()->count() + $book->chapters()->count(); $resp->assertStatus(200); $resp->assertJsonCount($directChildCount, 'contents'); $contents = $resp->json('contents'); $respChapter = array_values(array_filter($contents, fn ($item) => ($item['id'] === $chapter->id && $item['type'] === 'chapter')))[0]; $this->assertArrayMapIncludes([ 'id' => $chapter->id, 'type' => 'chapter', 'name' => $chapter->name, 'slug' => $chapter->slug, ], $respChapter); $respPage = array_values(array_filter($respChapter['pages'], fn ($item) => ($item['id'] === $chapterPage->id)))[0]; $this->assertArrayMapIncludes([ 'id' => $chapterPage->id, 'name' => $chapterPage->name, 'slug' => $chapterPage->slug, ], $respPage); } public function test_read_endpoint_contents_nested_pages_has_permissions_applied() { $this->actingAsApiEditor(); $book = $this->entities->bookHasChaptersAndPages(); $chapter = $book->chapters()->first(); $chapterPage = $chapter->pages()->first(); $customName = 'MyNonVisiblePageWithinAChapter'; $chapterPage->name = $customName; $chapterPage->save(); $this->permissions->disableEntityInheritedPermissions($chapterPage); $resp = $this->getJson($this->baseEndpoint . "/{$book->id}"); $resp->assertJsonMissing(['name' => $customName]); } public function test_update_endpoint() { $this->actingAsApiEditor(); $book = $this->entities->book(); $templatePage = $this->entities->templatePage(); $details = [ 'name' => 'My updated API book', 'description' => 'A book updated via the API', 'default_template_id' => $templatePage->id, ]; $resp = $this->putJson($this->baseEndpoint . "/{$book->id}", $details); $book->refresh(); $resp->assertStatus(200); $resp->assertJson(array_merge($details, [ 'id' => $book->id, 'slug' => $book->slug, 'description_html' => '<p>A book updated via the API</p>', ])); $this->assertActivityExists('book_update', $book); } public function test_update_endpoint_with_html() { $this->actingAsApiEditor(); $book = $this->entities->book(); $details = [ 'name' => 'My updated API book', 'description_html' => '<p>A book <strong>updated</strong> via the API</p>', ]; $resp = $this->putJson($this->baseEndpoint . "/{$book->id}", $details); $resp->assertStatus(200); $this->assertDatabaseHasEntityData('book', array_merge($details, ['id' => $book->id, 'description' => 'A book updated via the API'])); } public function test_update_increments_updated_date_if_only_tags_are_sent() { $this->actingAsApiEditor(); $book = $this->entities->book(); Book::query()->where('id', '=', $book->id)->update(['updated_at' => Carbon::now()->subWeek()]); $details = [ 'tags' => [['name' => 'Category', 'value' => 'Testing']], ]; $this->putJson($this->baseEndpoint . "/{$book->id}", $details); $book->refresh(); $this->assertGreaterThan(Carbon::now()->subDay()->unix(), $book->updated_at->unix()); } public function test_update_cover_image_control() { $this->actingAsApiEditor(); /** @var Book $book */ $book = $this->entities->book(); $this->assertNull($book->coverInfo()->getImage()); $file = $this->files->uploadedImage('image.png'); // Ensure cover image can be set via API $resp = $this->call('PUT', $this->baseEndpoint . "/{$book->id}", [ 'name' => 'My updated API book with image', ], [], ['image' => $file]); $book->refresh(); $resp->assertStatus(200); $this->assertNotNull($book->coverInfo()->getImage()); // Ensure further updates without image do not clear cover image $resp = $this->put($this->baseEndpoint . "/{$book->id}", [ 'name' => 'My updated book again', ]); $book->refresh(); $resp->assertStatus(200); $this->assertNotNull($book->coverInfo()->getImage()); // Ensure update with null image property clears image $resp = $this->put($this->baseEndpoint . "/{$book->id}", [ 'image' => null, ]); $book->refresh(); $resp->assertStatus(200); $this->assertNull($book->coverInfo()->getImage()); } public function test_delete_endpoint() { $this->actingAsApiEditor(); $book = $this->entities->book(); $resp = $this->deleteJson($this->baseEndpoint . "/{$book->id}"); $resp->assertStatus(204); $this->assertActivityExists('book_delete'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Api/AttachmentsApiTest.php
tests/Api/AttachmentsApiTest.php
<?php namespace Tests\Api; use BookStack\Entities\Models\Page; use BookStack\Uploads\Attachment; use Illuminate\Http\UploadedFile; use Illuminate\Testing\AssertableJsonString; use Tests\TestCase; class AttachmentsApiTest extends TestCase { use TestsApi; protected string $baseEndpoint = '/api/attachments'; public function test_index_endpoint_returns_expected_book() { $this->actingAsApiEditor(); $page = $this->entities->page(); $attachment = $this->createAttachmentForPage($page, [ 'name' => 'My test attachment', 'external' => true, ]); $resp = $this->getJson($this->baseEndpoint . '?count=1&sort=+id'); $resp->assertJson(['data' => [ [ 'id' => $attachment->id, 'name' => 'My test attachment', 'uploaded_to' => $page->id, 'external' => true, ], ]]); } public function test_attachments_listing_based_upon_page_visibility() { $this->actingAsApiEditor(); $page = $this->entities->page(); $attachment = $this->createAttachmentForPage($page, [ 'name' => 'My test attachment', 'external' => true, ]); $resp = $this->getJson($this->baseEndpoint . '?count=1&sort=+id'); $resp->assertJson(['data' => [ [ 'id' => $attachment->id, ], ]]); $this->permissions->setEntityPermissions($page, [], []); $resp = $this->getJson($this->baseEndpoint . '?count=1&sort=+id'); $resp->assertJsonMissing(['data' => [ [ 'id' => $attachment->id, ], ]]); } public function test_create_endpoint_for_link_attachment() { $this->actingAsApiAdmin(); $page = $this->entities->page(); $details = [ 'name' => 'My attachment', 'uploaded_to' => $page->id, 'link' => 'https://cats.example.com', ]; $resp = $this->postJson($this->baseEndpoint, $details); $resp->assertStatus(200); /** @var Attachment $newItem */ $newItem = Attachment::query()->orderByDesc('id')->where('name', '=', $details['name'])->first(); $resp->assertJson(['id' => $newItem->id, 'external' => true, 'name' => $details['name'], 'uploaded_to' => $page->id]); } public function test_create_endpoint_for_upload_attachment() { $this->actingAsApiAdmin(); $page = $this->entities->page(); $file = $this->getTestFile('textfile.txt'); $details = [ 'name' => 'My attachment', 'uploaded_to' => $page->id, ]; $resp = $this->call('POST', $this->baseEndpoint, $details, [], ['file' => $file]); $resp->assertStatus(200); /** @var Attachment $newItem */ $newItem = Attachment::query()->orderByDesc('id')->where('name', '=', $details['name'])->first(); $resp->assertJson(['id' => $newItem->id, 'external' => false, 'extension' => 'txt', 'name' => $details['name'], 'uploaded_to' => $page->id]); $this->assertTrue(file_exists(storage_path($newItem->path))); unlink(storage_path($newItem->path)); } public function test_upload_limit_restricts_attachment_uploads() { $this->actingAsApiAdmin(); $page = $this->entities->page(); config()->set('app.upload_limit', 1); $file = tmpfile(); $filePath = stream_get_meta_data($file)['uri']; fwrite($file, str_repeat('a', 1200000)); $file = new UploadedFile($filePath, 'test.txt', 'text/plain', null, true); $details = [ 'name' => 'My attachment', 'uploaded_to' => $page->id, ]; $resp = $this->call('POST', $this->baseEndpoint, $details, [], ['file' => $file]); $resp->assertStatus(422); $resp->assertJson($this->validationResponse([ 'file' => ['The file may not be greater than 1000 kilobytes.'], ])); } public function test_name_needed_to_create() { $this->actingAsApiAdmin(); $page = $this->entities->page(); $details = [ 'uploaded_to' => $page->id, 'link' => 'https://example.com', ]; $resp = $this->postJson($this->baseEndpoint, $details); $resp->assertStatus(422); $resp->assertJson($this->validationResponse(['name' => ['The name field is required.']])); } public function test_link_or_file_needed_to_create() { $this->actingAsApiAdmin(); $page = $this->entities->page(); $details = [ 'name' => 'my attachment', 'uploaded_to' => $page->id, ]; $resp = $this->postJson($this->baseEndpoint, $details); $resp->assertStatus(422); $resp->assertJson($this->validationResponse([ 'file' => ['The file field is required when link is not present.'], 'link' => ['The link field is required when file is not present.'], ])); } public function test_message_shown_if_file_is_not_a_valid_file() { $this->actingAsApiAdmin(); $page = $this->entities->page(); $details = [ 'name' => 'my attachment', 'uploaded_to' => $page->id, 'file' => 'cat', ]; $resp = $this->postJson($this->baseEndpoint, $details); $resp->assertStatus(422); $resp->assertJson($this->validationResponse(['file' => ['The file must be provided as a valid file.']])); } public function test_read_endpoint_for_link_attachment() { $this->actingAsApiAdmin(); $page = $this->entities->page(); $attachment = $this->createAttachmentForPage($page, [ 'name' => 'my attachment', 'path' => 'https://example.com', 'order' => 1, ]); $resp = $this->getJson("{$this->baseEndpoint}/{$attachment->id}"); $resp->assertStatus(200); $resp->assertJson([ 'id' => $attachment->id, 'content' => 'https://example.com', 'external' => true, 'uploaded_to' => $page->id, 'order' => 1, 'created_by' => [ 'name' => $attachment->createdBy->name, ], 'updated_by' => [ 'name' => $attachment->createdBy->name, ], 'links' => [ 'html' => "<a target=\"_blank\" href=\"http://localhost/attachments/{$attachment->id}\">my attachment</a>", 'markdown' => "[my attachment](http://localhost/attachments/{$attachment->id})", ], ]); } public function test_read_endpoint_for_file_attachment() { $this->actingAsApiAdmin(); $page = $this->entities->page(); $file = $this->getTestFile('textfile.txt'); $details = [ 'name' => 'My file attachment', 'uploaded_to' => $page->id, ]; $this->call('POST', $this->baseEndpoint, $details, [], ['file' => $file]); /** @var Attachment $attachment */ $attachment = Attachment::query()->orderByDesc('id')->where('name', '=', $details['name'])->firstOrFail(); $resp = $this->getJson("{$this->baseEndpoint}/{$attachment->id}"); $resp->assertStatus(200); $resp->assertHeader('Content-Type', 'application/json'); $json = new AssertableJsonString($resp->streamedContent()); $json->assertSubset([ 'id' => $attachment->id, 'content' => base64_encode(file_get_contents(storage_path($attachment->path))), 'external' => false, 'uploaded_to' => $page->id, 'order' => 1, 'created_by' => [ 'name' => $attachment->createdBy->name, ], 'updated_by' => [ 'name' => $attachment->updatedBy->name, ], 'links' => [ 'html' => "<a target=\"_blank\" href=\"http://localhost/attachments/{$attachment->id}\">My file attachment</a>", 'markdown' => "[My file attachment](http://localhost/attachments/{$attachment->id})", ], ]); unlink(storage_path($attachment->path)); } public function test_attachment_not_visible_on_other_users_draft() { $this->actingAsApiAdmin(); $editor = $this->users->editor(); $page = $this->entities->page(); $page->draft = true; $page->owned_by = $editor->id; $page->save(); $this->permissions->regenerateForEntity($page); $attachment = $this->createAttachmentForPage($page, [ 'name' => 'my attachment', 'path' => 'https://example.com', 'order' => 1, ]); $resp = $this->getJson("{$this->baseEndpoint}/{$attachment->id}"); $resp->assertStatus(404); } public function test_update_endpoint() { $this->actingAsApiAdmin(); $page = $this->entities->page(); $attachment = $this->createAttachmentForPage($page); $details = [ 'name' => 'My updated API attachment', ]; $resp = $this->putJson("{$this->baseEndpoint}/{$attachment->id}", $details); $attachment->refresh(); $resp->assertStatus(200); $resp->assertJson(['id' => $attachment->id, 'name' => 'My updated API attachment']); } public function test_update_link_attachment_to_file() { $this->actingAsApiAdmin(); $page = $this->entities->page(); $attachment = $this->createAttachmentForPage($page); $file = $this->getTestFile('textfile.txt'); $resp = $this->call('PUT', "{$this->baseEndpoint}/{$attachment->id}", ['name' => 'My updated file'], [], ['file' => $file]); $resp->assertStatus(200); $attachment->refresh(); $this->assertFalse($attachment->external); $this->assertEquals('txt', $attachment->extension); $this->assertStringStartsWith('uploads/files/', $attachment->path); $this->assertFileExists(storage_path($attachment->path)); unlink(storage_path($attachment->path)); } public function test_update_file_attachment_to_link() { $this->actingAsApiAdmin(); $page = $this->entities->page(); $attachment = $this->createAttachmentForPage($page); $resp = $this->putJson("{$this->baseEndpoint}/{$attachment->id}", [ 'link' => 'https://example.com/donkey', ]); $resp->assertStatus(200); $this->assertDatabaseHas('attachments', [ 'id' => $attachment->id, 'path' => 'https://example.com/donkey', ]); } public function test_update_does_not_require_name() { $this->actingAsApiAdmin(); $page = $this->entities->page(); $file = $this->getTestFile('textfile.txt'); $this->call('POST', $this->baseEndpoint, ['name' => 'My file attachment', 'uploaded_to' => $page->id], [], ['file' => $file]); /** @var Attachment $attachment */ $attachment = Attachment::query()->where('name', '=', 'My file attachment')->firstOrFail(); $filePath = storage_path($attachment->path); $this->assertFileExists($filePath); $details = [ 'name' => 'My updated API attachment', 'link' => 'https://cats.example.com', ]; $resp = $this->putJson("{$this->baseEndpoint}/{$attachment->id}", $details); $resp->assertStatus(200); $attachment->refresh(); $this->assertFileDoesNotExist($filePath); $this->assertTrue($attachment->external); $this->assertEquals('https://cats.example.com', $attachment->path); $this->assertEquals('', $attachment->extension); } public function test_delete_endpoint() { $this->actingAsApiAdmin(); $page = $this->entities->page(); $attachment = $this->createAttachmentForPage($page); $resp = $this->deleteJson("{$this->baseEndpoint}/{$attachment->id}"); $resp->assertStatus(204); $this->assertDatabaseMissing('attachments', ['id' => $attachment->id]); } protected function createAttachmentForPage(Page $page, $attributes = []): Attachment { $admin = $this->users->admin(); /** @var Attachment $attachment */ $attachment = $page->attachments()->forceCreate(array_merge([ 'uploaded_to' => $page->id, 'name' => 'test attachment', 'external' => true, 'order' => 1, 'created_by' => $admin->id, 'updated_by' => $admin->id, 'path' => 'https://attachment.example.com', ], $attributes)); return $attachment; } /** * Get a test file that can be uploaded. */ protected function getTestFile(string $fileName): UploadedFile { return new UploadedFile(base_path('tests/test-data/test-file.txt'), $fileName, 'text/plain', null, true); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Api/ExportsApiTest.php
tests/Api/ExportsApiTest.php
<?php namespace Tests\Api; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Chapter; use Tests\Exports\ZipTestHelper; use Tests\TestCase; class ExportsApiTest extends TestCase { use TestsApi; public function test_book_html_endpoint() { $this->actingAsApiEditor(); $book = $this->entities->book(); $resp = $this->get("/api/books/{$book->id}/export/html"); $resp->assertStatus(200); $resp->assertSee($book->name); $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $book->slug . '.html"'); } public function test_book_plain_text_endpoint() { $this->actingAsApiEditor(); $book = $this->entities->book(); $resp = $this->get("/api/books/{$book->id}/export/plaintext"); $resp->assertStatus(200); $resp->assertSee($book->name); $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $book->slug . '.txt"'); } public function test_book_pdf_endpoint() { $this->actingAsApiEditor(); $book = $this->entities->book(); $resp = $this->get("/api/books/{$book->id}/export/pdf"); $resp->assertStatus(200); $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $book->slug . '.pdf"'); } public function test_book_markdown_endpoint() { $this->actingAsApiEditor(); $book = Book::visible()->has('pages')->has('chapters')->first(); $resp = $this->get("/api/books/{$book->id}/export/markdown"); $resp->assertStatus(200); $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $book->slug . '.md"'); $resp->assertSee('# ' . $book->name); $resp->assertSee('# ' . $book->pages()->first()->name); $resp->assertSee('# ' . $book->chapters()->first()->name); } public function test_book_zip_endpoint() { $this->actingAsApiEditor(); $book = Book::visible()->has('pages')->has('chapters')->first(); $resp = $this->get("/api/books/{$book->id}/export/zip"); $resp->assertStatus(200); $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $book->slug . '.zip"'); $zip = ZipTestHelper::extractFromZipResponse($resp); $this->assertArrayHasKey('book', $zip->data); } public function test_chapter_html_endpoint() { $this->actingAsApiEditor(); $chapter = $this->entities->chapter(); $resp = $this->get("/api/chapters/{$chapter->id}/export/html"); $resp->assertStatus(200); $resp->assertSee($chapter->name); $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $chapter->slug . '.html"'); } public function test_chapter_plain_text_endpoint() { $this->actingAsApiEditor(); $chapter = $this->entities->chapter(); $resp = $this->get("/api/chapters/{$chapter->id}/export/plaintext"); $resp->assertStatus(200); $resp->assertSee($chapter->name); $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $chapter->slug . '.txt"'); } public function test_chapter_pdf_endpoint() { $this->actingAsApiEditor(); $chapter = $this->entities->chapter(); $resp = $this->get("/api/chapters/{$chapter->id}/export/pdf"); $resp->assertStatus(200); $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $chapter->slug . '.pdf"'); } public function test_chapter_markdown_endpoint() { $this->actingAsApiEditor(); $chapter = Chapter::visible()->has('pages')->first(); $resp = $this->get("/api/chapters/{$chapter->id}/export/markdown"); $resp->assertStatus(200); $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $chapter->slug . '.md"'); $resp->assertSee('# ' . $chapter->name); $resp->assertSee('# ' . $chapter->pages()->first()->name); } public function test_chapter_zip_endpoint() { $this->actingAsApiEditor(); $chapter = Chapter::visible()->has('pages')->first(); $resp = $this->get("/api/chapters/{$chapter->id}/export/zip"); $resp->assertStatus(200); $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $chapter->slug . '.zip"'); $zip = ZipTestHelper::extractFromZipResponse($resp); $this->assertArrayHasKey('chapter', $zip->data); } public function test_page_html_endpoint() { $this->actingAsApiEditor(); $page = $this->entities->page(); $resp = $this->get("/api/pages/{$page->id}/export/html"); $resp->assertStatus(200); $resp->assertSee($page->name); $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $page->slug . '.html"'); } public function test_page_plain_text_endpoint() { $this->actingAsApiEditor(); $page = $this->entities->page(); $resp = $this->get("/api/pages/{$page->id}/export/plaintext"); $resp->assertStatus(200); $resp->assertSee($page->name); $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $page->slug . '.txt"'); } public function test_page_pdf_endpoint() { $this->actingAsApiEditor(); $page = $this->entities->page(); $resp = $this->get("/api/pages/{$page->id}/export/pdf"); $resp->assertStatus(200); $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $page->slug . '.pdf"'); } public function test_page_markdown_endpoint() { $this->actingAsApiEditor(); $page = $this->entities->page(); $resp = $this->get("/api/pages/{$page->id}/export/markdown"); $resp->assertStatus(200); $resp->assertSee('# ' . $page->name); $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $page->slug . '.md"'); } public function test_page_zip_endpoint() { $this->actingAsApiEditor(); $page = $this->entities->page(); $resp = $this->get("/api/pages/{$page->id}/export/zip"); $resp->assertStatus(200); $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $page->slug . '.zip"'); $zip = ZipTestHelper::extractFromZipResponse($resp); $this->assertArrayHasKey('page', $zip->data); } public function test_cant_export_when_not_have_permission() { $types = ['html', 'plaintext', 'pdf', 'markdown', 'zip']; $this->actingAsApiEditor(); $this->permissions->removeUserRolePermissions($this->users->editor(), ['content-export']); $book = $this->entities->book(); foreach ($types as $type) { $resp = $this->get("/api/books/{$book->id}/export/{$type}"); $this->assertPermissionError($resp); } $chapter = Chapter::visible()->has('pages')->first(); foreach ($types as $type) { $resp = $this->get("/api/chapters/{$chapter->id}/export/{$type}"); $this->assertPermissionError($resp); } $page = $this->entities->page(); foreach ($types as $type) { $resp = $this->get("/api/pages/{$page->id}/export/{$type}"); $this->assertPermissionError($resp); } } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Api/ShelvesApiTest.php
tests/Api/ShelvesApiTest.php
<?php namespace Tests\Api; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Bookshelf; use BookStack\Entities\Repos\BaseRepo; use Carbon\Carbon; use Illuminate\Support\Facades\DB; use Tests\TestCase; class ShelvesApiTest extends TestCase { use TestsApi; protected string $baseEndpoint = '/api/shelves'; public function test_index_endpoint_returns_expected_shelf() { $this->actingAsApiEditor(); $firstBookshelf = Bookshelf::query()->orderBy('id', 'asc')->first(); $resp = $this->getJson($this->baseEndpoint . '?count=1&sort=+id'); $resp->assertJson(['data' => [ [ 'id' => $firstBookshelf->id, 'name' => $firstBookshelf->name, 'slug' => $firstBookshelf->slug, 'owned_by' => $firstBookshelf->owned_by, 'created_by' => $firstBookshelf->created_by, 'updated_by' => $firstBookshelf->updated_by, 'cover' => null, ], ]]); } public function test_index_endpoint_includes_cover_if_set() { $this->actingAsApiEditor(); $shelf = $this->entities->shelf(); $baseRepo = $this->app->make(BaseRepo::class); $image = $this->files->uploadedImage('shelf_cover'); $baseRepo->updateCoverImage($shelf, $image); $resp = $this->getJson($this->baseEndpoint . '?filter[id]=' . $shelf->id); $resp->assertJson(['data' => [ [ 'id' => $shelf->id, 'cover' => [ 'id' => $shelf->coverInfo()->getImage()->id, 'url' => $shelf->coverInfo()->getImage()->url, ], ], ]]); } public function test_create_endpoint() { $this->actingAsApiEditor(); $books = Book::query()->take(2)->get(); $details = [ 'name' => 'My API shelf', 'description' => 'A shelf created via the API', ]; $resp = $this->postJson($this->baseEndpoint, array_merge($details, ['books' => [$books[0]->id, $books[1]->id]])); $resp->assertStatus(200); $newItem = Bookshelf::query()->orderByDesc('id')->where('name', '=', $details['name'])->first(); $resp->assertJson(array_merge($details, [ 'id' => $newItem->id, 'slug' => $newItem->slug, 'description_html' => '<p>A shelf created via the API</p>', ])); $this->assertActivityExists('bookshelf_create', $newItem); foreach ($books as $index => $book) { $this->assertDatabaseHas('bookshelves_books', [ 'bookshelf_id' => $newItem->id, 'book_id' => $book->id, 'order' => $index, ]); } } public function test_create_endpoint_with_html() { $this->actingAsApiEditor(); $details = [ 'name' => 'My API shelf', 'description_html' => '<p>A <strong>shelf</strong> created via the API</p>', ]; $resp = $this->postJson($this->baseEndpoint, $details); $resp->assertStatus(200); $newItem = Bookshelf::query()->orderByDesc('id')->where('name', '=', $details['name'])->first(); $expectedDetails = array_merge($details, [ 'id' => $newItem->id, 'description' => 'A shelf created via the API', ]); $resp->assertJson($expectedDetails); $this->assertDatabaseHasEntityData('bookshelf', $expectedDetails); } public function test_shelf_name_needed_to_create() { $this->actingAsApiEditor(); $details = [ 'description' => 'A shelf created via the API', ]; $resp = $this->postJson($this->baseEndpoint, $details); $resp->assertStatus(422); $resp->assertJson([ 'error' => [ 'message' => 'The given data was invalid.', 'validation' => [ 'name' => ['The name field is required.'], ], 'code' => 422, ], ]); } public function test_read_endpoint() { $this->actingAsApiEditor(); $shelf = Bookshelf::visible()->first(); $resp = $this->getJson($this->baseEndpoint . "/{$shelf->id}"); $resp->assertStatus(200); $resp->assertJson([ 'id' => $shelf->id, 'slug' => $shelf->slug, 'created_by' => [ 'name' => $shelf->createdBy->name, ], 'updated_by' => [ 'name' => $shelf->createdBy->name, ], 'owned_by' => [ 'name' => $shelf->ownedBy->name, ], ]); } public function test_update_endpoint() { $this->actingAsApiEditor(); $shelf = Bookshelf::visible()->first(); $details = [ 'name' => 'My updated API shelf', 'description' => 'A shelf updated via the API', ]; $resp = $this->putJson($this->baseEndpoint . "/{$shelf->id}", $details); $shelf->refresh(); $resp->assertStatus(200); $resp->assertJson(array_merge($details, [ 'id' => $shelf->id, 'slug' => $shelf->slug, 'description_html' => '<p>A shelf updated via the API</p>', ])); $this->assertActivityExists('bookshelf_update', $shelf); } public function test_update_endpoint_with_html() { $this->actingAsApiEditor(); $shelf = Bookshelf::visible()->first(); $details = [ 'name' => 'My updated API shelf', 'description_html' => '<p>A shelf <em>updated</em> via the API</p>', ]; $resp = $this->putJson($this->baseEndpoint . "/{$shelf->id}", $details); $resp->assertStatus(200); $this->assertDatabaseHasEntityData('bookshelf', array_merge($details, ['id' => $shelf->id, 'description' => 'A shelf updated via the API'])); } public function test_update_increments_updated_date_if_only_tags_are_sent() { $this->actingAsApiEditor(); $shelf = Bookshelf::visible()->first(); $shelf->newQuery()->where('id', '=', $shelf->id)->update(['updated_at' => Carbon::now()->subWeek()]); $details = [ 'tags' => [['name' => 'Category', 'value' => 'Testing']], ]; $this->putJson($this->baseEndpoint . "/{$shelf->id}", $details); $shelf->refresh(); $this->assertGreaterThan(Carbon::now()->subDay()->unix(), $shelf->updated_at->unix()); } public function test_update_only_assigns_books_if_param_provided() { $this->actingAsApiEditor(); $shelf = Bookshelf::visible()->first(); $this->assertTrue($shelf->books()->count() > 0); $details = [ 'name' => 'My updated API shelf', ]; $resp = $this->putJson($this->baseEndpoint . "/{$shelf->id}", $details); $resp->assertStatus(200); $this->assertTrue($shelf->books()->count() > 0); $resp = $this->putJson($this->baseEndpoint . "/{$shelf->id}", ['books' => []]); $resp->assertStatus(200); $this->assertTrue($shelf->books()->count() === 0); } public function test_update_cover_image_control() { $this->actingAsApiEditor(); /** @var Book $shelf */ $shelf = Bookshelf::visible()->first(); $this->assertNull($shelf->coverInfo()->getImage()); $file = $this->files->uploadedImage('image.png'); // Ensure cover image can be set via API $resp = $this->call('PUT', $this->baseEndpoint . "/{$shelf->id}", [ 'name' => 'My updated API shelf with image', ], [], ['image' => $file]); $shelf->refresh(); $resp->assertStatus(200); $this->assertNotNull($shelf->coverInfo()->getImage()); // Ensure further updates without image do not clear cover image $resp = $this->put($this->baseEndpoint . "/{$shelf->id}", [ 'name' => 'My updated shelf again', ]); $shelf->refresh(); $resp->assertStatus(200); $this->assertNotNull($shelf->coverInfo()->getImage()); // Ensure update with null image property clears image $resp = $this->put($this->baseEndpoint . "/{$shelf->id}", [ 'image' => null, ]); $shelf->refresh(); $resp->assertStatus(200); $this->assertNull($shelf->coverInfo()->getImage()); } public function test_delete_endpoint() { $this->actingAsApiEditor(); $shelf = Bookshelf::visible()->first(); $resp = $this->deleteJson($this->baseEndpoint . "/{$shelf->id}"); $resp->assertStatus(204); $this->assertActivityExists('bookshelf_delete'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Api/ApiListingTest.php
tests/Api/ApiListingTest.php
<?php namespace Tests\Api; use BookStack\Entities\Models\Book; use Tests\TestCase; class ApiListingTest extends TestCase { use TestsApi; protected $endpoint = '/api/books'; public function test_count_parameter_limits_responses() { $this->actingAsApiEditor(); $bookCount = min(Book::visible()->count(), 100); $resp = $this->get($this->endpoint); $resp->assertJsonCount($bookCount, 'data'); $resp = $this->get($this->endpoint . '?count=1'); $resp->assertJsonCount(1, 'data'); } public function test_offset_parameter() { $this->actingAsApiEditor(); $books = Book::visible()->orderBy('id')->take(3)->get(); $resp = $this->get($this->endpoint . '?count=1'); $resp->assertJsonMissing(['name' => $books[1]->name]); $resp = $this->get($this->endpoint . '?count=1&offset=1000'); $resp->assertJsonCount(0, 'data'); } public function test_sort_parameter() { $this->actingAsApiEditor(); $sortChecks = [ '-id' => Book::visible()->orderBy('id', 'desc')->first(), '+name' => Book::visible()->orderBy('name', 'asc')->first(), 'name' => Book::visible()->orderBy('name', 'asc')->first(), '-name' => Book::visible()->orderBy('name', 'desc')->first(), ]; foreach ($sortChecks as $sortOption => $result) { $resp = $this->get($this->endpoint . '?count=1&sort=' . $sortOption); $resp->assertJson(['data' => [ [ 'id' => $result->id, 'name' => $result->name, ], ]]); } } public function test_filter_parameter() { $this->actingAsApiEditor(); $book = Book::visible()->first(); $nameSubstr = substr($book->name, 0, 4); $encodedNameSubstr = rawurlencode($nameSubstr); $filterChecks = [ // Test different types of filter "filter[id]={$book->id}" => 1, "filter[id:ne]={$book->id}" => Book::visible()->where('id', '!=', $book->id)->count(), "filter[id:gt]={$book->id}" => Book::visible()->where('id', '>', $book->id)->count(), "filter[id:gte]={$book->id}" => Book::visible()->where('id', '>=', $book->id)->count(), "filter[id:lt]={$book->id}" => Book::visible()->where('id', '<', $book->id)->count(), "filter[name:like]={$encodedNameSubstr}%" => Book::visible()->where('name', 'like', $nameSubstr . '%')->count(), // Test mulitple filters 'and' together "filter[id]={$book->id}&filter[name]=random_non_existing_string" => 0, ]; foreach ($filterChecks as $filterOption => $resultCount) { $resp = $this->get($this->endpoint . '?count=1&' . $filterOption); $resp->assertJson(['total' => $resultCount]); } } public function test_total_on_results_shows_correctly() { $this->actingAsApiEditor(); $bookCount = Book::query()->count(); $resp = $this->get($this->endpoint . '?count=1'); $resp->assertJson(['total' => $bookCount]); } public function test_total_on_results_shows_correctly_when_offset_provided() { $this->actingAsApiEditor(); $bookCount = Book::query()->count(); $resp = $this->get($this->endpoint . '?count=1&offset=1'); $resp->assertJson(['total' => $bookCount]); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Api/ImportsApiTest.php
tests/Api/ImportsApiTest.php
<?php namespace Tests\Api; use BookStack\Entities\Models\Page; use BookStack\Exports\Import; use Tests\Exports\ZipTestHelper; use Tests\TestCase; class ImportsApiTest extends TestCase { use TestsApi; protected string $baseEndpoint = '/api/imports'; public function test_create_and_run(): void { $book = $this->entities->book(); $zip = ZipTestHelper::zipUploadFromData([ 'page' => [ 'name' => 'My API import page', 'tags' => [ [ 'name' => 'My api tag', 'value' => 'api test value' ] ], ], ]); $resp = $this->actingAsApiAdmin()->call('POST', $this->baseEndpoint, [], [], ['file' => $zip]); $resp->assertStatus(200); $importId = $resp->json('id'); $import = Import::query()->findOrFail($importId); $this->assertEquals('page', $import->type); $resp = $this->post($this->baseEndpoint . "/{$import->id}", [ 'parent_type' => 'book', 'parent_id' => $book->id, ]); $resp->assertJson([ 'name' => 'My API import page', 'book_id' => $book->id, ]); $resp->assertJsonMissingPath('book'); $page = Page::query()->where('name', '=', 'My API import page')->first(); $this->assertEquals('My api tag', $page->tags()->first()->name); } public function test_create_validation_error(): void { $zip = ZipTestHelper::zipUploadFromData([ 'page' => [ 'tags' => [ [ 'name' => 'My api tag', 'value' => 'api test value' ] ], ], ]); $resp = $this->actingAsApiAdmin()->call('POST', $this->baseEndpoint, [], [], ['file' => $zip]); $resp->assertStatus(422); $message = $resp->json('message'); $this->assertStringContainsString('ZIP upload failed with the following validation errors:', $message); $this->assertStringContainsString('[page.name] The name field is required.', $message); } public function test_list(): void { $imports = Import::factory()->count(10)->create(); $resp = $this->actingAsApiAdmin()->get($this->baseEndpoint); $resp->assertJsonCount(10, 'data'); $resp->assertJsonPath('total', 10); $firstImport = $imports->first(); $resp = $this->actingAsApiAdmin()->get($this->baseEndpoint . '?filter[id]=' . $firstImport->id); $resp->assertJsonCount(1, 'data'); $resp->assertJsonPath('data.0.id', $firstImport->id); $resp->assertJsonPath('data.0.name', $firstImport->name); $resp->assertJsonPath('data.0.size', $firstImport->size); $resp->assertJsonPath('data.0.type', $firstImport->type); } public function test_list_visibility_limited(): void { $user = $this->users->editor(); $admin = $this->users->admin(); $userImport = Import::factory()->create(['name' => 'MySuperUserImport', 'created_by' => $user->id]); $adminImport = Import::factory()->create(['name' => 'MySuperAdminImport', 'created_by' => $admin->id]); $this->permissions->grantUserRolePermissions($user, ['content-import']); $resp = $this->actingAsForApi($user)->get($this->baseEndpoint); $resp->assertJsonCount(1, 'data'); $resp->assertJsonPath('data.0.name', 'MySuperUserImport'); $this->permissions->grantUserRolePermissions($user, ['settings-manage']); $resp = $this->actingAsForApi($user)->get($this->baseEndpoint); $resp->assertJsonCount(2, 'data'); $resp->assertJsonPath('data.1.name', 'MySuperAdminImport'); } public function test_read(): void { $zip = ZipTestHelper::zipUploadFromData([ 'book' => [ 'name' => 'My API import book', 'pages' => [ [ 'name' => 'My import page', 'tags' => [ [ 'name' => 'My api tag', 'value' => 'api test value' ] ] ] ], ], ]); $resp = $this->actingAsApiAdmin()->call('POST', $this->baseEndpoint, [], [], ['file' => $zip]); $resp->assertStatus(200); $resp = $this->get($this->baseEndpoint . "/{$resp->json('id')}"); $resp->assertStatus(200); $resp->assertJsonPath('details.name', 'My API import book'); $resp->assertJsonPath('details.pages.0.name', 'My import page'); $resp->assertJsonPath('details.pages.0.tags.0.name', 'My api tag'); $resp->assertJsonMissingPath('metadata'); } public function test_delete(): void { $import = Import::factory()->create(); $resp = $this->actingAsApiAdmin()->delete($this->baseEndpoint . "/{$import->id}"); $resp->assertStatus(204); } public function test_content_import_permissions_needed(): void { $user = $this->users->viewer(); $this->permissions->grantUserRolePermissions($user, ['access-api']); $this->actingAsForApi($user); $requests = [ ['GET', $this->baseEndpoint], ['POST', $this->baseEndpoint], ['GET', $this->baseEndpoint . "/1"], ['POST', $this->baseEndpoint . "/1"], ['DELETE', $this->baseEndpoint . "/1"], ]; foreach ($requests as $request) { [$method, $endpoint] = $request; $resp = $this->json($method, $endpoint); $resp->assertStatus(403); } $this->permissions->grantUserRolePermissions($user, ['content-import']); foreach ($requests as $request) { [$method, $endpoint] = $request; $resp = $this->call($method, $endpoint); $this->assertNotEquals(403, $resp->status(), "A {$method} request to {$endpoint} returned 403"); } } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Api/UsersApiTest.php
tests/Api/UsersApiTest.php
<?php namespace Tests\Api; use BookStack\Access\Notifications\UserInviteNotification; use BookStack\Activity\ActivityType; use BookStack\Activity\Models\Activity as ActivityModel; use BookStack\Entities\Models\Entity; use BookStack\Facades\Activity; use BookStack\Users\Models\Role; use BookStack\Users\Models\User; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Notification; use Tests\TestCase; class UsersApiTest extends TestCase { use TestsApi; protected string $baseEndpoint = '/api/users'; protected array $endpointMap = [ ['get', '/api/users'], ['post', '/api/users'], ['get', '/api/users/1'], ['put', '/api/users/1'], ['delete', '/api/users/1'], ]; public function test_users_manage_permission_needed_for_all_endpoints() { $this->actingAsApiEditor(); foreach ($this->endpointMap as [$method, $uri]) { $resp = $this->json($method, $uri); $resp->assertStatus(403); $resp->assertJson($this->permissionErrorResponse()); } } public function test_no_endpoints_accessible_in_demo_mode() { config()->set('app.env', 'demo'); $this->actingAsApiAdmin(); foreach ($this->endpointMap as [$method, $uri]) { $resp = $this->json($method, $uri); $resp->assertStatus(403); $resp->assertJson($this->permissionErrorResponse()); } } public function test_index_endpoint_returns_expected_user() { $this->actingAsApiAdmin(); /** @var User $firstUser */ $firstUser = User::query()->orderBy('id', 'asc')->first(); $resp = $this->getJson($this->baseEndpoint . '?count=1&sort=+id'); $resp->assertJson(['data' => [ [ 'id' => $firstUser->id, 'name' => $firstUser->name, 'slug' => $firstUser->slug, 'email' => $firstUser->email, 'profile_url' => $firstUser->getProfileUrl(), 'edit_url' => $firstUser->getEditUrl(), 'avatar_url' => $firstUser->getAvatar(), ], ]]); } public function test_index_endpoint_has_correct_created_and_last_activity_dates() { $user = $this->users->editor(); $user->created_at = now()->subYear(); $user->save(); $this->actingAs($user); Activity::add(ActivityType::AUTH_LOGIN, 'test login activity'); /** @var ActivityModel $activity */ $activity = ActivityModel::query()->where('user_id', '=', $user->id)->latest()->first(); $resp = $this->asAdmin()->getJson($this->baseEndpoint . '?filter[id]=3'); $resp->assertJson(['data' => [ [ 'id' => $user->id, 'created_at' => $user->created_at->toJSON(), 'last_activity_at' => $activity->created_at->toJson(), ], ]]); } public function test_create_endpoint() { $this->actingAsApiAdmin(); /** @var Role $role */ $role = Role::query()->first(); $resp = $this->postJson($this->baseEndpoint, [ 'name' => 'Benny Boris', 'email' => 'bboris@example.com', 'password' => 'mysuperpass', 'language' => 'it', 'roles' => [$role->id], 'send_invite' => false, ]); $resp->assertStatus(200); $resp->assertJson([ 'name' => 'Benny Boris', 'email' => 'bboris@example.com', 'external_auth_id' => '', 'roles' => [ [ 'id' => $role->id, 'display_name' => $role->display_name, ], ], ]); $this->assertDatabaseHas('users', ['email' => 'bboris@example.com']); /** @var User $user */ $user = User::query()->where('email', '=', 'bboris@example.com')->first(); $this->assertActivityExists(ActivityType::USER_CREATE, null, $user->logDescriptor()); $this->assertEquals(1, $user->roles()->count()); $this->assertEquals('it', setting()->getUser($user, 'language')); } public function test_create_with_send_invite() { $this->actingAsApiAdmin(); Notification::fake(); $resp = $this->postJson($this->baseEndpoint, [ 'name' => 'Benny Boris', 'email' => 'bboris@example.com', 'send_invite' => true, ]); $resp->assertStatus(200); /** @var User $user */ $user = User::query()->where('email', '=', 'bboris@example.com')->first(); Notification::assertSentTo($user, UserInviteNotification::class); } public function test_create_with_send_invite_works_with_value_of_1() { $this->actingAsApiAdmin(); Notification::fake(); $resp = $this->postJson($this->baseEndpoint, [ 'name' => 'Benny Boris', 'email' => 'bboris@example.com', 'send_invite' => '1', // Submissions via x-www-form-urlencoded/form-data may use 1 instead of boolean ]); $resp->assertStatus(200); /** @var User $user */ $user = User::query()->where('email', '=', 'bboris@example.com')->first(); Notification::assertSentTo($user, UserInviteNotification::class); } public function test_create_name_and_email_validation() { $this->actingAsApiAdmin(); /** @var User $existingUser */ $existingUser = User::query()->first(); $resp = $this->postJson($this->baseEndpoint, [ 'email' => 'bboris@example.com', ]); $resp->assertStatus(422); $resp->assertJson($this->validationResponse(['name' => ['The name field is required.']])); $resp = $this->postJson($this->baseEndpoint, [ 'name' => 'Benny Boris', ]); $resp->assertStatus(422); $resp->assertJson($this->validationResponse(['email' => ['The email field is required.']])); $resp = $this->postJson($this->baseEndpoint, [ 'email' => $existingUser->email, 'name' => 'Benny Boris', ]); $resp->assertStatus(422); $resp->assertJson($this->validationResponse(['email' => ['The email has already been taken.']])); } public function test_read_endpoint() { $this->actingAsApiAdmin(); /** @var User $user */ $user = User::query()->first(); /** @var Role $userRole */ $userRole = $user->roles()->first(); $resp = $this->getJson($this->baseEndpoint . "/{$user->id}"); $resp->assertStatus(200); $resp->assertJson([ 'id' => $user->id, 'slug' => $user->slug, 'email' => $user->email, 'external_auth_id' => $user->external_auth_id, 'roles' => [ [ 'id' => $userRole->id, 'display_name' => $userRole->display_name, ], ], ]); } public function test_update_endpoint() { $this->actingAsApiAdmin(); /** @var User $user */ $user = $this->users->admin(); $roles = Role::query()->pluck('id'); $resp = $this->putJson($this->baseEndpoint . "/{$user->id}", [ 'name' => 'My updated user', 'email' => 'barrytest@example.com', 'roles' => $roles, 'external_auth_id' => 'btest', 'password' => 'barrytester', 'language' => 'fr', ]); $resp->assertStatus(200); $resp->assertJson([ 'id' => $user->id, 'name' => 'My updated user', 'email' => 'barrytest@example.com', 'external_auth_id' => 'btest', ]); $user->refresh(); $this->assertEquals('fr', setting()->getUser($user, 'language')); $this->assertEquals(count($roles), $user->roles()->count()); $this->assertNotEquals('barrytester', $user->password); $this->assertTrue(Hash::check('barrytester', $user->password)); } public function test_update_endpoint_does_not_remove_info_if_not_provided() { $this->actingAsApiAdmin(); /** @var User $user */ $user = $this->users->admin(); $roleCount = $user->roles()->count(); $resp = $this->putJson($this->baseEndpoint . "/{$user->id}", []); $resp->assertStatus(200); $this->assertDatabaseHas('users', [ 'id' => $user->id, 'name' => $user->name, 'email' => $user->email, 'password' => $user->password, ]); $this->assertEquals($roleCount, $user->roles()->count()); } public function test_delete_endpoint() { $this->actingAsApiAdmin(); /** @var User $user */ $user = User::query()->where('id', '!=', $this->users->admin()->id) ->whereNull('system_name') ->first(); $resp = $this->deleteJson($this->baseEndpoint . "/{$user->id}"); $resp->assertStatus(204); $this->assertActivityExists('user_delete', null, $user->logDescriptor()); } public function test_delete_endpoint_with_ownership_migration_user() { $this->actingAsApiAdmin(); /** @var User $user */ $user = User::query()->where('id', '!=', $this->users->admin()->id) ->whereNull('system_name') ->first(); $entityChain = $this->entities->createChainBelongingToUser($user); /** @var User $newOwner */ $newOwner = User::query()->where('id', '!=', $user->id)->first(); /** @var Entity $entity */ foreach ($entityChain as $entity) { $this->assertEquals($user->id, $entity->owned_by); } $resp = $this->deleteJson($this->baseEndpoint . "/{$user->id}", [ 'migrate_ownership_id' => $newOwner->id, ]); $resp->assertStatus(204); /** @var Entity $entity */ foreach ($entityChain as $entity) { $this->assertEquals($newOwner->id, $entity->refresh()->owned_by); } } public function test_delete_endpoint_fails_deleting_only_admin() { $this->actingAsApiAdmin(); $adminRole = Role::getSystemRole('admin'); $adminToDelete = $adminRole->users()->first(); $adminRole->users()->where('id', '!=', $adminToDelete->id)->delete(); $resp = $this->deleteJson($this->baseEndpoint . "/{$adminToDelete->id}"); $resp->assertStatus(500); $resp->assertJson($this->errorResponse('You cannot delete the only admin', 500)); } public function test_delete_endpoint_fails_deleting_public_user() { $this->actingAsApiAdmin(); /** @var User $publicUser */ $publicUser = User::query()->where('system_name', '=', 'public')->first(); $resp = $this->deleteJson($this->baseEndpoint . "/{$publicUser->id}"); $resp->assertStatus(500); $resp->assertJson($this->errorResponse('You cannot delete the guest user', 500)); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Api/RecycleBinApiTest.php
tests/Api/RecycleBinApiTest.php
<?php namespace Tests\Api; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Deletion; use Illuminate\Support\Collection; use Tests\TestCase; class RecycleBinApiTest extends TestCase { use TestsApi; protected string $baseEndpoint = '/api/recycle-bin'; protected array $endpointMap = [ ['get', '/api/recycle-bin'], ['put', '/api/recycle-bin/1'], ['delete', '/api/recycle-bin/1'], ]; public function test_settings_manage_permission_needed_for_all_endpoints() { $editor = $this->users->editor(); $this->permissions->grantUserRolePermissions($editor, ['settings-manage']); $this->actingAs($editor); foreach ($this->endpointMap as [$method, $uri]) { $resp = $this->json($method, $uri); $resp->assertStatus(403); $resp->assertJson($this->permissionErrorResponse()); } } public function test_restrictions_manage_all_permission_needed_for_all_endpoints() { $editor = $this->users->editor(); $this->permissions->grantUserRolePermissions($editor, ['restrictions-manage-all']); $this->actingAs($editor); foreach ($this->endpointMap as [$method, $uri]) { $resp = $this->json($method, $uri); $resp->assertStatus(403); $resp->assertJson($this->permissionErrorResponse()); } } public function test_index_endpoint_returns_expected_page() { $admin = $this->users->admin(); $page = $this->entities->page(); $book = $this->entities->book(); $this->actingAs($admin)->delete($page->getUrl()); $this->delete($book->getUrl()); $deletions = Deletion::query()->orderBy('id')->get(); $resp = $this->getJson($this->baseEndpoint); $expectedData = $deletions ->zip([$page, $book]) ->map(function (Collection $data) use ($admin) { return [ 'id' => $data[0]->id, 'deleted_by' => $admin->id, 'created_at' => $data[0]->created_at->toJson(), 'updated_at' => $data[0]->updated_at->toJson(), 'deletable_type' => $data[1]->getMorphClass(), 'deletable_id' => $data[1]->id, 'deletable' => [ 'name' => $data[1]->name, ], ]; }); $resp->assertJson([ 'data' => $expectedData->values()->all(), 'total' => 2, ]); } public function test_index_endpoint_returns_children_count() { $admin = $this->users->admin(); $book = Book::query()->whereHas('pages')->whereHas('chapters')->withCount(['pages', 'chapters'])->first(); $this->actingAs($admin)->delete($book->getUrl()); $deletion = Deletion::query()->orderBy('id')->first(); $resp = $this->getJson($this->baseEndpoint); $expectedData = [ [ 'id' => $deletion->id, 'deletable' => [ 'pages_count' => $book->pages_count, 'chapters_count' => $book->chapters_count, ], ], ]; $resp->assertJson([ 'data' => $expectedData, 'total' => 1, ]); } public function test_index_endpoint_returns_parent() { $admin = $this->users->admin(); $page = $this->entities->pageWithinChapter(); $this->actingAs($admin)->delete($page->getUrl()); $deletion = Deletion::query()->orderBy('id')->first(); $resp = $this->getJson($this->baseEndpoint); $expectedData = [ [ 'id' => $deletion->id, 'deletable' => [ 'parent' => [ 'id' => $page->chapter->id, 'name' => $page->chapter->name, 'type' => 'chapter', ], ], ], ]; $resp->assertJson([ 'data' => $expectedData, 'total' => 1, ]); } public function test_restore_endpoint() { $page = $this->entities->page(); $this->asAdmin()->delete($page->getUrl()); $page->refresh(); $deletion = Deletion::query()->orderBy('id')->first(); $this->assertDatabaseHasEntityData('page', [ 'id' => $page->id, 'deleted_at' => $page->deleted_at, ]); $resp = $this->putJson($this->baseEndpoint . '/' . $deletion->id); $resp->assertJson([ 'restore_count' => 1, ]); $this->assertDatabaseHasEntityData('page', [ 'id' => $page->id, 'deleted_at' => null, ]); } public function test_destroy_endpoint() { $page = $this->entities->page(); $this->asAdmin()->delete($page->getUrl()); $page->refresh(); $deletion = Deletion::query()->orderBy('id')->first(); $this->assertDatabaseHasEntityData('page', [ 'id' => $page->id, 'deleted_at' => $page->deleted_at, ]); $resp = $this->deleteJson($this->baseEndpoint . '/' . $deletion->id); $resp->assertJson([ 'delete_count' => 1, ]); $this->assertDatabaseMissing('entities', ['id' => $page->id, 'type' => 'page']); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Api/SystemApiTest.php
tests/Api/SystemApiTest.php
<?php namespace Tests\Api; use Tests\TestCase; class SystemApiTest extends TestCase { use TestsApi; public function test_read_returns_app_info(): void { $resp = $this->actingAsApiEditor()->get('/api/system'); $data = $resp->json(); $this->assertStringStartsWith('v', $data['version']); $this->assertEquals(setting('instance-id'), $data['instance_id']); $this->assertEquals(setting('app-name'), $data['app_name']); $this->assertEquals(url('/logo.png'), $data['app_logo']); $this->assertEquals(url('/'), $data['base_url']); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Api/ContentPermissionsApiTest.php
tests/Api/ContentPermissionsApiTest.php
<?php namespace Tests\Api; use Tests\TestCase; class ContentPermissionsApiTest extends TestCase { use TestsApi; protected string $baseEndpoint = '/api/content-permissions'; public function test_user_roles_manage_permission_needed_for_all_endpoints() { $page = $this->entities->page(); $endpointMap = [ ['get', "/api/content-permissions/page/{$page->id}"], ['put', "/api/content-permissions/page/{$page->id}"], ]; $editor = $this->users->editor(); $this->actingAs($editor, 'api'); foreach ($endpointMap as [$method, $uri]) { $resp = $this->json($method, $uri); $resp->assertStatus(403); $resp->assertJson($this->permissionErrorResponse()); } $this->permissions->grantUserRolePermissions($editor, ['restrictions-manage-all']); foreach ($endpointMap as [$method, $uri]) { $resp = $this->json($method, $uri); $this->assertNotEquals(403, $resp->getStatusCode()); } } public function test_read_endpoint_shows_expected_detail() { $page = $this->entities->page(); $owner = $this->users->newUser(); $role = $this->users->createRole(); $this->permissions->addEntityPermission($page, ['view', 'delete'], $role); $this->permissions->changeEntityOwner($page, $owner); $this->permissions->setFallbackPermissions($page, ['update', 'create']); $this->actingAsApiAdmin(); $resp = $this->getJson($this->baseEndpoint . "/page/{$page->id}"); $resp->assertOk(); $resp->assertExactJson([ 'owner' => [ 'id' => $owner->id, 'name' => $owner->name, 'slug' => $owner->slug, ], 'role_permissions' => [ [ 'role_id' => $role->id, 'view' => true, 'create' => false, 'update' => false, 'delete' => true, 'role' => [ 'id' => $role->id, 'display_name' => $role->display_name, ] ] ], 'fallback_permissions' => [ 'inheriting' => false, 'view' => false, 'create' => true, 'update' => true, 'delete' => false, ], ]); } public function test_read_endpoint_shows_expected_detail_when_items_are_empty() { $page = $this->entities->page(); $page->permissions()->delete(); $page->owned_by = null; $page->save(); $this->actingAsApiAdmin(); $resp = $this->getJson($this->baseEndpoint . "/page/{$page->id}"); $resp->assertOk(); $resp->assertExactJson([ 'owner' => null, 'role_permissions' => [], 'fallback_permissions' => [ 'inheriting' => true, 'view' => null, 'create' => null, 'update' => null, 'delete' => null, ], ]); } public function test_update_endpoint_can_change_owner() { $page = $this->entities->page(); $newOwner = $this->users->newUser(); $this->actingAsApiAdmin(); $resp = $this->putJson($this->baseEndpoint . "/page/{$page->id}", [ 'owner_id' => $newOwner->id, ]); $resp->assertOk(); $resp->assertExactJson([ 'owner' => ['id' => $newOwner->id, 'name' => $newOwner->name, 'slug' => $newOwner->slug], 'role_permissions' => [], 'fallback_permissions' => [ 'inheriting' => true, 'view' => null, 'create' => null, 'update' => null, 'delete' => null, ], ]); } public function test_update_can_set_role_permissions() { $page = $this->entities->page(); $page->owned_by = null; $page->save(); $newRoleA = $this->users->createRole(); $newRoleB = $this->users->createRole(); $this->actingAsApiAdmin(); $resp = $this->putJson($this->baseEndpoint . "/page/{$page->id}", [ 'role_permissions' => [ ['role_id' => $newRoleA->id, 'view' => true, 'create' => false, 'update' => false, 'delete' => false], ['role_id' => $newRoleB->id, 'view' => true, 'create' => false, 'update' => true, 'delete' => true], ], ]); $resp->assertOk(); $resp->assertExactJson([ 'owner' => null, 'role_permissions' => [ [ 'role_id' => $newRoleA->id, 'view' => true, 'create' => false, 'update' => false, 'delete' => false, 'role' => [ 'id' => $newRoleA->id, 'display_name' => $newRoleA->display_name, ] ], [ 'role_id' => $newRoleB->id, 'view' => true, 'create' => false, 'update' => true, 'delete' => true, 'role' => [ 'id' => $newRoleB->id, 'display_name' => $newRoleB->display_name, ] ] ], 'fallback_permissions' => [ 'inheriting' => true, 'view' => null, 'create' => null, 'update' => null, 'delete' => null, ], ]); } public function test_update_can_set_fallback_permissions() { $page = $this->entities->page(); $page->owned_by = null; $page->save(); $this->actingAsApiAdmin(); $resp = $this->putJson($this->baseEndpoint . "/page/{$page->id}", [ 'fallback_permissions' => [ 'inheriting' => false, 'view' => true, 'create' => true, 'update' => true, 'delete' => false, ], ]); $resp->assertOk(); $resp->assertExactJson([ 'owner' => null, 'role_permissions' => [], 'fallback_permissions' => [ 'inheriting' => false, 'view' => true, 'create' => true, 'update' => true, 'delete' => false, ], ]); } public function test_update_can_clear_roles_permissions() { $page = $this->entities->page(); $this->permissions->addEntityPermission($page, ['view'], $this->users->createRole()); $page->owned_by = null; $page->save(); $this->actingAsApiAdmin(); $resp = $this->putJson($this->baseEndpoint . "/page/{$page->id}", [ 'role_permissions' => [], ]); $resp->assertOk(); $resp->assertExactJson([ 'owner' => null, 'role_permissions' => [], 'fallback_permissions' => [ 'inheriting' => true, 'view' => null, 'create' => null, 'update' => null, 'delete' => null, ], ]); } public function test_update_can_clear_fallback_permissions() { $page = $this->entities->page(); $this->permissions->setFallbackPermissions($page, ['view', 'update']); $page->owned_by = null; $page->save(); $this->actingAsApiAdmin(); $resp = $this->putJson($this->baseEndpoint . "/page/{$page->id}", [ 'fallback_permissions' => [ 'inheriting' => true, ], ]); $resp->assertOk(); $resp->assertExactJson([ 'owner' => null, 'role_permissions' => [], 'fallback_permissions' => [ 'inheriting' => true, 'view' => null, 'create' => null, 'update' => null, 'delete' => null, ], ]); } public function test_update_can_both_provide_owner_and_fallback_permissions() { $user = $this->users->viewer(); $page = $this->entities->page(); $page->owned_by = null; $page->save(); $this->actingAsApiAdmin(); $resp = $this->putJson($this->baseEndpoint . "/page/{$page->id}", [ "owner_id" => $user->id, 'fallback_permissions' => [ 'inheriting' => false, 'view' => false, 'create' => false, 'update' => false, 'delete' => false, ], ]); $resp->assertOk(); $this->assertDatabaseHasEntityData('page', ['id' => $page->id, 'owned_by' => $user->id]); $this->assertDatabaseHas('entity_permissions', [ 'entity_id' => $page->id, 'entity_type' => 'page', 'role_id' => 0, 'view' => false, 'create' => false, 'update' => false, 'delete' => false, ]); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Api/PagesApiTest.php
tests/Api/PagesApiTest.php
<?php namespace Tests\Api; use BookStack\Activity\Models\Comment; use BookStack\Entities\Models\Chapter; use BookStack\Entities\Models\Page; use Carbon\Carbon; use Illuminate\Support\Facades\DB; use Tests\TestCase; class PagesApiTest extends TestCase { use TestsApi; protected string $baseEndpoint = '/api/pages'; public function test_index_endpoint_returns_expected_page() { $this->actingAsApiEditor(); $firstPage = Page::query()->orderBy('id', 'asc')->first(); $resp = $this->getJson($this->baseEndpoint . '?count=1&sort=+id'); $resp->assertJson(['data' => [ [ 'id' => $firstPage->id, 'name' => $firstPage->name, 'slug' => $firstPage->slug, 'book_id' => $firstPage->book->id, 'priority' => $firstPage->priority, 'owned_by' => $firstPage->owned_by, 'created_by' => $firstPage->created_by, 'updated_by' => $firstPage->updated_by, 'revision_count' => $firstPage->revision_count, ], ]]); } public function test_create_endpoint() { $this->actingAsApiEditor(); $book = $this->entities->book(); $details = [ 'name' => 'My API page', 'book_id' => $book->id, 'html' => '<p>My new page content</p>', 'tags' => [ [ 'name' => 'tagname', 'value' => 'tagvalue', ], ], 'priority' => 15, ]; $resp = $this->postJson($this->baseEndpoint, $details); unset($details['html']); $resp->assertStatus(200); $newItem = Page::query()->orderByDesc('id')->where('name', '=', $details['name'])->first(); $resp->assertJson(array_merge($details, ['id' => $newItem->id, 'slug' => $newItem->slug])); $this->assertDatabaseHas('tags', [ 'entity_id' => $newItem->id, 'entity_type' => $newItem->getMorphClass(), 'name' => 'tagname', 'value' => 'tagvalue', ]); $resp->assertSeeText('My new page content'); $resp->assertJsonMissing(['book' => []]); $this->assertActivityExists('page_create', $newItem); } public function test_page_name_needed_to_create() { $this->actingAsApiEditor(); $book = $this->entities->book(); $details = [ 'book_id' => $book->id, 'html' => '<p>A page created via the API</p>', ]; $resp = $this->postJson($this->baseEndpoint, $details); $resp->assertStatus(422); $resp->assertJson($this->validationResponse([ 'name' => ['The name field is required.'], ])); } public function test_book_id_or_chapter_id_needed_to_create() { $this->actingAsApiEditor(); $details = [ 'name' => 'My api page', 'html' => '<p>A page created via the API</p>', ]; $resp = $this->postJson($this->baseEndpoint, $details); $resp->assertStatus(422); $resp->assertJson($this->validationResponse([ 'book_id' => ['The book id field is required when chapter id is not present.'], 'chapter_id' => ['The chapter id field is required when book id is not present.'], ])); $chapter = $this->entities->chapter(); $resp = $this->postJson($this->baseEndpoint, array_merge($details, ['chapter_id' => $chapter->id])); $resp->assertStatus(200); $book = $this->entities->book(); $resp = $this->postJson($this->baseEndpoint, array_merge($details, ['book_id' => $book->id])); $resp->assertStatus(200); } public function test_markdown_can_be_provided_for_create() { $this->actingAsApiEditor(); $book = $this->entities->book(); $details = [ 'book_id' => $book->id, 'name' => 'My api page', 'markdown' => "# A new API page \n[link](https://example.com)", ]; $resp = $this->postJson($this->baseEndpoint, $details); $resp->assertJson(['markdown' => $details['markdown']]); $respHtml = $resp->json('html'); $this->assertStringContainsString('new API page</h1>', $respHtml); $this->assertStringContainsString('link</a>', $respHtml); $this->assertStringContainsString('href="https://example.com"', $respHtml); } public function test_read_endpoint() { $this->actingAsApiEditor(); $page = $this->entities->page(); $resp = $this->getJson($this->baseEndpoint . "/{$page->id}"); $resp->assertStatus(200); $resp->assertJson([ 'id' => $page->id, 'slug' => $page->slug, 'created_by' => [ 'name' => $page->createdBy->name, ], 'book_id' => $page->book_id, 'updated_by' => [ 'name' => $page->createdBy->name, ], 'owned_by' => [ 'name' => $page->ownedBy->name, ], ]); } public function test_read_endpoint_provides_rendered_html() { $this->actingAsApiEditor(); $page = $this->entities->page(); $page->html = "<p>testing</p><script>alert('danger')</script><h1>Hello</h1>"; $page->save(); $resp = $this->getJson($this->baseEndpoint . "/{$page->id}"); $html = $resp->json('html'); $this->assertStringNotContainsString('script', $html); $this->assertStringContainsString('Hello', $html); $this->assertStringContainsString('testing', $html); } public function test_read_endpoint_provides_raw_html() { $html = "<p>testing</p><script>alert('danger')</script><h1>Hello</h1>"; $this->actingAsApiEditor(); $page = $this->entities->page(); $page->html = $html; $page->save(); $resp = $this->getJson($this->baseEndpoint . "/{$page->id}"); $this->assertEquals($html, $resp->json('raw_html')); $this->assertNotEquals($html, $resp->json('html')); } public function test_read_endpoint_returns_not_found() { $this->actingAsApiEditor(); // get an id that is not used $id = Page::orderBy('id', 'desc')->first()->id + 1; $this->assertNull(Page::find($id)); $resp = $this->getJson($this->baseEndpoint . "/$id"); $resp->assertNotFound(); $this->assertNull($resp->json('id')); $resp->assertJsonIsObject('error'); $resp->assertJsonStructure([ 'error' => [ 'code', 'message', ], ]); $this->assertSame(404, $resp->json('error')['code']); } public function test_read_endpoint_includes_page_comments_tree_structure() { $this->actingAsApiEditor(); $page = $this->entities->page(); $relation = ['commentable_type' => 'page', 'commentable_id' => $page->id]; $active = Comment::factory()->create([...$relation, 'html' => '<p>My active<script>cat</script> comment</p>']); Comment::factory()->count(5)->create([...$relation, 'parent_id' => $active->local_id]); $archived = Comment::factory()->create([...$relation, 'archived' => true]); Comment::factory()->count(2)->create([...$relation, 'parent_id' => $archived->local_id]); $resp = $this->getJson("{$this->baseEndpoint}/{$page->id}"); $resp->assertOk(); $resp->assertJsonCount(1, 'comments.active'); $resp->assertJsonCount(1, 'comments.archived'); $resp->assertJsonCount(5, 'comments.active.0.children'); $resp->assertJsonCount(2, 'comments.archived.0.children'); $resp->assertJsonFragment([ 'id' => $active->id, 'local_id' => $active->local_id, 'html' => '<p>My active comment</p>', ]); } public function test_update_endpoint() { $this->actingAsApiEditor(); $page = $this->entities->page(); $details = [ 'name' => 'My updated API page', 'html' => '<p>A page created via the API</p>', 'tags' => [ [ 'name' => 'freshtag', 'value' => 'freshtagval', ], ], 'priority' => 15, ]; $resp = $this->putJson($this->baseEndpoint . "/{$page->id}", $details); $page->refresh(); $resp->assertStatus(200); unset($details['html']); $resp->assertJson(array_merge($details, [ 'id' => $page->id, 'slug' => $page->slug, 'book_id' => $page->book_id, ])); $this->assertActivityExists('page_update', $page); } public function test_providing_new_chapter_id_on_update_will_move_page() { $this->actingAsApiEditor(); $page = $this->entities->page(); $chapter = Chapter::visible()->where('book_id', '!=', $page->book_id)->first(); $details = [ 'name' => 'My updated API page', 'chapter_id' => $chapter->id, 'html' => '<p>A page created via the API</p>', ]; $resp = $this->putJson($this->baseEndpoint . "/{$page->id}", $details); $resp->assertStatus(200); $resp->assertJson([ 'chapter_id' => $chapter->id, 'book_id' => $chapter->book_id, ]); } public function test_providing_move_via_update_requires_page_create_permission_on_new_parent() { $this->actingAsApiEditor(); $page = $this->entities->page(); $chapter = Chapter::visible()->where('book_id', '!=', $page->book_id)->first(); $this->permissions->setEntityPermissions($chapter, ['view'], [$this->users->editor()->roles()->first()]); $details = [ 'name' => 'My updated API page', 'chapter_id' => $chapter->id, 'html' => '<p>A page created via the API</p>', ]; $resp = $this->putJson($this->baseEndpoint . "/{$page->id}", $details); $resp->assertStatus(403); } public function test_update_endpoint_does_not_wipe_content_if_no_html_or_md_provided() { $this->actingAsApiEditor(); $page = $this->entities->page(); $originalContent = $page->html; $details = [ 'name' => 'My updated API page', 'tags' => [ [ 'name' => 'freshtag', 'value' => 'freshtagval', ], ], ]; $this->putJson($this->baseEndpoint . "/{$page->id}", $details); $page->refresh(); $this->assertEquals($originalContent, $page->html); } public function test_update_increments_updated_date_if_only_tags_are_sent() { $this->actingAsApiEditor(); $page = $this->entities->page(); $page->newQuery()->where('id', '=', $page->id)->update(['updated_at' => Carbon::now()->subWeek()]); $details = [ 'tags' => [['name' => 'Category', 'value' => 'Testing']], ]; $resp = $this->putJson($this->baseEndpoint . "/{$page->id}", $details); $resp->assertOk(); $page->refresh(); $this->assertGreaterThan(Carbon::now()->subDay()->unix(), $page->updated_at->unix()); } public function test_delete_endpoint() { $this->actingAsApiEditor(); $page = $this->entities->page(); $resp = $this->deleteJson($this->baseEndpoint . "/{$page->id}"); $resp->assertStatus(204); $this->assertActivityExists('page_delete', $page); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Api/ApiAuthTest.php
tests/Api/ApiAuthTest.php
<?php namespace Tests\Api; use BookStack\Permissions\Models\RolePermission; use BookStack\Users\Models\Role; use BookStack\Users\Models\User; use Carbon\Carbon; use Tests\TestCase; class ApiAuthTest extends TestCase { use TestsApi; protected string $endpoint = '/api/books'; public function test_requests_succeed_with_default_auth() { $viewer = $this->users->viewer(); $this->permissions->grantUserRolePermissions($viewer, ['access-api']); $resp = $this->get($this->endpoint); $resp->assertStatus(401); $this->actingAs($viewer, 'standard'); $resp = $this->get($this->endpoint); $resp->assertStatus(200); } public function test_no_token_throws_error() { $resp = $this->get($this->endpoint); $resp->assertStatus(401); $resp->assertJson($this->errorResponse('No authorization token found on the request', 401)); } public function test_bad_token_format_throws_error() { $resp = $this->get($this->endpoint, ['Authorization' => 'Token abc123']); $resp->assertStatus(401); $resp->assertJson($this->errorResponse('An authorization token was found on the request but the format appeared incorrect', 401)); } public function test_token_with_non_existing_id_throws_error() { $resp = $this->get($this->endpoint, ['Authorization' => 'Token abc:123']); $resp->assertStatus(401); $resp->assertJson($this->errorResponse('No matching API token was found for the provided authorization token', 401)); } public function test_token_with_bad_secret_value_throws_error() { $resp = $this->get($this->endpoint, ['Authorization' => "Token {$this->apiTokenId}:123"]); $resp->assertStatus(401); $resp->assertJson($this->errorResponse('The secret provided for the given used API token is incorrect', 401)); } public function test_api_access_permission_required_to_access_api() { $resp = $this->get($this->endpoint, $this->apiAuthHeader()); $resp->assertStatus(200); auth()->logout(); $accessApiPermission = RolePermission::getByName('access-api'); $editorRole = $this->users->editor()->roles()->first(); $editorRole->detachPermission($accessApiPermission); $resp = $this->get($this->endpoint, $this->apiAuthHeader()); $resp->assertStatus(403); $resp->assertJson($this->errorResponse('The owner of the used API token does not have permission to make API calls', 403)); } public function test_api_access_permission_required_to_access_api_with_session_auth() { $editor = $this->users->editor(); $this->actingAs($editor, 'standard'); $resp = $this->get($this->endpoint); $resp->assertStatus(200); auth('standard')->logout(); $accessApiPermission = RolePermission::getByName('access-api'); $editorRole = $this->users->editor()->roles()->first(); $editorRole->detachPermission($accessApiPermission); $editor = User::query()->where('id', '=', $editor->id)->first(); $this->actingAs($editor, 'standard'); $resp = $this->get($this->endpoint); $resp->assertStatus(403); $resp->assertJson($this->errorResponse('The owner of the used API token does not have permission to make API calls', 403)); } public function test_access_prevented_for_guest_users_with_api_permission_while_public_access_disabled() { $this->disableCookieEncryption(); $publicRole = Role::getSystemRole('public'); $accessApiPermission = RolePermission::getByName('access-api'); $publicRole->attachPermission($accessApiPermission); $this->withCookie('bookstack_session', 'abc123'); // Test API access when not public setting()->put('app-public', false); $resp = $this->get($this->endpoint); $resp->assertStatus(403); // Test API access when public setting()->put('app-public', true); $resp = $this->get($this->endpoint); $resp->assertStatus(200); } public function test_token_expiry_checked() { $editor = $this->users->editor(); $token = $editor->apiTokens()->first(); $resp = $this->get($this->endpoint, $this->apiAuthHeader()); $resp->assertStatus(200); auth()->logout(); $token->expires_at = Carbon::now()->subDay()->format('Y-m-d'); $token->save(); $resp = $this->get($this->endpoint, $this->apiAuthHeader()); $resp->assertJson($this->errorResponse('The authorization token used has expired', 403)); } public function test_email_confirmation_checked_using_api_auth() { $editor = $this->users->editor(); $editor->email_confirmed = false; $editor->save(); // Set settings and get user instance $this->setSettings(['registration-enabled' => 'true', 'registration-confirmation' => 'true']); $resp = $this->get($this->endpoint, $this->apiAuthHeader()); $resp->assertStatus(401); $resp->assertJson($this->errorResponse('The email address for the account in use needs to be confirmed', 401)); } public function test_rate_limit_headers_active_on_requests() { $resp = $this->actingAsApiEditor()->get($this->endpoint); $resp->assertHeader('x-ratelimit-limit', 180); $resp->assertHeader('x-ratelimit-remaining', 179); $resp = $this->actingAsApiEditor()->get($this->endpoint); $resp->assertHeader('x-ratelimit-remaining', 178); } public function test_rate_limit_hit_gives_json_error() { config()->set(['api.requests_per_minute' => 1]); $resp = $this->actingAsApiEditor()->get($this->endpoint); $resp->assertStatus(200); $resp = $this->actingAsApiEditor()->get($this->endpoint); $resp->assertStatus(429); $resp->assertHeader('x-ratelimit-remaining', 0); $resp->assertHeader('retry-after'); $resp->assertJson([ 'error' => [ 'code' => 429, ], ]); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Api/ChaptersApiTest.php
tests/Api/ChaptersApiTest.php
<?php namespace Tests\Api; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Chapter; use Carbon\Carbon; use Illuminate\Support\Facades\DB; use Tests\TestCase; class ChaptersApiTest extends TestCase { use TestsApi; protected string $baseEndpoint = '/api/chapters'; public function test_index_endpoint_returns_expected_chapter() { $this->actingAsApiEditor(); $firstChapter = Chapter::query()->orderBy('id', 'asc')->first(); $resp = $this->getJson($this->baseEndpoint . '?count=1&sort=+id'); $resp->assertJson(['data' => [ [ 'id' => $firstChapter->id, 'name' => $firstChapter->name, 'slug' => $firstChapter->slug, 'book_id' => $firstChapter->book->id, 'priority' => $firstChapter->priority, 'book_slug' => $firstChapter->book->slug, 'owned_by' => $firstChapter->owned_by, 'created_by' => $firstChapter->created_by, 'updated_by' => $firstChapter->updated_by, ], ]]); } public function test_create_endpoint() { $this->actingAsApiEditor(); $book = $this->entities->book(); $templatePage = $this->entities->templatePage(); $details = [ 'name' => 'My API chapter', 'description' => 'A chapter created via the API', 'book_id' => $book->id, 'tags' => [ [ 'name' => 'tagname', 'value' => 'tagvalue', ], ], 'priority' => 15, 'default_template_id' => $templatePage->id, ]; $resp = $this->postJson($this->baseEndpoint, $details); $resp->assertStatus(200); $newItem = Chapter::query()->orderByDesc('id')->where('name', '=', $details['name'])->first(); $resp->assertJson(array_merge($details, [ 'id' => $newItem->id, 'slug' => $newItem->slug, 'description_html' => '<p>A chapter created via the API</p>', ])); $this->assertDatabaseHas('tags', [ 'entity_id' => $newItem->id, 'entity_type' => $newItem->getMorphClass(), 'name' => 'tagname', 'value' => 'tagvalue', ]); $resp->assertJsonMissing(['pages' => []]); $this->assertActivityExists('chapter_create', $newItem); } public function test_create_endpoint_with_html() { $this->actingAsApiEditor(); $book = $this->entities->book(); $details = [ 'name' => 'My API chapter', 'description_html' => '<p>A chapter <strong>created</strong> via the API</p>', 'book_id' => $book->id, ]; $resp = $this->postJson($this->baseEndpoint, $details); $resp->assertStatus(200); $newItem = Chapter::query()->orderByDesc('id')->where('name', '=', $details['name'])->first(); $expectedDetails = array_merge($details, [ 'id' => $newItem->id, 'description' => 'A chapter created via the API', ]); $resp->assertJson($expectedDetails); $this->assertDatabaseHasEntityData('chapter', $expectedDetails); } public function test_chapter_name_needed_to_create() { $this->actingAsApiEditor(); $book = $this->entities->book(); $details = [ 'book_id' => $book->id, 'description' => 'A chapter created via the API', ]; $resp = $this->postJson($this->baseEndpoint, $details); $resp->assertStatus(422); $resp->assertJson($this->validationResponse([ 'name' => ['The name field is required.'], ])); } public function test_chapter_book_id_needed_to_create() { $this->actingAsApiEditor(); $details = [ 'name' => 'My api chapter', 'description' => 'A chapter created via the API', ]; $resp = $this->postJson($this->baseEndpoint, $details); $resp->assertStatus(422); $resp->assertJson($this->validationResponse([ 'book_id' => ['The book id field is required.'], ])); } public function test_read_endpoint() { $this->actingAsApiEditor(); $chapter = $this->entities->chapter(); $page = $chapter->pages()->first(); $resp = $this->getJson($this->baseEndpoint . "/{$chapter->id}"); $resp->assertStatus(200); $resp->assertJson([ 'id' => $chapter->id, 'slug' => $chapter->slug, 'book_slug' => $chapter->book->slug, 'created_by' => [ 'name' => $chapter->createdBy->name, ], 'book_id' => $chapter->book_id, 'updated_by' => [ 'name' => $chapter->createdBy->name, ], 'owned_by' => [ 'name' => $chapter->ownedBy->name, ], 'pages' => [ [ 'id' => $page->id, 'slug' => $page->slug, 'name' => $page->name, 'owned_by' => $page->owned_by, 'created_by' => $page->created_by, 'updated_by' => $page->updated_by, 'book_id' => $page->book->id, 'chapter_id' => $chapter->id, 'priority' => $page->priority, 'book_slug' => $chapter->book->slug, 'draft' => $page->draft, 'template' => $page->template, 'editor' => $page->editor, ], ], 'default_template_id' => null, ]); $resp->assertJsonMissingPath('book'); $resp->assertJsonCount($chapter->pages()->count(), 'pages'); } public function test_update_endpoint() { $this->actingAsApiEditor(); $chapter = $this->entities->chapter(); $templatePage = $this->entities->templatePage(); $details = [ 'name' => 'My updated API chapter', 'description' => 'A chapter updated via the API', 'tags' => [ [ 'name' => 'freshtag', 'value' => 'freshtagval', ], ], 'priority' => 15, 'default_template_id' => $templatePage->id, ]; $resp = $this->putJson($this->baseEndpoint . "/{$chapter->id}", $details); $chapter->refresh(); $resp->assertStatus(200); $resp->assertJson(array_merge($details, [ 'id' => $chapter->id, 'slug' => $chapter->slug, 'book_id' => $chapter->book_id, 'description_html' => '<p>A chapter updated via the API</p>', ])); $this->assertActivityExists('chapter_update', $chapter); } public function test_update_endpoint_with_html() { $this->actingAsApiEditor(); $chapter = $this->entities->chapter(); $details = [ 'name' => 'My updated API chapter', 'description_html' => '<p>A chapter <em>updated</em> via the API</p>', ]; $resp = $this->putJson($this->baseEndpoint . "/{$chapter->id}", $details); $resp->assertStatus(200); $this->assertDatabaseHasEntityData('chapter', array_merge($details, [ 'id' => $chapter->id, 'description' => 'A chapter updated via the API' ])); } public function test_update_increments_updated_date_if_only_tags_are_sent() { $this->actingAsApiEditor(); $chapter = $this->entities->chapter(); $chapter->newQuery()->where('id', '=', $chapter->id)->update(['updated_at' => Carbon::now()->subWeek()]); $details = [ 'tags' => [['name' => 'Category', 'value' => 'Testing']], ]; $this->putJson($this->baseEndpoint . "/{$chapter->id}", $details); $chapter->refresh(); $this->assertGreaterThan(Carbon::now()->subDay()->unix(), $chapter->updated_at->unix()); } public function test_update_with_book_id_moves_chapter() { $this->actingAsApiEditor(); $chapter = $this->entities->chapterHasPages(); $page = $chapter->pages()->first(); $newBook = Book::query()->where('id', '!=', $chapter->book_id)->first(); $resp = $this->putJson($this->baseEndpoint . "/{$chapter->id}", ['book_id' => $newBook->id]); $resp->assertOk(); $chapter->refresh(); $this->assertDatabaseHasEntityData('chapter', ['id' => $chapter->id, 'book_id' => $newBook->id]); $this->assertDatabaseHasEntityData('page', ['id' => $page->id, 'book_id' => $newBook->id, 'chapter_id' => $chapter->id]); } public function test_update_with_new_book_id_requires_delete_permission() { $editor = $this->users->editor(); $this->permissions->removeUserRolePermissions($editor, ['chapter-delete-all', 'chapter-delete-own']); $this->actingAs($editor); $chapter = $this->entities->chapterHasPages(); $newBook = Book::query()->where('id', '!=', $chapter->book_id)->first(); $resp = $this->putJson($this->baseEndpoint . "/{$chapter->id}", ['book_id' => $newBook->id]); $this->assertPermissionError($resp); } public function test_delete_endpoint() { $this->actingAsApiEditor(); $chapter = $this->entities->chapter(); $resp = $this->deleteJson($this->baseEndpoint . "/{$chapter->id}"); $resp->assertStatus(204); $this->assertActivityExists('chapter_delete'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Api/SearchApiTest.php
tests/Api/SearchApiTest.php
<?php namespace Tests\Api; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Bookshelf; use BookStack\Entities\Models\Chapter; use BookStack\Entities\Models\Entity; use BookStack\Entities\Models\Page; use Tests\TestCase; class SearchApiTest extends TestCase { use TestsApi; protected string $baseEndpoint = '/api/search'; public function test_all_endpoint_returns_search_filtered_results_with_query() { $this->actingAsApiEditor(); $uniqueTerm = 'MySuperUniqueTermForSearching'; /** @var Entity $entityClass */ foreach ([Page::class, Chapter::class, Book::class, Bookshelf::class] as $entityClass) { /** @var Entity $first */ $first = $entityClass::query()->first(); $first->update(['name' => $uniqueTerm]); $first->indexForSearch(); } $resp = $this->getJson($this->baseEndpoint . '?query=' . $uniqueTerm . '&count=5&page=1'); $resp->assertJsonCount(4, 'data'); $resp->assertJsonFragment(['name' => $uniqueTerm, 'type' => 'book']); $resp->assertJsonFragment(['name' => $uniqueTerm, 'type' => 'chapter']); $resp->assertJsonFragment(['name' => $uniqueTerm, 'type' => 'page']); $resp->assertJsonFragment(['name' => $uniqueTerm, 'type' => 'bookshelf']); } public function test_all_endpoint_returns_entity_url() { $page = $this->entities->page(); $page->update(['name' => 'name with superuniquevalue within']); $page->indexForSearch(); $resp = $this->actingAsApiAdmin()->getJson($this->baseEndpoint . '?query=superuniquevalue'); $resp->assertJsonFragment([ 'type' => 'page', 'url' => $page->getUrl(), ]); } public function test_all_endpoint_returns_items_with_preview_html() { $book = $this->entities->book(); $book->forceFill(['name' => 'name with superuniquevalue within', 'description' => 'Description with superuniquevalue within'])->save(); $book->indexForSearch(); $resp = $this->actingAsApiAdmin()->getJson($this->baseEndpoint . '?query=superuniquevalue'); $resp->assertJsonFragment([ 'type' => 'book', 'url' => $book->getUrl(), 'preview_html' => [ 'name' => 'name with <strong>superuniquevalue</strong> within', 'content' => 'Description with <strong>superuniquevalue</strong> within', ], ]); } public function test_all_endpoint_requires_query_parameter() { $resp = $this->actingAsApiEditor()->get($this->baseEndpoint); $resp->assertStatus(422); $resp = $this->actingAsApiEditor()->get($this->baseEndpoint . '?query=myqueryvalue'); $resp->assertOk(); } public function test_all_endpoint_includes_parent_details_where_visible() { $page = $this->entities->pageWithinChapter(); $chapter = $page->chapter; $book = $page->book; $page->update(['name' => 'name with superextrauniquevalue within']); $page->indexForSearch(); $editor = $this->users->editor(); $this->actingAsApiEditor(); $resp = $this->getJson($this->baseEndpoint . '?query=superextrauniquevalue'); $resp->assertJsonFragment([ 'id' => $page->id, 'type' => 'page', 'book' => [ 'id' => $book->id, 'name' => $book->name, 'slug' => $book->slug, ], 'chapter' => [ 'id' => $chapter->id, 'name' => $chapter->name, 'slug' => $chapter->slug, ], ]); $this->permissions->disableEntityInheritedPermissions($chapter); $this->permissions->setEntityPermissions($page, ['view'], [$editor->roles()->first()]); $resp = $this->getJson($this->baseEndpoint . '?query=superextrauniquevalue'); $resp->assertJsonPath('data.0.id', $page->id); $resp->assertJsonPath('data.0.book.name', $book->name); $resp->assertJsonMissingPath('data.0.chapter'); $this->permissions->disableEntityInheritedPermissions($book); $resp = $this->getJson($this->baseEndpoint . '?query=superextrauniquevalue'); $resp->assertOk(); $resp->assertJsonPath('data.0.id', $page->id); $resp->assertJsonMissingPath('data.0.book.name'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Api/TestsApi.php
tests/Api/TestsApi.php
<?php namespace Tests\Api; use BookStack\Users\Models\User; trait TestsApi { protected string $apiTokenId = 'apitoken'; protected string $apiTokenSecret = 'password'; /** * Set the given user as the current logged-in user via the API driver. * This does not ensure API access. The user may still lack required role permissions. */ protected function actingAsForApi(User $user): static { parent::actingAs($user, 'api'); return $this; } /** * Set the API editor role as the current user via the API driver. */ protected function actingAsApiEditor(): static { $this->actingAs($this->users->editor(), 'api'); return $this; } /** * Set the API admin role as the current user via the API driver. */ protected function actingAsApiAdmin(): static { $this->actingAs($this->users->admin(), 'api'); return $this; } /** * Format the given items into a standardised error format. */ protected function errorResponse(string $message, int $code): array { return ['error' => ['code' => $code, 'message' => $message]]; } /** * Get the structure that matches a permission error response. */ protected function permissionErrorResponse(): array { return $this->errorResponse('You do not have permission to perform the requested action.', 403); } /** * Format the given (field_name => ["messages"]) array * into a standard validation response format. */ protected function validationResponse(array $messages): array { $err = $this->errorResponse('The given data was invalid.', 422); $err['error']['validation'] = $messages; return $err; } /** * Get an approved API auth header. */ protected function apiAuthHeader(): array { return [ 'Authorization' => "Token {$this->apiTokenId}:{$this->apiTokenSecret}", ]; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Api/ApiConfigTest.php
tests/Api/ApiConfigTest.php
<?php namespace Tests\Api; use Tests\TestCase; class ApiConfigTest extends TestCase { use TestsApi; protected $endpoint = '/api/books'; public function test_default_item_count_reflected_in_listing_requests() { $this->actingAsApiEditor(); config()->set(['api.default_item_count' => 5]); $resp = $this->get($this->endpoint); $resp->assertJsonCount(5, 'data'); config()->set(['api.default_item_count' => 1]); $resp = $this->get($this->endpoint); $resp->assertJsonCount(1, 'data'); } public function test_default_item_count_does_not_limit_count_param() { $this->actingAsApiEditor(); config()->set(['api.default_item_count' => 1]); $resp = $this->get($this->endpoint . '?count=5'); $resp->assertJsonCount(5, 'data'); } public function test_max_item_count_limits_listing_requests() { $this->actingAsApiEditor(); config()->set(['api.max_item_count' => 2]); $resp = $this->get($this->endpoint); $resp->assertJsonCount(2, 'data'); $resp = $this->get($this->endpoint . '?count=5'); $resp->assertJsonCount(2, 'data'); } public function test_requests_per_min_alters_rate_limit() { $resp = $this->actingAsApiEditor()->get($this->endpoint); $resp->assertHeader('x-ratelimit-limit', 180); config()->set(['api.requests_per_minute' => 10]); $resp = $this->actingAsApiEditor()->get($this->endpoint); $resp->assertHeader('x-ratelimit-limit', 10); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Api/RolesApiTest.php
tests/Api/RolesApiTest.php
<?php namespace Tests\Api; use BookStack\Activity\ActivityType; use BookStack\Users\Models\Role; use BookStack\Users\Models\User; use Tests\TestCase; class RolesApiTest extends TestCase { use TestsApi; protected string $baseEndpoint = '/api/roles'; protected array $endpointMap = [ ['get', '/api/roles'], ['post', '/api/roles'], ['get', '/api/roles/1'], ['put', '/api/roles/1'], ['delete', '/api/roles/1'], ]; public function test_user_roles_manage_permission_needed_for_all_endpoints() { $this->actingAsApiEditor(); foreach ($this->endpointMap as [$method, $uri]) { $resp = $this->json($method, $uri); $resp->assertStatus(403); $resp->assertJson($this->permissionErrorResponse()); } } public function test_index_endpoint_returns_expected_role_and_count() { $this->actingAsApiAdmin(); /** @var Role $firstRole */ $firstRole = Role::query()->orderBy('id', 'asc')->first(); $resp = $this->getJson($this->baseEndpoint . '?count=1&sort=+id'); $resp->assertJson(['data' => [ [ 'id' => $firstRole->id, 'display_name' => $firstRole->display_name, 'description' => $firstRole->description, 'mfa_enforced' => $firstRole->mfa_enforced, 'external_auth_id' => $firstRole->external_auth_id, 'permissions_count' => $firstRole->permissions()->count(), 'users_count' => $firstRole->users()->count(), 'created_at' => $firstRole->created_at->toJSON(), 'updated_at' => $firstRole->updated_at->toJSON(), ], ]]); $resp->assertJson(['total' => Role::query()->count()]); } public function test_create_endpoint() { $this->actingAsApiAdmin(); /** @var Role $role */ $role = Role::query()->first(); $resp = $this->postJson($this->baseEndpoint, [ 'display_name' => 'My awesome role', 'description' => 'My great role description', 'mfa_enforced' => true, 'external_auth_id' => 'auth_id', 'permissions' => [ 'content-export', 'page-view-all', 'page-view-own', 'users-manage', ] ]); $resp->assertStatus(200); $resp->assertJson([ 'display_name' => 'My awesome role', 'description' => 'My great role description', 'mfa_enforced' => true, 'external_auth_id' => 'auth_id', 'permissions' => [ 'content-export', 'page-view-all', 'page-view-own', 'users-manage', ] ]); $this->assertDatabaseHas('roles', [ 'display_name' => 'My awesome role', 'description' => 'My great role description', 'mfa_enforced' => true, 'external_auth_id' => 'auth_id', ]); /** @var Role $role */ $role = Role::query()->where('display_name', '=', 'My awesome role')->first(); $this->assertActivityExists(ActivityType::ROLE_CREATE, null, $role->logDescriptor()); $this->assertEquals(4, $role->permissions()->count()); } public function test_create_name_and_description_validation() { $this->actingAsApiAdmin(); /** @var User $existingUser */ $existingUser = User::query()->first(); $resp = $this->postJson($this->baseEndpoint, [ 'description' => 'My new role', ]); $resp->assertStatus(422); $resp->assertJson($this->validationResponse(['display_name' => ['The display name field is required.']])); $resp = $this->postJson($this->baseEndpoint, [ 'name' => 'My great role with a too long desc', 'description' => str_repeat('My great desc', 20), ]); $resp->assertStatus(422); $resp->assertJson($this->validationResponse(['description' => ['The description may not be greater than 180 characters.']])); } public function test_read_endpoint() { $this->actingAsApiAdmin(); $role = $this->users->editor()->roles()->first(); $resp = $this->getJson($this->baseEndpoint . "/{$role->id}"); $resp->assertStatus(200); $resp->assertJson([ 'display_name' => $role->display_name, 'description' => $role->description, 'mfa_enforced' => $role->mfa_enforced, 'external_auth_id' => $role->external_auth_id, 'permissions' => $role->permissions()->orderBy('name', 'asc')->pluck('name')->toArray(), 'users' => $role->users()->get()->map(function (User $user) { return [ 'id' => $user->id, 'name' => $user->name, 'slug' => $user->slug, ]; })->toArray(), ]); } public function test_update_endpoint() { $this->actingAsApiAdmin(); $role = $this->users->editor()->roles()->first(); $resp = $this->putJson($this->baseEndpoint . "/{$role->id}", [ 'display_name' => 'My updated role', 'description' => 'My great role description', 'mfa_enforced' => true, 'external_auth_id' => 'updated_auth_id', 'permissions' => [ 'content-export', 'page-view-all', 'page-view-own', 'users-manage', ] ]); $resp->assertStatus(200); $resp->assertJson([ 'id' => $role->id, 'display_name' => 'My updated role', 'description' => 'My great role description', 'mfa_enforced' => true, 'external_auth_id' => 'updated_auth_id', 'permissions' => [ 'content-export', 'page-view-all', 'page-view-own', 'users-manage', ] ]); $role->refresh(); $this->assertEquals(4, $role->permissions()->count()); $this->assertActivityExists(ActivityType::ROLE_UPDATE); } public function test_update_endpoint_does_not_remove_info_if_not_provided() { $this->actingAsApiAdmin(); $role = $this->users->editor()->roles()->first(); $resp = $this->putJson($this->baseEndpoint . "/{$role->id}", []); $permissionCount = $role->permissions()->count(); $resp->assertStatus(200); $this->assertDatabaseHas('roles', [ 'id' => $role->id, 'display_name' => $role->display_name, 'description' => $role->description, 'external_auth_id' => $role->external_auth_id, ]); $role->refresh(); $this->assertEquals($permissionCount, $role->permissions()->count()); } public function test_delete_endpoint() { $this->actingAsApiAdmin(); $role = $this->users->editor()->roles()->first(); $resp = $this->deleteJson($this->baseEndpoint . "/{$role->id}"); $resp->assertStatus(204); $this->assertActivityExists(ActivityType::ROLE_DELETE, null, $role->logDescriptor()); } public function test_delete_endpoint_fails_deleting_system_role() { $this->actingAsApiAdmin(); $adminRole = Role::getSystemRole('admin'); $resp = $this->deleteJson($this->baseEndpoint . "/{$adminRole->id}"); $resp->assertStatus(500); $resp->assertJson($this->errorResponse('This role is a system role and cannot be deleted', 500)); } public function test_delete_endpoint_fails_deleting_default_registration_role() { $this->actingAsApiAdmin(); $role = $this->users->attachNewRole($this->users->editor()); $this->setSettings(['registration-role' => $role->id]); $resp = $this->deleteJson($this->baseEndpoint . "/{$role->id}"); $resp->assertStatus(500); $resp->assertJson($this->errorResponse('This role cannot be deleted while set as the default registration role', 500)); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Api/ApiDocsTest.php
tests/Api/ApiDocsTest.php
<?php namespace Tests\Api; use Tests\TestCase; class ApiDocsTest extends TestCase { use TestsApi; protected string $endpoint = '/api/docs'; public function test_api_endpoint_redirects_to_docs() { $resp = $this->actingAsApiEditor()->get('/api'); $resp->assertRedirect('api/docs'); } public function test_docs_page_returns_view_with_docs_content() { $resp = $this->actingAsApiEditor()->get($this->endpoint); $resp->assertStatus(200); $resp->assertSee(url('/api/docs.json')); $resp->assertSee('Show a JSON view of the API docs data.'); $resp->assertHeader('Content-Type', 'text/html; charset=utf-8'); } public function test_docs_json_endpoint_returns_json() { $resp = $this->actingAsApiEditor()->get($this->endpoint . '.json'); $resp->assertStatus(200); $resp->assertHeader('Content-Type', 'application/json'); $resp->assertJson([ 'docs' => [[ 'name' => 'docs-display', 'uri' => 'api/docs', ]], ]); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Api/ImageGalleryApiTest.php
tests/Api/ImageGalleryApiTest.php
<?php namespace Tests\Api; use BookStack\Entities\Models\Page; use BookStack\Uploads\Image; use Tests\TestCase; class ImageGalleryApiTest extends TestCase { use TestsApi; protected string $baseEndpoint = '/api/image-gallery'; public function test_index_endpoint_returns_expected_image_and_count() { $this->actingAsApiAdmin(); $imagePage = $this->entities->page(); $data = $this->files->uploadGalleryImageToPage($this, $imagePage); $image = Image::findOrFail($data['response']->id); $resp = $this->getJson($this->baseEndpoint . '?count=1&sort=+id'); $resp->assertJson(['data' => [ [ 'id' => $image->id, 'name' => $image->name, 'url' => $image->url, 'path' => $image->path, 'type' => 'gallery', 'uploaded_to' => $imagePage->id, 'created_by' => $this->users->admin()->id, 'updated_by' => $this->users->admin()->id, ], ]]); $resp->assertJson(['total' => Image::query()->count()]); } public function test_index_endpoint_doesnt_show_images_for_those_uploaded_to_non_visible_pages() { $this->actingAsApiEditor(); $imagePage = $this->entities->page(); $data = $this->files->uploadGalleryImageToPage($this, $imagePage); $image = Image::findOrFail($data['response']->id); $resp = $this->getJson($this->baseEndpoint . '?filter[id]=' . $image->id); $resp->assertJsonCount(1, 'data'); $resp->assertJson(['total' => 1]); $this->permissions->disableEntityInheritedPermissions($imagePage); $resp = $this->getJson($this->baseEndpoint . '?filter[id]=' . $image->id); $resp->assertJsonCount(0, 'data'); $resp->assertJson(['total' => 0]); } public function test_index_endpoint_doesnt_show_other_image_types() { $this->actingAsApiEditor(); $imagePage = $this->entities->page(); $data = $this->files->uploadGalleryImageToPage($this, $imagePage); $image = Image::findOrFail($data['response']->id); $typesByCountExpectation = [ 'cover_book' => 0, 'drawio' => 1, 'gallery' => 1, 'user' => 0, 'system' => 0, ]; foreach ($typesByCountExpectation as $type => $count) { $image->type = $type; $image->save(); $resp = $this->getJson($this->baseEndpoint . '?filter[id]=' . $image->id); $resp->assertJsonCount($count, 'data'); $resp->assertJson(['total' => $count]); } } public function test_create_endpoint() { $this->actingAsApiAdmin(); $imagePage = $this->entities->page(); $resp = $this->call('POST', $this->baseEndpoint, [ 'type' => 'gallery', 'uploaded_to' => $imagePage->id, 'name' => 'My awesome image!', ], [], [ 'image' => $this->files->uploadedImage('my-cool-image.png'), ]); $resp->assertStatus(200); $image = Image::query()->where('uploaded_to', '=', $imagePage->id)->first(); $expectedUser = [ 'id' => $this->users->admin()->id, 'name' => $this->users->admin()->name, 'slug' => $this->users->admin()->slug, ]; $resp->assertJson([ 'id' => $image->id, 'name' => 'My awesome image!', 'url' => $image->url, 'path' => $image->path, 'type' => 'gallery', 'uploaded_to' => $imagePage->id, 'created_by' => $expectedUser, 'updated_by' => $expectedUser, ]); } public function test_create_endpoint_requires_image_create_permissions() { $user = $this->users->editor(); $this->actingAsForApi($user); $this->permissions->removeUserRolePermissions($user, ['image-create-all']); $makeRequest = function () { return $this->call('POST', $this->baseEndpoint, []); }; $resp = $makeRequest(); $resp->assertStatus(403); $this->permissions->grantUserRolePermissions($user, ['image-create-all']); $resp = $makeRequest(); $resp->assertStatus(422); } public function test_create_fails_if_uploaded_to_not_visible_or_not_exists() { $this->actingAsApiEditor(); $makeRequest = function (int $uploadedTo) { return $this->call('POST', $this->baseEndpoint, [ 'type' => 'gallery', 'uploaded_to' => $uploadedTo, 'name' => 'My awesome image!', ], [], [ 'image' => $this->files->uploadedImage('my-cool-image.png'), ]); }; $page = $this->entities->page(); $this->permissions->disableEntityInheritedPermissions($page); $resp = $makeRequest($page->id); $resp->assertStatus(404); $resp = $makeRequest(Page::query()->max('id') + 55); $resp->assertStatus(404); } public function test_create_has_restricted_types() { $this->actingAsApiEditor(); $typesByStatusExpectation = [ 'cover_book' => 422, 'drawio' => 200, 'gallery' => 200, 'user' => 422, 'system' => 422, ]; $makeRequest = function (string $type) { return $this->call('POST', $this->baseEndpoint, [ 'type' => $type, 'uploaded_to' => $this->entities->page()->id, 'name' => 'My awesome image!', ], [], [ 'image' => $this->files->uploadedImage('my-cool-image.png'), ]); }; foreach ($typesByStatusExpectation as $type => $status) { $resp = $makeRequest($type); $resp->assertStatus($status); } } public function test_create_will_use_file_name_if_no_name_provided_in_request() { $this->actingAsApiEditor(); $imagePage = $this->entities->page(); $resp = $this->call('POST', $this->baseEndpoint, [ 'type' => 'gallery', 'uploaded_to' => $imagePage->id, ], [], [ 'image' => $this->files->uploadedImage('my-cool-image.png'), ]); $resp->assertStatus(200); $this->assertDatabaseHas('images', [ 'type' => 'gallery', 'uploaded_to' => $imagePage->id, 'name' => 'my-cool-image.png', ]); } public function test_read_endpoint() { $this->actingAsApiAdmin(); $imagePage = $this->entities->page(); $data = $this->files->uploadGalleryImageToPage($this, $imagePage); $image = Image::findOrFail($data['response']->id); $resp = $this->getJson($this->baseEndpoint . "/{$image->id}"); $resp->assertStatus(200); $expectedUser = [ 'id' => $this->users->admin()->id, 'name' => $this->users->admin()->name, 'slug' => $this->users->admin()->slug, ]; $displayUrl = $image->getThumb(1680, null, true); $resp->assertJson([ 'id' => $image->id, 'name' => $image->name, 'url' => $image->url, 'path' => $image->path, 'type' => 'gallery', 'uploaded_to' => $imagePage->id, 'created_by' => $expectedUser, 'updated_by' => $expectedUser, 'content' => [ 'html' => "<a href=\"{$image->url}\" target=\"_blank\"><img src=\"{$displayUrl}\" alt=\"{$image->name}\"></a>", 'markdown' => "![{$image->name}]({$displayUrl})", ], 'created_at' => $image->created_at->toISOString(), 'updated_at' => $image->updated_at->toISOString(), ]); $this->assertStringStartsWith('http://', $resp->json('thumbs.gallery')); $this->assertStringStartsWith('http://', $resp->json('thumbs.display')); } public function test_read_endpoint_provides_different_content_for_drawings() { $this->actingAsApiAdmin(); $imagePage = $this->entities->page(); $data = $this->files->uploadGalleryImageToPage($this, $imagePage); $image = Image::findOrFail($data['response']->id); $image->type = 'drawio'; $image->save(); $resp = $this->getJson($this->baseEndpoint . "/{$image->id}"); $resp->assertStatus(200); $drawing = "<div drawio-diagram=\"{$image->id}\"><img src=\"{$image->url}\"></div>"; $resp->assertJson([ 'id' => $image->id, 'content' => [ 'html' => $drawing, 'markdown' => $drawing, ], ]); } public function test_read_endpoint_does_not_show_if_no_permissions_for_related_page() { $this->actingAsApiEditor(); $imagePage = $this->entities->page(); $data = $this->files->uploadGalleryImageToPage($this, $imagePage); $image = Image::findOrFail($data['response']->id); $this->permissions->disableEntityInheritedPermissions($imagePage); $resp = $this->getJson($this->baseEndpoint . "/{$image->id}"); $resp->assertStatus(404); } public function test_read_data_endpoint() { $this->actingAsApiAdmin(); $imagePage = $this->entities->page(); $data = $this->files->uploadGalleryImageToPage($this, $imagePage, 'test-image.png'); $image = Image::findOrFail($data['response']->id); $resp = $this->get("{$this->baseEndpoint}/{$image->id}/data"); $resp->assertStatus(200); $resp->assertHeader('Content-Type', 'image/png'); $respData = $resp->streamedContent(); $this->assertEquals(file_get_contents($this->files->testFilePath('test-image.png')), $respData); } public function test_read_data_endpoint_permission_controlled() { $this->actingAsApiEditor(); $imagePage = $this->entities->page(); $data = $this->files->uploadGalleryImageToPage($this, $imagePage, 'test-image.png'); $image = Image::findOrFail($data['response']->id); $this->get("{$this->baseEndpoint}/{$image->id}/data")->assertOk(); $this->permissions->disableEntityInheritedPermissions($imagePage); $resp = $this->get("{$this->baseEndpoint}/{$image->id}/data"); $resp->assertStatus(404); } public function test_read_url_data_endpoint() { $this->actingAsApiAdmin(); $imagePage = $this->entities->page(); $data = $this->files->uploadGalleryImageToPage($this, $imagePage, 'test-image.png'); $url = url($data['response']->path); $resp = $this->get("{$this->baseEndpoint}/url/data?url=" . urlencode($url)); $resp->assertStatus(200); $resp->assertHeader('Content-Type', 'image/png'); $respData = $resp->streamedContent(); $this->assertEquals(file_get_contents($this->files->testFilePath('test-image.png')), $respData); } public function test_read_url_data_endpoint_permission_controlled_when_local_secure_restricted_storage_is_used() { config()->set('filesystems.images', 'local_secure_restricted'); $this->actingAsApiEditor(); $imagePage = $this->entities->page(); $data = $this->files->uploadGalleryImageToPage($this, $imagePage, 'test-image.png'); $url = url($data['response']->path); $resp = $this->get("{$this->baseEndpoint}/url/data?url=" . urlencode($url)); $resp->assertStatus(200); $this->permissions->disableEntityInheritedPermissions($imagePage); $resp = $this->get("{$this->baseEndpoint}/url/data?url=" . urlencode($url)); $resp->assertStatus(404); } public function test_update_endpoint() { $this->actingAsApiAdmin(); $imagePage = $this->entities->page(); $data = $this->files->uploadGalleryImageToPage($this, $imagePage); $image = Image::findOrFail($data['response']->id); $resp = $this->putJson($this->baseEndpoint . "/{$image->id}", [ 'name' => 'My updated image name!', ]); $resp->assertStatus(200); $resp->assertJson([ 'id' => $image->id, 'name' => 'My updated image name!', ]); $this->assertDatabaseHas('images', [ 'id' => $image->id, 'name' => 'My updated image name!', ]); } public function test_update_existing_image_file() { $this->actingAsApiAdmin(); $imagePage = $this->entities->page(); $data = $this->files->uploadGalleryImageToPage($this, $imagePage); $image = Image::findOrFail($data['response']->id); $this->assertFileEquals($this->files->testFilePath('test-image.png'), public_path($data['path'])); $resp = $this->call('PUT', $this->baseEndpoint . "/{$image->id}", [], [], [ 'image' => $this->files->uploadedImage('my-cool-image.png', 'compressed.png'), ]); $resp->assertStatus(200); $this->assertFileEquals($this->files->testFilePath('compressed.png'), public_path($data['path'])); } public function test_update_endpoint_requires_image_update_permission() { $user = $this->users->editor(); $this->actingAsForApi($user); $imagePage = $this->entities->page(); $this->permissions->removeUserRolePermissions($user, ['image-update-all', 'image-update-own']); $data = $this->files->uploadGalleryImageToPage($this, $imagePage); $image = Image::findOrFail($data['response']->id); $resp = $this->putJson($this->baseEndpoint . "/{$image->id}", ['name' => 'My new name']); $resp->assertStatus(403); $resp->assertJson($this->permissionErrorResponse()); $this->permissions->grantUserRolePermissions($user, ['image-update-all']); $resp = $this->putJson($this->baseEndpoint . "/{$image->id}", ['name' => 'My new name']); $resp->assertStatus(200); } public function test_delete_endpoint() { $this->actingAsApiAdmin(); $imagePage = $this->entities->page(); $data = $this->files->uploadGalleryImageToPage($this, $imagePage); $image = Image::findOrFail($data['response']->id); $this->assertDatabaseHas('images', ['id' => $image->id]); $resp = $this->deleteJson($this->baseEndpoint . "/{$image->id}"); $resp->assertStatus(204); $this->assertDatabaseMissing('images', ['id' => $image->id]); } public function test_delete_endpoint_requires_image_delete_permission() { $user = $this->users->editor(); $this->actingAsForApi($user); $imagePage = $this->entities->page(); $this->permissions->removeUserRolePermissions($user, ['image-delete-all', 'image-delete-own']); $data = $this->files->uploadGalleryImageToPage($this, $imagePage); $image = Image::findOrFail($data['response']->id); $resp = $this->deleteJson($this->baseEndpoint . "/{$image->id}"); $resp->assertStatus(403); $resp->assertJson($this->permissionErrorResponse()); $this->permissions->grantUserRolePermissions($user, ['image-delete-all']); $resp = $this->deleteJson($this->baseEndpoint . "/{$image->id}"); $resp->assertStatus(204); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Search/EntitySearchTest.php
tests/Search/EntitySearchTest.php
<?php namespace Tests\Search; use BookStack\Activity\Models\Tag; use BookStack\Entities\Models\Book; use Tests\TestCase; class EntitySearchTest extends TestCase { public function test_page_search() { $book = $this->entities->book(); $page = $book->pages->first(); $search = $this->asEditor()->get('/search?term=' . urlencode($page->name)); $search->assertSee('Search Results'); $search->assertSeeText($page->name, true); } public function test_bookshelf_search() { $shelf = $this->entities->shelf(); $search = $this->asEditor()->get('/search?term=' . urlencode($shelf->name) . ' {type:bookshelf}'); $search->assertSee('Search Results'); $search->assertSeeText($shelf->name, true); } public function test_search_shows_pagination() { $search = $this->asEditor()->get('/search?term=a'); $this->withHtml($search)->assertLinkExists(url('/search?term=a&page=2'), '2'); } public function test_pagination_considers_sub_path_url_handling() { $this->runWithEnv(['APP_URL' => 'https://example.com/subpath'], function () { $search = $this->asEditor()->get('https://example.com/search?term=a'); $this->withHtml($search)->assertLinkExists('https://example.com/subpath/search?term=a&page=2', '2'); }); } public function test_invalid_page_search() { $resp = $this->asEditor()->get('/search?term=' . urlencode('<p>test</p>')); $resp->assertSee('Search Results'); $resp->assertStatus(200); $this->get('/search?term=cat+-')->assertStatus(200); } public function test_empty_search_shows_search_page() { $res = $this->asEditor()->get('/search'); $res->assertStatus(200); } public function test_searching_accents_and_small_terms() { $page = $this->entities->newPage(['name' => 'My new test quaffleachits', 'html' => 'some áéííúü¿¡ test content a2 orange dog']); $this->asEditor(); $accentSearch = $this->get('/search?term=' . urlencode('áéíí')); $accentSearch->assertStatus(200)->assertSee($page->name); $smallSearch = $this->get('/search?term=' . urlencode('a2')); $smallSearch->assertStatus(200)->assertSee($page->name); } public function test_book_search() { $book = Book::first(); $page = $book->pages->last(); $chapter = $book->chapters->last(); $pageTestResp = $this->asEditor()->get('/search/book/' . $book->id . '?term=' . urlencode($page->name)); $pageTestResp->assertSee($page->name); $chapterTestResp = $this->asEditor()->get('/search/book/' . $book->id . '?term=' . urlencode($chapter->name)); $chapterTestResp->assertSee($chapter->name); } public function test_chapter_search() { $chapter = $this->entities->chapterHasPages(); $page = $chapter->pages[0]; $pageTestResp = $this->asEditor()->get('/search/chapter/' . $chapter->id . '?term=' . urlencode($page->name)); $pageTestResp->assertSee($page->name); } public function test_tag_search() { $newTags = [ new Tag([ 'name' => 'animal', 'value' => 'cat', ]), new Tag([ 'name' => 'color', 'value' => 'red', ]), ]; $pageA = $this->entities->page(); $pageA->tags()->saveMany($newTags); $pageB = $this->entities->page(); $pageB->tags()->create(['name' => 'animal', 'value' => 'dog']); $this->asEditor(); $tNameSearch = $this->get('/search?term=%5Banimal%5D'); $tNameSearch->assertSee($pageA->name)->assertSee($pageB->name); $tNameSearch2 = $this->get('/search?term=%5Bcolor%5D'); $tNameSearch2->assertSee($pageA->name)->assertDontSee($pageB->name); $tNameValSearch = $this->get('/search?term=%5Banimal%3Dcat%5D'); $tNameValSearch->assertSee($pageA->name)->assertDontSee($pageB->name); } public function test_exact_searches() { $page = $this->entities->newPage(['name' => 'My new test page', 'html' => 'this is a story about an orange donkey']); $exactSearchA = $this->asEditor()->get('/search?term=' . urlencode('"story about an orange"')); $exactSearchA->assertStatus(200)->assertSee($page->name); $exactSearchB = $this->asEditor()->get('/search?term=' . urlencode('"story not about an orange"')); $exactSearchB->assertStatus(200)->assertDontSee($page->name); } public function test_negated_searches() { $page = $this->entities->newPage(['name' => 'My new test negation page', 'html' => '<p>An angry tortoise wore trumpeted plimsoles</p>']); $page->tags()->saveMany([new Tag(['name' => 'DonkCount', 'value' => '500'])]); $page->created_by = $this->users->admin()->id; $page->save(); $editor = $this->users->editor(); $this->actingAs($editor); $exactSearch = $this->get('/search?term=' . urlencode('negation -"tortoise"')); $exactSearch->assertStatus(200)->assertDontSeeText($page->name); $tagSearchA = $this->get('/search?term=' . urlencode('negation [DonkCount=500]')); $tagSearchA->assertStatus(200)->assertSeeText($page->name); $tagSearchB = $this->get('/search?term=' . urlencode('negation -[DonkCount=500]')); $tagSearchB->assertStatus(200)->assertDontSeeText($page->name); $filterSearchA = $this->get('/search?term=' . urlencode('negation -{created_by:me}')); $filterSearchA->assertStatus(200)->assertSeeText($page->name); $page->created_by = $editor->id; $page->save(); $filterSearchB = $this->get('/search?term=' . urlencode('negation -{created_by:me}')); $filterSearchB->assertStatus(200)->assertDontSeeText($page->name); } public function test_search_terms_with_delimiters_are_converted_to_exact_matches() { $this->asEditor(); $page = $this->entities->newPage(['name' => 'Delimiter test', 'html' => '<p>1.1 2,2 3?3 4:4 5;5 (8) &lt;9&gt; "10" \'11\' `12`</p>']); $terms = explode(' ', '1.1 2,2 3?3 4:4 5;5 (8) <9> "10" \'11\' `12`'); foreach ($terms as $term) { $search = $this->get('/search?term=' . urlencode($term)); $search->assertSee($page->name); } } public function test_search_filters() { $page = $this->entities->newPage(['name' => 'My new test quaffleachits', 'html' => 'this is about an orange donkey danzorbhsing']); $editor = $this->users->editor(); $this->actingAs($editor); // Viewed filter searches $this->get('/search?term=' . urlencode('danzorbhsing {not_viewed_by_me}'))->assertSee($page->name); $this->get('/search?term=' . urlencode('danzorbhsing {viewed_by_me}'))->assertDontSee($page->name); $this->get($page->getUrl()); $this->get('/search?term=' . urlencode('danzorbhsing {not_viewed_by_me}'))->assertDontSee($page->name); $this->get('/search?term=' . urlencode('danzorbhsing {viewed_by_me}'))->assertSee($page->name); // User filters $this->get('/search?term=' . urlencode('danzorbhsing {created_by:me}'))->assertDontSee($page->name); $this->get('/search?term=' . urlencode('danzorbhsing {updated_by:me}'))->assertDontSee($page->name); $this->get('/search?term=' . urlencode('danzorbhsing {owned_by:me}'))->assertDontSee($page->name); $this->get('/search?term=' . urlencode('danzorbhsing {updated_by:' . $editor->slug . '}'))->assertDontSee($page->name); $page->created_by = $editor->id; $page->save(); $this->get('/search?term=' . urlencode('danzorbhsing {created_by:me}'))->assertSee($page->name); $this->get('/search?term=' . urlencode('danzorbhsing {created_by: ' . $editor->slug . '}'))->assertSee($page->name); $this->get('/search?term=' . urlencode('danzorbhsing {updated_by:me}'))->assertDontSee($page->name); $this->get('/search?term=' . urlencode('danzorbhsing {owned_by:me}'))->assertDontSee($page->name); $page->updated_by = $editor->id; $page->save(); $this->get('/search?term=' . urlencode('danzorbhsing {updated_by:me}'))->assertSee($page->name); $this->get('/search?term=' . urlencode('danzorbhsing {updated_by:' . $editor->slug . '}'))->assertSee($page->name); $this->get('/search?term=' . urlencode('danzorbhsing {owned_by:me}'))->assertDontSee($page->name); $page->owned_by = $editor->id; $page->save(); $this->get('/search?term=' . urlencode('danzorbhsing {owned_by:me}'))->assertSee($page->name); $this->get('/search?term=' . urlencode('danzorbhsing {owned_by:' . $editor->slug . '}'))->assertSee($page->name); // Content filters $this->get('/search?term=' . urlencode('{in_name:danzorbhsing}'))->assertDontSee($page->name); $this->get('/search?term=' . urlencode('{in_body:danzorbhsing}'))->assertSee($page->name); $this->get('/search?term=' . urlencode('{in_name:test quaffleachits}'))->assertSee($page->name); $this->get('/search?term=' . urlencode('{in_body:test quaffleachits}'))->assertDontSee($page->name); // Restricted filter $this->get('/search?term=' . urlencode('danzorbhsing {is_restricted}'))->assertDontSee($page->name); $this->permissions->setEntityPermissions($page, ['view'], [$editor->roles->first()]); $this->get('/search?term=' . urlencode('danzorbhsing {is_restricted}'))->assertSee($page->name); // Date filters $this->get('/search?term=' . urlencode('danzorbhsing {updated_after:2037-01-01}'))->assertDontSee($page->name); $this->get('/search?term=' . urlencode('danzorbhsing {updated_before:2037-01-01}'))->assertSee($page->name); $page->updated_at = '2037-02-01'; $page->save(); $this->get('/search?term=' . urlencode('danzorbhsing {updated_after:2037-01-01}'))->assertSee($page->name); $this->get('/search?term=' . urlencode('danzorbhsing {updated_before:2037-01-01}'))->assertDontSee($page->name); $this->get('/search?term=' . urlencode('danzorbhsing {created_after:2037-01-01}'))->assertDontSee($page->name); $this->get('/search?term=' . urlencode('danzorbhsing {created_before:2037-01-01}'))->assertSee($page->name); $page->created_at = '2037-02-01'; $page->save(); $this->get('/search?term=' . urlencode('danzorbhsing {created_after:2037-01-01}'))->assertSee($page->name); $this->get('/search?term=' . urlencode('danzorbhsing {created_before:2037-01-01}'))->assertDontSee($page->name); } public function test_entity_selector_search() { $page = $this->entities->newPage(['name' => 'my ajax search test', 'html' => 'ajax test']); $notVisitedPage = $this->entities->page(); // Visit the page to make popular $this->asEditor()->get($page->getUrl()); $normalSearch = $this->get('/search/entity-selector?term=' . urlencode($page->name)); $normalSearch->assertSee($page->name); $bookSearch = $this->get('/search/entity-selector?types=book&term=' . urlencode($page->name)); $bookSearch->assertDontSee($page->name); $defaultListTest = $this->get('/search/entity-selector'); $defaultListTest->assertSee($page->name); $defaultListTest->assertDontSee($notVisitedPage->name); } public function test_entity_selector_search_shows_breadcrumbs() { $chapter = $this->entities->chapter(); $page = $chapter->pages->first(); $this->asEditor(); $pageSearch = $this->get('/search/entity-selector?term=' . urlencode($page->name)); $pageSearch->assertSee($page->name); $pageSearch->assertSee($chapter->getShortName(42)); $pageSearch->assertSee($page->book->getShortName(42)); $chapterSearch = $this->get('/search/entity-selector?term=' . urlencode($chapter->name)); $chapterSearch->assertSee($chapter->name); $chapterSearch->assertSee($chapter->book->getShortName(42)); } public function test_entity_selector_shows_breadcrumbs_on_default_view() { $page = $this->entities->pageWithinChapter(); $this->asEditor()->get($page->chapter->getUrl()); $resp = $this->asEditor()->get('/search/entity-selector?types=book,chapter&permission=page-create'); $html = $this->withHtml($resp); $html->assertElementContains('.chapter.entity-list-item', $page->chapter->name); $html->assertElementContains('.chapter.entity-list-item .entity-item-snippet', $page->book->getShortName(42)); } public function test_entity_selector_search_reflects_items_without_permission() { $page = $this->entities->page(); $baseSelector = 'a[data-entity-type="page"][data-entity-id="' . $page->id . '"]'; $searchUrl = '/search/entity-selector?permission=update&term=' . urlencode($page->name); $resp = $this->asEditor()->get($searchUrl); $this->withHtml($resp)->assertElementContains($baseSelector, $page->name); $this->withHtml($resp)->assertElementNotContains($baseSelector, "You don't have the required permissions to select this item"); $resp = $this->actingAs($this->users->viewer())->get($searchUrl); $this->withHtml($resp)->assertElementContains($baseSelector, $page->name); $this->withHtml($resp)->assertElementContains($baseSelector, "You don't have the required permissions to select this item"); } public function test_entity_template_selector_search() { $templatePage = $this->entities->newPage(['name' => 'Template search test', 'html' => 'template test']); $templatePage->template = true; $templatePage->save(); $nonTemplatePage = $this->entities->newPage(['name' => 'Nontemplate page', 'html' => 'nontemplate', 'template' => false]); // Visit both to make popular $this->asEditor()->get($templatePage->getUrl()); $this->get($nonTemplatePage->getUrl()); $normalSearch = $this->get('/search/entity-selector-templates?term=test'); $normalSearch->assertSee($templatePage->name); $normalSearch->assertDontSee($nonTemplatePage->name); $normalSearch = $this->get('/search/entity-selector-templates?term=beans'); $normalSearch->assertDontSee($templatePage->name); $normalSearch->assertDontSee($nonTemplatePage->name); $defaultListTest = $this->get('/search/entity-selector-templates'); $defaultListTest->assertSee($templatePage->name); $defaultListTest->assertDontSee($nonTemplatePage->name); $this->permissions->disableEntityInheritedPermissions($templatePage); $normalSearch = $this->get('/search/entity-selector-templates?term=test'); $normalSearch->assertDontSee($templatePage->name); $defaultListTest = $this->get('/search/entity-selector-templates'); $defaultListTest->assertDontSee($templatePage->name); } public function test_search_works_on_updated_page_content() { $page = $this->entities->page(); $this->asEditor(); $update = $this->put($page->getUrl(), [ 'name' => $page->name, 'html' => '<p>dog pandabearmonster spaghetti</p>', ]); $search = $this->asEditor()->get('/search?term=pandabearmonster'); $search->assertStatus(200); $search->assertSeeText($page->name); $search->assertSee($page->getUrl()); } public function test_search_ranks_common_words_lower() { $this->entities->newPage(['name' => 'Test page A', 'html' => '<p>dog biscuit dog dog</p>']); $this->entities->newPage(['name' => 'Test page B', 'html' => '<p>cat biscuit</p>']); $search = $this->asEditor()->get('/search?term=cat+dog+biscuit'); $this->withHtml($search)->assertElementContains('.entity-list > .page:nth-child(1)', 'Test page A'); $this->withHtml($search)->assertElementContains('.entity-list > .page:nth-child(2)', 'Test page B'); for ($i = 0; $i < 2; $i++) { $this->entities->newPage(['name' => 'Test page ' . $i, 'html' => '<p>dog</p>']); } $search = $this->asEditor()->get('/search?term=cat+dog+biscuit'); $this->withHtml($search)->assertElementContains('.entity-list > .page:nth-child(1)', 'Test page B'); $this->withHtml($search)->assertElementContains('.entity-list > .page:nth-child(2)', 'Test page A'); } public function test_matching_terms_in_search_results_are_highlighted() { $this->entities->newPage(['name' => 'My Meowie Cat', 'html' => '<p>A superimportant page about meowieable animals</p>', 'tags' => [ ['name' => 'Animal', 'value' => 'MeowieCat'], ['name' => 'SuperImportant'], ]]); $search = $this->asEditor()->get('/search?term=SuperImportant+Meowie'); // Title $search->assertSee('My <strong>Meowie</strong> Cat', false); // Content $search->assertSee('A <strong>superimportant</strong> page about <strong>meowie</strong>able animals', false); // Tag name $this->withHtml($search)->assertElementContains('.tag-name.highlight', 'SuperImportant'); // Tag value $this->withHtml($search)->assertElementContains('.tag-value.highlight', 'MeowieCat'); } public function test_match_highlighting_works_with_multibyte_content() { $this->entities->newPage([ 'name' => 'Test Page', 'html' => '<p>На мен ми трябва нещо добро test</p>', ]); $search = $this->asEditor()->get('/search?term=' . urlencode('На мен ми трябва нещо добро')); $search->assertSee('<strong>На</strong> <strong>мен</strong> <strong>ми</strong> <strong>трябва</strong> <strong>нещо</strong> <strong>добро</strong> test', false); } public function test_match_highlighting_is_efficient_with_large_frequency_in_content() { $content = str_repeat('superbeans ', 10000); $this->entities->newPage([ 'name' => 'Test Page', 'html' => "<p>{$content}</p>", ]); $time = microtime(true); $resp = $this->asEditor()->get('/search?term=' . urlencode('superbeans')); $this->assertLessThan(0.5, microtime(true) - $time); $resp->assertSee('<strong>superbeans</strong>', false); } public function test_html_entities_in_item_details_remains_escaped_in_search_results() { $this->entities->newPage(['name' => 'My <cool> TestPageContent', 'html' => '<p>My supercool &lt;great&gt; TestPageContent page</p>']); $search = $this->asEditor()->get('/search?term=TestPageContent'); $search->assertSee('My &lt;cool&gt; <strong>TestPageContent</strong>', false); $search->assertSee('My supercool &lt;great&gt; <strong>TestPageContent</strong> page', false); } public function test_words_adjacent_to_lines_breaks_can_be_matched_with_normal_terms() { $page = $this->entities->newPage(['name' => 'TermA', 'html' => ' <p>TermA<br>TermB<br>TermC</p> ']); $search = $this->asEditor()->get('/search?term=' . urlencode('TermB TermC')); $search->assertSee($page->getUrl(), false); } public function test_backslashes_can_be_searched_upon() { $page = $this->entities->newPage(['name' => 'TermA', 'html' => ' <p>More info is at the path \\\\cat\\dog\\badger</p> ']); $page->tags()->save(new Tag(['name' => '\\Category', 'value' => '\\animals\\fluffy'])); $search = $this->asEditor()->get('/search?term=' . urlencode('\\\\cat\\dog')); $search->assertSee($page->getUrl(), false); $search = $this->asEditor()->get('/search?term=' . urlencode('"\\dog\\\\"')); $search->assertSee($page->getUrl(), false); $search = $this->asEditor()->get('/search?term=' . urlencode('"\\badger\\\\"')); $search->assertDontSee($page->getUrl(), false); $search = $this->asEditor()->get('/search?term=' . urlencode('[\\Categorylike%\\fluffy]')); $search->assertSee($page->getUrl(), false); } public function test_searches_with_terms_without_controls_includes_them_in_extras() { $resp = $this->asEditor()->get('/search?term=' . urlencode('test {updated_by:dan} {created_by:dan} -{viewed_by_me} -[a=b] -"dog" {is_template} {sort_by:last_commented}')); $this->withHtml($resp)->assertFieldHasValue('extras', '{updated_by:dan} {created_by:dan} {is_template} {sort_by:last_commented} -"dog" -[a=b] -{viewed_by_me}'); } public function test_negated_searches_dont_show_in_inputs() { $resp = $this->asEditor()->get('/search?term=' . urlencode('-{created_by:me} -[a=b] -"dog"')); $this->withHtml($resp)->assertElementNotExists('input[name="tags[]"][value="a=b"]'); $this->withHtml($resp)->assertElementNotExists('input[name="exact[]"][value="dog"]'); $this->withHtml($resp)->assertElementNotExists('input[name="filters[created_by]"][value="me"][checked="checked"]'); } public function test_searches_with_user_filters_using_me_adds_them_into_advanced_search_form() { $resp = $this->asEditor()->get('/search?term=' . urlencode('test {updated_by:me} {created_by:me}')); $this->withHtml($resp)->assertElementExists('form input[name="filters[updated_by]"][value="me"][checked="checked"]'); $this->withHtml($resp)->assertElementExists('form input[name="filters[created_by]"][value="me"][checked="checked"]'); } public function test_search_suggestion_endpoint() { $this->entities->newPage(['name' => 'My suggestion page', 'html' => '<p>My supercool suggestion page</p>']); // Test specific search $resp = $this->asEditor()->get('/search/suggest?term="supercool+suggestion"'); $resp->assertSee('My suggestion page'); $resp->assertDontSee('My supercool suggestion page'); $resp->assertDontSee('No items available'); $this->withHtml($resp)->assertElementCount('a', 1); // Test search limit $resp = $this->asEditor()->get('/search/suggest?term=et'); $this->withHtml($resp)->assertElementCount('a', 5); // Test empty state $resp = $this->asEditor()->get('/search/suggest?term=spaghettisaurusrex'); $this->withHtml($resp)->assertElementCount('a', 0); $resp->assertSee('No items available'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Search/SiblingSearchTest.php
tests/Search/SiblingSearchTest.php
<?php namespace Tests\Search; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Bookshelf; use Tests\TestCase; class SiblingSearchTest extends TestCase { public function test_sibling_search_for_pages() { $chapter = $this->entities->chapterHasPages(); $this->assertGreaterThan(2, count($chapter->pages), 'Ensure we\'re testing with at least 1 sibling'); $page = $chapter->pages->first(); $search = $this->actingAs($this->users->viewer())->get("/search/entity/siblings?entity_id={$page->id}&entity_type=page"); $search->assertSuccessful(); foreach ($chapter->pages as $page) { $search->assertSee($page->name); } $search->assertDontSee($chapter->name); } public function test_sibling_search_for_pages_without_chapter() { $page = $this->entities->pageNotWithinChapter(); $bookChildren = $page->book->getDirectVisibleChildren(); $this->assertGreaterThan(2, count($bookChildren), 'Ensure we\'re testing with at least 1 sibling'); $search = $this->actingAs($this->users->viewer())->get("/search/entity/siblings?entity_id={$page->id}&entity_type=page"); $search->assertSuccessful(); foreach ($bookChildren as $child) { $search->assertSee($child->name); } $search->assertDontSee($page->book->name); } public function test_sibling_search_for_chapters() { $chapter = $this->entities->chapter(); $bookChildren = $chapter->book->getDirectVisibleChildren(); $this->assertGreaterThan(2, count($bookChildren), 'Ensure we\'re testing with at least 1 sibling'); $search = $this->actingAs($this->users->viewer())->get("/search/entity/siblings?entity_id={$chapter->id}&entity_type=chapter"); $search->assertSuccessful(); foreach ($bookChildren as $child) { $search->assertSee($child->name); } $search->assertDontSee($chapter->book->name); } public function test_sibling_search_for_books() { $books = Book::query()->take(10)->get(); $book = $books->first(); $this->assertGreaterThan(2, count($books), 'Ensure we\'re testing with at least 1 sibling'); $search = $this->actingAs($this->users->viewer())->get("/search/entity/siblings?entity_id={$book->id}&entity_type=book"); $search->assertSuccessful(); foreach ($books as $expectedBook) { $search->assertSee($expectedBook->name); } } public function test_sibling_search_for_shelves() { $shelves = Bookshelf::query()->take(10)->get(); $shelf = $shelves->first(); $this->assertGreaterThan(2, count($shelves), 'Ensure we\'re testing with at least 1 sibling'); $search = $this->actingAs($this->users->viewer())->get("/search/entity/siblings?entity_id={$shelf->id}&entity_type=bookshelf"); $search->assertSuccessful(); foreach ($shelves as $expectedShelf) { $search->assertSee($expectedShelf->name); } } public function test_sibling_search_for_books_provides_results_in_alphabetical_order() { $contextBook = $this->entities->book(); $searchBook = $this->entities->book(); $searchBook->name = 'Zebras'; $searchBook->save(); $search = $this->actingAs($this->users->viewer())->get("/search/entity/siblings?entity_id={$contextBook->id}&entity_type=book"); $this->withHtml($search)->assertElementNotContains('a:first-child', 'Zebras'); $searchBook->name = '1AAAAAAArdvarks'; $searchBook->save(); $search = $this->actingAs($this->users->viewer())->get("/search/entity/siblings?entity_id={$contextBook->id}&entity_type=book"); $this->withHtml($search)->assertElementContains('a:first-child', '1AAAAAAArdvarks'); } public function test_sibling_search_for_shelves_provides_results_in_alphabetical_order() { $contextShelf = $this->entities->shelf(); $searchShelf = $this->entities->shelf(); $searchShelf->name = 'Zebras'; $searchShelf->save(); $search = $this->actingAs($this->users->viewer())->get("/search/entity/siblings?entity_id={$contextShelf->id}&entity_type=bookshelf"); $this->withHtml($search)->assertElementNotContains('a:first-child', 'Zebras'); $searchShelf->name = '1AAAAAAArdvarks'; $searchShelf->save(); $search = $this->actingAs($this->users->viewer())->get("/search/entity/siblings?entity_id={$contextShelf->id}&entity_type=bookshelf"); $this->withHtml($search)->assertElementContains('a:first-child', '1AAAAAAArdvarks'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Search/SearchOptionsTest.php
tests/Search/SearchOptionsTest.php
<?php namespace Tests\Search; use BookStack\Search\Options\ExactSearchOption; use BookStack\Search\Options\FilterSearchOption; use BookStack\Search\Options\TagSearchOption; use BookStack\Search\Options\TermSearchOption; use BookStack\Search\SearchOptions; use BookStack\Search\SearchOptionSet; use Illuminate\Http\Request; use Tests\TestCase; class SearchOptionsTest extends TestCase { public function test_from_string_parses_a_search_string_properly() { $options = SearchOptions::fromString('cat "dog" [tag=good] {is_tree}'); $this->assertEquals(['cat'], $options->searches->toValueArray()); $this->assertEquals(['dog'], $options->exacts->toValueArray()); $this->assertEquals(['tag=good'], $options->tags->toValueArray()); $this->assertEquals(['is_tree' => ''], $options->filters->toValueMap()); } public function test_from_string_parses_negations() { $options = SearchOptions::fromString('cat -"dog" -[tag=good] -{is_tree}'); $this->assertEquals(['cat'], $options->searches->toValueArray()); $this->assertTrue($options->exacts->all()[0]->negated); $this->assertTrue($options->tags->all()[0]->negated); $this->assertTrue($options->filters->all()[0]->negated); } public function test_from_string_properly_parses_escaped_quotes() { $options = SearchOptions::fromString('"\"cat\"" surprise'); $this->assertEquals(['"cat"'], $options->exacts->toValueArray()); $options = SearchOptions::fromString('"\"\"" "\"donkey"'); $this->assertEquals(['""', '"donkey'], $options->exacts->toValueArray()); $options = SearchOptions::fromString('"\"" "\\\\"'); $this->assertEquals(['"', '\\'], $options->exacts->toValueArray()); } public function test_to_string_includes_all_items_in_the_correct_format() { $expected = 'cat "dog" [tag=good] {is_tree} {beans:valid}'; $options = new SearchOptions(); $options->searches = SearchOptionSet::fromValueArray(['cat'], TermSearchOption::class); $options->exacts = SearchOptionSet::fromValueArray(['dog'], ExactSearchOption::class); $options->tags = SearchOptionSet::fromValueArray(['tag=good'], TagSearchOption::class); $options->filters = new SearchOptionSet([ new FilterSearchOption('', 'is_tree'), new FilterSearchOption('valid', 'beans'), ]); $output = $options->toString(); foreach (explode(' ', $expected) as $term) { $this->assertStringContainsString($term, $output); } } public function test_to_string_handles_negations_as_expected() { $expected = 'cat -"dog" -[tag=good] -{is_tree}'; $options = new SearchOptions(); $options->searches = new SearchOptionSet([new TermSearchOption('cat')]); $options->exacts = new SearchOptionSet([new ExactSearchOption('dog', true)]); $options->tags = new SearchOptionSet([new TagSearchOption('tag=good', true)]); $options->filters = new SearchOptionSet([ new FilterSearchOption('', 'is_tree', true), ]); $output = $options->toString(); foreach (explode(' ', $expected) as $term) { $this->assertStringContainsString($term, $output); } } public function test_to_string_escapes_as_expected() { $options = new SearchOptions(); $options->exacts = SearchOptionSet::fromValueArray(['"cat"', '""', '"donkey', '"', '\\', '\\"'], ExactSearchOption::class); $output = $options->toString(); $this->assertEquals('"\"cat\"" "\"\"" "\"donkey" "\"" "\\\\" "\\\\\""', $output); } public function test_correct_filter_values_are_set_from_string() { $opts = SearchOptions::fromString('{is_tree} {name:dan} {cat:happy}'); $this->assertEquals([ 'is_tree' => '', 'name' => 'dan', 'cat' => 'happy', ], $opts->filters->toValueMap()); } public function test_it_cannot_parse_out_empty_exacts() { $options = SearchOptions::fromString('"" test ""'); $this->assertEmpty($options->exacts->toValueArray()); $this->assertCount(1, $options->searches->toValueArray()); } public function test_from_request_properly_parses_exacts_from_search_terms() { $this->asEditor(); $request = new Request([ 'search' => 'biscuits "cheese" "" "baked beans"' ]); $options = SearchOptions::fromRequest($request); $this->assertEquals(["biscuits"], $options->searches->toValueArray()); $this->assertEquals(['"cheese"', '""', '"baked', 'beans"'], $options->exacts->toValueArray()); } public function test_from_request_properly_parses_provided_types() { $request = new Request([ 'search' => '', 'types' => ['page', 'book'], ]); $options = SearchOptions::fromRequest($request); $filters = $options->filters->toValueMap(); $this->assertCount(1, $filters); $this->assertEquals('page|book', $filters['type'] ?? 'notfound'); } public function test_from_request_properly_parses_out_extras_as_string() { $request = new Request([ 'search' => '', 'tags' => ['a=b'], 'extras' => '-[b=c] -{viewed_by_me} -"dino"' ]); $options = SearchOptions::fromRequest($request); $this->assertCount(2, $options->tags->all()); $this->assertEquals('b=c', $options->tags->negated()->all()[0]->value); $this->assertEquals('viewed_by_me', $options->filters->all()[0]->getKey()); $this->assertTrue($options->filters->all()[0]->negated); $this->assertEquals('dino', $options->exacts->all()[0]->value); $this->assertTrue($options->exacts->all()[0]->negated); } public function test_from_string_results_are_count_limited_and_larger_for_logged_in_users() { $terms = [ ...array_fill(0, 40, 'cat'), ...array_fill(0, 50, '"bees"'), ...array_fill(0, 50, '{is_template}'), ...array_fill(0, 50, '[a=b]'), ]; $options = SearchOptions::fromString(implode(' ', $terms)); $this->assertCount(5, $options->searches->all()); $this->assertCount(2, $options->exacts->all()); $this->assertCount(4, $options->tags->all()); $this->assertCount(5, $options->filters->all()); $this->asEditor(); $options = SearchOptions::fromString(implode(' ', $terms)); $this->assertCount(10, $options->searches->all()); $this->assertCount(4, $options->exacts->all()); $this->assertCount(8, $options->tags->all()); $this->assertCount(10, $options->filters->all()); } public function test_from_request_results_are_count_limited_and_larger_for_logged_in_users() { $request = new Request([ 'search' => str_repeat('hello ', 20), 'tags' => array_fill(0, 20, 'a=b'), 'extras' => str_repeat('-[b=c] -{viewed_by_me} -"dino"', 20), ]); $options = SearchOptions::fromRequest($request); $this->assertCount(5, $options->searches->all()); $this->assertCount(2, $options->exacts->all()); $this->assertCount(4, $options->tags->all()); $this->assertCount(5, $options->filters->all()); $this->asEditor(); $options = SearchOptions::fromRequest($request); $this->assertCount(10, $options->searches->all()); $this->assertCount(4, $options->exacts->all()); $this->assertCount(8, $options->tags->all()); $this->assertCount(10, $options->filters->all()); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Search/SearchIndexingTest.php
tests/Search/SearchIndexingTest.php
<?php namespace Tests\Search; use Tests\TestCase; class SearchIndexingTest extends TestCase { public function test_terms_in_headers_have_an_adjusted_index_score() { $page = $this->entities->newPage(['name' => 'Test page A', 'html' => ' <p>TermA</p> <h1>TermB <strong>TermNested</strong></h1> <h2>TermC</h2> <h3>TermD</h3> <h4>TermE</h4> <h5>TermF</h5> <h6>TermG</h6> ']); $scoreByTerm = $page->searchTerms()->pluck('score', 'term'); $this->assertEquals(1, $scoreByTerm->get('TermA')); $this->assertEquals(10, $scoreByTerm->get('TermB')); $this->assertEquals(10, $scoreByTerm->get('TermNested')); $this->assertEquals(5, $scoreByTerm->get('TermC')); $this->assertEquals(4, $scoreByTerm->get('TermD')); $this->assertEquals(3, $scoreByTerm->get('TermE')); $this->assertEquals(2, $scoreByTerm->get('TermF')); // Is 1.5 but stored as integer, rounding up $this->assertEquals(2, $scoreByTerm->get('TermG')); } public function test_indexing_works_as_expected_for_page_with_lots_of_terms() { $this->markTestSkipped('Time consuming test'); $count = 100000; $text = ''; $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_#'; for ($i = 0; $i < $count; $i++) { $text .= substr(str_shuffle($chars), 0, 5) . ' '; } $page = $this->entities->newPage(['name' => 'Test page A', 'html' => '<p>' . $text . '</p>']); $termCount = $page->searchTerms()->count(); // Expect at least 90% unique rate $this->assertGreaterThan($count * 0.9, $termCount); } public function test_name_and_content_terms_are_merged_to_single_score() { $page = $this->entities->newPage(['name' => 'TermA', 'html' => ' <p>TermA</p> ']); $scoreByTerm = $page->searchTerms()->pluck('score', 'term'); // Scores 40 for being in the name then 1 for being in the content $this->assertEquals(41, $scoreByTerm->get('TermA')); } public function test_tag_names_and_values_are_indexed_for_search() { $page = $this->entities->newPage(['name' => 'PageA', 'html' => '<p>content</p>', 'tags' => [ ['name' => 'Animal', 'value' => 'MeowieCat'], ['name' => 'SuperImportant'], ]]); $scoreByTerm = $page->searchTerms()->pluck('score', 'term'); $this->assertEquals(5, $scoreByTerm->get('MeowieCat')); $this->assertEquals(3, $scoreByTerm->get('Animal')); $this->assertEquals(3, $scoreByTerm->get('SuperImportant')); } public function test_terms_containing_guillemets_handled() { $page = $this->entities->newPage(['html' => '<p>«Hello there» and « there »</p>']); $scoreByTerm = $page->searchTerms()->pluck('score', 'term'); $expected = ['Hello', 'there', 'and']; foreach ($expected as $term) { $this->assertNotNull($scoreByTerm->get($term), "Failed asserting that \"$term\" is indexed"); } $nonExpected = ['«', '»']; foreach ($nonExpected as $term) { $this->assertNull($scoreByTerm->get($term), "Failed asserting that \"$term\" is not indexed"); } } public function test_terms_containing_punctuation_within_retain_original_form_and_split_form_in_index() { $page = $this->entities->newPage(['html' => '<p>super.duper awesome-beans big- barry cheese.</p><p>biscuits</p><p>a-bs</p>']); $scoreByTerm = $page->searchTerms()->pluck('score', 'term'); $expected = ['super', 'duper', 'super.duper', 'awesome-beans', 'awesome', 'beans', 'big', 'barry', 'cheese', 'biscuits', 'a-bs', 'a', 'bs']; foreach ($expected as $term) { $this->assertNotNull($scoreByTerm->get($term), "Failed asserting that \"$term\" is indexed"); } $nonExpected = ['big-', 'big-barry', 'cheese.', 'cheese.biscuits']; foreach ($nonExpected as $term) { $this->assertNull($scoreByTerm->get($term), "Failed asserting that \"$term\" is not indexed"); } } public function test_non_breaking_spaces_handled_as_spaces() { $page = $this->entities->newPage(['html' => '<p>a&nbsp;tigerbadger is a dangerous&nbsp;animal</p>']); $scoreByTerm = $page->searchTerms()->pluck('score', 'term'); $this->assertNotNull($scoreByTerm->get('tigerbadger')); $this->assertNotNull($scoreByTerm->get('dangerous')); $this->assertNotNull($scoreByTerm->get('animal')); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Permissions/RolePermissionsTest.php
tests/Permissions/RolePermissionsTest.php
<?php namespace Tests\Permissions; use BookStack\Activity\Models\Comment; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Bookshelf; use BookStack\Entities\Models\Chapter; use BookStack\Entities\Models\Entity; use BookStack\Entities\Models\Page; use BookStack\Uploads\Image; use BookStack\Users\Models\User; use Illuminate\Testing\TestResponse; use Tests\TestCase; class RolePermissionsTest extends TestCase { protected User $user; protected function setUp(): void { parent::setUp(); $this->user = $this->users->viewer(); } public function test_manage_user_permission() { $this->actingAs($this->user)->get('/settings/users')->assertRedirect('/'); $this->permissions->grantUserRolePermissions($this->user, ['users-manage']); $this->actingAs($this->user)->get('/settings/users')->assertOk(); } public function test_manage_users_permission_shows_link_in_header_if_does_not_have_settings_manage_permision() { $usersLink = 'href="' . url('/settings/users') . '"'; $this->actingAs($this->user)->get('/')->assertDontSee($usersLink, false); $this->permissions->grantUserRolePermissions($this->user, ['users-manage']); $this->actingAs($this->user)->get('/')->assertSee($usersLink, false); $this->permissions->grantUserRolePermissions($this->user, ['settings-manage', 'users-manage']); $this->actingAs($this->user)->get('/')->assertDontSee($usersLink, false); } public function test_user_cannot_change_email_unless_they_have_manage_users_permission() { $originalEmail = $this->user->email; $this->actingAs($this->user); $resp = $this->get('/my-account/profile')->assertOk(); $this->withHtml($resp)->assertElementExists('input[name=email][disabled]'); $resp->assertSee('Unfortunately you don\'t have permission to change your email address.'); $this->put('/my-account/profile', [ 'name' => 'my_new_name', 'email' => 'new_email@example.com', ]); $this->assertDatabaseHas('users', [ 'id' => $this->user->id, 'email' => $originalEmail, 'name' => 'my_new_name', ]); $this->permissions->grantUserRolePermissions($this->user, ['users-manage']); $resp = $this->get('/my-account/profile')->assertOk(); $this->withHtml($resp) ->assertElementNotExists('input[name=email][disabled]') ->assertElementExists('input[name=email]'); $this->put('/my-account/profile', [ 'name' => 'my_new_name_2', 'email' => 'new_email@example.com', ]); $this->assertDatabaseHas('users', [ 'id' => $this->user->id, 'email' => 'new_email@example.com', 'name' => 'my_new_name_2', ]); } public function test_user_roles_manage_permission() { $this->actingAs($this->user)->get('/settings/roles')->assertRedirect('/'); $this->get('/settings/roles/1')->assertRedirect('/'); $this->permissions->grantUserRolePermissions($this->user, ['user-roles-manage']); $this->actingAs($this->user)->get('/settings/roles')->assertOk(); $this->get('/settings/roles/1') ->assertOk() ->assertSee('Admin'); } public function test_settings_manage_permission() { $this->actingAs($this->user)->get('/settings/features')->assertRedirect('/'); $this->permissions->grantUserRolePermissions($this->user, ['settings-manage']); $this->get('/settings/features')->assertOk(); $resp = $this->post('/settings/features', []); $resp->assertRedirect('/settings/features'); $resp = $this->get('/settings/features'); $resp->assertSee('Settings successfully updated'); } public function test_restrictions_manage_all_permission() { $page = $this->entities->page(); $this->actingAs($this->user)->get($page->getUrl())->assertDontSee('Permissions'); $this->get($page->getUrl('/permissions'))->assertRedirect('/'); $this->permissions->grantUserRolePermissions($this->user, ['restrictions-manage-all']); $this->actingAs($this->user)->get($page->getUrl())->assertSee('Permissions'); $this->get($page->getUrl('/permissions')) ->assertOk() ->assertSee('Page Permissions'); } public function test_restrictions_manage_own_permission() { $otherUsersPage = $this->entities->page(); $content = $this->entities->createChainBelongingToUser($this->user); // Set a different creator on the page we're checking to ensure // that the owner fields are checked $page = $content['page']; /** @var Page $page */ $page->created_by = $otherUsersPage->id; $page->owned_by = $this->user->id; $page->save(); // Check can't restrict other's content $this->actingAs($this->user)->get($otherUsersPage->getUrl())->assertDontSee('Permissions'); $this->get($otherUsersPage->getUrl('/permissions'))->assertRedirect('/'); // Check can't restrict own content $this->actingAs($this->user)->get($page->getUrl())->assertDontSee('Permissions'); $this->get($page->getUrl('/permissions'))->assertRedirect('/'); $this->permissions->grantUserRolePermissions($this->user, ['restrictions-manage-own']); // Check can't restrict other's content $this->actingAs($this->user)->get($otherUsersPage->getUrl())->assertDontSee('Permissions'); $this->get($otherUsersPage->getUrl('/permissions'))->assertRedirect(); // Check can restrict own content $this->actingAs($this->user)->get($page->getUrl())->assertSee('Permissions'); $this->get($page->getUrl('/permissions'))->assertOk(); } /** * Check a standard entity access permission. */ private function checkAccessPermission( string $permission, array $accessUrls = [], array $visibles = [], string $expectedRedirectUri = '/', ) { foreach ($accessUrls as $url) { $this->actingAs($this->user)->get($url)->assertRedirect($expectedRedirectUri); } foreach ($visibles as $url => $text) { $resp = $this->actingAs($this->user)->get($url); $this->withHtml($resp)->assertElementNotContains('.action-buttons', $text); } $this->permissions->grantUserRolePermissions($this->user, [$permission]); foreach ($accessUrls as $url) { $this->actingAs($this->user)->get($url)->assertOk(); } foreach ($visibles as $url => $text) { $this->actingAs($this->user)->get($url)->assertSee($text); } } public function test_bookshelves_create_all_permissions() { $this->checkAccessPermission('bookshelf-create-all', [ '/create-shelf', ], [ '/shelves' => 'New Shelf', ]); $this->post('/shelves', [ 'name' => 'test shelf', 'description' => 'shelf desc', ])->assertRedirect('/shelves/test-shelf'); } public function test_bookshelves_edit_own_permission() { /** @var Bookshelf $otherShelf */ $otherShelf = Bookshelf::query()->first(); $ownShelf = $this->entities->newShelf(['name' => 'test-shelf', 'slug' => 'test-shelf']); $ownShelf->forceFill(['owned_by' => $this->user->id, 'updated_by' => $this->user->id])->save(); $this->permissions->regenerateForEntity($ownShelf); $this->checkAccessPermission('bookshelf-update-own', [ $ownShelf->getUrl('/edit'), ], [ $ownShelf->getUrl() => 'Edit', ]); $resp = $this->get($otherShelf->getUrl()); $this->withHtml($resp)->assertElementNotContains('.action-buttons', 'Edit'); $this->get($otherShelf->getUrl('/edit'))->assertRedirect('/'); } public function test_bookshelves_edit_all_permission() { /** @var Bookshelf $otherShelf */ $otherShelf = Bookshelf::query()->first(); $this->checkAccessPermission('bookshelf-update-all', [ $otherShelf->getUrl('/edit'), ], [ $otherShelf->getUrl() => 'Edit', ]); } public function test_bookshelves_delete_own_permission() { $this->permissions->grantUserRolePermissions($this->user, ['bookshelf-update-all']); /** @var Bookshelf $otherShelf */ $otherShelf = Bookshelf::query()->first(); $ownShelf = $this->entities->newShelf(['name' => 'test-shelf', 'slug' => 'test-shelf']); $ownShelf->forceFill(['owned_by' => $this->user->id, 'updated_by' => $this->user->id])->save(); $this->permissions->regenerateForEntity($ownShelf); $this->checkAccessPermission('bookshelf-delete-own', [ $ownShelf->getUrl('/delete'), ], [ $ownShelf->getUrl() => 'Delete', ]); $resp = $this->get($otherShelf->getUrl()); $this->withHtml($resp)->assertElementNotContains('.action-buttons', 'Delete'); $this->get($otherShelf->getUrl('/delete'))->assertRedirect('/'); $this->get($ownShelf->getUrl()); $this->delete($ownShelf->getUrl())->assertRedirect('/shelves'); $this->get('/shelves')->assertDontSee($ownShelf->name); } public function test_bookshelves_delete_all_permission() { $this->permissions->grantUserRolePermissions($this->user, ['bookshelf-update-all']); /** @var Bookshelf $otherShelf */ $otherShelf = Bookshelf::query()->first(); $this->checkAccessPermission('bookshelf-delete-all', [ $otherShelf->getUrl('/delete'), ], [ $otherShelf->getUrl() => 'Delete', ]); $this->delete($otherShelf->getUrl())->assertRedirect('/shelves'); $this->get('/shelves')->assertDontSee($otherShelf->name); } public function test_books_create_all_permissions() { $this->checkAccessPermission('book-create-all', [ '/create-book', ], [ '/books' => 'Create New Book', ]); $this->post('/books', [ 'name' => 'test book', 'description' => 'book desc', ])->assertRedirect('/books/test-book'); } public function test_books_edit_own_permission() { /** @var Book $otherBook */ $otherBook = Book::query()->take(1)->get()->first(); $ownBook = $this->entities->createChainBelongingToUser($this->user)['book']; $this->checkAccessPermission('book-update-own', [ $ownBook->getUrl() . '/edit', ], [ $ownBook->getUrl() => 'Edit', ]); $resp = $this->get($otherBook->getUrl()); $this->withHtml($resp)->assertElementNotContains('.action-buttons', 'Edit'); $this->get($otherBook->getUrl('/edit'))->assertRedirect('/'); } public function test_books_edit_all_permission() { /** @var Book $otherBook */ $otherBook = Book::query()->take(1)->get()->first(); $this->checkAccessPermission('book-update-all', [ $otherBook->getUrl() . '/edit', ], [ $otherBook->getUrl() => 'Edit', ]); } public function test_books_delete_own_permission() { $this->permissions->grantUserRolePermissions($this->user, ['book-update-all']); /** @var Book $otherBook */ $otherBook = Book::query()->take(1)->get()->first(); $ownBook = $this->entities->createChainBelongingToUser($this->user)['book']; $this->checkAccessPermission('book-delete-own', [ $ownBook->getUrl() . '/delete', ], [ $ownBook->getUrl() => 'Delete', ]); $resp = $this->get($otherBook->getUrl()); $this->withHtml($resp)->assertElementNotContains('.action-buttons', 'Delete'); $this->get($otherBook->getUrl('/delete'))->assertRedirect('/'); $this->get($ownBook->getUrl()); $this->delete($ownBook->getUrl())->assertRedirect('/books'); $this->get('/books')->assertDontSee($ownBook->name); } public function test_books_delete_all_permission() { $this->permissions->grantUserRolePermissions($this->user, ['book-update-all']); /** @var Book $otherBook */ $otherBook = Book::query()->take(1)->get()->first(); $this->checkAccessPermission('book-delete-all', [ $otherBook->getUrl() . '/delete', ], [ $otherBook->getUrl() => 'Delete', ]); $this->get($otherBook->getUrl()); $this->delete($otherBook->getUrl())->assertRedirect('/books'); $this->get('/books')->assertDontSee($otherBook->name); } public function test_chapter_create_own_permissions() { /** @var Book $book */ $book = Book::query()->take(1)->get()->first(); $ownBook = $this->entities->createChainBelongingToUser($this->user)['book']; $this->checkAccessPermission('chapter-create-own', [ $ownBook->getUrl('/create-chapter'), ], [ $ownBook->getUrl() => 'New Chapter', ]); $this->post($ownBook->getUrl('/create-chapter'), [ 'name' => 'test chapter', 'description' => 'chapter desc', ])->assertRedirect($ownBook->getUrl('/chapter/test-chapter')); $resp = $this->get($book->getUrl()); $this->withHtml($resp)->assertElementNotContains('.action-buttons', 'New Chapter'); $this->get($book->getUrl('/create-chapter'))->assertRedirect('/'); } public function test_chapter_create_all_permissions() { $book = $this->entities->book(); $this->checkAccessPermission('chapter-create-all', [ $book->getUrl('/create-chapter'), ], [ $book->getUrl() => 'New Chapter', ]); $this->post($book->getUrl('/create-chapter'), [ 'name' => 'test chapter', 'description' => 'chapter desc', ])->assertRedirect($book->getUrl('/chapter/test-chapter')); } public function test_chapter_edit_own_permission() { /** @var Chapter $otherChapter */ $otherChapter = Chapter::query()->first(); $ownChapter = $this->entities->createChainBelongingToUser($this->user)['chapter']; $this->checkAccessPermission('chapter-update-own', [ $ownChapter->getUrl() . '/edit', ], [ $ownChapter->getUrl() => 'Edit', ]); $resp = $this->get($otherChapter->getUrl()); $this->withHtml($resp)->assertElementNotContains('.action-buttons', 'Edit'); $this->get($otherChapter->getUrl('/edit'))->assertRedirect('/'); } public function test_chapter_edit_all_permission() { /** @var Chapter $otherChapter */ $otherChapter = Chapter::query()->take(1)->get()->first(); $this->checkAccessPermission('chapter-update-all', [ $otherChapter->getUrl() . '/edit', ], [ $otherChapter->getUrl() => 'Edit', ]); } public function test_chapter_delete_own_permission() { $this->permissions->grantUserRolePermissions($this->user, ['chapter-update-all']); /** @var Chapter $otherChapter */ $otherChapter = Chapter::query()->first(); $ownChapter = $this->entities->createChainBelongingToUser($this->user)['chapter']; $this->checkAccessPermission('chapter-delete-own', [ $ownChapter->getUrl() . '/delete', ], [ $ownChapter->getUrl() => 'Delete', ]); $bookUrl = $ownChapter->book->getUrl(); $resp = $this->get($otherChapter->getUrl()); $this->withHtml($resp)->assertElementNotContains('.action-buttons', 'Delete'); $this->get($otherChapter->getUrl('/delete'))->assertRedirect('/'); $this->get($ownChapter->getUrl()); $this->delete($ownChapter->getUrl())->assertRedirect($bookUrl); $resp = $this->get($bookUrl); $this->withHtml($resp)->assertElementNotContains('.book-content', $ownChapter->name); } public function test_chapter_delete_all_permission() { $this->permissions->grantUserRolePermissions($this->user, ['chapter-update-all']); /** @var Chapter $otherChapter */ $otherChapter = Chapter::query()->first(); $this->checkAccessPermission('chapter-delete-all', [ $otherChapter->getUrl() . '/delete', ], [ $otherChapter->getUrl() => 'Delete', ]); $bookUrl = $otherChapter->book->getUrl(); $this->get($otherChapter->getUrl()); $this->delete($otherChapter->getUrl())->assertRedirect($bookUrl); $resp = $this->get($bookUrl); $this->withHtml($resp)->assertElementNotContains('.book-content', $otherChapter->name); } public function test_page_create_own_permissions() { $book = $this->entities->book(); $chapter = $this->entities->chapter(); $entities = $this->entities->createChainBelongingToUser($this->user); $ownBook = $entities['book']; $ownChapter = $entities['chapter']; $createUrl = $ownBook->getUrl('/create-page'); $createUrlChapter = $ownChapter->getUrl('/create-page'); $accessUrls = [$createUrl, $createUrlChapter]; foreach ($accessUrls as $url) { $this->actingAs($this->user)->get($url)->assertRedirect('/'); } $this->checkAccessPermission('page-create-own', [], [ $ownBook->getUrl() => 'New Page', $ownChapter->getUrl() => 'New Page', ]); $this->permissions->grantUserRolePermissions($this->user, ['page-create-own']); foreach ($accessUrls as $index => $url) { $resp = $this->actingAs($this->user)->get($url); $expectedUrl = Page::query()->where('draft', '=', true)->orderBy('id', 'desc')->first()->getUrl(); $resp->assertRedirect($expectedUrl); } $this->get($createUrl); /** @var Page $draft */ $draft = Page::query()->where('draft', '=', true)->orderBy('id', 'desc')->first(); $this->post($draft->getUrl(), [ 'name' => 'test page', 'html' => 'page desc', ])->assertRedirect($ownBook->getUrl('/page/test-page')); $resp = $this->get($book->getUrl()); $this->withHtml($resp)->assertElementNotContains('.action-buttons', 'New Page'); $this->get($book->getUrl('/create-page'))->assertRedirect('/'); $resp = $this->get($chapter->getUrl()); $this->withHtml($resp)->assertElementNotContains('.action-buttons', 'New Page'); $this->get($chapter->getUrl('/create-page'))->assertRedirect('/'); } public function test_page_create_all_permissions() { $book = $this->entities->book(); $chapter = $this->entities->chapter(); $createUrl = $book->getUrl('/create-page'); $createUrlChapter = $chapter->getUrl('/create-page'); $accessUrls = [$createUrl, $createUrlChapter]; foreach ($accessUrls as $url) { $this->actingAs($this->user)->get($url)->assertRedirect('/'); } $this->checkAccessPermission('page-create-all', [], [ $book->getUrl() => 'New Page', $chapter->getUrl() => 'New Page', ]); $this->permissions->grantUserRolePermissions($this->user, ['page-create-all']); foreach ($accessUrls as $index => $url) { $resp = $this->actingAs($this->user)->get($url); $expectedUrl = Page::query()->where('draft', '=', true)->orderBy('id', 'desc')->first()->getUrl(); $resp->assertRedirect($expectedUrl); } $this->get($createUrl); /** @var Page $draft */ $draft = Page::query()->where('draft', '=', true)->orderByDesc('id')->first(); $this->post($draft->getUrl(), [ 'name' => 'test page', 'html' => 'page desc', ])->assertRedirect($book->getUrl('/page/test-page')); $this->get($chapter->getUrl('/create-page')); /** @var Page $draft */ $draft = Page::query()->where('draft', '=', true)->orderByDesc('id')->first(); $this->post($draft->getUrl(), [ 'name' => 'new test page', 'html' => 'page desc', ])->assertRedirect($book->getUrl('/page/new-test-page')); } public function test_page_edit_own_permission() { /** @var Page $otherPage */ $otherPage = Page::query()->first(); $ownPage = $this->entities->createChainBelongingToUser($this->user)['page']; $this->checkAccessPermission('page-update-own', [ $ownPage->getUrl() . '/edit', ], [ $ownPage->getUrl() => 'Edit', ], $ownPage->getUrl()); $resp = $this->get($otherPage->getUrl()); $this->withHtml($resp)->assertElementNotContains('.action-buttons', 'Edit'); $this->get($otherPage->getUrl() . '/edit')->assertRedirect($otherPage->getUrl()); } public function test_page_edit_all_permission() { /** @var Page $otherPage */ $otherPage = Page::query()->first(); $this->checkAccessPermission('page-update-all', [ $otherPage->getUrl('/edit'), ], [ $otherPage->getUrl() => 'Edit', ], $otherPage->getUrl()); } public function test_page_delete_own_permission() { $this->permissions->grantUserRolePermissions($this->user, ['page-update-all']); /** @var Page $otherPage */ $otherPage = Page::query()->first(); $ownPage = $this->entities->createChainBelongingToUser($this->user)['page']; $this->checkAccessPermission('page-delete-own', [ $ownPage->getUrl() . '/delete', ], [ $ownPage->getUrl() => 'Delete', ]); $parent = $ownPage->chapter ?? $ownPage->book; $resp = $this->get($otherPage->getUrl()); $this->withHtml($resp)->assertElementNotContains('.action-buttons', 'Delete'); $this->get($otherPage->getUrl('/delete'))->assertRedirect('/'); $this->get($ownPage->getUrl()); $this->delete($ownPage->getUrl())->assertRedirect($parent->getUrl()); $resp = $this->get($parent->getUrl()); $this->withHtml($resp)->assertElementNotContains('.book-content', $ownPage->name); } public function test_page_delete_all_permission() { $this->permissions->grantUserRolePermissions($this->user, ['page-update-all']); /** @var Page $otherPage */ $otherPage = Page::query()->first(); $this->checkAccessPermission('page-delete-all', [ $otherPage->getUrl() . '/delete', ], [ $otherPage->getUrl() => 'Delete', ]); /** @var Entity $parent */ $parent = $otherPage->chapter ?? $otherPage->book; $this->get($otherPage->getUrl()); $this->delete($otherPage->getUrl())->assertRedirect($parent->getUrl()); $this->get($parent->getUrl())->assertDontSee($otherPage->name); } public function test_image_delete_own_permission() { $this->permissions->grantUserRolePermissions($this->user, ['image-update-all']); $page = $this->entities->page(); $image = Image::factory()->create([ 'uploaded_to' => $page->id, 'created_by' => $this->user->id, 'updated_by' => $this->user->id, ]); $this->actingAs($this->user)->json('delete', '/images/' . $image->id)->assertStatus(403); $this->permissions->grantUserRolePermissions($this->user, ['image-delete-own']); $this->actingAs($this->user)->json('delete', '/images/' . $image->id)->assertOk(); $this->assertDatabaseMissing('images', ['id' => $image->id]); } public function test_image_delete_all_permission() { $this->permissions->grantUserRolePermissions($this->user, ['image-update-all']); $admin = $this->users->admin(); $page = $this->entities->page(); $image = Image::factory()->create(['uploaded_to' => $page->id, 'created_by' => $admin->id, 'updated_by' => $admin->id]); $this->actingAs($this->user)->json('delete', '/images/' . $image->id)->assertStatus(403); $this->permissions->grantUserRolePermissions($this->user, ['image-delete-own']); $this->actingAs($this->user)->json('delete', '/images/' . $image->id)->assertStatus(403); $this->permissions->grantUserRolePermissions($this->user, ['image-delete-all']); $this->actingAs($this->user)->json('delete', '/images/' . $image->id)->assertOk(); $this->assertDatabaseMissing('images', ['id' => $image->id]); } public function test_empty_state_actions_not_visible_without_permission() { $admin = $this->users->admin(); // Book links $book = Book::factory()->create(['created_by' => $admin->id, 'updated_by' => $admin->id]); $this->permissions->regenerateForEntity($book); $this->actingAs($this->users->viewer())->get($book->getUrl()) ->assertDontSee('Create a new page') ->assertDontSee('Add a chapter'); // Chapter links $chapter = Chapter::factory()->create(['created_by' => $admin->id, 'updated_by' => $admin->id, 'book_id' => $book->id]); $this->permissions->regenerateForEntity($chapter); $this->actingAs($this->users->viewer())->get($chapter->getUrl()) ->assertDontSee('Create a new page') ->assertDontSee('Sort the current book'); } public function test_comment_create_permission() { $ownPage = $this->entities->createChainBelongingToUser($this->user)['page']; $this->actingAs($this->user) ->addComment($ownPage) ->assertStatus(403); $this->permissions->grantUserRolePermissions($this->user, ['comment-create-all']); $this->actingAs($this->user) ->addComment($ownPage) ->assertOk(); } public function test_comment_update_own_permission() { $ownPage = $this->entities->createChainBelongingToUser($this->user)['page']; $this->permissions->grantUserRolePermissions($this->user, ['comment-create-all']); $this->actingAs($this->user)->addComment($ownPage); /** @var Comment $comment */ $comment = $ownPage->comments()->latest()->first(); // no comment-update-own $this->actingAs($this->user)->updateComment($comment)->assertStatus(403); $this->permissions->grantUserRolePermissions($this->user, ['comment-update-own']); // now has comment-update-own $this->actingAs($this->user)->updateComment($comment)->assertOk(); } public function test_comment_update_all_permission() { /** @var Page $ownPage */ $ownPage = $this->entities->createChainBelongingToUser($this->user)['page']; $this->asAdmin()->addComment($ownPage); /** @var Comment $comment */ $comment = $ownPage->comments()->latest()->first(); // no comment-update-all $this->actingAs($this->user)->updateComment($comment)->assertStatus(403); $this->permissions->grantUserRolePermissions($this->user, ['comment-update-all']); // now has comment-update-all $this->actingAs($this->user)->updateComment($comment)->assertOk(); } public function test_comment_delete_own_permission() { /** @var Page $ownPage */ $ownPage = $this->entities->createChainBelongingToUser($this->user)['page']; $this->permissions->grantUserRolePermissions($this->user, ['comment-create-all']); $this->actingAs($this->user)->addComment($ownPage); /** @var Comment $comment */ $comment = $ownPage->comments()->latest()->first(); // no comment-delete-own $this->actingAs($this->user)->deleteComment($comment)->assertStatus(403); $this->permissions->grantUserRolePermissions($this->user, ['comment-delete-own']); // now has comment-update-own $this->actingAs($this->user)->deleteComment($comment)->assertOk(); } public function test_comment_delete_all_permission() { /** @var Page $ownPage */ $ownPage = $this->entities->createChainBelongingToUser($this->user)['page']; $this->asAdmin()->addComment($ownPage); /** @var Comment $comment */ $comment = $ownPage->comments()->latest()->first(); // no comment-delete-all $this->actingAs($this->user)->deleteComment($comment)->assertStatus(403); $this->permissions->grantUserRolePermissions($this->user, ['comment-delete-all']); // now has comment-delete-all $this->actingAs($this->user)->deleteComment($comment)->assertOk(); } private function addComment(Page $page): TestResponse { return $this->postJson("/comment/$page->id", ['html' => '<p>New comment content</p>']); } private function updateComment(Comment $comment): TestResponse { return $this->putJson("/comment/{$comment->id}", ['html' => '<p>Updated comment content</p>']); } private function deleteComment(Comment $comment): TestResponse { return $this->json('DELETE', '/comment/' . $comment->id); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Permissions/ExportPermissionsTest.php
tests/Permissions/ExportPermissionsTest.php
<?php namespace Tests\Permissions; use Illuminate\Support\Str; use Tests\TestCase; class ExportPermissionsTest extends TestCase { public function test_page_content_without_view_access_hidden_on_chapter_export() { $chapter = $this->entities->chapter(); $page = $chapter->pages()->firstOrFail(); $pageContent = Str::random(48); $page->html = '<p>' . $pageContent . '</p>'; $page->save(); $viewer = $this->users->viewer(); $this->actingAs($viewer); $formats = ['html', 'plaintext']; foreach ($formats as $format) { $resp = $this->get($chapter->getUrl("export/{$format}")); $resp->assertStatus(200); $resp->assertSee($page->name); $resp->assertSee($pageContent); } $this->permissions->setEntityPermissions($page, []); foreach ($formats as $format) { $resp = $this->get($chapter->getUrl("export/{$format}")); $resp->assertStatus(200); $resp->assertDontSee($page->name); $resp->assertDontSee($pageContent); } } public function test_page_content_without_view_access_hidden_on_book_export() { $book = $this->entities->book(); $page = $book->pages()->firstOrFail(); $pageContent = Str::random(48); $page->html = '<p>' . $pageContent . '</p>'; $page->save(); $viewer = $this->users->viewer(); $this->actingAs($viewer); $formats = ['html', 'plaintext']; foreach ($formats as $format) { $resp = $this->get($book->getUrl("export/{$format}")); $resp->assertStatus(200); $resp->assertSee($page->name); $resp->assertSee($pageContent); } $this->permissions->setEntityPermissions($page, []); foreach ($formats as $format) { $resp = $this->get($book->getUrl("export/{$format}")); $resp->assertStatus(200); $resp->assertDontSee($page->name); $resp->assertDontSee($pageContent); } } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Permissions/EntityPermissionsTest.php
tests/Permissions/EntityPermissionsTest.php
<?php namespace Tests\Permissions; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Bookshelf; use BookStack\Entities\Models\Chapter; use BookStack\Entities\Models\Entity; use BookStack\Entities\Models\Page; use BookStack\Permissions\Permission; use BookStack\Users\Models\Role; use BookStack\Users\Models\User; use Exception; use Illuminate\Support\Str; use Tests\TestCase; class EntityPermissionsTest extends TestCase { protected User $user; protected User $viewer; protected function setUp(): void { parent::setUp(); $this->user = $this->users->editor(); $this->viewer = $this->users->viewer(); } protected function setRestrictionsForTestRoles(Entity $entity, array $actions = []): void { $roles = [ $this->user->roles->first(), $this->viewer->roles->first(), ]; $this->permissions->setEntityPermissions($entity, $actions, $roles); } public function test_bookshelf_view_restriction() { $shelf = $this->entities->shelf(); $this->actingAs($this->user) ->get($shelf->getUrl()) ->assertStatus(200); $this->setRestrictionsForTestRoles($shelf, []); $this->followingRedirects()->get($shelf->getUrl()) ->assertSee('Shelf not found'); $this->setRestrictionsForTestRoles($shelf, ['view']); $this->get($shelf->getUrl()) ->assertSee($shelf->name); } public function test_bookshelf_update_restriction() { $shelf = $this->entities->shelf(); $this->actingAs($this->user) ->get($shelf->getUrl('/edit')) ->assertSee('Edit Shelf'); $this->setRestrictionsForTestRoles($shelf, ['view', 'delete']); $resp = $this->get($shelf->getUrl('/edit')) ->assertRedirect('/'); $this->followRedirects($resp)->assertSee('You do not have permission'); $this->setRestrictionsForTestRoles($shelf, ['view', 'update']); $this->get($shelf->getUrl('/edit')) ->assertOk(); } public function test_bookshelf_delete_restriction() { $shelf = $this->entities->shelf(); $this->actingAs($this->user) ->get($shelf->getUrl('/delete')) ->assertSee('Delete Shelf'); $this->setRestrictionsForTestRoles($shelf, ['view', 'update']); $this->get($shelf->getUrl('/delete'))->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->setRestrictionsForTestRoles($shelf, ['view', 'delete']); $this->get($shelf->getUrl('/delete')) ->assertOk() ->assertSee('Delete Shelf'); } public function test_book_view_restriction() { $book = $this->entities->book(); $bookPage = $book->pages->first(); $bookChapter = $book->chapters->first(); $bookUrl = $book->getUrl(); $this->actingAs($this->user) ->get($bookUrl) ->assertOk(); $this->setRestrictionsForTestRoles($book, []); $this->followingRedirects()->get($bookUrl) ->assertSee('Book not found'); $this->followingRedirects()->get($bookPage->getUrl()) ->assertSee('Page not found'); $this->followingRedirects()->get($bookChapter->getUrl()) ->assertSee('Chapter not found'); $this->setRestrictionsForTestRoles($book, ['view']); $this->get($bookUrl) ->assertSee($book->name); $this->get($bookPage->getUrl()) ->assertSee($bookPage->name); $this->get($bookChapter->getUrl()) ->assertSee($bookChapter->name); } public function test_book_create_restriction() { $book = $this->entities->book(); $bookUrl = $book->getUrl(); $resp = $this->actingAs($this->viewer)->get($bookUrl); $this->withHtml($resp)->assertElementNotContains('.actions', 'New Page') ->assertElementNotContains('.actions', 'New Chapter'); $resp = $this->actingAs($this->user)->get($bookUrl); $this->withHtml($resp)->assertElementContains('.actions', 'New Page') ->assertElementContains('.actions', 'New Chapter'); $this->setRestrictionsForTestRoles($book, ['view', 'delete', 'update']); $this->get($bookUrl . '/create-chapter')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->get($bookUrl . '/create-page')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $resp = $this->get($bookUrl); $this->withHtml($resp)->assertElementNotContains('.actions', 'New Page') ->assertElementNotContains('.actions', 'New Chapter'); $this->setRestrictionsForTestRoles($book, ['view', 'create']); $resp = $this->post($book->getUrl('/create-chapter'), [ 'name' => 'test chapter', 'description' => 'desc', ]); $resp->assertRedirect($book->getUrl('/chapter/test-chapter')); $this->get($book->getUrl('/create-page')); /** @var Page $page */ $page = Page::query()->where('draft', '=', true)->orderBy('id', 'desc')->first(); $resp = $this->post($page->getUrl(), [ 'name' => 'test page', 'html' => 'test content', ]); $resp->assertRedirect($book->getUrl('/page/test-page')); $resp = $this->get($bookUrl); $this->withHtml($resp)->assertElementContains('.actions', 'New Page') ->assertElementContains('.actions', 'New Chapter'); } public function test_book_update_restriction() { $book = $this->entities->book(); $bookPage = $book->pages->first(); $bookChapter = $book->chapters->first(); $bookUrl = $book->getUrl(); $this->actingAs($this->user) ->get($bookUrl . '/edit') ->assertSee('Edit Book'); $this->setRestrictionsForTestRoles($book, ['view', 'delete']); $this->get($bookUrl . '/edit')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->get($bookPage->getUrl() . '/edit')->assertRedirect($bookPage->getUrl()); $this->get('/')->assertSee('You do not have permission'); $this->get($bookChapter->getUrl() . '/edit')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->setRestrictionsForTestRoles($book, ['view', 'update']); $this->get($bookUrl . '/edit')->assertOk(); $this->get($bookPage->getUrl() . '/edit')->assertOk(); $this->get($bookChapter->getUrl() . '/edit')->assertSee('Edit Chapter'); } public function test_book_delete_restriction() { $book = $this->entities->book(); $bookPage = $book->pages->first(); $bookChapter = $book->chapters->first(); $bookUrl = $book->getUrl(); $this->actingAs($this->user)->get($bookUrl . '/delete') ->assertSee('Delete Book'); $this->setRestrictionsForTestRoles($book, ['view', 'update']); $this->get($bookUrl . '/delete')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->get($bookPage->getUrl() . '/delete')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->get($bookChapter->getUrl() . '/delete')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->setRestrictionsForTestRoles($book, ['view', 'delete']); $this->get($bookUrl . '/delete')->assertOk()->assertSee('Delete Book'); $this->get($bookPage->getUrl('/delete'))->assertOk()->assertSee('Delete Page'); $this->get($bookChapter->getUrl('/delete'))->assertSee('Delete Chapter'); } public function test_chapter_view_restriction() { $chapter = $this->entities->chapter(); $chapterPage = $chapter->pages->first(); $chapterUrl = $chapter->getUrl(); $this->actingAs($this->user)->get($chapterUrl)->assertOk(); $this->setRestrictionsForTestRoles($chapter, []); $this->followingRedirects()->get($chapterUrl)->assertSee('Chapter not found'); $this->followingRedirects()->get($chapterPage->getUrl())->assertSee('Page not found'); $this->setRestrictionsForTestRoles($chapter, ['view']); $this->get($chapterUrl)->assertSee($chapter->name); $this->get($chapterPage->getUrl())->assertSee($chapterPage->name); } public function test_chapter_create_restriction() { $chapter = $this->entities->chapter(); $chapterUrl = $chapter->getUrl(); $resp = $this->actingAs($this->user)->get($chapterUrl); $this->withHtml($resp)->assertElementContains('.actions', 'New Page'); $this->setRestrictionsForTestRoles($chapter, ['view', 'delete', 'update']); $this->get($chapterUrl . '/create-page')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->withHtml($this->get($chapterUrl))->assertElementNotContains('.actions', 'New Page'); $this->setRestrictionsForTestRoles($chapter, ['view', 'create']); $this->get($chapter->getUrl('/create-page')); /** @var Page $page */ $page = Page::query()->where('draft', '=', true)->orderBy('id', 'desc')->first(); $resp = $this->post($page->getUrl(), [ 'name' => 'test page', 'html' => 'test content', ]); $resp->assertRedirect($chapter->book->getUrl('/page/test-page')); $this->withHtml($this->get($chapterUrl))->assertElementContains('.actions', 'New Page'); } public function test_chapter_update_restriction() { $chapter = $this->entities->chapter(); $chapterPage = $chapter->pages->first(); $chapterUrl = $chapter->getUrl(); $this->actingAs($this->user)->get($chapterUrl . '/edit') ->assertSee('Edit Chapter'); $this->setRestrictionsForTestRoles($chapter, ['view', 'delete']); $this->get($chapterUrl . '/edit')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->get($chapterPage->getUrl() . '/edit')->assertRedirect($chapterPage->getUrl()); $this->get('/')->assertSee('You do not have permission'); $this->setRestrictionsForTestRoles($chapter, ['view', 'update']); $this->get($chapterUrl . '/edit')->assertOk()->assertSee('Edit Chapter'); $this->get($chapterPage->getUrl() . '/edit')->assertOk(); } public function test_chapter_delete_restriction() { $chapter = $this->entities->chapter(); $chapterPage = $chapter->pages->first(); $chapterUrl = $chapter->getUrl(); $this->actingAs($this->user) ->get($chapterUrl . '/delete') ->assertSee('Delete Chapter'); $this->setRestrictionsForTestRoles($chapter, ['view', 'update']); $this->get($chapterUrl . '/delete')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->get($chapterPage->getUrl() . '/delete')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->setRestrictionsForTestRoles($chapter, ['view', 'delete']); $this->get($chapterUrl . '/delete')->assertOk()->assertSee('Delete Chapter'); $this->get($chapterPage->getUrl() . '/delete')->assertOk()->assertSee('Delete Page'); } public function test_page_view_restriction() { $page = $this->entities->page(); $pageUrl = $page->getUrl(); $this->actingAs($this->user)->get($pageUrl)->assertOk(); $this->setRestrictionsForTestRoles($page, ['update', 'delete']); $this->get($pageUrl)->assertSee('Page not found'); $this->setRestrictionsForTestRoles($page, ['view']); $this->get($pageUrl)->assertSee($page->name); } public function test_page_update_restriction() { $page = $this->entities->page(); $pageUrl = $page->getUrl(); $resp = $this->actingAs($this->user) ->get($pageUrl . '/edit'); $this->withHtml($resp)->assertElementExists('input[name="name"][value="' . $page->name . '"]'); $this->setRestrictionsForTestRoles($page, ['view', 'delete']); $this->get($pageUrl . '/edit')->assertRedirect($pageUrl); $this->get('/')->assertSee('You do not have permission'); $this->setRestrictionsForTestRoles($page, ['view', 'update']); $resp = $this->get($pageUrl . '/edit') ->assertOk(); $this->withHtml($resp)->assertElementExists('input[name="name"][value="' . $page->name . '"]'); } public function test_page_delete_restriction() { $page = $this->entities->page(); $pageUrl = $page->getUrl(); $this->actingAs($this->user) ->get($pageUrl . '/delete') ->assertSee('Delete Page'); $this->setRestrictionsForTestRoles($page, ['view', 'update']); $this->get($pageUrl . '/delete')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->setRestrictionsForTestRoles($page, ['view', 'delete']); $this->get($pageUrl . '/delete')->assertOk()->assertSee('Delete Page'); } protected function entityRestrictionFormTest(string $model, string $title, string $permission, string $roleId) { /** @var Entity $modelInstance */ $modelInstance = $model::query()->first(); $this->asAdmin()->get($modelInstance->getUrl('/permissions')) ->assertSee($title); $this->put($modelInstance->getUrl('/permissions'), [ 'permissions' => [ $roleId => [ $permission => 'true', ], ], ]); $this->assertDatabaseHas('entity_permissions', [ 'entity_id' => $modelInstance->id, 'entity_type' => $modelInstance->getMorphClass(), 'role_id' => $roleId, $permission => true, ]); } public function test_bookshelf_restriction_form() { $this->entityRestrictionFormTest(Bookshelf::class, 'Shelf Permissions', 'view', '2'); } public function test_book_restriction_form() { $this->entityRestrictionFormTest(Book::class, 'Book Permissions', 'view', '2'); } public function test_chapter_restriction_form() { $this->entityRestrictionFormTest(Chapter::class, 'Chapter Permissions', 'update', '2'); } public function test_page_restriction_form() { $this->entityRestrictionFormTest(Page::class, 'Page Permissions', 'delete', '2'); } public function test_shelf_create_permission_visible_with_notice() { $shelf = $this->entities->shelf(); $resp = $this->asAdmin()->get($shelf->getUrl('/permissions')); $html = $this->withHtml($resp); $html->assertElementExists('input[name$="[create]"]'); $resp->assertSee('Shelf create permissions are only used for copying permissions to child books using the action below.'); } public function test_restricted_pages_not_visible_in_book_navigation_on_pages() { $chapter = $this->entities->chapter(); $page = $chapter->pages->first(); $page2 = $chapter->pages[2]; $this->setRestrictionsForTestRoles($page, []); $resp = $this->actingAs($this->user)->get($page2->getUrl()); $this->withHtml($resp)->assertElementNotContains('.sidebar-page-list', $page->name); } public function test_restricted_pages_not_visible_in_book_navigation_on_chapters() { $chapter = $this->entities->chapter(); $page = $chapter->pages->first(); $this->setRestrictionsForTestRoles($page, []); $resp = $this->actingAs($this->user)->get($chapter->getUrl()); $this->withHtml($resp)->assertElementNotContains('.sidebar-page-list', $page->name); } public function test_restricted_pages_not_visible_on_chapter_pages() { $chapter = $this->entities->chapter(); $page = $chapter->pages->first(); $this->setRestrictionsForTestRoles($page, []); $this->actingAs($this->user) ->get($chapter->getUrl()) ->assertDontSee($page->name); } public function test_restricted_chapter_pages_not_visible_on_book_page() { $chapter = $this->entities->chapter(); $this->actingAs($this->user) ->get($chapter->book->getUrl()) ->assertSee($chapter->pages->first()->name); foreach ($chapter->pages as $page) { $this->setRestrictionsForTestRoles($page, []); } $this->actingAs($this->user) ->get($chapter->book->getUrl()) ->assertDontSee($chapter->pages->first()->name); } public function test_bookshelf_update_restriction_override() { $shelf = $this->entities->shelf(); $this->actingAs($this->viewer) ->get($shelf->getUrl('/edit')) ->assertDontSee('Edit Book'); $this->setRestrictionsForTestRoles($shelf, ['view', 'delete']); $this->get($shelf->getUrl('/edit'))->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->setRestrictionsForTestRoles($shelf, ['view', 'update']); $this->get($shelf->getUrl('/edit'))->assertOk(); } public function test_bookshelf_delete_restriction_override() { $shelf = $this->entities->shelf(); $this->actingAs($this->viewer) ->get($shelf->getUrl('/delete')) ->assertDontSee('Delete Book'); $this->setRestrictionsForTestRoles($shelf, ['view', 'update']); $this->get($shelf->getUrl('/delete'))->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->setRestrictionsForTestRoles($shelf, ['view', 'delete']); $this->get($shelf->getUrl('/delete'))->assertOk()->assertSee('Delete Shelf'); } public function test_book_create_restriction_override() { $book = $this->entities->book(); $bookUrl = $book->getUrl(); $resp = $this->actingAs($this->viewer)->get($bookUrl); $this->withHtml($resp)->assertElementNotContains('.actions', 'New Page') ->assertElementNotContains('.actions', 'New Chapter'); $this->setRestrictionsForTestRoles($book, ['view', 'delete', 'update']); $this->get($bookUrl . '/create-chapter')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->get($bookUrl . '/create-page')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $resp = $this->get($bookUrl); $this->withHtml($resp)->assertElementNotContains('.actions', 'New Page') ->assertElementNotContains('.actions', 'New Chapter'); $this->setRestrictionsForTestRoles($book, ['view', 'create']); $resp = $this->post($book->getUrl('/create-chapter'), [ 'name' => 'test chapter', 'description' => 'test desc', ]); $resp->assertRedirect($book->getUrl('/chapter/test-chapter')); $this->get($book->getUrl('/create-page')); /** @var Page $page */ $page = Page::query()->where('draft', '=', true)->orderByDesc('id')->first(); $resp = $this->post($page->getUrl(), [ 'name' => 'test page', 'html' => 'test desc', ]); $resp->assertRedirect($book->getUrl('/page/test-page')); $resp = $this->get($bookUrl); $this->withHtml($resp)->assertElementContains('.actions', 'New Page') ->assertElementContains('.actions', 'New Chapter'); } public function test_book_update_restriction_override() { $book = $this->entities->book(); $bookPage = $book->pages->first(); $bookChapter = $book->chapters->first(); $bookUrl = $book->getUrl(); $this->actingAs($this->viewer)->get($bookUrl . '/edit') ->assertDontSee('Edit Book'); $this->setRestrictionsForTestRoles($book, ['view', 'delete']); $this->get($bookUrl . '/edit')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->get($bookPage->getUrl() . '/edit')->assertRedirect($bookPage->getUrl()); $this->get('/')->assertSee('You do not have permission'); $this->get($bookChapter->getUrl() . '/edit')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->setRestrictionsForTestRoles($book, ['view', 'update']); $this->get($bookUrl . '/edit')->assertOk(); $this->get($bookPage->getUrl() . '/edit')->assertOk(); $this->get($bookChapter->getUrl() . '/edit')->assertSee('Edit Chapter'); } public function test_book_delete_restriction_override() { $book = $this->entities->book(); $bookPage = $book->pages->first(); $bookChapter = $book->chapters->first(); $bookUrl = $book->getUrl(); $this->actingAs($this->viewer) ->get($bookUrl . '/delete') ->assertDontSee('Delete Book'); $this->setRestrictionsForTestRoles($book, ['view', 'update']); $this->get($bookUrl . '/delete')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->get($bookPage->getUrl() . '/delete')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->get($bookChapter->getUrl() . '/delete')->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); $this->setRestrictionsForTestRoles($book, ['view', 'delete']); $this->get($bookUrl . '/delete')->assertOk()->assertSee('Delete Book'); $this->get($bookPage->getUrl() . '/delete')->assertOk()->assertSee('Delete Page'); $this->get($bookChapter->getUrl() . '/delete')->assertSee('Delete Chapter'); } public function test_page_visible_if_has_permissions_when_book_not_visible() { $book = $this->entities->book(); $bookChapter = $book->chapters->first(); $bookPage = $bookChapter->pages->first(); foreach ([$book, $bookChapter, $bookPage] as $entity) { $entity->name = Str::random(24); $entity->save(); } $this->setRestrictionsForTestRoles($book, []); $this->setRestrictionsForTestRoles($bookPage, ['view']); $this->actingAs($this->viewer); $resp = $this->get($bookPage->getUrl()); $resp->assertOk(); $resp->assertSee($bookPage->name); $resp->assertDontSee(substr($book->name, 0, 15)); $resp->assertDontSee(substr($bookChapter->name, 0, 15)); } public function test_book_sort_view_permission() { $firstBook = $this->entities->book(); $secondBook = $this->entities->book(); $this->setRestrictionsForTestRoles($firstBook, ['view', 'update']); $this->setRestrictionsForTestRoles($secondBook, ['view']); // Test sort page visibility $this->actingAs($this->user)->get($secondBook->getUrl('/sort'))->assertRedirect('/'); $this->get('/')->assertSee('You do not have permission'); // Check sort page on first book $this->actingAs($this->user)->get($firstBook->getUrl('/sort')); } public function test_can_create_page_if_chapter_has_permissions_when_book_not_visible() { $book = $this->entities->book(); $this->setRestrictionsForTestRoles($book, []); $bookChapter = $book->chapters->first(); $this->setRestrictionsForTestRoles($bookChapter, ['view']); $this->actingAs($this->user)->get($bookChapter->getUrl()) ->assertDontSee('New Page'); $this->setRestrictionsForTestRoles($bookChapter, ['view', 'create']); $this->get($bookChapter->getUrl('/create-page')); /** @var Page $page */ $page = Page::query()->where('draft', '=', true)->orderByDesc('id')->first(); $resp = $this->post($page->getUrl(), [ 'name' => 'test page', 'html' => 'test content', ]); $resp->assertRedirect($book->getUrl('/page/test-page')); } public function test_access_to_item_prevented_if_inheritance_active_but_permission_prevented_via_role() { $user = $this->users->viewer(); $viewerRole = $user->roles->first(); $chapter = $this->entities->chapter(); $book = $chapter->book; $this->permissions->setEntityPermissions($book, ['update'], [$viewerRole], false); $this->permissions->setEntityPermissions($chapter, [], [$viewerRole], true); $this->assertFalse(userCan(Permission::ChapterUpdate, $chapter)); } public function test_access_to_item_allowed_if_inheritance_active_and_permission_prevented_via_role_but_allowed_via_parent() { $user = $this->users->viewer(); $viewerRole = $user->roles->first(); $editorRole = Role::getRole('Editor'); $user->attachRole($editorRole); $chapter = $this->entities->chapter(); $book = $chapter->book; $this->permissions->setEntityPermissions($book, ['update'], [$editorRole], false); $this->permissions->setEntityPermissions($chapter, [], [$viewerRole], true); $this->actingAs($user); $this->assertTrue(userCan(Permission::ChapterUpdate, $chapter)); } public function test_book_permissions_can_be_generated_without_error_if_child_chapter_is_in_recycle_bin() { $book = $this->entities->bookHasChaptersAndPages(); /** @var Chapter $chapter */ $chapter = $book->chapters()->first(); $this->asAdmin()->delete($chapter->getUrl()); $error = null; try { $this->permissions->setEntityPermissions($book, ['view'], []); } catch (Exception $e) { $error = $e; } $this->assertNull($error); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Permissions/EntityOwnerChangeTest.php
tests/Permissions/EntityOwnerChangeTest.php
<?php namespace Tests\Permissions; use BookStack\Users\Models\User; use Tests\TestCase; class EntityOwnerChangeTest extends TestCase { public function test_changing_page_owner() { $page = $this->entities->page(); $user = User::query()->where('id', '!=', $page->owned_by)->first(); $this->asAdmin()->put($page->getUrl('permissions'), ['owned_by' => $user->id]); $this->assertDatabaseHasEntityData('page', ['owned_by' => $user->id, 'id' => $page->id]); } public function test_changing_chapter_owner() { $chapter = $this->entities->chapter(); $user = User::query()->where('id', '!=', $chapter->owned_by)->first(); $this->asAdmin()->put($chapter->getUrl('permissions'), ['owned_by' => $user->id]); $this->assertDatabaseHasEntityData('chapter', ['owned_by' => $user->id, 'id' => $chapter->id]); } public function test_changing_book_owner() { $book = $this->entities->book(); $user = User::query()->where('id', '!=', $book->owned_by)->first(); $this->asAdmin()->put($book->getUrl('permissions'), ['owned_by' => $user->id]); $this->assertDatabaseHasEntityData('book', ['owned_by' => $user->id, 'id' => $book->id]); } public function test_changing_shelf_owner() { $shelf = $this->entities->shelf(); $user = User::query()->where('id', '!=', $shelf->owned_by)->first(); $this->asAdmin()->put($shelf->getUrl('permissions'), ['owned_by' => $user->id]); $this->assertDatabaseHasEntityData('bookshelf', ['owned_by' => $user->id, 'id' => $shelf->id]); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Permissions/Scenarios/RoleContentPermissionsTest.php
tests/Permissions/Scenarios/RoleContentPermissionsTest.php
<?php namespace Tests\Permissions\Scenarios; class RoleContentPermissionsTest extends PermissionScenarioTestCase { public function test_01_allow() { [$user] = $this->users->newUserWithRole([], ['page-view-all']); $page = $this->entities->page(); $this->assertVisibleToUser($page, $user); } public function test_02_deny() { [$user] = $this->users->newUserWithRole([], []); $page = $this->entities->page(); $this->assertNotVisibleToUser($page, $user); } public function test_10_allow_on_own_with_own() { [$user] = $this->users->newUserWithRole([], ['page-view-own']); $page = $this->entities->page(); $this->permissions->changeEntityOwner($page, $user); $this->assertVisibleToUser($page, $user); } public function test_11_deny_on_other_with_own() { [$user] = $this->users->newUserWithRole([], ['page-view-own']); $page = $this->entities->page(); $this->permissions->changeEntityOwner($page, $this->users->editor()); $this->assertNotVisibleToUser($page, $user); } public function test_20_multiple_role_conflicting_all() { [$user] = $this->users->newUserWithRole([], ['page-view-all']); $this->users->attachNewRole($user, []); $page = $this->entities->page(); $this->assertVisibleToUser($page, $user); } public function test_21_multiple_role_conflicting_own() { [$user] = $this->users->newUserWithRole([], ['page-view-own']); $this->users->attachNewRole($user, []); $page = $this->entities->page(); $this->permissions->changeEntityOwner($page, $user); $this->assertVisibleToUser($page, $user); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Permissions/Scenarios/EntityRolePermissionsTest.php
tests/Permissions/Scenarios/EntityRolePermissionsTest.php
<?php namespace Tests\Permissions\Scenarios; class EntityRolePermissionsTest extends PermissionScenarioTestCase { public function test_01_explicit_allow() { [$user, $role] = $this->users->newUserWithRole(); $page = $this->entities->page(); $this->permissions->setEntityPermissions($page, ['view'], [$role], false); $this->assertVisibleToUser($page, $user); } public function test_02_explicit_deny() { [$user, $role] = $this->users->newUserWithRole(); $page = $this->entities->page(); $this->permissions->setEntityPermissions($page, [], [$role], false); $this->assertNotVisibleToUser($page, $user); } public function test_03_same_level_conflicting() { [$user, $roleA] = $this->users->newUserWithRole(); $roleB = $this->users->attachNewRole($user); $page = $this->entities->page(); $this->permissions->disableEntityInheritedPermissions($page); $this->permissions->addEntityPermission($page, [], $roleA); $this->permissions->addEntityPermission($page, ['view'], $roleB); $this->assertVisibleToUser($page, $user); } public function test_20_inherit_allow() { [$user, $roleA] = $this->users->newUserWithRole(); $page = $this->entities->pageWithinChapter(); $chapter = $page->chapter; $this->permissions->disableEntityInheritedPermissions($chapter); $this->permissions->addEntityPermission($chapter, ['view'], $roleA); $this->assertVisibleToUser($page, $user); } public function test_21_inherit_deny() { [$user, $roleA] = $this->users->newUserWithRole(); $page = $this->entities->pageWithinChapter(); $chapter = $page->chapter; $this->permissions->disableEntityInheritedPermissions($chapter); $this->permissions->addEntityPermission($chapter, [], $roleA); $this->assertNotVisibleToUser($page, $user); } public function test_22_same_level_conflict_inherit() { [$user, $roleA] = $this->users->newUserWithRole(); $roleB = $this->users->attachNewRole($user); $page = $this->entities->pageWithinChapter(); $chapter = $page->chapter; $this->permissions->disableEntityInheritedPermissions($chapter); $this->permissions->addEntityPermission($chapter, [], $roleA); $this->permissions->addEntityPermission($chapter, ['view'], $roleB); $this->assertVisibleToUser($page, $user); } public function test_30_child_inherit_override_allow() { [$user, $roleA] = $this->users->newUserWithRole(); $page = $this->entities->pageWithinChapter(); $chapter = $page->chapter; $this->permissions->disableEntityInheritedPermissions($chapter); $this->permissions->addEntityPermission($chapter, [], $roleA); $this->permissions->addEntityPermission($page, ['view'], $roleA); $this->assertVisibleToUser($page, $user); } public function test_31_child_inherit_override_deny() { [$user, $roleA] = $this->users->newUserWithRole(); $page = $this->entities->pageWithinChapter(); $chapter = $page->chapter; $this->permissions->disableEntityInheritedPermissions($chapter); $this->permissions->addEntityPermission($chapter, ['view'], $roleA); $this->permissions->addEntityPermission($page, [], $roleA); $this->assertNotVisibleToUser($page, $user); } public function test_40_multi_role_inherit_conflict_override_deny() { [$user, $roleA] = $this->users->newUserWithRole(); $roleB = $this->users->attachNewRole($user); $page = $this->entities->pageWithinChapter(); $chapter = $page->chapter; $this->permissions->disableEntityInheritedPermissions($chapter); $this->permissions->addEntityPermission($page, [], $roleA); $this->permissions->addEntityPermission($chapter, ['view'], $roleB); $this->assertVisibleToUser($page, $user); } public function test_41_multi_role_inherit_conflict_retain_allow() { [$user, $roleA] = $this->users->newUserWithRole(); $roleB = $this->users->attachNewRole($user); $page = $this->entities->pageWithinChapter(); $chapter = $page->chapter; $this->permissions->disableEntityInheritedPermissions($chapter); $this->permissions->addEntityPermission($page, ['view'], $roleA); $this->permissions->addEntityPermission($chapter, [], $roleB); $this->assertVisibleToUser($page, $user); } public function test_50_role_override_allow() { [$user, $roleA] = $this->users->newUserWithRole(); $page = $this->entities->page(); $this->permissions->addEntityPermission($page, ['view'], $roleA); $this->assertVisibleToUser($page, $user); } public function test_51_role_override_deny() { [$user, $roleA] = $this->users->newUserWithRole([], ['page-view-all']); $page = $this->entities->page(); $this->permissions->addEntityPermission($page, [], $roleA); $this->assertNotVisibleToUser($page, $user); } public function test_60_inherited_role_override_allow() { [$user, $roleA] = $this->users->newUserWithRole([], []); $page = $this->entities->pageWithinChapter(); $chapter = $page->chapter; $this->permissions->addEntityPermission($chapter, ['view'], $roleA); $this->assertVisibleToUser($page, $user); } public function test_61_inherited_role_override_deny() { [$user, $roleA] = $this->users->newUserWithRole([], ['page-view-all']); $page = $this->entities->pageWithinChapter(); $chapter = $page->chapter; $this->permissions->addEntityPermission($chapter, [], $roleA); $this->assertNotVisibleToUser($page, $user); } public function test_62_inherited_role_override_deny_on_own() { [$user, $roleA] = $this->users->newUserWithRole([], ['page-view-own']); $page = $this->entities->pageWithinChapter(); $chapter = $page->chapter; $this->permissions->addEntityPermission($chapter, [], $roleA); $this->permissions->changeEntityOwner($page, $user); $this->assertNotVisibleToUser($page, $user); } public function test_70_multi_role_inheriting_deny() { [$user, $roleA] = $this->users->newUserWithRole([], ['page-view-all']); $roleB = $this->users->attachNewRole($user); $page = $this->entities->page(); $this->permissions->addEntityPermission($page, [], $roleB); $this->assertNotVisibleToUser($page, $user); } public function test_71_multi_role_inheriting_deny_on_own() { [$user, $roleA] = $this->users->newUserWithRole([], ['page-view-own']); $roleB = $this->users->attachNewRole($user); $page = $this->entities->page(); $this->permissions->changeEntityOwner($page, $user); $this->permissions->addEntityPermission($page, [], $roleB); $this->assertNotVisibleToUser($page, $user); } public function test_75_multi_role_inherited_deny_via_parent() { [$user, $roleA] = $this->users->newUserWithRole([], ['page-view-all']); $roleB = $this->users->attachNewRole($user); $page = $this->entities->pageWithinChapter(); $chapter = $page->chapter; $this->permissions->addEntityPermission($chapter, [], $roleB); $this->assertNotVisibleToUser($page, $user); } public function test_76_multi_role_inherited_deny_via_parent_on_own() { [$user, $roleA] = $this->users->newUserWithRole([], ['page-view-own']); $roleB = $this->users->attachNewRole($user); $page = $this->entities->pageWithinChapter(); $chapter = $page->chapter; $this->permissions->changeEntityOwner($page, $user); $this->permissions->addEntityPermission($chapter, [], $roleB); $this->assertNotVisibleToUser($page, $user); } public function test_80_fallback_override_allow() { [$user, $roleA] = $this->users->newUserWithRole(); $page = $this->entities->page(); $this->permissions->setFallbackPermissions($page, []); $this->permissions->addEntityPermission($page, ['view'], $roleA); $this->assertVisibleToUser($page, $user); } public function test_81_fallback_override_deny() { [$user, $roleA] = $this->users->newUserWithRole(); $page = $this->entities->page(); $this->permissions->setFallbackPermissions($page, ['view']); $this->permissions->addEntityPermission($page, [], $roleA); $this->assertNotVisibleToUser($page, $user); } public function test_84_fallback_override_allow_multi_role() { [$user, $roleA] = $this->users->newUserWithRole(); $roleB = $this->users->attachNewRole($user); $page = $this->entities->page(); $this->permissions->setFallbackPermissions($page, []); $this->permissions->addEntityPermission($page, ['view'], $roleA); $this->assertVisibleToUser($page, $user); } public function test_85_fallback_override_deny_multi_role() { [$user, $roleA] = $this->users->newUserWithRole(); $roleB = $this->users->attachNewRole($user); $page = $this->entities->page(); $this->permissions->setFallbackPermissions($page, ['view']); $this->permissions->addEntityPermission($page, [], $roleA); $this->assertNotVisibleToUser($page, $user); } public function test_86_fallback_override_allow_inherit() { [$user, $roleA] = $this->users->newUserWithRole(); $page = $this->entities->page(); $chapter = $page->chapter; $this->permissions->setFallbackPermissions($chapter, []); $this->permissions->addEntityPermission($chapter, ['view'], $roleA); $this->assertVisibleToUser($page, $user); } public function test_87_fallback_override_deny_inherit() { [$user, $roleA] = $this->users->newUserWithRole(); $page = $this->entities->page(); $chapter = $page->chapter; $this->permissions->setFallbackPermissions($chapter, ['view']); $this->permissions->addEntityPermission($chapter, [], $roleA); $this->assertNotVisibleToUser($page, $user); } public function test_88_fallback_override_allow_multi_role_inherit() { [$user, $roleA] = $this->users->newUserWithRole(); $roleB = $this->users->attachNewRole($user); $page = $this->entities->page(); $chapter = $page->chapter; $this->permissions->setFallbackPermissions($chapter, []); $this->permissions->addEntityPermission($chapter, ['view'], $roleA); $this->assertVisibleToUser($page, $user); } public function test_89_fallback_override_deny_multi_role_inherit() { [$user, $roleA] = $this->users->newUserWithRole(); $roleB = $this->users->attachNewRole($user); $page = $this->entities->page(); $chapter = $page->chapter; $this->permissions->setFallbackPermissions($chapter, ['view']); $this->permissions->addEntityPermission($chapter, [], $roleA); $this->assertNotVisibleToUser($page, $user); } public function test_90_fallback_overrides_parent_entity_role_deny() { [$user, $roleA] = $this->users->newUserWithRole(); $page = $this->entities->page(); $chapter = $page->chapter; $this->permissions->setFallbackPermissions($chapter, []); $this->permissions->setFallbackPermissions($page, []); $this->permissions->addEntityPermission($chapter, ['view'], $roleA); $this->assertNotVisibleToUser($page, $user); } public function test_91_fallback_overrides_parent_entity_role_inherit() { [$user, $roleA] = $this->users->newUserWithRole(); $page = $this->entities->page(); $chapter = $page->chapter; $book = $page->book; $this->permissions->setFallbackPermissions($book, []); $this->permissions->setFallbackPermissions($chapter, []); $this->permissions->addEntityPermission($book, ['view'], $roleA); $this->assertNotVisibleToUser($page, $user); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Permissions/Scenarios/PermissionScenarioTestCase.php
tests/Permissions/Scenarios/PermissionScenarioTestCase.php
<?php namespace Tests\Permissions\Scenarios; use BookStack\Entities\Models\Entity; use BookStack\Users\Models\User; use Tests\TestCase; // Cases defined in dev/docs/permission-scenario-testing.md class PermissionScenarioTestCase extends TestCase { protected function assertVisibleToUser(Entity $entity, User $user) { $this->actingAs($user); $funcView = userCan($entity->getMorphClass() . '-view', $entity); $queryView = $entity->newQuery()->scopes(['visible'])->find($entity->id) !== null; $id = $entity->getMorphClass() . ':' . $entity->id; $msg = "Item [{$id}] should be visible but was not found via "; $msg .= implode(' and ', array_filter([!$funcView ? 'userCan' : '', !$queryView ? 'query' : ''])); static::assertTrue($funcView && $queryView, $msg); } protected function assertNotVisibleToUser(Entity $entity, User $user) { $this->actingAs($user); $funcView = userCan($entity->getMorphClass() . '-view', $entity); $queryView = $entity->newQuery()->scopes(['visible'])->find($entity->id) !== null; $id = $entity->getMorphClass() . ':' . $entity->id; $msg = "Item [{$id}] should not be visible but was found via "; $msg .= implode(' and ', array_filter([$funcView ? 'userCan' : '', $queryView ? 'query' : ''])); static::assertTrue(!$funcView && !$queryView, $msg); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Exports/ZipExportValidatorTest.php
tests/Exports/ZipExportValidatorTest.php
<?php namespace Tests\Exports; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Chapter; use BookStack\Entities\Models\Page; use BookStack\Exports\ZipExports\ZipExportReader; use BookStack\Exports\ZipExports\ZipExportValidator; use BookStack\Exports\ZipExports\ZipImportRunner; use BookStack\Uploads\Image; use Tests\TestCase; class ZipExportValidatorTest extends TestCase { protected array $filesToRemove = []; protected function tearDown(): void { foreach ($this->filesToRemove as $file) { unlink($file); } parent::tearDown(); } protected function getValidatorForData(array $zipData, array $files = []): ZipExportValidator { $upload = ZipTestHelper::zipUploadFromData($zipData, $files); $path = $upload->getRealPath(); $this->filesToRemove[] = $path; $reader = new ZipExportReader($path); return new ZipExportValidator($reader); } public function test_ids_have_to_be_unique() { $validator = $this->getValidatorForData([ 'book' => [ 'id' => 4, 'name' => 'My book', 'pages' => [ [ 'id' => 4, 'name' => 'My page', 'markdown' => 'hello', 'attachments' => [ ['id' => 4, 'name' => 'Attachment A', 'link' => 'https://example.com'], ['id' => 4, 'name' => 'Attachment B', 'link' => 'https://example.com'] ], 'images' => [ ['id' => 4, 'name' => 'Image A', 'type' => 'gallery', 'file' => 'cat'], ['id' => 4, 'name' => 'Image b', 'type' => 'gallery', 'file' => 'cat'], ], ], ['id' => 4, 'name' => 'My page', 'markdown' => 'hello'], ], 'chapters' => [ ['id' => 4, 'name' => 'Chapter 1'], ['id' => 4, 'name' => 'Chapter 2'] ] ] ], ['cat' => $this->files->testFilePath('test-image.png')]); $results = $validator->validate(); $this->assertCount(4, $results); $expectedMessage = 'The id must be unique for the object type within the ZIP.'; $this->assertEquals($expectedMessage, $results['book.pages.0.attachments.1.id']); $this->assertEquals($expectedMessage, $results['book.pages.0.images.1.id']); $this->assertEquals($expectedMessage, $results['book.pages.1.id']); $this->assertEquals($expectedMessage, $results['book.chapters.1.id']); } public function test_image_files_need_to_be_a_valid_detected_image_file() { $validator = $this->getValidatorForData([ 'page' => [ 'id' => 4, 'name' => 'My page', 'markdown' => 'hello', 'images' => [ ['id' => 4, 'name' => 'Image A', 'type' => 'gallery', 'file' => 'cat'], ], ] ], ['cat' => $this->files->testFilePath('test-file.txt')]); $results = $validator->validate(); $this->assertCount(1, $results); $this->assertEquals('The file needs to reference a file of type image/png,image/jpeg,image/gif,image/webp, found text/plain.', $results['page.images.0.file']); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Exports/ZipTestHelper.php
tests/Exports/ZipTestHelper.php
<?php namespace Tests\Exports; use BookStack\Exports\Import; use Illuminate\Http\UploadedFile; use Illuminate\Testing\TestResponse; use ZipArchive; class ZipTestHelper { public static function importFromData(array $importData, array $zipData, array $files = []): Import { if (isset($zipData['book'])) { $importData['type'] = 'book'; } else if (isset($zipData['chapter'])) { $importData['type'] = 'chapter'; } else if (isset($zipData['page'])) { $importData['type'] = 'page'; } $import = Import::factory()->create($importData); $zip = static::zipUploadFromData($zipData, $files); $targetPath = storage_path($import->path); $targetDir = dirname($targetPath); if (!file_exists($targetDir)) { mkdir($targetDir); } rename($zip->getRealPath(), $targetPath); return $import; } public static function deleteZipForImport(Import $import): void { $path = storage_path($import->path); if (file_exists($path)) { unlink($path); } } public static function zipUploadFromData(array $data, array $files = []): UploadedFile { $zipFile = tempnam(sys_get_temp_dir(), 'bstest-'); $zip = new ZipArchive(); $zip->open($zipFile, ZipArchive::OVERWRITE); $zip->addFromString('data.json', json_encode($data)); foreach ($files as $name => $file) { $zip->addFile($file, "files/$name"); } $zip->close(); return new UploadedFile($zipFile, 'upload.zip', 'application/zip', null, true); } public static function extractFromZipResponse(TestResponse $response): ZipResultData { $zipData = $response->streamedContent(); $zipFile = tempnam(sys_get_temp_dir(), 'bstest-'); file_put_contents($zipFile, $zipData); $extractDir = tempnam(sys_get_temp_dir(), 'bstestextracted-'); if (file_exists($extractDir)) { unlink($extractDir); } mkdir($extractDir); $zip = new ZipArchive(); $zip->open($zipFile, ZipArchive::RDONLY); $zip->extractTo($extractDir); $dataJson = file_get_contents($extractDir . DIRECTORY_SEPARATOR . "data.json"); $data = json_decode($dataJson, true); return new ZipResultData( $zipFile, $extractDir, $data, ); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Exports/PdfExportTest.php
tests/Exports/PdfExportTest.php
<?php namespace Tests\Exports; use BookStack\Entities\Models\Page; use BookStack\Exceptions\PdfExportException; use BookStack\Exports\PdfGenerator; use FilesystemIterator; use Tests\TestCase; class PdfExportTest extends TestCase { public function test_page_pdf_export() { $page = $this->entities->page(); $this->asEditor(); $resp = $this->get($page->getUrl('/export/pdf')); $resp->assertStatus(200); $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $page->slug . '.pdf"'); } public function test_book_pdf_export() { $page = $this->entities->page(); $book = $page->book; $this->asEditor(); $resp = $this->get($book->getUrl('/export/pdf')); $resp->assertStatus(200); $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $book->slug . '.pdf"'); } public function test_chapter_pdf_export() { $chapter = $this->entities->chapter(); $this->asEditor(); $resp = $this->get($chapter->getUrl('/export/pdf')); $resp->assertStatus(200); $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $chapter->slug . '.pdf"'); } public function test_page_pdf_export_converts_iframes_to_links() { $page = Page::query()->first()->forceFill([ 'html' => '<iframe width="560" height="315" src="//www.youtube.com/embed/ShqUjt33uOs"></iframe>', ]); $page->save(); $pdfHtml = ''; $mockPdfGenerator = $this->mock(PdfGenerator::class); $mockPdfGenerator->shouldReceive('fromHtml') ->with(\Mockery::capture($pdfHtml)) ->andReturn(''); $mockPdfGenerator->shouldReceive('getActiveEngine')->andReturn(PdfGenerator::ENGINE_DOMPDF); $this->asEditor()->get($page->getUrl('/export/pdf')); $this->assertStringNotContainsString('iframe>', $pdfHtml); $this->assertStringContainsString('<p><a href="https://www.youtube.com/embed/ShqUjt33uOs">https://www.youtube.com/embed/ShqUjt33uOs</a></p>', $pdfHtml); } public function test_page_pdf_export_opens_details_blocks() { $page = $this->entities->page()->forceFill([ 'html' => '<details><summary>Hello</summary><p>Content!</p></details>', ]); $page->save(); $pdfHtml = ''; $mockPdfGenerator = $this->mock(PdfGenerator::class); $mockPdfGenerator->shouldReceive('fromHtml') ->with(\Mockery::capture($pdfHtml)) ->andReturn(''); $mockPdfGenerator->shouldReceive('getActiveEngine')->andReturn(PdfGenerator::ENGINE_DOMPDF); $this->asEditor()->get($page->getUrl('/export/pdf')); $this->assertStringContainsString('<details open="open"', $pdfHtml); } public function test_wkhtmltopdf_only_used_when_allow_untrusted_is_true() { $page = $this->entities->page(); config()->set('exports.snappy.pdf_binary', '/abc123'); config()->set('app.allow_untrusted_server_fetching', false); $resp = $this->asEditor()->get($page->getUrl('/export/pdf')); $resp->assertStatus(200); // Sucessful response with invalid snappy binary indicates dompdf usage. config()->set('app.allow_untrusted_server_fetching', true); $resp = $this->get($page->getUrl('/export/pdf')); $resp->assertStatus(500); // Bad response indicates wkhtml usage } public function test_pdf_command_option_used_if_set() { $page = $this->entities->page(); $command = 'cp {input_html_path} {output_pdf_path}'; config()->set('exports.pdf_command', $command); $resp = $this->asEditor()->get($page->getUrl('/export/pdf')); $download = $resp->getContent(); $this->assertStringContainsString(e($page->name), $download); $this->assertStringContainsString('<html lang=', $download); } public function test_pdf_command_option_errors_if_output_path_not_written_to() { $page = $this->entities->page(); $command = 'echo "hi"'; config()->set('exports.pdf_command', $command); $this->assertThrows(function () use ($page) { $this->withoutExceptionHandling()->asEditor()->get($page->getUrl('/export/pdf')); }, PdfExportException::class); } public function test_pdf_command_option_errors_if_command_returns_error_status() { $page = $this->entities->page(); $command = 'exit 1'; config()->set('exports.pdf_command', $command); $this->assertThrows(function () use ($page) { $this->withoutExceptionHandling()->asEditor()->get($page->getUrl('/export/pdf')); }, PdfExportException::class); } public function test_pdf_command_timeout_option_limits_export_time() { $page = $this->entities->page(); $command = 'php -r \'sleep(4);\''; config()->set('exports.pdf_command', $command); config()->set('exports.pdf_command_timeout', 1); $this->assertThrows(function () use ($page) { $start = time(); $this->withoutExceptionHandling()->asEditor()->get($page->getUrl('/export/pdf')); $this->assertTrue(time() < ($start + 3)); }, PdfExportException::class, "PDF Export via command failed due to timeout at 1 second(s)"); } public function test_pdf_command_option_does_not_leave_temp_files() { $tempDir = sys_get_temp_dir(); $startTempFileCount = iterator_count((new FileSystemIterator($tempDir, FilesystemIterator::SKIP_DOTS))); $page = $this->entities->page(); $command = 'cp {input_html_path} {output_pdf_path}'; config()->set('exports.pdf_command', $command); $this->asEditor()->get($page->getUrl('/export/pdf')); $afterTempFileCount = iterator_count((new FileSystemIterator($tempDir, FilesystemIterator::SKIP_DOTS))); $this->assertEquals($startTempFileCount, $afterTempFileCount); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Exports/MarkdownExportTest.php
tests/Exports/MarkdownExportTest.php
<?php namespace Tests\Exports; use BookStack\Entities\Models\Book; use Tests\TestCase; class MarkdownExportTest extends TestCase { public function test_page_markdown_export() { $page = $this->entities->page(); $resp = $this->asEditor()->get($page->getUrl('/export/markdown')); $resp->assertStatus(200); $resp->assertSee($page->name); $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $page->slug . '.md"'); } public function test_page_markdown_export_uses_existing_markdown_if_apparent() { $page = $this->entities->page()->forceFill([ 'markdown' => '# A header', 'html' => '<h1>Dogcat</h1>', ]); $page->save(); $resp = $this->asEditor()->get($page->getUrl('/export/markdown')); $resp->assertSee('A header'); $resp->assertDontSee('Dogcat'); } public function test_page_markdown_export_converts_html_where_no_markdown() { $page = $this->entities->page()->forceFill([ 'markdown' => '', 'html' => '<h1>Dogcat</h1><p>Some <strong>bold</strong> text</p>', ]); $page->save(); $resp = $this->asEditor()->get($page->getUrl('/export/markdown')); $resp->assertSee("# Dogcat\n\nSome **bold** text"); } public function test_chapter_markdown_export() { $chapter = $this->entities->chapter(); $chapter->description_html = '<p>My <strong>chapter</strong> description</p>'; $chapter->save(); $page = $chapter->pages()->first(); $resp = $this->asEditor()->get($chapter->getUrl('/export/markdown')); $resp->assertSee('# ' . $chapter->name); $resp->assertSee('# ' . $page->name); $resp->assertSee('My **chapter** description'); } public function test_book_markdown_export() { $book = Book::query()->whereHas('pages')->whereHas('chapters')->first(); $book->description_html = '<p>My <strong>book</strong> description</p>'; $book->save(); $chapter = $book->chapters()->first(); $chapter->description_html = '<p>My <strong>chapter</strong> description</p>'; $chapter->save(); $page = $chapter->pages()->first(); $resp = $this->asEditor()->get($book->getUrl('/export/markdown')); $resp->assertSee('# ' . $book->name); $resp->assertSee('# ' . $chapter->name); $resp->assertSee('# ' . $page->name); $resp->assertSee('My **book** description'); $resp->assertSee('My **chapter** description'); } public function test_book_markdown_export_concats_immediate_pages_with_newlines() { /** @var Book $book */ $book = Book::query()->whereHas('pages')->first(); $this->asEditor()->get($book->getUrl('/create-page')); $this->get($book->getUrl('/create-page')); [$pageA, $pageB] = $book->pages()->whereNull('chapter_id')->get(); $pageA->html = '<p>hello tester</p>'; $pageA->save(); $pageB->name = 'The second page in this test'; $pageB->save(); $resp = $this->get($book->getUrl('/export/markdown')); $resp->assertDontSee('hello tester# The second page in this test'); $resp->assertSee("hello tester\n\n# The second page in this test"); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Exports/HtmlExportTest.php
tests/Exports/HtmlExportTest.php
<?php namespace Tests\Exports; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Chapter; use BookStack\Entities\Models\Page; use Illuminate\Support\Facades\Storage; use Tests\TestCase; class HtmlExportTest extends TestCase { public function test_page_html_export() { $page = $this->entities->page(); $this->asEditor(); $resp = $this->get($page->getUrl('/export/html')); $resp->assertStatus(200); $resp->assertSee($page->name); $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $page->slug . '.html"'); } public function test_book_html_export() { $page = $this->entities->page(); $book = $page->book; $this->asEditor(); $resp = $this->get($book->getUrl('/export/html')); $resp->assertStatus(200); $resp->assertSee($book->name); $resp->assertSee($page->name); $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $book->slug . '.html"'); } public function test_book_html_export_shows_html_descriptions() { $book = $this->entities->bookHasChaptersAndPages(); $chapter = $book->chapters()->first(); $book->description_html = '<p>A description with <strong>HTML</strong> within!</p>'; $chapter->description_html = '<p>A chapter description with <strong>HTML</strong> within!</p>'; $book->save(); $chapter->save(); $resp = $this->asEditor()->get($book->getUrl('/export/html')); $resp->assertSee($book->description_html, false); $resp->assertSee($chapter->description_html, false); } public function test_chapter_html_export() { $chapter = $this->entities->chapter(); $page = $chapter->pages[0]; $this->asEditor(); $resp = $this->get($chapter->getUrl('/export/html')); $resp->assertStatus(200); $resp->assertSee($chapter->name); $resp->assertSee($page->name); $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $chapter->slug . '.html"'); } public function test_chapter_html_export_shows_html_descriptions() { $chapter = $this->entities->chapter(); $chapter->description_html = '<p>A description with <strong>HTML</strong> within!</p>'; $chapter->save(); $resp = $this->asEditor()->get($chapter->getUrl('/export/html')); $resp->assertSee($chapter->description_html, false); } public function test_page_html_export_contains_custom_head_if_set() { $page = $this->entities->page(); $customHeadContent = '<style>p{color: red;}</style>'; $this->setSettings(['app-custom-head' => $customHeadContent]); $resp = $this->asEditor()->get($page->getUrl('/export/html')); $resp->assertSee($customHeadContent, false); } public function test_page_html_export_does_not_break_with_only_comments_in_custom_head() { $page = $this->entities->page(); $customHeadContent = '<!-- A comment -->'; $this->setSettings(['app-custom-head' => $customHeadContent]); $resp = $this->asEditor()->get($page->getUrl('/export/html')); $resp->assertStatus(200); $resp->assertSee($customHeadContent, false); } public function test_page_html_export_use_absolute_dates() { $page = $this->entities->page(); $resp = $this->asEditor()->get($page->getUrl('/export/html')); $resp->assertSee($page->created_at->format('Y-m-d H:i:s T')); $resp->assertDontSee($page->created_at->diffForHumans()); $resp->assertSee($page->updated_at->format('Y-m-d H:i:s T')); $resp->assertDontSee($page->updated_at->diffForHumans()); } public function test_page_export_does_not_include_user_or_revision_links() { $page = $this->entities->page(); $resp = $this->asEditor()->get($page->getUrl('/export/html')); $resp->assertDontSee($page->getUrl('/revisions')); $resp->assertDontSee($page->createdBy->getProfileUrl()); $resp->assertSee($page->createdBy->name); } public function test_page_export_sets_right_data_type_for_svg_embeds() { $page = $this->entities->page(); Storage::disk('local')->makeDirectory('uploads/images/gallery'); Storage::disk('local')->put('uploads/images/gallery/svg_test.svg', '<svg></svg>'); $page->html = '<img src="http://localhost/uploads/images/gallery/svg_test.svg">'; $page->save(); $this->asEditor(); $resp = $this->get($page->getUrl('/export/html')); Storage::disk('local')->delete('uploads/images/gallery/svg_test.svg'); $resp->assertStatus(200); $resp->assertSee('<img src="data:image/svg+xml;base64', false); } public function test_page_image_containment_works_on_multiple_images_within_a_single_line() { $page = $this->entities->page(); Storage::disk('local')->makeDirectory('uploads/images/gallery'); Storage::disk('local')->put('uploads/images/gallery/svg_test.svg', '<svg></svg>'); Storage::disk('local')->put('uploads/images/gallery/svg_test2.svg', '<svg></svg>'); $page->html = '<img src="http://localhost/uploads/images/gallery/svg_test.svg" class="a"><img src="http://localhost/uploads/images/gallery/svg_test2.svg" class="b">'; $page->save(); $resp = $this->asEditor()->get($page->getUrl('/export/html')); Storage::disk('local')->delete('uploads/images/gallery/svg_test.svg'); Storage::disk('local')->delete('uploads/images/gallery/svg_test2.svg'); $resp->assertDontSee('http://localhost/uploads/images/gallery/svg_test'); } public function test_page_export_contained_html_image_fetches_only_run_when_url_points_to_image_upload_folder() { $page = $this->entities->page(); $page->html = '<img src="http://localhost/uploads/images/gallery/svg_test.svg"/>' . '<img src="http://localhost/uploads/svg_test.svg"/>' . '<img src="/uploads/svg_test.svg"/>'; $storageDisk = Storage::disk('local'); $storageDisk->makeDirectory('uploads/images/gallery'); $storageDisk->put('uploads/images/gallery/svg_test.svg', '<svg>good</svg>'); $storageDisk->put('uploads/svg_test.svg', '<svg>bad</svg>'); $page->save(); $resp = $this->asEditor()->get($page->getUrl('/export/html')); $storageDisk->delete('uploads/images/gallery/svg_test.svg'); $storageDisk->delete('uploads/svg_test.svg'); $resp->assertDontSee('http://localhost/uploads/images/gallery/svg_test.svg', false); $resp->assertSee('http://localhost/uploads/svg_test.svg'); $resp->assertSee('src="/uploads/svg_test.svg"', false); } public function test_page_export_contained_html_does_not_allow_upward_traversal_with_local() { $contents = file_get_contents(public_path('.htaccess')); config()->set('filesystems.images', 'local'); $page = $this->entities->page(); $page->html = '<img src="http://localhost/uploads/images/../../.htaccess"/>'; $page->save(); $resp = $this->asEditor()->get($page->getUrl('/export/html')); $resp->assertDontSee(base64_encode($contents)); } public function test_page_export_contained_html_does_not_allow_upward_traversal_with_local_secure() { $testFilePath = storage_path('logs/test.txt'); config()->set('filesystems.images', 'local_secure'); file_put_contents($testFilePath, 'I am a cat'); $page = $this->entities->page(); $page->html = '<img src="http://localhost/uploads/images/../../logs/test.txt"/>'; $page->save(); $resp = $this->asEditor()->get($page->getUrl('/export/html')); $resp->assertDontSee(base64_encode('I am a cat')); unlink($testFilePath); } public function test_exports_removes_scripts_from_custom_head() { $entities = [ Page::query()->first(), Chapter::query()->first(), Book::query()->first(), ]; setting()->put('app-custom-head', '<script>window.donkey = "cat";</script><style>.my-test-class { color: red; }</style>'); foreach ($entities as $entity) { $resp = $this->asEditor()->get($entity->getUrl('/export/html')); $resp->assertDontSee('window.donkey'); $resp->assertDontSee('<script', false); $resp->assertSee('.my-test-class { color: red; }'); } } public function test_page_export_with_deleted_creator_and_updater() { $user = $this->users->viewer(['name' => 'ExportWizardTheFifth']); $page = $this->entities->page(); $page->created_by = $user->id; $page->updated_by = $user->id; $page->save(); $resp = $this->asEditor()->get($page->getUrl('/export/html')); $resp->assertSee('ExportWizardTheFifth'); $user->delete(); $resp = $this->get($page->getUrl('/export/html')); $resp->assertStatus(200); $resp->assertDontSee('ExportWizardTheFifth'); } public function test_html_exports_contain_csp_meta_tag() { $entities = [ $this->entities->page(), $this->entities->book(), $this->entities->chapter(), ]; foreach ($entities as $entity) { $resp = $this->asEditor()->get($entity->getUrl('/export/html')); $this->withHtml($resp)->assertElementExists('head meta[http-equiv="Content-Security-Policy"][content*="script-src "]'); } } public function test_html_exports_contain_body_classes_for_export_identification() { $page = $this->entities->page(); $resp = $this->asEditor()->get($page->getUrl('/export/html')); $this->withHtml($resp)->assertElementExists('body.export.export-format-html.export-engine-none'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Exports/ZipResultData.php
tests/Exports/ZipResultData.php
<?php namespace Tests\Exports; class ZipResultData { public function __construct( public string $zipPath, public string $extractedDirPath, public array $data, ) { } /** * Build a path to a location the extracted content, using the given relative $path. */ public function extractPath(string $path): string { $relPath = implode(DIRECTORY_SEPARATOR, explode('/', $path)); return $this->extractedDirPath . DIRECTORY_SEPARATOR . ltrim($relPath, DIRECTORY_SEPARATOR); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Exports/ZipExportTest.php
tests/Exports/ZipExportTest.php
<?php namespace Tests\Exports; use BookStack\Activity\Models\Tag; use BookStack\Entities\Repos\BookRepo; use BookStack\Entities\Tools\PageContent; use BookStack\Uploads\Attachment; use BookStack\Uploads\Image; use FilesystemIterator; use Illuminate\Support\Carbon; use Illuminate\Testing\TestResponse; use Tests\TestCase; use ZipArchive; class ZipExportTest extends TestCase { public function test_export_results_in_zip_format() { $page = $this->entities->page(); $response = $this->asEditor()->get($page->getUrl("/export/zip")); $zipData = $response->streamedContent(); $zipFile = tempnam(sys_get_temp_dir(), 'bstesta-'); file_put_contents($zipFile, $zipData); $zip = new ZipArchive(); $zip->open($zipFile, ZipArchive::RDONLY); $this->assertNotFalse($zip->locateName('data.json')); $this->assertNotFalse($zip->locateName('files/')); $data = json_decode($zip->getFromName('data.json'), true); $this->assertIsArray($data); $this->assertGreaterThan(0, count($data)); $zip->close(); unlink($zipFile); } public function test_export_metadata() { $page = $this->entities->page(); $zipResp = $this->asEditor()->get($page->getUrl("/export/zip")); $zip = ZipTestHelper::extractFromZipResponse($zipResp); $this->assertEquals($page->id, $zip->data['page']['id'] ?? null); $this->assertArrayNotHasKey('book', $zip->data); $this->assertArrayNotHasKey('chapter', $zip->data); $now = time(); $date = Carbon::parse($zip->data['exported_at'])->unix(); $this->assertLessThan($now + 2, $date); $this->assertGreaterThan($now - 2, $date); $version = trim(file_get_contents(base_path('version'))); $this->assertEquals($version, $zip->data['instance']['version']); $zipInstanceId = $zip->data['instance']['id']; $instanceId = setting('instance-id'); $this->assertNotEmpty($instanceId); $this->assertEquals($instanceId, $zipInstanceId); } public function test_export_leaves_no_temp_files() { $tempDir = sys_get_temp_dir(); $startTempFileCount = iterator_count((new FileSystemIterator($tempDir, FilesystemIterator::SKIP_DOTS))); $page = $this->entities->pageWithinChapter(); $this->asEditor(); $pageResp = $this->get($page->getUrl("/export/zip")); $pageResp->streamedContent(); $pageResp->assertOk(); $this->get($page->chapter->getUrl("/export/zip"))->assertOk(); $this->get($page->book->getUrl("/export/zip"))->assertOk(); $afterTempFileCount = iterator_count((new FileSystemIterator($tempDir, FilesystemIterator::SKIP_DOTS))); $this->assertEquals($startTempFileCount, $afterTempFileCount); } public function test_page_export() { $page = $this->entities->page(); $zipResp = $this->asEditor()->get($page->getUrl("/export/zip")); $zip = ZipTestHelper::extractFromZipResponse($zipResp); $pageData = $zip->data['page']; $this->assertEquals([ 'id' => $page->id, 'name' => $page->name, 'html' => (new PageContent($page))->render(), 'priority' => $page->priority, 'attachments' => [], 'images' => [], 'tags' => [], ], $pageData); } public function test_page_export_with_markdown() { $page = $this->entities->page(); $markdown = "# My page\n\nwritten in markdown for export\n"; $page->markdown = $markdown; $page->save(); $zipResp = $this->asEditor()->get($page->getUrl("/export/zip")); $zip = ZipTestHelper::extractFromZipResponse($zipResp); $pageData = $zip->data['page']; $this->assertEquals($markdown, $pageData['markdown']); $this->assertNotEmpty($pageData['html']); } public function test_page_export_with_tags() { $page = $this->entities->page(); $page->tags()->saveMany([ new Tag(['name' => 'Exporty', 'value' => 'Content', 'order' => 1]), new Tag(['name' => 'Another', 'value' => '', 'order' => 2]), ]); $zipResp = $this->asEditor()->get($page->getUrl("/export/zip")); $zip = ZipTestHelper::extractFromZipResponse($zipResp); $pageData = $zip->data['page']; $this->assertEquals([ [ 'name' => 'Exporty', 'value' => 'Content', ], [ 'name' => 'Another', 'value' => '', ] ], $pageData['tags']); } public function test_page_export_with_images() { $this->asEditor(); $page = $this->entities->page(); $result = $this->files->uploadGalleryImageToPage($this, $page); $displayThumb = $result['response']->thumbs->gallery ?? ''; $page->html = '<p><img src="' . $displayThumb . '" alt="My image"></p>'; $page->save(); $image = Image::findOrFail($result['response']->id); $zipResp = $this->asEditor()->get($page->getUrl("/export/zip")); $zip = ZipTestHelper::extractFromZipResponse($zipResp); $pageData = $zip->data['page']; $this->assertCount(1, $pageData['images']); $imageData = $pageData['images'][0]; $this->assertEquals($image->id, $imageData['id']); $this->assertEquals($image->name, $imageData['name']); $this->assertEquals('gallery', $imageData['type']); $this->assertNotEmpty($imageData['file']); $filePath = $zip->extractPath("files/{$imageData['file']}"); $this->assertFileExists($filePath); $this->assertEquals(file_get_contents(public_path($image->path)), file_get_contents($filePath)); $this->assertEquals('<p><img src="[[bsexport:image:' . $imageData['id'] . ']]" alt="My image"></p>', $pageData['html']); } public function test_page_export_file_attachments() { $contents = 'My great attachment content!'; $page = $this->entities->page(); $this->asAdmin(); $attachment = $this->files->uploadAttachmentDataToPage($this, $page, 'PageAttachmentExport.txt', $contents, 'text/plain'); $zipResp = $this->get($page->getUrl("/export/zip")); $zip = ZipTestHelper::extractFromZipResponse($zipResp); $pageData = $zip->data['page']; $this->assertCount(1, $pageData['attachments']); $attachmentData = $pageData['attachments'][0]; $this->assertEquals('PageAttachmentExport.txt', $attachmentData['name']); $this->assertEquals($attachment->id, $attachmentData['id']); $this->assertArrayNotHasKey('link', $attachmentData); $this->assertNotEmpty($attachmentData['file']); $fileRef = $attachmentData['file']; $filePath = $zip->extractPath("/files/$fileRef"); $this->assertFileExists($filePath); $this->assertEquals($contents, file_get_contents($filePath)); } public function test_page_export_link_attachments() { $page = $this->entities->page(); $this->asEditor(); $attachment = Attachment::factory()->create([ 'name' => 'My link attachment for export', 'path' => 'https://example.com/cats', 'external' => true, 'uploaded_to' => $page->id, 'order' => 1, ]); $zipResp = $this->get($page->getUrl("/export/zip")); $zip = ZipTestHelper::extractFromZipResponse($zipResp); $pageData = $zip->data['page']; $this->assertCount(1, $pageData['attachments']); $attachmentData = $pageData['attachments'][0]; $this->assertEquals('My link attachment for export', $attachmentData['name']); $this->assertEquals($attachment->id, $attachmentData['id']); $this->assertEquals('https://example.com/cats', $attachmentData['link']); $this->assertArrayNotHasKey('file', $attachmentData); } public function test_book_export() { $book = $this->entities->bookHasChaptersAndPages(); $book->tags()->saveMany(Tag::factory()->count(2)->make()); $zipResp = $this->asEditor()->get($book->getUrl("/export/zip")); $zip = ZipTestHelper::extractFromZipResponse($zipResp); $this->assertArrayHasKey('book', $zip->data); $bookData = $zip->data['book']; $this->assertEquals($book->id, $bookData['id']); $this->assertEquals($book->name, $bookData['name']); $this->assertEquals($book->descriptionInfo()->getHtml(), $bookData['description_html']); $this->assertCount(2, $bookData['tags']); $this->assertCount($book->directPages()->count(), $bookData['pages']); $this->assertCount($book->chapters()->count(), $bookData['chapters']); $this->assertArrayNotHasKey('cover', $bookData); } public function test_book_export_with_cover_image() { $book = $this->entities->book(); $bookRepo = $this->app->make(BookRepo::class); $coverImageFile = $this->files->uploadedImage('cover.png'); $bookRepo->updateCoverImage($book, $coverImageFile); $coverImage = $book->coverInfo()->getImage(); $zipResp = $this->asEditor()->get($book->getUrl("/export/zip")); $zip = ZipTestHelper::extractFromZipResponse($zipResp); $this->assertArrayHasKey('cover', $zip->data['book']); $coverRef = $zip->data['book']['cover']; $coverPath = $zip->extractPath("/files/$coverRef"); $this->assertFileExists($coverPath); $this->assertEquals(file_get_contents(public_path($coverImage->path)), file_get_contents($coverPath)); } public function test_chapter_export() { $chapter = $this->entities->chapter(); $chapter->tags()->saveMany(Tag::factory()->count(2)->make()); $zipResp = $this->asEditor()->get($chapter->getUrl("/export/zip")); $zip = ZipTestHelper::extractFromZipResponse($zipResp); $this->assertArrayHasKey('chapter', $zip->data); $chapterData = $zip->data['chapter']; $this->assertEquals($chapter->id, $chapterData['id']); $this->assertEquals($chapter->name, $chapterData['name']); $this->assertEquals($chapter->descriptionInfo()->getHtml(), $chapterData['description_html']); $this->assertCount(2, $chapterData['tags']); $this->assertEquals($chapter->priority, $chapterData['priority']); $this->assertCount($chapter->pages()->count(), $chapterData['pages']); } public function test_draft_pages_are_not_included() { $editor = $this->users->editor(); $entities = $this->entities->createChainBelongingToUser($editor); $book = $entities['book']; $page = $entities['page']; $chapter = $entities['chapter']; $book->tags()->saveMany(Tag::factory()->count(2)->make()); $page->created_by = $editor->id; $page->draft = true; $page->save(); $zipResp = $this->actingAs($editor)->get($book->getUrl("/export/zip")); $zip = ZipTestHelper::extractFromZipResponse($zipResp); $this->assertCount(0, $zip->data['book']['chapters'][0]['pages'] ?? ['cat']); $zipResp = $this->actingAs($editor)->get($chapter->getUrl("/export/zip")); $zip = ZipTestHelper::extractFromZipResponse($zipResp); $this->assertCount(0, $zip->data['chapter']['pages'] ?? ['cat']); $page->chapter_id = 0; $page->save(); $zipResp = $this->actingAs($editor)->get($book->getUrl("/export/zip")); $zip = ZipTestHelper::extractFromZipResponse($zipResp); $this->assertCount(0, $zip->data['book']['pages'] ?? ['cat']); } public function test_cross_reference_links_are_converted() { $book = $this->entities->bookHasChaptersAndPages(); $chapter = $book->chapters()->first(); $page = $chapter->pages()->first(); $book->description_html = '<p><a href="' . $chapter->getUrl() . '">Link to chapter</a></p>'; $book->save(); $chapter->description_html = '<p><a href="' . $page->getUrl() . '#section2">Link to page</a></p>'; $chapter->save(); $page->html = '<p><a href="' . $book->getUrl() . '?view=true">Link to book</a></p>'; $page->save(); $zipResp = $this->asEditor()->get($book->getUrl("/export/zip")); $zip = ZipTestHelper::extractFromZipResponse($zipResp); $bookData = $zip->data['book']; $chapterData = $bookData['chapters'][0]; $pageData = $chapterData['pages'][0]; $this->assertStringContainsString('href="[[bsexport:chapter:' . $chapter->id . ']]"', $bookData['description_html']); $this->assertStringContainsString('href="[[bsexport:page:' . $page->id . ']]#section2"', $chapterData['description_html']); $this->assertStringContainsString('href="[[bsexport:book:' . $book->id . ']]?view=true"', $pageData['html']); } public function test_book_and_chapter_description_links_to_images_in_pages_are_converted() { $book = $this->entities->bookHasChaptersAndPages(); $chapter = $book->chapters()->first(); $page = $chapter->pages()->first(); $this->asEditor(); $this->files->uploadGalleryImageToPage($this, $page); /** @var Image $image */ $image = Image::query()->where('type', '=', 'gallery') ->where('uploaded_to', '=', $page->id)->first(); $book->description_html = '<p><a href="' . $image->url . '">Link to image</a></p>'; $book->save(); $chapter->description_html = '<p><a href="' . $image->url . '">Link to image</a></p>'; $chapter->save(); $zipResp = $this->get($book->getUrl("/export/zip")); $zip = ZipTestHelper::extractFromZipResponse($zipResp); $bookData = $zip->data['book']; $chapterData = $bookData['chapters'][0]; $this->assertStringContainsString('href="[[bsexport:image:' . $image->id . ']]"', $bookData['description_html']); $this->assertStringContainsString('href="[[bsexport:image:' . $image->id . ']]"', $chapterData['description_html']); } public function test_image_links_are_handled_when_using_external_storage_url() { $page = $this->entities->page(); $this->asEditor(); $this->files->uploadGalleryImageToPage($this, $page); /** @var Image $image */ $image = Image::query()->where('type', '=', 'gallery') ->where('uploaded_to', '=', $page->id)->first(); config()->set('filesystems.url', 'https://i.example.com/content'); $storageUrl = 'https://i.example.com/content/' . ltrim($image->path, '/'); $page->html = '<p><a href="' . $image->url . '">Original URL</a><a href="' . $storageUrl . '">Storage URL</a></p>'; $page->save(); $zipResp = $this->get($page->getUrl("/export/zip")); $zip = ZipTestHelper::extractFromZipResponse($zipResp); $pageData = $zip->data['page']; $ref = '[[bsexport:image:' . $image->id . ']]'; $this->assertStringContainsString("<a href=\"{$ref}\">Original URL</a><a href=\"{$ref}\">Storage URL</a>", $pageData['html']); } public function test_orphaned_images_can_be_used_on_default_local_storage() { $this->asEditor(); $page = $this->entities->page(); $result = $this->files->uploadGalleryImageToPage($this, $page); $displayThumb = $result['response']->thumbs->gallery ?? ''; $page->html = '<p><img src="' . $displayThumb . '" alt="My image"></p>'; $page->save(); $image = Image::findOrFail($result['response']->id); $image->uploaded_to = null; $image->save(); $zipResp = $this->asEditor()->get($page->getUrl("/export/zip")); $zipResp->assertOk(); $zip = ZipTestHelper::extractFromZipResponse($zipResp); $pageData = $zip->data['page']; $this->assertCount(1, $pageData['images']); $imageData = $pageData['images'][0]; $this->assertEquals($image->id, $imageData['id']); $this->assertEquals('<p><img src="[[bsexport:image:' . $imageData['id'] . ']]" alt="My image"></p>', $pageData['html']); } public function test_orphaned_images_cannot_be_used_on_local_secure_restricted() { config()->set('filesystems.images', 'local_secure_restricted'); $this->asEditor(); $page = $this->entities->page(); $result = $this->files->uploadGalleryImageToPage($this, $page); $displayThumb = $result['response']->thumbs->gallery ?? ''; $page->html = '<p><img src="' . $displayThumb . '" alt="My image"></p>'; $page->save(); $image = Image::findOrFail($result['response']->id); $image->uploaded_to = null; $image->save(); $zipResp = $this->asEditor()->get($page->getUrl("/export/zip")); $zipResp->assertOk(); $zip = ZipTestHelper::extractFromZipResponse($zipResp); $pageData = $zip->data['page']; $this->assertCount(0, $pageData['images']); } public function test_cross_reference_links_external_to_export_are_not_converted() { $page = $this->entities->page(); $page->html = '<p><a href="' . $page->book->getUrl() . '">Link to book</a></p>'; $page->save(); $zipResp = $this->asEditor()->get($page->getUrl("/export/zip")); $zip = ZipTestHelper::extractFromZipResponse($zipResp); $pageData = $zip->data['page']; $this->assertStringContainsString('href="' . $page->book->getUrl() . '"', $pageData['html']); } public function test_attachments_links_are_converted() { $page = $this->entities->page(); $attachment = Attachment::factory()->create([ 'name' => 'My link attachment for export reference', 'path' => 'https://example.com/cats/ref', 'external' => true, 'uploaded_to' => $page->id, 'order' => 1, ]); $page->html = '<p><a href="' . url("/attachments/{$attachment->id}") . '?open=true">Link to attachment</a></p>'; $page->save(); $zipResp = $this->asEditor()->get($page->getUrl("/export/zip")); $zip = ZipTestHelper::extractFromZipResponse($zipResp); $pageData = $zip->data['page']; $this->assertStringContainsString('href="[[bsexport:attachment:' . $attachment->id . ']]?open=true"', $pageData['html']); } public function test_links_in_markdown_are_parsed() { $chapter = $this->entities->chapterHasPages(); $page = $chapter->pages()->first(); $page->markdown = "[Link to chapter]({$chapter->getUrl()})"; $page->save(); $zipResp = $this->asEditor()->get($chapter->getUrl("/export/zip")); $zip = ZipTestHelper::extractFromZipResponse($zipResp); $pageData = $zip->data['chapter']['pages'][0]; $this->assertStringContainsString("[Link to chapter]([[bsexport:chapter:{$chapter->id}]])", $pageData['markdown']); } public function test_exports_rate_limited_low_for_guest_viewers() { $this->setSettings(['app-public' => 'true']); $page = $this->entities->page(); for ($i = 0; $i < 4; $i++) { $this->get($page->getUrl("/export/zip"))->assertOk(); } $this->get($page->getUrl("/export/zip"))->assertStatus(429); } public function test_exports_rate_limited_higher_for_logged_in_viewers() { $this->asAdmin(); $page = $this->entities->page(); for ($i = 0; $i < 10; $i++) { $this->get($page->getUrl("/export/zip"))->assertOk(); } $this->get($page->getUrl("/export/zip"))->assertStatus(429); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Exports/ZipImportRunnerTest.php
tests/Exports/ZipImportRunnerTest.php
<?php namespace Tests\Exports; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Chapter; use BookStack\Entities\Models\Page; use BookStack\Exceptions\ZipImportException; use BookStack\Exports\ZipExports\ZipImportRunner; use BookStack\Uploads\Image; use Tests\TestCase; class ZipImportRunnerTest extends TestCase { protected ZipImportRunner $runner; protected function setUp(): void { parent::setUp(); $this->runner = app()->make(ZipImportRunner::class); } public function test_book_import() { $testImagePath = $this->files->testFilePath('test-image.png'); $testFilePath = $this->files->testFilePath('test-file.txt'); $import = ZipTestHelper::importFromData([], [ 'book' => [ 'id' => 5, 'name' => 'Import test', 'cover' => 'book_cover_image', 'description_html' => '<p><a href="[[bsexport:page:3]]">Link to chapter page</a></p>', 'tags' => [ ['name' => 'Animal', 'value' => 'Cat'], ['name' => 'Category', 'value' => 'Test'], ], 'chapters' => [ [ 'id' => 6, 'name' => 'Chapter A', 'description_html' => '<p><a href="[[bsexport:book:5]]">Link to book</a></p>', 'priority' => 1, 'tags' => [ ['name' => 'Reviewed'], ['name' => 'Category', 'value' => 'Test Chapter'], ], 'pages' => [ [ 'id' => 3, 'name' => 'Page A', 'priority' => 6, 'html' => ' <p><a href="[[bsexport:page:3]]">Link to self</a></p> <p><a href="[[bsexport:image:1]]">Link to cat image</a></p> <p><a href="[[bsexport:attachment:4]]">Link to text attachment</a></p>', 'tags' => [ ['name' => 'Unreviewed'], ], 'attachments' => [ [ 'id' => 4, 'name' => 'Text attachment', 'file' => 'file_attachment' ], [ 'name' => 'Cats', 'link' => 'https://example.com/cats', ] ], 'images' => [ [ 'id' => 1, 'name' => 'Cat', 'type' => 'gallery', 'file' => 'cat_image' ], [ 'id' => 2, 'name' => 'Dog Drawing', 'type' => 'drawio', 'file' => 'dog_image' ] ], ], ], ], [ 'name' => 'Chapter child B', 'priority' => 5, ] ], 'pages' => [ [ 'name' => 'Page C', 'markdown' => '[Link to text]([[bsexport:attachment:4]]?scale=big)', 'priority' => 3, ] ], ], ], [ 'book_cover_image' => $testImagePath, 'file_attachment' => $testFilePath, 'cat_image' => $testImagePath, 'dog_image' => $testImagePath, ]); $this->asAdmin(); /** @var Book $book */ $book = $this->runner->run($import); // Book checks $this->assertEquals('Import test', $book->name); $this->assertFileExists(public_path($book->coverInfo()->getImage()->path)); $this->assertCount(2, $book->tags); $this->assertEquals('Cat', $book->tags()->first()->value); $this->assertCount(2, $book->chapters); $this->assertEquals(1, $book->directPages()->count()); // Chapter checks $chapterA = $book->chapters()->where('name', 'Chapter A')->first(); $this->assertCount(2, $chapterA->tags); $firstChapterTag = $chapterA->tags()->first(); $this->assertEquals('Reviewed', $firstChapterTag->name); $this->assertEquals('', $firstChapterTag->value); $this->assertCount(1, $chapterA->pages); // Page checks /** @var Page $pageA */ $pageA = $chapterA->pages->first(); $this->assertEquals('Page A', $pageA->name); $this->assertCount(1, $pageA->tags); $firstPageTag = $pageA->tags()->first(); $this->assertEquals('Unreviewed', $firstPageTag->name); $this->assertCount(2, $pageA->attachments); $firstAttachment = $pageA->attachments->first(); $this->assertEquals('Text attachment', $firstAttachment->name); $this->assertFileEquals($testFilePath, storage_path($firstAttachment->path)); $this->assertFalse($firstAttachment->external); $secondAttachment = $pageA->attachments->last(); $this->assertEquals('Cats', $secondAttachment->name); $this->assertEquals('https://example.com/cats', $secondAttachment->path); $this->assertTrue($secondAttachment->external); $pageAImages = Image::where('uploaded_to', '=', $pageA->id)->whereIn('type', ['gallery', 'drawio'])->get(); $this->assertCount(2, $pageAImages); $this->assertEquals('Cat', $pageAImages[0]->name); $this->assertEquals('gallery', $pageAImages[0]->type); $this->assertFileEquals($testImagePath, public_path($pageAImages[0]->path)); $this->assertEquals('Dog Drawing', $pageAImages[1]->name); $this->assertEquals('drawio', $pageAImages[1]->type); // Book order check $children = $book->getDirectVisibleChildren()->values()->all(); $this->assertEquals($children[0]->name, 'Chapter A'); $this->assertEquals($children[1]->name, 'Page C'); $this->assertEquals($children[2]->name, 'Chapter child B'); // Reference checks $textAttachmentUrl = $firstAttachment->getUrl(); $this->assertStringContainsString($pageA->getUrl(), $book->description_html); $this->assertStringContainsString($book->getUrl(), $chapterA->description_html); $this->assertStringContainsString($pageA->getUrl(), $pageA->html); $this->assertStringContainsString($pageAImages[0]->getThumb(1680, null, true), $pageA->html); $this->assertStringContainsString($firstAttachment->getUrl(), $pageA->html); // Reference in converted markdown $pageC = $children[1]; $this->assertStringContainsString("href=\"{$textAttachmentUrl}?scale=big\"", $pageC->html); ZipTestHelper::deleteZipForImport($import); } public function test_chapter_import() { $testImagePath = $this->files->testFilePath('test-image.png'); $testFilePath = $this->files->testFilePath('test-file.txt'); $parent = $this->entities->book(); $import = ZipTestHelper::importFromData([], [ 'chapter' => [ 'id' => 6, 'name' => 'Chapter A', 'description_html' => '<p><a href="[[bsexport:page:3]]">Link to page</a></p>', 'priority' => 1, 'tags' => [ ['name' => 'Reviewed', 'value' => '2024'], ], 'pages' => [ [ 'id' => 3, 'name' => 'Page A', 'priority' => 6, 'html' => '<p><a href="[[bsexport:chapter:6]]">Link to chapter</a></p> <p><a href="[[bsexport:image:2]]">Link to dog drawing</a></p> <p><a href="[[bsexport:attachment:4]]">Link to text attachment</a></p>', 'tags' => [ ['name' => 'Unreviewed'], ], 'attachments' => [ [ 'id' => 4, 'name' => 'Text attachment', 'file' => 'file_attachment' ] ], 'images' => [ [ 'id' => 2, 'name' => 'Dog Drawing', 'type' => 'drawio', 'file' => 'dog_image' ] ], ], [ 'name' => 'Page B', 'markdown' => '[Link to page A]([[bsexport:page:3]])', 'priority' => 9, ], ], ], ], [ 'file_attachment' => $testFilePath, 'dog_image' => $testImagePath, ]); $this->asAdmin(); /** @var Chapter $chapter */ $chapter = $this->runner->run($import, $parent); // Chapter checks $this->assertEquals('Chapter A', $chapter->name); $this->assertEquals($parent->id, $chapter->book_id); $this->assertCount(1, $chapter->tags); $firstChapterTag = $chapter->tags()->first(); $this->assertEquals('Reviewed', $firstChapterTag->name); $this->assertEquals('2024', $firstChapterTag->value); $this->assertCount(2, $chapter->pages); // Page checks /** @var Page $pageA */ $pageA = $chapter->pages->first(); $this->assertEquals('Page A', $pageA->name); $this->assertCount(1, $pageA->tags); $this->assertCount(1, $pageA->attachments); $pageAImages = Image::where('uploaded_to', '=', $pageA->id)->whereIn('type', ['gallery', 'drawio'])->get(); $this->assertCount(1, $pageAImages); // Reference checks $attachment = $pageA->attachments->first(); $this->assertStringContainsString($pageA->getUrl(), $chapter->description_html); $this->assertStringContainsString($chapter->getUrl(), $pageA->html); $this->assertStringContainsString($pageAImages[0]->url, $pageA->html); $this->assertStringContainsString($attachment->getUrl(), $pageA->html); ZipTestHelper::deleteZipForImport($import); } public function test_page_import() { $testImagePath = $this->files->testFilePath('test-image.png'); $testFilePath = $this->files->testFilePath('test-file.txt'); $parent = $this->entities->chapter(); $import = ZipTestHelper::importFromData([], [ 'page' => [ 'id' => 3, 'name' => 'Page A', 'priority' => 6, 'html' => '<p><a href="[[bsexport:page:3]]">Link to self</a></p> <p><a href="[[bsexport:image:2]]">Link to dog drawing</a></p> <p><a href="[[bsexport:attachment:4]]">Link to text attachment</a></p>', 'tags' => [ ['name' => 'Unreviewed'], ], 'attachments' => [ [ 'id' => 4, 'name' => 'Text attachment', 'file' => 'file_attachment' ] ], 'images' => [ [ 'id' => 2, 'name' => 'Dog Drawing', 'type' => 'drawio', 'file' => 'dog_image' ] ], ], ], [ 'file_attachment' => $testFilePath, 'dog_image' => $testImagePath, ]); $this->asAdmin(); /** @var Page $page */ $page = $this->runner->run($import, $parent); // Page checks $this->assertEquals('Page A', $page->name); $this->assertCount(1, $page->tags); $this->assertCount(1, $page->attachments); $pageImages = Image::where('uploaded_to', '=', $page->id)->whereIn('type', ['gallery', 'drawio'])->get(); $this->assertCount(1, $pageImages); $this->assertFileEquals($testImagePath, public_path($pageImages[0]->path)); // Reference checks $this->assertStringContainsString($page->getUrl(), $page->html); $this->assertStringContainsString($pageImages[0]->url, $page->html); $this->assertStringContainsString($page->attachments->first()->getUrl(), $page->html); ZipTestHelper::deleteZipForImport($import); } public function test_revert_cleans_up_uploaded_files() { $testImagePath = $this->files->testFilePath('test-image.png'); $testFilePath = $this->files->testFilePath('test-file.txt'); $parent = $this->entities->chapter(); $import = ZipTestHelper::importFromData([], [ 'page' => [ 'name' => 'Page A', 'html' => '<p>Hello</p>', 'attachments' => [ [ 'name' => 'Text attachment', 'file' => 'file_attachment' ] ], 'images' => [ [ 'name' => 'Dog Image', 'type' => 'gallery', 'file' => 'dog_image' ] ], ], ], [ 'file_attachment' => $testFilePath, 'dog_image' => $testImagePath, ]); $this->asAdmin(); /** @var Page $page */ $page = $this->runner->run($import, $parent); $attachment = $page->attachments->first(); $image = Image::query()->where('uploaded_to', '=', $page->id)->where('type', '=', 'gallery')->first(); $this->assertFileExists(public_path($image->path)); $this->assertFileExists(storage_path($attachment->path)); $this->runner->revertStoredFiles(); $this->assertFileDoesNotExist(public_path($image->path)); $this->assertFileDoesNotExist(storage_path($attachment->path)); ZipTestHelper::deleteZipForImport($import); } public function test_imported_images_have_their_detected_extension_added() { $testImagePath = $this->files->testFilePath('test-image.png'); $parent = $this->entities->chapter(); $import = ZipTestHelper::importFromData([], [ 'page' => [ 'name' => 'Page A', 'html' => '<p>hello</p>', 'images' => [ [ 'id' => 2, 'name' => 'Cat', 'type' => 'gallery', 'file' => 'cat_image' ] ], ], ], [ 'cat_image' => $testImagePath, ]); $this->asAdmin(); /** @var Page $page */ $page = $this->runner->run($import, $parent); $pageImages = Image::where('uploaded_to', '=', $page->id)->whereIn('type', ['gallery', 'drawio'])->get(); $this->assertCount(1, $pageImages); $this->assertStringEndsWith('.png', $pageImages[0]->url); $this->assertStringEndsWith('.png', $pageImages[0]->path); ZipTestHelper::deleteZipForImport($import); } public function test_drawing_references_are_updated_within_content() { $testImagePath = $this->files->testFilePath('test-image.png'); $parent = $this->entities->chapter(); $import = ZipTestHelper::importFromData([], [ 'page' => [ 'name' => 'Page A', 'html' => '<div drawio-diagram="1125"><img src="[[bsexport:image:1125]]"></div>', 'images' => [ [ 'id' => 1125, 'name' => 'Cat', 'type' => 'drawio', 'file' => 'my_drawing' ] ], ], ], [ 'my_drawing' => $testImagePath, ]); $this->asAdmin(); /** @var Page $page */ $page = $this->runner->run($import, $parent); $pageImages = Image::where('uploaded_to', '=', $page->id)->whereIn('type', ['gallery', 'drawio'])->get(); $this->assertCount(1, $pageImages); $this->assertEquals('drawio', $pageImages[0]->type); $drawingId = $pageImages[0]->id; $this->assertStringContainsString("drawio-diagram=\"{$drawingId}\"", $page->html); $this->assertStringNotContainsString('[[bsexport:image:1125]]', $page->html); $this->assertStringNotContainsString('drawio-diagram="1125"', $page->html); ZipTestHelper::deleteZipForImport($import); } public function test_error_thrown_if_zip_item_exceeds_app_file_upload_limit() { $tempFile = tempnam(sys_get_temp_dir(), 'bs-zip-test'); file_put_contents($tempFile, str_repeat('a', 2500000)); $parent = $this->entities->chapter(); config()->set('app.upload_limit', 1); $import = ZipTestHelper::importFromData([], [ 'page' => [ 'name' => 'Page A', 'html' => '<p>Hello</p>', 'attachments' => [ [ 'name' => 'Text attachment', 'file' => 'file_attachment' ] ], ], ], [ 'file_attachment' => $tempFile, ]); $this->asAdmin(); $this->expectException(ZipImportException::class); $this->expectExceptionMessage('The file file_attachment must not exceed 1 MB.'); $this->runner->run($import, $parent); ZipTestHelper::deleteZipForImport($import); } public function test_error_thrown_if_zip_data_exceeds_app_file_upload_limit() { $parent = $this->entities->chapter(); config()->set('app.upload_limit', 1); $import = ZipTestHelper::importFromData([], [ 'page' => [ 'name' => 'Page A', 'html' => '<p>' . str_repeat('a', 2500000) . '</p>', ], ]); $this->asAdmin(); $this->expectException(ZipImportException::class); $this->expectExceptionMessage('ZIP data.json content exceeds the configured application maximum upload size.'); $this->runner->run($import, $parent); ZipTestHelper::deleteZipForImport($import); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Exports/ExportUiTest.php
tests/Exports/ExportUiTest.php
<?php namespace Tests\Exports; use BookStack\Entities\Models\Book; use Tests\TestCase; class ExportUiTest extends TestCase { public function test_export_option_only_visible_and_accessible_with_permission() { $book = Book::query()->whereHas('pages')->whereHas('chapters')->first(); $chapter = $book->chapters()->first(); $page = $chapter->pages()->first(); $entities = [$book, $chapter, $page]; $user = $this->users->viewer(); $this->actingAs($user); foreach ($entities as $entity) { $resp = $this->get($entity->getUrl()); $resp->assertSee('/export/pdf'); } $this->permissions->removeUserRolePermissions($user, ['content-export']); foreach ($entities as $entity) { $resp = $this->get($entity->getUrl()); $resp->assertDontSee('/export/pdf'); $resp = $this->get($entity->getUrl('/export/pdf')); $this->assertPermissionError($resp); } } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Exports/ZipImportTest.php
tests/Exports/ZipImportTest.php
<?php namespace Tests\Exports; use BookStack\Activity\ActivityType; use BookStack\Entities\Models\Book; use BookStack\Exports\Import; use BookStack\Exports\ZipExports\Models\ZipExportBook; use BookStack\Exports\ZipExports\Models\ZipExportChapter; use BookStack\Exports\ZipExports\Models\ZipExportPage; use Illuminate\Http\UploadedFile; use Illuminate\Testing\TestResponse; use Tests\TestCase; use ZipArchive; class ZipImportTest extends TestCase { public function test_import_page_view() { $resp = $this->asAdmin()->get('/import'); $resp->assertSee('Import'); $this->withHtml($resp)->assertElementExists('form input[type="file"][name="file"]'); } public function test_permissions_needed_for_import_page() { $user = $this->users->viewer(); $this->actingAs($user); $resp = $this->get('/books'); $this->withHtml($resp)->assertLinkNotExists(url('/import')); $resp = $this->get('/import'); $resp->assertRedirect('/'); $this->permissions->grantUserRolePermissions($user, ['content-import']); $resp = $this->get('/books'); $this->withHtml($resp)->assertLinkExists(url('/import')); $resp = $this->get('/import'); $resp->assertOk(); $resp->assertSeeText('Select ZIP file to upload'); } public function test_import_page_pending_import_visibility_limited() { $user = $this->users->viewer(); $admin = $this->users->admin(); $userImport = Import::factory()->create(['name' => 'MySuperUserImport', 'created_by' => $user->id]); $adminImport = Import::factory()->create(['name' => 'MySuperAdminImport', 'created_by' => $admin->id]); $this->permissions->grantUserRolePermissions($user, ['content-import']); $resp = $this->actingAs($user)->get('/import'); $resp->assertSeeText('MySuperUserImport'); $resp->assertDontSeeText('MySuperAdminImport'); $this->permissions->grantUserRolePermissions($user, ['settings-manage']); $resp = $this->actingAs($user)->get('/import'); $resp->assertSeeText('MySuperUserImport'); $resp->assertSeeText('MySuperAdminImport'); } public function test_zip_read_errors_are_shown_on_validation() { $invalidUpload = $this->files->uploadedImage('image.zip'); $this->asAdmin(); $resp = $this->runImportFromFile($invalidUpload); $resp->assertRedirect('/import'); $resp = $this->followRedirects($resp); $resp->assertSeeText('Could not read ZIP file'); } public function test_error_shown_if_missing_data() { $zipFile = tempnam(sys_get_temp_dir(), 'bstest-'); $zip = new ZipArchive(); $zip->open($zipFile, ZipArchive::OVERWRITE); $zip->addFromString('beans', 'cat'); $zip->close(); $this->asAdmin(); $upload = new UploadedFile($zipFile, 'upload.zip', 'application/zip', null, true); $resp = $this->runImportFromFile($upload); $resp->assertRedirect('/import'); $resp = $this->followRedirects($resp); $resp->assertSeeText('Could not find and decode ZIP data.json content.'); } public function test_error_shown_if_no_importable_key() { $this->asAdmin(); $resp = $this->runImportFromFile(ZipTestHelper::zipUploadFromData([ 'instance' => [] ])); $resp->assertRedirect('/import'); $resp = $this->followRedirects($resp); $resp->assertSeeText('ZIP file data has no expected book, chapter or page content.'); } public function test_zip_data_validation_messages_shown() { $this->asAdmin(); $resp = $this->runImportFromFile(ZipTestHelper::zipUploadFromData([ 'book' => [ 'id' => 4, 'pages' => [ 'cat', [ 'name' => 'My inner page', 'tags' => [ [ 'value' => 5 ] ], ] ], ] ])); $resp->assertRedirect('/import'); $resp = $this->followRedirects($resp); $resp->assertSeeText('[book.name]: The name field is required.'); $resp->assertSeeText('[book.pages.0.0]: Data object expected but "string" found.'); $resp->assertSeeText('[book.pages.1.tags.0.name]: The name field is required.'); $resp->assertSeeText('[book.pages.1.tags.0.value]: The value must be a string.'); } public function test_import_upload_success() { $admin = $this->users->admin(); $this->actingAs($admin); $data = [ 'book' => [ 'name' => 'My great book name', 'chapters' => [ [ 'name' => 'my chapter', 'pages' => [ [ 'name' => 'my chapter page', ] ] ] ], 'pages' => [ [ 'name' => 'My page', ] ], ], ]; $resp = $this->runImportFromFile(ZipTestHelper::zipUploadFromData($data)); $this->assertDatabaseHas('imports', [ 'name' => 'My great book name', 'type' => 'book', 'created_by' => $admin->id, ]); /** @var Import $import */ $import = Import::query()->latest()->first(); $resp->assertRedirect("/import/{$import->id}"); $this->assertFileExists(storage_path($import->path)); $this->assertActivityExists(ActivityType::IMPORT_CREATE); ZipTestHelper::deleteZipForImport($import); } public function test_import_show_page() { $exportBook = new ZipExportBook(); $exportBook->name = 'My exported book'; $exportChapter = new ZipExportChapter(); $exportChapter->name = 'My exported chapter'; $exportPage = new ZipExportPage(); $exportPage->name = 'My exported page'; $exportBook->chapters = [$exportChapter]; $exportChapter->pages = [$exportPage]; $import = Import::factory()->create([ 'name' => 'MySuperAdminImport', 'metadata' => json_encode($exportBook) ]); $resp = $this->asAdmin()->get("/import/{$import->id}"); $resp->assertOk(); $resp->assertSeeText('My exported book'); $resp->assertSeeText('My exported chapter'); $resp->assertSeeText('My exported page'); } public function test_import_show_page_access_limited() { $user = $this->users->viewer(); $admin = $this->users->admin(); $userImport = Import::factory()->create(['name' => 'MySuperUserImport', 'created_by' => $user->id]); $adminImport = Import::factory()->create(['name' => 'MySuperAdminImport', 'created_by' => $admin->id]); $this->actingAs($user); $this->get("/import/{$userImport->id}")->assertRedirect('/'); $this->get("/import/{$adminImport->id}")->assertRedirect('/'); $this->permissions->grantUserRolePermissions($user, ['content-import']); $this->get("/import/{$userImport->id}")->assertOk(); $this->get("/import/{$adminImport->id}")->assertStatus(404); $this->permissions->grantUserRolePermissions($user, ['settings-manage']); $this->get("/import/{$userImport->id}")->assertOk(); $this->get("/import/{$adminImport->id}")->assertOk(); } public function test_import_delete() { $this->asAdmin(); $this->runImportFromFile(ZipTestHelper::zipUploadFromData([ 'book' => [ 'name' => 'My great book name' ], ])); /** @var Import $import */ $import = Import::query()->latest()->first(); $this->assertDatabaseHas('imports', [ 'id' => $import->id, 'name' => 'My great book name' ]); $this->assertFileExists(storage_path($import->path)); $resp = $this->delete("/import/{$import->id}"); $resp->assertRedirect('/import'); $this->assertActivityExists(ActivityType::IMPORT_DELETE); $this->assertDatabaseMissing('imports', [ 'id' => $import->id, ]); $this->assertFileDoesNotExist(storage_path($import->path)); } public function test_import_delete_access_limited() { $user = $this->users->viewer(); $admin = $this->users->admin(); $userImport = Import::factory()->create(['name' => 'MySuperUserImport', 'created_by' => $user->id]); $adminImport = Import::factory()->create(['name' => 'MySuperAdminImport', 'created_by' => $admin->id]); $this->actingAs($user); $this->delete("/import/{$userImport->id}")->assertRedirect('/'); $this->delete("/import/{$adminImport->id}")->assertRedirect('/'); $this->permissions->grantUserRolePermissions($user, ['content-import']); $this->delete("/import/{$userImport->id}")->assertRedirect('/import'); $this->delete("/import/{$adminImport->id}")->assertStatus(404); $this->permissions->grantUserRolePermissions($user, ['settings-manage']); $this->delete("/import/{$adminImport->id}")->assertRedirect('/import'); } public function test_run_simple_success_scenario() { $import = ZipTestHelper::importFromData([], [ 'book' => [ 'name' => 'My imported book', 'pages' => [ [ 'name' => 'My imported book page', 'html' => '<p>Hello there from child page!</p>' ] ], ] ]); $resp = $this->asAdmin()->post("/import/{$import->id}"); $book = Book::query()->where('name', '=', 'My imported book')->latest()->first(); $resp->assertRedirect($book->getUrl()); $resp = $this->followRedirects($resp); $resp->assertSee('My imported book page'); $resp->assertSee('Hello there from child page!'); $this->assertDatabaseMissing('imports', ['id' => $import->id]); $this->assertFileDoesNotExist(storage_path($import->path)); $this->assertActivityExists(ActivityType::IMPORT_RUN, null, $import->logDescriptor()); } public function test_import_run_access_limited() { $user = $this->users->editor(); $admin = $this->users->admin(); $userImport = Import::factory()->create(['name' => 'MySuperUserImport', 'created_by' => $user->id]); $adminImport = Import::factory()->create(['name' => 'MySuperAdminImport', 'created_by' => $admin->id]); $this->actingAs($user); $this->post("/import/{$userImport->id}")->assertRedirect('/'); $this->post("/import/{$adminImport->id}")->assertRedirect('/'); $this->permissions->grantUserRolePermissions($user, ['content-import']); $this->post("/import/{$userImport->id}")->assertRedirect($userImport->getUrl()); // Getting validation response instead of access issue response $this->post("/import/{$adminImport->id}")->assertStatus(404); $this->permissions->grantUserRolePermissions($user, ['settings-manage']); $this->post("/import/{$adminImport->id}")->assertRedirect($adminImport->getUrl()); // Getting validation response instead of access issue response } public function test_run_revalidates_content() { $import = ZipTestHelper::importFromData([], [ 'book' => [ 'id' => 'abc', ] ]); $resp = $this->asAdmin()->post("/import/{$import->id}"); $resp->assertRedirect($import->getUrl()); $resp = $this->followRedirects($resp); $resp->assertSeeText('The name field is required.'); $resp->assertSeeText('The id must be an integer.'); ZipTestHelper::deleteZipForImport($import); } public function test_run_checks_permissions_on_import() { $viewer = $this->users->viewer(); $this->permissions->grantUserRolePermissions($viewer, ['content-import']); $import = ZipTestHelper::importFromData(['created_by' => $viewer->id], [ 'book' => ['name' => 'My import book'], ]); $resp = $this->asViewer()->post("/import/{$import->id}"); $resp->assertRedirect($import->getUrl()); $resp = $this->followRedirects($resp); $resp->assertSeeText('You are lacking the required permissions to create books.'); ZipTestHelper::deleteZipForImport($import); } public function test_run_requires_parent_for_chapter_and_page_imports() { $book = $this->entities->book(); $pageImport = ZipTestHelper::importFromData([], [ 'page' => ['name' => 'My page', 'html' => '<p>page test!</p>'], ]); $chapterImport = ZipTestHelper::importFromData([], [ 'chapter' => ['name' => 'My chapter'], ]); $resp = $this->asAdmin()->post("/import/{$pageImport->id}"); $resp->assertRedirect($pageImport->getUrl()); $this->followRedirects($resp)->assertSee('The parent field is required.'); $resp = $this->asAdmin()->post("/import/{$pageImport->id}", ['parent' => "book:{$book->id}"]); $resp->assertRedirectContains($book->getUrl()); $resp = $this->asAdmin()->post("/import/{$chapterImport->id}"); $resp->assertRedirect($chapterImport->getUrl()); $this->followRedirects($resp)->assertSee('The parent field is required.'); $resp = $this->asAdmin()->post("/import/{$chapterImport->id}", ['parent' => "book:{$book->id}"]); $resp->assertRedirectContains($book->getUrl()); } public function test_run_validates_correct_parent_type() { $chapter = $this->entities->chapter(); $import = ZipTestHelper::importFromData([], [ 'chapter' => ['name' => 'My chapter'], ]); $resp = $this->asAdmin()->post("/import/{$import->id}", ['parent' => "chapter:{$chapter->id}"]); $resp->assertRedirect($import->getUrl()); $resp = $this->followRedirects($resp); $resp->assertSee('Parent book required for chapter import.'); ZipTestHelper::deleteZipForImport($import); } protected function runImportFromFile(UploadedFile $file): TestResponse { return $this->call('POST', '/import', [], [], ['file' => $file]); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Exports/TextExportTest.php
tests/Exports/TextExportTest.php
<?php namespace Tests\Exports; use Tests\TestCase; class TextExportTest extends TestCase { public function test_page_text_export() { $page = $this->entities->page(); $this->asEditor(); $resp = $this->get($page->getUrl('/export/plaintext')); $resp->assertStatus(200); $resp->assertSee($page->name); $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $page->slug . '.txt"'); } public function test_book_text_export() { $book = $this->entities->bookHasChaptersAndPages(); $directPage = $book->directPages()->first(); $chapter = $book->chapters()->first(); $chapterPage = $chapter->pages()->first(); $this->entities->updatePage($directPage, ['html' => '<p>My awesome page</p>']); $this->entities->updatePage($chapterPage, ['html' => '<p>My little nested page</p>']); $this->asEditor(); $resp = $this->get($book->getUrl('/export/plaintext')); $resp->assertStatus(200); $resp->assertSee($book->name); $resp->assertSee($chapterPage->name); $resp->assertSee($chapter->name); $resp->assertSee($directPage->name); $resp->assertSee('My awesome page'); $resp->assertSee('My little nested page'); $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $book->slug . '.txt"'); } public function test_book_text_export_format() { $entities = $this->entities->createChainBelongingToUser($this->users->viewer()); $this->entities->updatePage($entities['page'], ['html' => '<p>My great page</p><p>Full of <strong>great</strong> stuff</p>', 'name' => 'My wonderful page!']); $entities['chapter']->name = 'Export chapter'; $entities['chapter']->description = "A test chapter to be exported\nIt has loads of info within"; $entities['book']->name = 'Export Book'; $entities['book']->description = "This is a book with stuff to export"; $entities['chapter']->save(); $entities['book']->save(); $resp = $this->asEditor()->get($entities['book']->getUrl('/export/plaintext')); $expected = "Export Book\nThis is a book with stuff to export\n\nExport chapter\nA test chapter to be exported\nIt has loads of info within\n\n"; $expected .= "My wonderful page!\nMy great page Full of great stuff"; $resp->assertSee($expected); } public function test_chapter_text_export() { $chapter = $this->entities->chapter(); $page = $chapter->pages[0]; $this->entities->updatePage($page, ['html' => '<p>This is content within the page!</p>']); $this->asEditor(); $resp = $this->get($chapter->getUrl('/export/plaintext')); $resp->assertStatus(200); $resp->assertSee($chapter->name); $resp->assertSee($page->name); $resp->assertSee('This is content within the page!'); $resp->assertHeader('Content-Disposition', 'attachment; filename="' . $chapter->slug . '.txt"'); } public function test_chapter_text_export_format() { $entities = $this->entities->createChainBelongingToUser($this->users->viewer()); $this->entities->updatePage($entities['page'], ['html' => '<p>My great page</p><p>Full of <strong>great</strong> stuff</p>', 'name' => 'My wonderful page!']); $entities['chapter']->name = 'Export chapter'; $entities['chapter']->description = "A test chapter to be exported\nIt has loads of info within"; $entities['chapter']->save(); $resp = $this->asEditor()->get($entities['book']->getUrl('/export/plaintext')); $expected = "Export chapter\nA test chapter to be exported\nIt has loads of info within\n\n"; $expected .= "My wonderful page!\nMy great page Full of great stuff"; $resp->assertSee($expected); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/References/ReferencesTest.php
tests/References/ReferencesTest.php
<?php namespace Tests\References; use BookStack\App\Model; use BookStack\Entities\Repos\PageRepo; use BookStack\Entities\Tools\TrashCan; use BookStack\References\Reference; use Tests\TestCase; class ReferencesTest extends TestCase { public function test_references_created_on_page_update() { $pageA = $this->entities->page(); $pageB = $this->entities->page(); $this->assertDatabaseMissing('references', ['from_id' => $pageA->id, 'from_type' => $pageA->getMorphClass()]); $this->asEditor()->put($pageA->getUrl(), [ 'name' => 'Reference test', 'html' => '<a href="' . $pageB->getUrl() . '">Testing</a>', ]); $this->assertDatabaseHas('references', [ 'from_id' => $pageA->id, 'from_type' => $pageA->getMorphClass(), 'to_id' => $pageB->id, 'to_type' => $pageB->getMorphClass(), ]); } public function test_references_created_on_book_chapter_bookshelf_update() { $entities = [$this->entities->book(), $this->entities->chapter(), $this->entities->shelf()]; $shelf = $this->entities->shelf(); foreach ($entities as $entity) { $entity->refresh(); $this->assertDatabaseMissing('references', ['from_id' => $entity->id, 'from_type' => $entity->getMorphClass()]); $this->asEditor()->put($entity->getUrl(), [ 'name' => 'Reference test', 'description_html' => '<a href="' . $shelf->getUrl() . '">Testing</a>', ]); $this->assertDatabaseHas('references', [ 'from_id' => $entity->id, 'from_type' => $entity->getMorphClass(), 'to_id' => $shelf->id, 'to_type' => $shelf->getMorphClass(), ]); } } public function test_references_deleted_on_page_delete() { $pageA = $this->entities->page(); $pageB = $this->entities->page(); $this->createReference($pageA, $pageB); $this->createReference($pageB, $pageA); $this->assertDatabaseHas('references', ['from_id' => $pageA->id, 'from_type' => $pageA->getMorphClass()]); $this->assertDatabaseHas('references', ['to_id' => $pageA->id, 'to_type' => $pageA->getMorphClass()]); app(PageRepo::class)->destroy($pageA); app(TrashCan::class)->empty(); $this->assertDatabaseMissing('references', ['from_id' => $pageA->id, 'from_type' => $pageA->getMorphClass()]); $this->assertDatabaseMissing('references', ['to_id' => $pageA->id, 'to_type' => $pageA->getMorphClass()]); } public function test_references_from_deleted_on_book_chapter_shelf_delete() { $entities = [$this->entities->chapter(), $this->entities->book(), $this->entities->shelf()]; $shelf = $this->entities->shelf(); foreach ($entities as $entity) { $this->createReference($entity, $shelf); $this->assertDatabaseHas('references', ['from_id' => $entity->id, 'from_type' => $entity->getMorphClass()]); $this->asEditor()->delete($entity->getUrl()); app(TrashCan::class)->empty(); $this->assertDatabaseMissing('references', [ 'from_id' => $entity->id, 'from_type' => $entity->getMorphClass() ]); } } public function test_references_to_count_visible_on_entity_show_view() { $entities = $this->entities->all(); $otherPage = $this->entities->page(); $this->asEditor(); foreach ($entities as $entity) { $this->createReference($entities['page'], $entity); } foreach ($entities as $entity) { $resp = $this->get($entity->getUrl()); $resp->assertSee('Referenced by 1 item'); $resp->assertDontSee('Referenced by 1 items'); } $this->createReference($otherPage, $entities['page']); $resp = $this->get($entities['page']->getUrl()); $resp->assertSee('Referenced by 2 items'); } public function test_references_to_visible_on_references_page() { $entities = $this->entities->all(); $this->asEditor(); foreach ($entities as $entity) { $this->createReference($entities['page'], $entity); } foreach ($entities as $entity) { $resp = $this->get($entity->getUrl('/references')); $resp->assertSee('References'); $resp->assertSee($entities['page']->name); $resp->assertDontSee('There are no tracked references'); } } public function test_reference_not_visible_if_view_permission_does_not_permit() { $page = $this->entities->page(); $pageB = $this->entities->page(); $this->createReference($pageB, $page); $this->permissions->setEntityPermissions($pageB); $this->asEditor()->get($page->getUrl('/references'))->assertDontSee($pageB->name); $this->asAdmin()->get($page->getUrl('/references'))->assertSee($pageB->name); } public function test_reference_page_shows_empty_state_with_no_references() { $page = $this->entities->page(); $this->asEditor() ->get($page->getUrl('/references')) ->assertSee('There are no tracked references'); } public function test_pages_leading_to_entity_updated_on_url_change() { $pageA = $this->entities->page(); $pageB = $this->entities->page(); $book = $this->entities->book(); foreach ([$pageA, $pageB] as $page) { $page->html = '<a href="' . $book->getUrl() . '">Link</a>'; $page->save(); $this->createReference($page, $book); } $this->asEditor()->put($book->getUrl(), [ 'name' => 'my updated book slugaroo', ]); foreach ([$pageA, $pageB] as $page) { $page->refresh(); $this->assertStringContainsString('href="http://localhost/books/my-updated-book-slugaroo"', $page->html); $this->assertDatabaseHas('page_revisions', [ 'page_id' => $page->id, 'summary' => 'System auto-update of internal links', ]); } } public function test_pages_linking_to_other_page_updated_on_parent_book_url_change() { $bookPage = $this->entities->page(); $otherPage = $this->entities->page(); $book = $bookPage->book; $otherPage->html = '<a href="' . $bookPage->getUrl() . '">Link</a>'; $otherPage->save(); $this->createReference($otherPage, $bookPage); $this->asEditor()->put($book->getUrl(), [ 'name' => 'my updated book slugaroo', ]); $otherPage->refresh(); $this->assertStringContainsString('href="http://localhost/books/my-updated-book-slugaroo/page/' . $bookPage->slug . '"', $otherPage->html); $this->assertDatabaseHas('page_revisions', [ 'page_id' => $otherPage->id, 'summary' => 'System auto-update of internal links', ]); } public function test_pages_linking_to_chapter_updated_on_parent_book_url_change() { $bookChapter = $this->entities->chapter(); $otherPage = $this->entities->page(); $book = $bookChapter->book; $otherPage->html = '<a href="' . $bookChapter->getUrl() . '">Link</a>'; $otherPage->save(); $this->createReference($otherPage, $bookChapter); $this->asEditor()->put($book->getUrl(), [ 'name' => 'my updated book slugaroo', ]); $otherPage->refresh(); $this->assertStringContainsString('href="http://localhost/books/my-updated-book-slugaroo/chapter/' . $bookChapter->slug . '"', $otherPage->html); $this->assertDatabaseHas('page_revisions', [ 'page_id' => $otherPage->id, 'summary' => 'System auto-update of internal links', ]); } public function test_markdown_links_leading_to_entity_updated_on_url_change() { $page = $this->entities->page(); $book = $this->entities->book(); $bookUrl = $book->getUrl(); $markdown = ' [An awesome link](' . $bookUrl . ') [An awesome link with query & hash](' . $bookUrl . '?test=yes#cats) [An awesome link with path](' . $bookUrl . '/an/extra/trail) [An awesome link with title](' . $bookUrl . ' "title") [ref]: ' . $bookUrl . '?test=yes#dogs [ref_without_space]:' . $bookUrl . ' [ref_with_title]: ' . $bookUrl . ' "title"'; $page->markdown = $markdown; $page->save(); $this->createReference($page, $book); $this->asEditor()->put($book->getUrl(), [ 'name' => 'my updated book slugadoo', ]); $page->refresh(); $expected = str_replace($bookUrl, 'http://localhost/books/my-updated-book-slugadoo', $markdown); $this->assertEquals($expected, $page->markdown); } public function test_description_links_from_book_chapter_shelf_updated_on_url_change() { $entities = [$this->entities->chapter(), $this->entities->book(), $this->entities->shelf()]; $shelf = $this->entities->shelf(); $this->asEditor(); foreach ($entities as $entity) { $this->put($entity->getUrl(), [ 'name' => 'Reference test', 'description_html' => '<a href="' . $shelf->getUrl() . '">Testing</a>', ]); } $oldUrl = $shelf->getUrl(); $this->put($shelf->getUrl(), ['name' => 'My updated shelf link'])->assertRedirect(); $shelf->refresh(); $this->assertNotEquals($oldUrl, $shelf->getUrl()); foreach ($entities as $entity) { $oldHtml = $entity->description_html; $entity->refresh(); $this->assertNotEquals($oldHtml, $entity->description_html); $this->assertStringContainsString($shelf->getUrl(), $entity->description_html); } } public function test_reference_from_deleted_item_does_not_count_or_show_in_references_page() { $page = $this->entities->page(); $referencingPageA = $this->entities->page(); $referencingPageB = $this->entities->page(); $this->asEditor(); $this->createReference($referencingPageA, $page); $this->createReference($referencingPageB, $page); $resp = $this->get($page->getUrl()); $resp->assertSee('Referenced by 2 items'); $this->delete($referencingPageA->getUrl()); $resp = $this->get($page->getUrl()); $resp->assertSee('Referenced by 1 item'); $resp = $this->get($page->getUrl('/references')); $resp->assertOk(); $resp->assertSee($referencingPageB->getUrl()); $resp->assertDontSee($referencingPageA->getUrl()); } protected function createReference(Model $from, Model $to): void { (new Reference())->forceFill([ 'from_type' => $from->getMorphClass(), 'from_id' => $from->id, 'to_type' => $to->getMorphClass(), 'to_id' => $to->id, ])->save(); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/References/CrossLinkParserTest.php
tests/References/CrossLinkParserTest.php
<?php namespace Tests\References; use BookStack\References\CrossLinkParser; use Tests\TestCase; class CrossLinkParserTest extends TestCase { public function test_instance_with_entity_resolvers_matches_entity_links() { $entities = $this->entities->all(); $otherPage = $this->entities->page(); $html = ' <a href="' . url('/link/' . $otherPage->id) . '#cat">Page Permalink</a> <a href="' . $entities['page']->getUrl() . '?a=b">Page Link</a> <a href="' . $entities['chapter']->getUrl() . '?cat=mouse#donkey">Chapter Link</a> <a href="' . $entities['book']->getUrl() . '/edit">Book Link</a> <a href="' . $entities['bookshelf']->getUrl() . '/edit?cat=happy#hello">Shelf Link</a> <a href="' . url('/settings') . '">Settings Link</a> '; $parser = CrossLinkParser::createWithEntityResolvers(); $results = $parser->extractLinkedModels($html); $this->assertCount(5, $results); $this->assertEquals(get_class($otherPage), get_class($results[0])); $this->assertEquals($otherPage->id, $results[0]->id); $this->assertEquals(get_class($entities['page']), get_class($results[1])); $this->assertEquals($entities['page']->id, $results[1]->id); $this->assertEquals(get_class($entities['chapter']), get_class($results[2])); $this->assertEquals($entities['chapter']->id, $results[2]->id); $this->assertEquals(get_class($entities['book']), get_class($results[3])); $this->assertEquals($entities['book']->id, $results[3]->id); $this->assertEquals(get_class($entities['bookshelf']), get_class($results[4])); $this->assertEquals($entities['bookshelf']->id, $results[4]->id); } public function test_similar_page_and_book_reference_links_dont_conflict() { $page = $this->entities->page(); $book = $page->book; $html = ' <a href="' . $page->getUrl() . '">Page Link</a> <a href="' . $book->getUrl() . '">Book Link</a> '; $parser = CrossLinkParser::createWithEntityResolvers(); $results = $parser->extractLinkedModels($html); $this->assertCount(2, $results); $this->assertEquals(get_class($page), get_class($results[0])); $this->assertEquals($page->id, $results[0]->id); $this->assertEquals(get_class($book), get_class($results[1])); $this->assertEquals($book->id, $results[1]->id); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Commands/ResetMfaCommandTest.php
tests/Commands/ResetMfaCommandTest.php
<?php namespace Tests\Commands; use BookStack\Access\Mfa\MfaValue; use BookStack\Users\Models\User; use Tests\TestCase; class ResetMfaCommandTest extends TestCase { public function test_command_requires_email_or_id_option() { $this->artisan('bookstack:reset-mfa') ->expectsOutputToContain('Either a --id=<number> or --email=<email> option must be provided.') ->assertExitCode(1); } public function test_command_runs_with_provided_email() { /** @var User $user */ $user = User::query()->first(); MfaValue::upsertWithValue($user, MfaValue::METHOD_TOTP, 'test'); $this->assertEquals(1, $user->mfaValues()->count()); $this->artisan("bookstack:reset-mfa --email={$user->email}") ->expectsQuestion('Are you sure you want to proceed?', true) ->expectsOutput('User MFA methods have been reset.') ->assertExitCode(0); $this->assertEquals(0, $user->mfaValues()->count()); } public function test_command_runs_with_provided_id() { /** @var User $user */ $user = User::query()->first(); MfaValue::upsertWithValue($user, MfaValue::METHOD_TOTP, 'test'); $this->assertEquals(1, $user->mfaValues()->count()); $this->artisan("bookstack:reset-mfa --id={$user->id}") ->expectsQuestion('Are you sure you want to proceed?', true) ->expectsOutput('User MFA methods have been reset.') ->assertExitCode(0); $this->assertEquals(0, $user->mfaValues()->count()); } public function test_saying_no_to_confirmation_does_not_reset_mfa() { /** @var User $user */ $user = User::query()->first(); MfaValue::upsertWithValue($user, MfaValue::METHOD_TOTP, 'test'); $this->assertEquals(1, $user->mfaValues()->count()); $this->artisan("bookstack:reset-mfa --id={$user->id}") ->expectsQuestion('Are you sure you want to proceed?', false) ->assertExitCode(1); $this->assertEquals(1, $user->mfaValues()->count()); } public function test_giving_non_existing_user_shows_error_message() { $this->artisan('bookstack:reset-mfa --email=donkeys@example.com') ->expectsOutput('A user where email=donkeys@example.com could not be found.') ->assertExitCode(1); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Commands/RefreshAvatarCommandTest.php
tests/Commands/RefreshAvatarCommandTest.php
<?php namespace Tests\Commands; use BookStack\Uploads\Image; use BookStack\Users\Models\User; use GuzzleHttp\Psr7\Response; use Illuminate\Database\Eloquent\Collection; use Tests\TestCase; class RefreshAvatarCommandTest extends TestCase { public function setUp(): void { parent::setUp(); config()->set([ 'services.disable_services' => false, 'services.avatar_url' => 'https://avatars.example.com?a=b', ]); } public function test_command_errors_if_avatar_fetch_disabled() { config()->set(['services.avatar_url' => false]); $this->artisan('bookstack:refresh-avatar') ->expectsOutputToContain("Avatar fetching is disabled on this instance") ->assertExitCode(1); } public function test_command_requires_email_or_id_option() { $this->artisan('bookstack:refresh-avatar') ->expectsOutputToContain("Either a --id=<number> or --email=<email> option must be provided") ->assertExitCode(1); } public function test_command_runs_with_provided_email() { $requests = $this->mockHttpClient([new Response(200, ['Content-Type' => 'image/png'], $this->files->pngImageData())]); $user = $this->users->viewer(); $this->assertFalse($user->avatar()->exists()); $this->artisan("bookstack:refresh-avatar --email={$user->email} -f") ->expectsQuestion('Are you sure you want to proceed?', true) ->expectsOutput("[ID: {$user->id}] {$user->email} - Updated") ->expectsOutputToContain('This will destroy any existing avatar images these users have, and attempt to fetch new avatar images from avatars.example.com') ->assertExitCode(0); $this->assertEquals('https://avatars.example.com?a=b', $requests->latestRequest()->getUri()); $user->refresh(); $this->assertTrue($user->avatar()->exists()); } public function test_command_runs_with_provided_id() { $requests = $this->mockHttpClient([new Response(200, ['Content-Type' => 'image/png'], $this->files->pngImageData())]); $user = $this->users->viewer(); $this->assertFalse($user->avatar()->exists()); $this->artisan("bookstack:refresh-avatar --id={$user->id} -f") ->expectsQuestion('Are you sure you want to proceed?', true) ->expectsOutput("[ID: {$user->id}] {$user->email} - Updated") ->assertExitCode(0); $this->assertEquals('https://avatars.example.com?a=b', $requests->latestRequest()->getUri()); $user->refresh(); $this->assertTrue($user->avatar()->exists()); } public function test_command_runs_with_provided_id_error_upstream() { $requests = $this->mockHttpClient([new Response(404)]); $user = $this->users->viewer(); $this->assertFalse($user->avatar()->exists()); $this->artisan("bookstack:refresh-avatar --id={$user->id} -f") ->expectsQuestion('Are you sure you want to proceed?', true) ->expectsOutput("[ID: {$user->id}] {$user->email} - Not updated") ->assertExitCode(1); $this->assertEquals(1, $requests->requestCount()); $this->assertFalse($user->avatar()->exists()); } public function test_saying_no_to_confirmation_does_not_refresh_avatar() { $user = $this->users->viewer(); $this->assertFalse($user->avatar()->exists()); $this->artisan("bookstack:refresh-avatar --id={$user->id} -f") ->expectsQuestion('Are you sure you want to proceed?', false) ->assertExitCode(0); $this->assertFalse($user->avatar()->exists()); } public function test_giving_non_existing_user_shows_error_message() { $this->artisan('bookstack:refresh-avatar --email=donkeys@example.com') ->expectsOutput('A user where email=donkeys@example.com could not be found.') ->assertExitCode(1); } public function test_command_runs_all_users_without_avatars_dry_run() { $users = User::query()->where('image_id', '=', 0)->get(); $this->artisan('bookstack:refresh-avatar --users-without-avatars') ->expectsOutput(count($users) . ' user(s) found to update avatars for.') ->expectsOutput("[ID: {$users[0]->id}] {$users[0]->email} - Not updated") ->expectsOutput('Dry run, no avatars were updated.') ->assertExitCode(0); } public function test_command_runs_all_users_without_avatars_with_none_to_update() { $requests = $this->mockHttpClient(); $image = Image::factory()->create(); User::query()->update(['image_id' => $image->id]); $this->artisan('bookstack:refresh-avatar --users-without-avatars -f') ->expectsOutput('0 user(s) found to update avatars for.') ->assertExitCode(0); $this->assertEquals(0, $requests->requestCount()); } public function test_command_runs_all_users_without_avatars() { /** @var Collection|User[] $users */ $users = User::query()->where('image_id', '=', 0)->get(); $pendingCommand = $this->artisan('bookstack:refresh-avatar --users-without-avatars -f'); $pendingCommand ->expectsOutput($users->count() . ' user(s) found to update avatars for.') ->expectsQuestion('Are you sure you want to proceed?', true); $responses = []; foreach ($users as $user) { $pendingCommand->expectsOutput("[ID: {$user->id}] {$user->email} - Updated"); $responses[] = new Response(200, ['Content-Type' => 'image/png'], $this->files->pngImageData()); } $requests = $this->mockHttpClient($responses); $pendingCommand->assertExitCode(0); $pendingCommand->run(); $this->assertEquals(0, User::query()->where('image_id', '=', 0)->count()); $this->assertEquals($users->count(), $requests->requestCount()); } public function test_saying_no_to_confirmation_all_users_without_avatars() { $requests = $this->mockHttpClient(); $this->artisan('bookstack:refresh-avatar --users-without-avatars -f') ->expectsQuestion('Are you sure you want to proceed?', false) ->assertExitCode(0); $this->assertEquals(0, $requests->requestCount()); } public function test_command_runs_all_users_dry_run() { $users = User::query()->where('image_id', '=', 0)->get(); $this->artisan('bookstack:refresh-avatar --all') ->expectsOutput(count($users) . ' user(s) found to update avatars for.') ->expectsOutput("[ID: {$users[0]->id}] {$users[0]->email} - Not updated") ->expectsOutput('Dry run, no avatars were updated.') ->assertExitCode(0); } public function test_command_runs_update_all_users_avatar() { /** @var Collection|User[] $users */ $users = User::query()->get(); $pendingCommand = $this->artisan('bookstack:refresh-avatar --all -f'); $pendingCommand ->expectsOutput($users->count() . ' user(s) found to update avatars for.') ->expectsQuestion('Are you sure you want to proceed?', true); $responses = []; foreach ($users as $user) { $pendingCommand->expectsOutput("[ID: {$user->id}] {$user->email} - Updated"); $responses[] = new Response(200, ['Content-Type' => 'image/png'], $this->files->pngImageData()); } $requests = $this->mockHttpClient($responses); $pendingCommand->assertExitCode(0); $pendingCommand->run(); $this->assertEquals(0, User::query()->where('image_id', '=', 0)->count()); $this->assertEquals($users->count(), $requests->requestCount()); } public function test_command_runs_update_all_users_avatar_errors() { /** @var Collection|User[] $users */ $users = array_values(User::query()->get()->all()); $pendingCommand = $this->artisan('bookstack:refresh-avatar --all -f'); $pendingCommand ->expectsOutput(count($users) . ' user(s) found to update avatars for.') ->expectsQuestion('Are you sure you want to proceed?', true); $responses = []; foreach ($users as $index => $user) { if ($index === 0) { $pendingCommand->expectsOutput("[ID: {$user->id}] {$user->email} - Not updated"); $responses[] = new Response(404); continue; } $pendingCommand->expectsOutput("[ID: {$user->id}] {$user->email} - Updated"); $responses[] = new Response(200, ['Content-Type' => 'image/png'], $this->files->pngImageData()); } $requests = $this->mockHttpClient($responses); $pendingCommand->assertExitCode(1); $pendingCommand->run(); $userWithAvatars = User::query()->where('image_id', '!=', 0)->count(); $this->assertEquals(count($users) - 1, $userWithAvatars); $this->assertEquals(count($users), $requests->requestCount()); } public function test_saying_no_to_confirmation_update_all_users_avatar() { $requests = $this->mockHttpClient([new Response(200, ['Content-Type' => 'image/png'], $this->files->pngImageData())]); $this->artisan('bookstack:refresh-avatar --all -f') ->expectsQuestion('Are you sure you want to proceed?', false) ->assertExitCode(0); $this->assertEquals(0, $requests->requestCount()); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false