diff --git a/cypress/e2e/share.spec.js b/cypress/e2e/share.spec.js deleted file mode 100644 index e72c32e223c..00000000000 --- a/cypress/e2e/share.spec.js +++ /dev/null @@ -1,160 +0,0 @@ -/** - * SPDX-FileCopyrightText: 2020 Nextcloud GmbH and Nextcloud contributors - * SPDX-License-Identifier: AGPL-3.0-or-later - */ - -import { randUser } from '../utils/index.js' - -const user = randUser() -const recipient = randUser() - -describe('Open test.md in viewer', function() { - before(function() { - // Init user - cy.createUser(user) - cy.login(user) - - // Upload test files - cy.createFolder('folder') - cy.uploadFile('test.md', 'text/markdown', 'folder/test.md') - cy.uploadFile('test.md', 'text/markdown', 'folder/Readme.md') - cy.uploadFile('test.md', 'text/markdown', 'test3.md') - cy.uploadFile('test.md', 'text/markdown', 'test2.md') - cy.uploadFile('test.md', 'text/markdown') - - cy.createUser(recipient) - }) - beforeEach(function() { - cy.login(user) - }) - - it('Shares the file as a public read only link', function() { - cy.shareFile('/test.md') - .then((token) => { - cy.clearCookies() - cy.visit(`/s/${token}`) - }) - .then(() => { - cy.getEditor().should('be.visible') - cy.getContent() - .should('contain', 'Hello world') - .find('h2') - .should('contain', 'Hello world') - - cy.get('[data-text-el="readonly-bar"]') - .getActionEntry('outline') - .click() - - cy.getTOC().find('.editor__toc-header').should('exist') - }) - }) - - it('Shares the file as a public link with write permissions', function() { - cy.shareFile('/test2.md', { edit: true }) - .then((token) => { - cy.visit(`/s/${token}`) - }) - .then(() => { - cy.getEditor().should('be.visible') - cy.getContent() - .should('contain', 'Hello world') - .find('h2') - .should('contain', 'Hello world') - - cy.getMenu().should('be.visible') - cy.getActionEntry('undo').should('be.visible') - cy.getActionEntry('redo').should('be.visible') - cy.getActionEntry('bold').should('be.visible') - }) - }) - - it('Opens the editor as guest', function() { - cy.shareFile('/test2.md', { edit: true }) - .then((token) => { - cy.clearCookies() - cy.visit(`/s/${token}`) - }) - .then(() => { - cy.getEditor().should('be.visible') - cy.getContent() - .should('contain', 'Hello world') - .find('h2') - .should('contain', 'Hello world') - - cy.getMenu().should('be.visible') - cy.getActionEntry('undo').should('be.visible') - cy.getActionEntry('redo').should('be.visible') - cy.getActionEntry('bold').should('be.visible') - }) - }) - - it('Shares a folder as a public read only link', function() { - cy.shareFile('/folder') - .then((token) => { - cy.clearCookies() - cy.visit(`/s/${token}`) - }) - .then(() => { - cy.openFile('test.md') - cy.getModal().getContent().should('be.visible') - cy.getModal().getContent().should('contain', 'Hello world') - cy.getModal() - .getContent() - .find('h2') - .should('contain', 'Hello world') - cy.getModal().find('.modal-header button.header-close').click() - cy.get('.modal-mask').should('not.be.visible') - // cy.get('#rich-workspace').getContent().should('contain', 'Hello world') - }) - }) - - it('Opens the editor as guest and set a session username', function() { - cy.shareFile('/test3.md', { edit: true }) - .then((token) => { - cy.clearCookies() - cy.visit(`/s/${token}`) - }) - .then(() => { - cy.getEditor().should('be.visible') - cy.getContent().find('h2').should('contain', 'Hello world') - cy.get('button.avatar-list').click() - cy.get('.session-menu button').click() - cy.get('.guest-name-dialog input[type="text"]').type('someone{enter}') - cy.get('.session-menu .session-label.guest').should( - 'contain', - 'someone', - ) - }) - }) - - it('Share a file with download disabled shows an error', function() { - cy.shareFileToUser('test.md', recipient, { - attributes: '[{"scope":"permissions","key":"download","value":false}]', - }).then(() => { - cy.login(recipient) - cy.visit('/apps/files') - cy.openFile('test.md') - cy.getModal() - .find('.document-status') - .should( - 'contain', - 'This file cannot be displayed as download is disabled by the share', - ) - cy.getModal().getContent().should('not.exist') - }) - }) - - it('makes use of the file id', function() { - cy.intercept({ - method: 'PUT', - url: '**/apps/text/public/session/*/create', - }).as('create') - cy.shareFile('/test2.md', { edit: true }).then((token) => { - cy.clearCookies() - cy.visit(`/s/${token}`) - }) - cy.wait('@create', { timeout: 10000 }) - .its('request.body.fileId') - .should('be.a', 'Number') - }) -}) diff --git a/lib/Context/FileContext.php b/lib/Context/FileContext.php index 42cd6904392..832887fdb7c 100644 --- a/lib/Context/FileContext.php +++ b/lib/Context/FileContext.php @@ -89,8 +89,8 @@ public function buildDocument(): Document { $this->logger->warning('No permission to access this file', ['exception' => $e]); throw new NotFoundException($this->l10n->t('File not found'), $e->getCode(), $e); } - // Block using text for disabled download internal shares - if ($this->fileService->isDownloadDisabled($file)) { + // Block using text when the share does not allow viewing the content + if (!$this->fileService->canSeeContent($file)) { throw new NotPermittedException( $this->l10n->t('This file cannot be displayed as download is disabled by the share') ); diff --git a/lib/Context/FileContextFactory.php b/lib/Context/FileContextFactory.php index 5125a49897e..a9326430b6e 100644 --- a/lib/Context/FileContextFactory.php +++ b/lib/Context/FileContextFactory.php @@ -12,6 +12,7 @@ use OCA\Text\Service\LockService; use OCP\Files\File; use OCP\Files\NotFoundException; +use OCP\Files\NotPermittedException; use OCP\IL10N; use OCP\IUser; use OCP\Share\IShare; @@ -39,6 +40,11 @@ public function build( * If not then well 404 it is. */ $this->fileService->checkSharePermissions($auth); + if (!$auth->canSeeContent()) { + throw new NotPermittedException( + $this->l10n->t('This file cannot be displayed as download is disabled by the share') + ); + } } return new FileContext( $this->fileService, diff --git a/lib/Controller/AttachmentController.php b/lib/Controller/AttachmentController.php index 6af1ded8978..72ed82d5e26 100644 --- a/lib/Controller/AttachmentController.php +++ b/lib/Controller/AttachmentController.php @@ -215,7 +215,7 @@ public function getImageFile( try { $auth = $this->getAuth($shareToken, false); $context = $this->getContext($auth, $fileId); - $imageFile = $this->attachmentService->getImageFile($context, $imageFileName, $preferRawImage === 1); + $imageFile = $this->attachmentService->getImageFile($context, $imageFileName, $preferRawImage === 1, $auth); if ($imageFile !== null) { $response = new DataDownloadResponse( $imageFile->getContent(), @@ -252,7 +252,7 @@ public function getMediaFile( try { $auth = $this->getAuth($shareToken, false); $context = $this->getContext($auth, $fileId); - $mediaFile = $this->attachmentService->getMediaFile($context, $mediaFileName); + $mediaFile = $this->attachmentService->getMediaFile($context, $mediaFileName, $auth); return $mediaFile !== null ? new DataDownloadResponse( $mediaFile->getContent(), diff --git a/lib/Controller/PublicSessionController.php b/lib/Controller/PublicSessionController.php index 6332b7dd3cb..ce2e36a6d40 100644 --- a/lib/Controller/PublicSessionController.php +++ b/lib/Controller/PublicSessionController.php @@ -18,6 +18,7 @@ use OCP\AppFramework\Http\DataResponse; use OCP\AppFramework\PublicShareController; use OCP\Files\NotFoundException; +use OCP\Files\NotPermittedException; use OCP\IRequest; use OCP\ISession; use OCP\Share\Exceptions\ShareNotFound; @@ -79,6 +80,8 @@ public function create(string $token, ?string $filePath = null, ?string $baseVer return $this->apiService->create($context, $baseVersionEtag, $guestName); } catch (NotFoundException|\InvalidArgumentException) { return new DataResponse([], Http::STATUS_NOT_FOUND); + } catch (NotPermittedException $e) { + return new DataResponse(['error' => $e->getMessage()], Http::STATUS_FORBIDDEN); } } diff --git a/lib/DAV/WorkspacePlugin.php b/lib/DAV/WorkspacePlugin.php index 29f38db26dc..9ed8915f8a4 100644 --- a/lib/DAV/WorkspacePlugin.php +++ b/lib/DAV/WorkspacePlugin.php @@ -13,6 +13,8 @@ use OCA\DAV\Connector\Sabre\Directory; use OCA\DAV\Files\FilesHome; use OCA\Text\Service\ConfigService; +use OCA\Text\Service\EncodingService; +use OCA\Text\Service\FileService; use OCA\Text\Service\WorkspaceService; use OCP\Files\GenericFileException; use OCP\Files\NotPermittedException; @@ -34,8 +36,10 @@ class WorkspacePlugin extends ServerPlugin { public function __construct( private readonly WorkspaceService $workspaceService, + private readonly FileService $fileService, private readonly ICacheFactory $cacheFactory, private readonly ConfigService $configService, + private readonly EncodingService $encodingService, private readonly LoggerInterface $logger, private readonly ?string $userId, ) { @@ -102,7 +106,7 @@ public function propFind(PropFind $propFind, INode $node) { } $workspaceContentCallback = function () use ($file) { $cachedContent = ''; - if ($file instanceof File) { + if ($file instanceof File && $this->fileService->canSeeContent($file)) { $cache = $this->cacheFactory->createDistributed('text_workspace'); $cacheKey = $file->getFileInfo()->getId() . '_' . $file->getFileInfo()->getEtag(); if (($cachedContent = $cache->get($cacheKey)) !== null) { @@ -110,7 +114,7 @@ public function propFind(PropFind $propFind, INode $node) { } try { - $cachedContent = $file->getContent(); + $cachedContent = $this->encodingService->encodeToXmlSafeUtf8($file->getContent()); $cache->set($cacheKey, $cachedContent, 3600); } catch (GenericFileException|NotPermittedException|LockedException $e) { // Ignore but log when debugging diff --git a/lib/Service/AttachmentService.php b/lib/Service/AttachmentService.php index 844f68bfa51..13345885622 100755 --- a/lib/Service/AttachmentService.php +++ b/lib/Service/AttachmentService.php @@ -56,8 +56,9 @@ public function __construct( * @throws NotFoundException * @throws NotPermittedException */ - public function getImageFile(IContext $context, string $imageFileName, bool $preferRawImage): File|ISimpleFile|null { + public function getImageFile(IContext $context, string $imageFileName, bool $preferRawImage, IShare|IUser $auth): File|ISimpleFile|null { $textFile = $this->getTextFile($context); + $preferRawImage = $preferRawImage && $this->canDownload($textFile, $auth); return $this->getImageFileContent($imageFileName, $textFile, $preferRawImage); } @@ -96,11 +97,21 @@ private function getImageFileContent(string $imageFileName, File $textFile, bool * @throws NotPermittedException * @throws NoUserException */ - public function getMediaFile(IContext $context, string $mediaFileName): ?File { + public function getMediaFile(IContext $context, string $mediaFileName, IShare|IUser $auth): ?File { $textFile = $this->getTextFile($context); + if (!$this->canDownload($textFile, $auth)) { + return null; + } return $this->getMediaFullFile($mediaFileName, $textFile); } + private function canDownload(File $textFile, IShare|IUser $auth): bool { + if ($auth instanceof IShare) { + return $auth->canDownload(); + } + return !$this->fileService->isDownloadDisabled($textFile); + } + /** * @throws NotFoundException * @throws NotPermittedException @@ -110,7 +121,7 @@ public function getMediaFile(IContext $context, string $mediaFileName): ?File { private function getMediaFullFile(string $mediaFileName, File $textFile): ?File { $attachmentFolder = $this->getAttachmentDirectoryForFile($textFile, true); $mediaFile = $attachmentFolder->get($mediaFileName); - if ($mediaFile instanceof File && !$this->fileService->isDownloadDisabled($mediaFile)) { + if ($mediaFile instanceof File) { return $mediaFile; } return null; @@ -138,7 +149,7 @@ public function getMediaFilePreview(IContext $context, string $mediaFileName): ? private function getMediaFilePreviewFile(string $mediaFileName, File $textFile): ?array { $attachmentFolder = $this->getAttachmentDirectoryForFile($textFile, true); $mediaFile = $attachmentFolder->get($mediaFileName); - if ($mediaFile instanceof File && !$this->fileService->isDownloadDisabled($mediaFile)) { + if ($mediaFile instanceof File) { if ($this->previewManager->isMimeSupported($mediaFile->getMimeType())) { try { return [ @@ -167,7 +178,6 @@ private function getMediaFilePreviewFile(string $mediaFileName, File $textFile): public function getAttachmentList(IContext $context, IShare|IUser $auth, ?Session $session = null): array { $textFile = $this->getTextFile($context); try { - $attachmentDir = $this->getAttachmentDirectoryForFile($textFile); } catch (NotFoundException) { return []; @@ -181,6 +191,7 @@ public function getAttachmentList(IContext $context, IShare|IUser $auth, ?Sessio : '?fileId=' . $context->getId() . $shareTokenUrlString; $attachments = []; + $canDownload = $this->canDownload($textFile, $auth); // Folder davPath need to be relative to. $davFolder = ($auth instanceof IUser) @@ -214,9 +225,11 @@ public function getAttachmentList(IContext $context, IShare|IUser $auth, ?Sessio 'isImage' => $isImage, 'davPath' => $davFolder?->getRelativePath($node->getPath()), 'metadata' => $metadata, - 'fullUrl' => $isImage - ? $this->urlGenerator->linkToRouteAbsolute('text.Attachment.getImageFile') . $urlParamsBase . '&imageFileName=' . rawurlencode($name) . '&preferRawImage=1' - : $this->urlGenerator->linkToRouteAbsolute('text.Attachment.getMediaFile') . $urlParamsBase . '&mediaFileName=' . rawurlencode($name), + 'fullUrl' => match (true) { + $isImage => $this->urlGenerator->linkToRouteAbsolute('text.Attachment.getImageFile') . $urlParamsBase . '&imageFileName=' . rawurlencode($name) . ($canDownload ? '&preferRawImage=1' : ''), + $canDownload => $this->urlGenerator->linkToRouteAbsolute('text.Attachment.getMediaFile') . $urlParamsBase . '&mediaFileName=' . rawurlencode($name), + default => null, + }, 'previewUrl' => $isImage ? $this->urlGenerator->linkToRouteAbsolute('text.Attachment.getImageFile') . $urlParamsBase . '&imageFileName=' . rawurlencode($name) : $this->urlGenerator->linkToRouteAbsolute('text.Attachment.getMediaFilePreview') . $urlParamsBase . '&mediaFileName=' . rawurlencode($name), @@ -403,7 +416,7 @@ private function getFileFromPath(string $filePath, string $userId): File { */ private function getTextFile(IContext $context): File { $file = $context->getFile(); - if ($file instanceof File && !$this->fileService->isDownloadDisabled($file)) { + if ($file instanceof File && $this->fileService->canSeeContent($file)) { return $file; } throw new NotFoundException('Text file for ' diff --git a/lib/Service/EncodingService.php b/lib/Service/EncodingService.php index 1ed1cea5494..a4248f95a04 100644 --- a/lib/Service/EncodingService.php +++ b/lib/Service/EncodingService.php @@ -20,6 +20,14 @@ class EncodingService { 'UTF-8' => "\xef\xbb\xbf" ]; + /** + * Matches characters outside the XML 1.0 Char production, which cannot be + * part of an XML document, not even escaped. + * + * @see https://www.w3.org/TR/xml/#charsets + */ + private const string XML_INVALID_CHARS = '/[^\x{9}\x{A}\x{D}\x{20}-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF}]/u'; + public function encodeToUtf8(string $string): ?string { $encoding = $this->detectEncoding($string); if ($encoding === null) { @@ -30,6 +38,18 @@ public function encodeToUtf8(string $string): ?string { return is_string($encoded) ? $encoded : null; } + /** + * Encode to UTF-8 and replace characters that are not allowed in XML with U+FFFD + */ + public function encodeToXmlSafeUtf8(string $string): ?string { + $encoded = $this->encodeToUtf8($string); + if ($encoded === null) { + return null; + } + + return preg_replace(self::XML_INVALID_CHARS, "\u{FFFD}", $encoded); + } + public function detectEncoding(string $string): ?string { $bomDetect = $this->detectUtfBom($string); if ($bomDetect !== null) { diff --git a/lib/Service/FileService.php b/lib/Service/FileService.php index c41dcdd57f7..0803c1fcb05 100644 --- a/lib/Service/FileService.php +++ b/lib/Service/FileService.php @@ -7,7 +7,6 @@ namespace OCA\Text\Service; -use OCA\Files_Sharing\SharedStorage; use OCA\Text\Exception\InvalidSessionException; use OCP\Constants; use OCP\Files\File; @@ -16,6 +15,7 @@ use OCP\Files\Node; use OCP\Files\NotFoundException; use OCP\Files\NotPermittedException; +use OCP\Files\Storage\ISharedStorage; use OCP\ISession; use OCP\IUser; use OCP\Share\Exceptions\ShareNotFound; @@ -129,13 +129,22 @@ public function isReadOnly(File $file, IUser|IShare $auth): bool { public function isDownloadDisabled(File $file): bool { $storage = $file->getStorage(); - if (!$storage->instanceOfStorage(SharedStorage::class)) { + if (!$storage->instanceOfStorage(ISharedStorage::class)) { return false; } - /** @var SharedStorage $storage */ + /** @var ISharedStorage $storage */ return $this->isShareDownloadDisabled($storage->getShare()); } + public function canSeeContent(File $file): bool { + $storage = $file->getStorage(); + if (!$storage->instanceOfStorage(ISharedStorage::class)) { + return true; + } + /** @var ISharedStorage $storage */ + return $storage->getShare()->canSeeContent(); + } + public function isShareDownloadDisabled(IShare $share): bool { $attributes = $share->getAttributes(); return $attributes !== null @@ -193,7 +202,7 @@ public function checkFileAccessFromShare(int $fileId, string $shareToken): void throw new InvalidSessionException(); } - if ($this->isShareDownloadDisabled($share)) { + if (!$share->canSeeContent()) { throw new InvalidSessionException(); } } diff --git a/playwright/e2e/propfind.spec.ts b/playwright/e2e/propfind.spec.ts index 72d4f09bf6f..f5f454f2c61 100644 --- a/playwright/e2e/propfind.spec.ts +++ b/playwright/e2e/propfind.spec.ts @@ -6,7 +6,8 @@ import { expect } from '@playwright/test' import { createFolder, uploadFile } from '../support/fixtures/Node.ts' import { test } from '../support/fixtures/random-user.ts' -import { setTextSetting } from '../support/fixtures/settings.ts' +import { setAppConfig, setTextSetting } from '../support/fixtures/settings.ts' +import { test as sharedFileTest } from '../support/fixtures/shared-file.ts' import { deleteWebDAVResource, PROPERTY_WORKSPACE, @@ -100,4 +101,36 @@ test.describe('Text PROPFIND extension', () => { expect(folder).not.toHaveProperty(PROPERTY_WORKSPACE) }) }) + + sharedFileTest.describe('in a folder shared with download disabled', () => { + sharedFileTest.beforeEach(async ({ owner, recipient }) => { + await setTextSetting(recipient, 'workspace_enabled', 1) + const folder = await createFolder({ name: 'shared', owner }) + await owner.uploadFile({ name: 'shared/Readme.md', content: '## Hello world\n' }) + await folder.shareWithUser(recipient.account.userId, { + attributes: [{ scope: 'permissions', key: 'download', value: false }], + }) + }) + + sharedFileTest('returns the rich workspace content', async ({ recipient }) => { + const [folder] = await propfindFolder(recipient, '/shared', 0) + expect(folder).toHaveProperty(PROPERTY_WORKSPACE, '## Hello world\n') + }) + + sharedFileTest.describe('with viewing without download disallowed', () => { + sharedFileTest.beforeEach(async ({ request }) => { + await setAppConfig(request, 'core', 'shareapi_allow_view_without_download', 'no') + }) + + sharedFileTest.afterEach(async ({ request }) => { + await setAppConfig(request, 'core', 'shareapi_allow_view_without_download', null) + }) + + sharedFileTest('does not return the rich workspace content', async ({ recipient }) => { + const [folder] = await propfindFolder(recipient, '/shared', 0) + expect(folder).toHaveProperty(PROPERTY_WORKSPACE, '') + expect(folder[PROPERTY_WORKSPACE_FILE]).not.toBe('') + }) + }) + }) }) diff --git a/playwright/e2e/share.spec.ts b/playwright/e2e/share.spec.ts new file mode 100644 index 00000000000..efde49d8bfd --- /dev/null +++ b/playwright/e2e/share.spec.ts @@ -0,0 +1,167 @@ +/** + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import { expect, mergeTests } from '@playwright/test' +import { test as editorTest } from '../support/fixtures/editor.ts' +import { createFolder, Node } from '../support/fixtures/Node.ts' +import { setAppConfig } from '../support/fixtures/settings.ts' +import { test as sharedFileTest } from '../support/fixtures/shared-file.ts' +import { EditorSection } from '../support/sections/EditorSection.ts' +import { ViewerSection } from '../support/sections/ViewerSection.ts' + +const test = mergeTests(editorTest, sharedFileTest) + +const downloadDisabled = [{ scope: 'permissions', key: 'download', value: false }] + +test.use({ + fileName: 'test.md', + fileContent: '## Hello world', +}) + +test.describe('Public link share', () => { + test('opens a read only file share', async ({ editor, file, page }) => { + const { token } = await file.shareLink() + await page.goto(`s/${token}`) + await expect(editor.getHeading({ name: 'Hello world' })).toBeVisible() + await expect(editor.menubar).not.toBeVisible() + + await page.getByRole('dialog').getByRole('button', { name: 'Show outline' }).click() + await expect(editor.el.locator('[data-text-el="editor-table-of-contents"]')) + .toBeVisible() + }) + + test('opens an editable file share as logged in user', async ({ owner, share }) => { + const editor = new EditorSection(owner.page) + await owner.page.goto(`s/${share.token}`) + await expect(editor.getHeading({ name: 'Hello world' })).toBeVisible() + await expect(editor.getMenu('Undo')).toBeVisible() + await expect(editor.getMenu('Redo')).toBeVisible() + await expect(editor.getMenu('Bold')).toBeVisible() + }) + + test('opens an editable file share as guest', async ({ editor, open }) => { + await open() + await expect(editor.getHeading({ name: 'Hello world' })).toBeVisible() + await expect(editor.getMenu('Undo')).toBeVisible() + await expect(editor.getMenu('Redo')).toBeVisible() + await expect(editor.getMenu('Bold')).toBeVisible() + }) + + test('sets a guest name', async ({ open, page }) => { + await open() + await page.getByRole('dialog').getByRole('button', { name: 'Active people' }).click() + await page.getByRole('button', { name: 'edit' }).click() + const nameInput = page.getByRole('textbox', { name: 'Enter your name' }) + await nameInput.fill('someone') + await nameInput.press('Enter') + await expect(page.locator('.session-label.guest')).toHaveText('someone') + }) + + test('opens a file in a read only folder share', async ({ editor, owner, page, viewer }) => { + const folder = await createFolder({ name: 'folder', owner }) + await owner.uploadFile({ name: 'folder/test.md', content: '## Hello world' }) + const { token } = await folder.shareLink() + await page.goto(`s/${token}`) + await page.getByRole('button', { name: 'View: test.md' }).click() + await expect(editor.getHeading({ name: 'Hello world' })).toBeVisible() + await viewer.close() + }) + + test('uses the file id', async ({ file, page, share }) => { + const createRequest = page.waitForRequest(/\/apps\/text\/public\/session\/\d+\/create$/) + await page.goto(`s/${share.token}`) + expect((await createRequest).postDataJSON().fileId).toBe(file.id) + }) +}) + +test.describe('User share with download disabled', () => { + test('opens the file', async ({ file, recipient }) => { + await file.shareWithUser(recipient.account.userId, { attributes: downloadDisabled }) + const editor = new EditorSection(recipient.page) + await new Node({ ...file, page: recipient.page }).open() + await expect(editor.getHeading({ name: 'Hello world' })).toBeVisible() + await expect(editor.getMenu('Bold')).toBeVisible() + }) + + test('shows the folder description', async ({ owner, recipient }) => { + const folder = await createFolder({ name: 'folder', owner }) + await owner.uploadFile({ name: 'folder/Readme.md', content: '## Folder description' }) + await folder.shareWithUser(recipient.account.userId, { attributes: downloadDisabled }) + const createResponse = recipient.page.waitForResponse(/\/apps\/text\/session\/file\/\d+\/create$/) + await recipient.page.goto('apps/files/files?dir=/folder') + expect((await createResponse).status()).toBe(200) + await expect(new EditorSection(recipient.page).getHeading({ name: 'Folder description' })) + .toBeVisible() + }) + + test.describe('with viewing without download disallowed', () => { + test.beforeEach(async ({ request }) => { + await setAppConfig(request, 'core', 'shareapi_allow_view_without_download', 'no') + }) + + test.afterEach(async ({ request }) => { + await setAppConfig(request, 'core', 'shareapi_allow_view_without_download', null) + }) + + test('shows an error', async ({ file, recipient }) => { + await file.shareWithUser(recipient.account.userId, { attributes: downloadDisabled }) + const viewer = new ViewerSection(file.name, recipient.page) + await new Node({ ...file, page: recipient.page }).open() + await expect(viewer.el.getByText('This file cannot be displayed as download is disabled by the share')) + .toBeVisible() + await expect(new EditorSection(recipient.page).content).not.toBeVisible() + }) + }) +}) + +test.describe('Link share of a share with download disabled', () => { + test('opens the file', async ({ file, page, recipient }) => { + await file.shareWithUser(recipient.account.userId, { attributes: downloadDisabled }) + const { token } = await new Node({ ...file, page: recipient.page }).shareLink() + await page.goto(`s/${token}`) + await expect(new EditorSection(page).getHeading({ name: 'Hello world' })).toBeVisible() + }) + + test('shows the folder description', async ({ owner, page, recipient }) => { + const folder = await createFolder({ name: 'folder', owner }) + await owner.uploadFile({ name: 'folder/Readme.md', content: '## Folder description' }) + await folder.shareWithUser(recipient.account.userId, { attributes: downloadDisabled }) + const { token } = await new Node({ ...folder, page: recipient.page }).shareLink() + await page.goto(`s/${token}`) + await expect(new EditorSection(page).getHeading({ name: 'Folder description' })).toBeVisible() + }) + + test.describe('with viewing without download disallowed', () => { + test.beforeEach(async ({ request }) => { + await setAppConfig(request, 'core', 'shareapi_allow_view_without_download', 'no') + }) + + test.afterEach(async ({ request }) => { + await setAppConfig(request, 'core', 'shareapi_allow_view_without_download', null) + }) + + test('shows an error', async ({ file, page, recipient }) => { + await file.shareWithUser(recipient.account.userId, { attributes: downloadDisabled }) + const { token } = await new Node({ ...file, page: recipient.page }).shareLink() + const createResponse = page.waitForResponse(/\/apps\/text\/public\/session\/\d+\/create$/) + await page.goto(`s/${token}`) + expect((await createResponse).status()).toBe(403) + await expect(page.getByText('This file cannot be displayed as download is disabled by the share')) + .toBeVisible() + await expect(new EditorSection(page).content).not.toBeVisible() + }) + + test('does not show the folder description', async ({ owner, page, recipient }) => { + const folder = await createFolder({ name: 'folder', owner }) + await owner.uploadFile({ name: 'folder/Readme.md', content: '## Folder description' }) + await folder.shareWithUser(recipient.account.userId, { attributes: downloadDisabled }) + const { token } = await new Node({ ...folder, page: recipient.page }).shareLink() + const createResponse = page.waitForResponse(/\/apps\/text\/public\/session\/\d+\/create$/) + await page.goto(`s/${token}`) + expect((await createResponse).status()).toBe(403) + await expect(new EditorSection(page).getHeading({ name: 'Folder description' })).not.toBeVisible() + }) + }) +}) diff --git a/playwright/support/fixtures/Node.ts b/playwright/support/fixtures/Node.ts index 1fccf2e8bfb..7faead3e14f 100644 --- a/playwright/support/fixtures/Node.ts +++ b/playwright/support/fixtures/Node.ts @@ -57,12 +57,34 @@ export class Node { { data: { shareType, path }, headers: ocsHeaders, + failOnStatusCode: true, }, ) const { ocs } = await response.json() as { ocs: { data: { token: string, id: number } } } return ocs.data } + async shareWithUser(shareWith: string, { attributes }: { attributes?: object[] } = {}) { + // 0 = user share + const shareType = 0 + const path = `/${this.name}` + const response = await this.page.request.post( + '/ocs/v2.php/apps/files_sharing/api/v1/shares', + { + data: { + shareType, + path, + shareWith, + ...(attributes && { attributes: JSON.stringify(attributes) }), + }, + headers: ocsHeaders, + failOnStatusCode: true, + }, + ) + const { ocs } = await response.json() as { ocs: { data: { id: number } } } + return ocs.data + } + async shareEditableLink() { const { token, id } = await this.shareLink() // Same permissions makeing the share editable in the UI would set diff --git a/playwright/support/fixtures/settings.ts b/playwright/support/fixtures/settings.ts index bc1418f9649..020f45548e4 100644 --- a/playwright/support/fixtures/settings.ts +++ b/playwright/support/fixtures/settings.ts @@ -3,6 +3,7 @@ * SPDX-License-Identifier: AGPL-3.0-or-later */ +import type { APIRequestContext } from '@playwright/test' import type { User } from './User.ts' /** @@ -18,3 +19,21 @@ export async function setTextSetting(user: User, key: string, value: number | st failOnStatusCode: true, }) } + +/** + * Set a server app configuration value as admin. + * + * @param request Request context without a user session + * @param app The app id + * @param key The setting key to set + * @param value The value, or null to reset the setting to its default + */ +export async function setAppConfig(request: APIRequestContext, app: string, key: string, value: string | null): Promise { + const credentials = Buffer.from('admin:admin').toString('base64') + await request.fetch(`/ocs/v2.php/apps/provisioning_api/api/v1/config/apps/${app}/${key}`, { + method: value === null ? 'DELETE' : 'POST', + headers: { 'OCS-APIRequest': 'true', Authorization: `Basic ${credentials}` }, + ...(value !== null && { form: { value } }), + failOnStatusCode: true, + }) +} diff --git a/playwright/support/fixtures/shared-file.ts b/playwright/support/fixtures/shared-file.ts index 49d17028828..82617e7b7b1 100644 --- a/playwright/support/fixtures/shared-file.ts +++ b/playwright/support/fixtures/shared-file.ts @@ -3,6 +3,8 @@ * SPDX-License-Identifier: AGPL-3.0-or-later */ +import type { Browser } from '@playwright/test' + import { createRandomUser, login } from '@nextcloud/e2e-test-server/playwright' import { expect } from '@playwright/test' import { test as base } from './upload-file.ts' @@ -10,30 +12,44 @@ import { User } from './User.ts' export interface SharedFileFixture { owner: User + recipient: User share: { token: string } } +/** + * Create a random user and log in on a new page. + * + * @param browser Browser to open the page in + * @param baseURL Base URL of the page + */ +async function createLoggedInUser(browser: Browser, baseURL: string | undefined): Promise { + const account = await createRandomUser() + // Important: make sure we authenticate in a clean environment by unsetting storage state. + const page = await browser.newPage({ + storageState: undefined, + baseURL, + }) + + await login(page.request, account) + const tokenResponse = await page.request.get('./csrftoken', { + failOnStatusCode: true, + }) + const { token } = (await tokenResponse.json()) as { token: string } + page.context().setExtraHTTPHeaders({ requesttoken: token }) + return new User(account, page) +} + /** * This test fixture uploads the file to a user's root directory and shares it. */ export const test = base.extend({ owner: async ({ browser, baseURL }, use) => { - const account = await createRandomUser() - // Important: make sure we authenticate in a clean environment by unsetting storage state. - const page = await browser.newPage({ - storageState: undefined, - baseURL, - }) + await use(await createLoggedInUser(browser, baseURL)) + }, - await login(page.request, account) - const tokenResponse = await page.request.get('./csrftoken', { - failOnStatusCode: true, - }) - const { token } = (await tokenResponse.json()) as { token: string } - page.context().setExtraHTTPHeaders({ requesttoken: token }) - const user = new User(account, page) - await use(user) + recipient: async ({ browser, baseURL }, use) => { + await use(await createLoggedInUser(browser, baseURL)) }, file: async ({ fileContent, fileName, owner }, use) => { diff --git a/src/nodes/ImageView.vue b/src/nodes/ImageView.vue index 2c45da40f27..d5d3754b867 100644 --- a/src/nodes/ImageView.vue +++ b/src/nodes/ImageView.vue @@ -27,6 +27,7 @@