From f513ea720e3f90f745d59cb8f4f0c82bf185c656 Mon Sep 17 00:00:00 2001 From: Jonas Date: Mon, 9 Nov 2026 14:58:37 +0100 Subject: [PATCH 1/3] fix(share): allow viewing files in shares with download disabled Text refused to open files from shares with the download permission disabled, including the folder description (Readme.md) of shared folders and attachments in such files. Use `IShare::canSeeContent()` to decide whether Text may show a file and its attachments. Copying a file into the attachment folder still requires the download permission, as WebDAV COPY and MOVE do on the server. Migrate the share e2e tests from Cypress to Playwright and test both values of the admin setting. Fixes: #7023 Signed-off-by: Jonas Assisted-by: ClaudeCode:claude-opus-5-5 --- cypress/e2e/share.spec.js | 160 ------------------- lib/Context/FileContext.php | 4 +- lib/Controller/AttachmentController.php | 4 +- lib/Service/AttachmentService.php | 31 ++-- lib/Service/FileService.php | 11 +- playwright/e2e/share.spec.ts | 117 ++++++++++++++ playwright/support/fixtures/Node.ts | 22 +++ playwright/support/fixtures/settings.ts | 19 +++ playwright/support/fixtures/shared-file.ts | 44 +++-- src/nodes/ImageView.vue | 41 +++-- tests/unit/Service/AttachmentServiceTest.php | 129 +++++++++++++-- tests/unit/Service/FileServiceTest.php | 33 +++- 12 files changed, 397 insertions(+), 218 deletions(-) delete mode 100644 cypress/e2e/share.spec.js create mode 100644 playwright/e2e/share.spec.ts diff --git a/cypress/e2e/share.spec.js b/cypress/e2e/share.spec.js deleted file mode 100644 index f0e16830050..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('.viewer__modal').should('not.exist') - // 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/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/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/FileService.php b/lib/Service/FileService.php index c41dcdd57f7..9cd440b881e 100644 --- a/lib/Service/FileService.php +++ b/lib/Service/FileService.php @@ -136,6 +136,15 @@ public function isDownloadDisabled(File $file): bool { return $this->isShareDownloadDisabled($storage->getShare()); } + public function canSeeContent(File $file): bool { + $storage = $file->getStorage(); + if (!$storage->instanceOfStorage(SharedStorage::class)) { + return true; + } + /** @var SharedStorage $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/share.spec.ts b/playwright/e2e/share.spec.ts new file mode 100644 index 00000000000..4586226b20d --- /dev/null +++ b/playwright/e2e/share.spec.ts @@ -0,0 +1,117 @@ +/** + * 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, viewer }) => { + 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 viewer.el.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, viewer }) => { + await open() + await viewer.el.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() + }) + }) +}) 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 @@