diff --git a/cypress/e2e/share.spec.js b/cypress/e2e/share.spec.js index ca901fe63aa..f851e9091b6 100644 --- a/cypress/e2e/share.spec.js +++ b/cypress/e2e/share.spec.js @@ -6,7 +6,6 @@ import { randUser } from '../utils/index.js' const user = randUser() -const recipient = randUser() describe('Open test.md in viewer', function () { before(function () { @@ -21,8 +20,6 @@ describe('Open test.md in viewer', function () { 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) @@ -129,23 +126,6 @@ describe('Open test.md in viewer', function () { }) }) - 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', diff --git a/lib/DAV/WorkspacePlugin.php b/lib/DAV/WorkspacePlugin.php index eaac84a903c..ae2b5dfe580 100644 --- a/lib/DAV/WorkspacePlugin.php +++ b/lib/DAV/WorkspacePlugin.php @@ -16,6 +16,7 @@ use OCA\Text\Service\WorkspaceService; use OCP\Files\GenericFileException; use OCP\Files\NotPermittedException; +use OCP\Files\Storage\ISharedStorage; use OCP\ICacheFactory; use OCP\Lock\LockedException; use Psr\Log\LoggerInterface; @@ -103,7 +104,7 @@ public function propFind(PropFind $propFind, INode $node) { } $workspaceContentCallback = function () use ($file) { $cachedContent = ''; - if ($file instanceof File) { + if ($file instanceof File && $this->canSeeContent($file)) { $cache = $this->cacheFactory->createDistributed('text_workspace'); $cacheKey = $file->getFileInfo()->getId() . '_' . $file->getFileInfo()->getEtag(); if (($cachedContent = $cache->get($cacheKey)) !== null) { @@ -139,4 +140,13 @@ public function propFind(PropFind $propFind, INode $node) { $propFind->handle(self::WORKSPACE_FILE_PROPERTY, $workspaceFileCallback); $propFind->handle(self::WORKSPACE_FILE_PROPERTY_FLAT, $workspaceFileCallback); } + + private function canSeeContent(File $file): bool { + $storage = $file->getStorage(); + if (!$storage->instanceOfStorage(ISharedStorage::class)) { + return true; + } + /** @var ISharedStorage $storage */ + return $storage->getShare()->canSeeContent(); + } } diff --git a/lib/Middleware/SessionMiddleware.php b/lib/Middleware/SessionMiddleware.php index 72f19602133..8eb75520259 100644 --- a/lib/Middleware/SessionMiddleware.php +++ b/lib/Middleware/SessionMiddleware.php @@ -176,8 +176,7 @@ private function assertUserOrShareToken(ISessionAwareController $controller): vo throw new InvalidSessionException(); } - $attributes = $share->getAttributes(); - if ($attributes !== null && $attributes->getAttribute('permissions', 'download') === false) { + if (!$share->canSeeContent()) { throw new InvalidSessionException(); } diff --git a/lib/Service/ApiService.php b/lib/Service/ApiService.php index d03944d8844..cf509b2784f 100644 --- a/lib/Service/ApiService.php +++ b/lib/Service/ApiService.php @@ -11,7 +11,6 @@ use Exception; use InvalidArgumentException; -use OCA\Files_Sharing\SharedStorage; use OCA\NotifyPush\Queue\IQueue; use OCA\Text\AppInfo\Application; use OCA\Text\Db\Document; @@ -25,6 +24,7 @@ use OCP\Files\Lock\ILock; use OCP\Files\NotFoundException; use OCP\Files\NotPermittedException; +use OCP\Files\Storage\ISharedStorage; use OCP\IL10N; use OCP\IRequest; use OCP\Lock\LockedException; @@ -56,10 +56,11 @@ public function create(?int $fileId = null, ?string $filePath = null, ?string $b */ try { $this->documentService->checkSharePermissions($token, Constants::PERMISSION_READ); + $this->documentService->checkShareCanSeeContent($token); } catch (NotFoundException $e) { return new DataResponse([], Http::STATUS_NOT_FOUND); } catch (NotPermittedException $e) { - return new DataResponse(['error' => $this->l10n->t('This file cannot be displayed as download is disabled by the share')], Http::STATUS_NOT_FOUND); + return new DataResponse(['error' => $this->l10n->t('This file cannot be displayed as download is disabled by the share')], Http::STATUS_FORBIDDEN); } } elseif ($fileId !== null) { try { @@ -76,12 +77,11 @@ public function create(?int $fileId = null, ?string $filePath = null, ?string $b $storage = $file->getStorage(); - // Block using text for disabled download internal shares - if ($storage->instanceOfStorage(SharedStorage::class)) { + // Block using text when the share does not allow viewing the content + if ($storage->instanceOfStorage(ISharedStorage::class)) { /** @var IShare $share */ $share = $storage->getShare(); - $shareAttribtues = $share->getAttributes(); - if ($shareAttribtues !== null && $shareAttribtues->getAttribute('permissions', 'download') === false) { + if (!$share->canSeeContent()) { return new DataResponse(['error' => $this->l10n->t('This file cannot be displayed as download is disabled by the share')], Http::STATUS_FORBIDDEN); } } diff --git a/lib/Service/AttachmentService.php b/lib/Service/AttachmentService.php index 94a74020ea3..d12a80a2e1b 100755 --- a/lib/Service/AttachmentService.php +++ b/lib/Service/AttachmentService.php @@ -11,7 +11,6 @@ use OC\User\NoUserException; use OCA\DAV\Connector\Sabre\PublicAuth; -use OCA\Files_Sharing\SharedStorage; use OCA\Text\Controller\AttachmentController; use OCA\Text\Db\Session; use OCP\Constants; @@ -24,6 +23,7 @@ use OCP\Files\NotFoundException; use OCP\Files\NotPermittedException; use OCP\Files\SimpleFS\ISimpleFile; +use OCP\Files\Storage\ISharedStorage; use OCP\FilesMetadata\IFilesMetadataManager; use OCP\IPreview; use OCP\ISession; @@ -57,6 +57,7 @@ public function __construct( */ public function getImageFile(int $documentId, string $imageFileName, string $userId, bool $preferRawImage): File|ISimpleFile|null { $textFile = $this->getTextFile($documentId, $userId); + $preferRawImage = $preferRawImage && !$this->isDownloadDisabled($textFile); return $this->getImageFileContent($imageFileName, $textFile, $preferRawImage); } @@ -70,6 +71,7 @@ public function getImageFile(int $documentId, string $imageFileName, string $use */ public function getImageFilePublic(int $documentId, string $imageFileName, string $shareToken, bool $preferRawImage): File|ISimpleFile|null { $textFile = $this->getTextFilePublic($documentId, $shareToken); + $preferRawImage = $preferRawImage && $this->canDownloadPublic($shareToken); return $this->getImageFileContent($imageFileName, $textFile, $preferRawImage); } @@ -110,6 +112,9 @@ private function getImageFileContent(string $imageFileName, File $textFile, bool */ public function getMediaFile(int $documentId, string $mediaFileName, string $userId): ?File { $textFile = $this->getTextFile($documentId, $userId); + if ($this->isDownloadDisabled($textFile)) { + return null; + } return $this->getMediaFullFile($mediaFileName, $textFile); } @@ -123,6 +128,9 @@ public function getMediaFile(int $documentId, string $mediaFileName, string $use */ public function getMediaFilePublic(int $documentId, string $mediaFileName, string $shareToken): ?File { $textFile = $this->getTextFilePublic($documentId, $shareToken); + if (!$this->canDownloadPublic($shareToken)) { + return null; + } return $this->getMediaFullFile($mediaFileName, $textFile); } @@ -135,7 +143,7 @@ public function getMediaFilePublic(int $documentId, string $mediaFileName, strin private function getMediaFullFile(string $mediaFileName, File $textFile): ?File { $attachmentFolder = $this->getAttachmentDirectoryForFile($textFile, true); $mediaFile = $attachmentFolder->get($mediaFileName); - if ($mediaFile instanceof File && !$this->isDownloadDisabled($mediaFile)) { + if ($mediaFile instanceof File) { return $mediaFile; } return null; @@ -174,7 +182,7 @@ public function getMediaFilePreviewPublic(int $documentId, string $mediaFileName private function getMediaFilePreviewFile(string $mediaFileName, File $textFile): ?array { $attachmentFolder = $this->getAttachmentDirectoryForFile($textFile, true); $mediaFile = $attachmentFolder->get($mediaFileName); - if ($mediaFile instanceof File && !$this->isDownloadDisabled($mediaFile)) { + if ($mediaFile instanceof File) { if ($this->previewManager->isMimeSupported($mediaFile->getMimeType())) { try { return [ @@ -223,6 +231,9 @@ public function getAttachmentList(int $documentId, ?string $userId = null, ?Sess : '?documentId=' . $documentId . $shareTokenUrlString; $attachments = []; + $canDownload = $shareToken !== null + ? $this->canDownloadPublic($shareToken) + : !$this->isDownloadDisabled($textFile); // Folder davPath need to be relative to. $davFolder = $userId !== null @@ -256,9 +267,11 @@ public function getAttachmentList(int $documentId, ?string $userId = null, ?Sess '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), @@ -500,8 +513,8 @@ private function getFileFromPath(string $filePath, string $userId): File { */ private function isDownloadDisabled(File $file): bool { $storage = $file->getStorage(); - if ($storage->instanceOfStorage(SharedStorage::class)) { - /** @var SharedStorage $storage */ + if ($storage->instanceOfStorage(ISharedStorage::class)) { + /** @var ISharedStorage $storage */ $share = $storage->getShare(); $attributes = $share->getAttributes(); if ($attributes !== null && $attributes->getAttribute('permissions', 'download') === false) { @@ -512,6 +525,23 @@ private function isDownloadDisabled(File $file): bool { return false; } + private function canSeeContent(File $file): bool { + $storage = $file->getStorage(); + if (!$storage->instanceOfStorage(ISharedStorage::class)) { + return true; + } + /** @var ISharedStorage $storage */ + return $storage->getShare()->canSeeContent(); + } + + private function canDownloadPublic(string $shareToken): bool { + try { + return $this->shareManager->getShareByToken($shareToken)->canDownload(); + } catch (ShareNotFound) { + return false; + } + } + /** * Get a user file from file ID * @@ -522,7 +552,7 @@ private function isDownloadDisabled(File $file): bool { private function getTextFile(int $documentId, string $userId): File { $userFolder = $this->rootFolder->getUserFolder($userId); $file = $userFolder->getFirstNodeById($documentId); - if ($file instanceof File && !$this->isDownloadDisabled($file)) { + if ($file instanceof File && $this->canSeeContent($file)) { return $file; } throw new NotFoundException('Text file with id=' . $documentId . ' was not found in storage of ' . $userId); @@ -542,7 +572,7 @@ private function getTextFilePublic(?int $documentId, string $shareToken): File { if ($share->getNodeType() === 'file') { $textFile = $share->getNode(); if ($textFile instanceof File - && !$this->isDownloadDisabled($textFile) + && $this->canSeeContent($textFile) && $textFile->getId() === $documentId ) { return $textFile; @@ -551,7 +581,7 @@ private function getTextFilePublic(?int $documentId, string $shareToken): File { $folder = $share->getNode(); if ($folder instanceof Folder) { $textFile = $folder->getFirstNodeById($documentId); - if ($textFile instanceof File && !$this->isDownloadDisabled($textFile)) { + if ($textFile instanceof File && $this->canSeeContent($textFile)) { return $textFile; } } diff --git a/lib/Service/DocumentService.php b/lib/Service/DocumentService.php index ba4a3452f69..4a4ae332f1d 100644 --- a/lib/Service/DocumentService.php +++ b/lib/Service/DocumentService.php @@ -671,6 +671,22 @@ public function checkSharePermissions(string $shareToken, int $permission = Cons } } + /** + * @throws NotFoundException + * @throws NotPermittedException + */ + public function checkShareCanSeeContent(string $shareToken): void { + try { + $share = $this->shareManager->getShareByToken($shareToken); + } catch (ShareNotFound $e) { + throw new NotFoundException(); + } + + if (!$share->canSeeContent()) { + throw new NotPermittedException(); + } + } + public function hasUnsavedChanges(Document $document): bool { $stepsVersion = $this->stepMapper->getLatestVersion($document->getId()) ?: 0; $docVersion = $document->getLastSavedVersion(); diff --git a/playwright/e2e/propfind.spec.ts b/playwright/e2e/propfind.spec.ts index 912b10b9f12..5cb0f0ced46 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, @@ -140,4 +141,57 @@ 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..a1391a1d5b1 --- /dev/null +++ b/playwright/e2e/share.spec.ts @@ -0,0 +1,188 @@ +/** + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import { expect } from '@playwright/test' +import { createFolder, Node } from '../support/fixtures/Node.ts' +import { setAppConfig } from '../support/fixtures/settings.ts' +import { test } from '../support/fixtures/shared-file.ts' +import { EditorSection } from '../support/sections/EditorSection.ts' +import { ViewerSection } from '../support/sections/ViewerSection.ts' + +const downloadDisabled = [{ scope: 'permissions', key: 'download', value: false }] + +test.use({ + fileName: 'test.md', + fileContent: '## Hello world', +}) + +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\/\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 3ddd0731807..6812df1b321 100644 --- a/playwright/support/fixtures/Node.ts +++ b/playwright/support/fixtures/Node.ts @@ -109,11 +109,32 @@ 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 dc354777e66..b8a1f8ad429 100644 --- a/playwright/support/fixtures/shared-file.ts +++ b/playwright/support/fixtures/shared-file.ts @@ -3,16 +3,39 @@ * SPDX-License-Identifier: AGPL-3.0-or-later */ -import { expect } from '@playwright/test' +import { expect, type Browser } from '@playwright/test' import { test as base } from './upload-file' import { createRandomUser, login } from '@nextcloud/e2e-test-server/playwright' import { User } from './User' 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. @@ -21,21 +44,11 @@ export const test = base.extend({ // eslint-disable-next-line no-empty-pattern 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 e0ba12beee3..dff965c1dee 100644 --- a/src/nodes/ImageView.vue +++ b/src/nodes/ImageView.vue @@ -427,7 +427,9 @@ export default { } // Download file - window.location.assign(this.attachment.fullUrl) + if (this.attachment.fullUrl) { + window.location.assign(this.attachment.fullUrl) + } }, async handleImageClick() { await this.updateEmbeddedImageList() diff --git a/tests/unit/DAV/WorkspacePluginTest.php b/tests/unit/DAV/WorkspacePluginTest.php new file mode 100644 index 00000000000..0391ae79e48 --- /dev/null +++ b/tests/unit/DAV/WorkspacePluginTest.php @@ -0,0 +1,100 @@ +createMock(FileInfo::class); + $fileInfo->method('getId')->willReturn(42); + $fileInfo->method('getEtag')->willReturn('etag'); + $file = $this->createMock(File::class); + $file->method('getFileInfo')->willReturn($fileInfo); + $file->method('getContent')->willReturn('## Readme'); + $this->share = $this->createMock(IShare::class); + $storage = $this->createMock(ISharedStorage::class); + $storage->method('instanceOfStorage') + ->willReturnCallback(fn (string $class): bool => $class === ISharedStorage::class); + $storage->method('getShare')->willReturn($this->share); + $file->method('getStorage')->willReturn($storage); + + $workspaceService = $this->createMock(WorkspaceService::class); + $workspaceService->method('getFile')->willReturn($file); + + $this->cache = $this->createMock(ICache::class); + $cacheFactory = $this->createMock(ICacheFactory::class); + $cacheFactory->method('createDistributed')->willReturn($this->cache); + + $configService = $this->createMock(ConfigService::class); + $configService->method('isRichWorkspaceAvailable')->willReturn(true); + $configService->method('isRichWorkspaceEnabledForUser')->willReturn(true); + + $this->plugin = new WorkspacePlugin( + $workspaceService, + $cacheFactory, + $configService, + $this->createMock(LoggerInterface::class), + 'user', + ); + $server = $this->createMock(Server::class); + $server->method('getHTTPDepth')->willReturn(0); + $this->plugin->initialize($server); + } + + public function testWorkspaceContent(): void { + $this->share->method('canSeeContent')->willReturn(true); + + $propFind = $this->propFind(); + + $this->assertSame('## Readme', $propFind->get(WorkspacePlugin::WORKSPACE_PROPERTY)); + $this->assertSame(42, $propFind->get(WorkspacePlugin::WORKSPACE_FILE_PROPERTY)); + } + + public function testWorkspaceContentHidden(): void { + $this->share->method('canSeeContent')->willReturn(false); + $this->cache->expects($this->never())->method('get'); + + $propFind = $this->propFind(); + + $this->assertSame('', $propFind->get(WorkspacePlugin::WORKSPACE_PROPERTY)); + $this->assertSame(42, $propFind->get(WorkspacePlugin::WORKSPACE_FILE_PROPERTY)); + } + + private function propFind(): PropFind { + $propFind = new PropFind('files/user/folder', [ + WorkspacePlugin::WORKSPACE_PROPERTY, + WorkspacePlugin::WORKSPACE_FILE_PROPERTY, + ], 0); + $node = $this->createMock(Directory::class); + $node->method('getNode')->willReturn($this->createMock(Folder::class)); + $this->plugin->propFind($propFind, $node); + return $propFind; + } +} diff --git a/tests/unit/Middleware/SessionMiddlewareTest.php b/tests/unit/Middleware/SessionMiddlewareTest.php index e00a7bdb394..d7a20211c0a 100644 --- a/tests/unit/Middleware/SessionMiddlewareTest.php +++ b/tests/unit/Middleware/SessionMiddlewareTest.php @@ -106,6 +106,15 @@ public function testWrongArrayBlocked(): void { $this->invokeMiddleware($share); } + public function testValidTokenContentHidden(): void { + $this->expectException(InvalidSessionException::class); + + $share = $this->createPasswordProtectedShare('42', canSeeContent: false); + $this->session->method('get')->with('public_link_authenticated')->willReturn('42'); + + $this->invokeMiddleware($share); + } + public function testLoggedInUserWithInvalidToken(): void { $this->expectException(InvalidSessionException::class); @@ -128,6 +137,7 @@ public function testLoggedInUserWithValidToken(): void { $share->method('getPermissions')->willReturn(Constants::PERMISSION_READ); $share->method('getShareOwner')->willReturn('user2'); $share->method('getAttributes')->willReturn(null); + $share->method('canSeeContent')->willReturn(true); $this->shareManager->method('getShareByToken')->willReturn($share); @@ -235,13 +245,14 @@ private function invokeAssertDocumentSession(ISessionAwareController $controller self::invokePrivate($this->middleware, 'assertDocumentSession', [$controller]); } - private function createPasswordProtectedShare(string $id): IShare { + private function createPasswordProtectedShare(string $id, bool $canSeeContent = true): IShare { $share = $this->createMock(IShare::class); $share->method('getId')->willReturn($id); $share->method('getPassword')->willReturn('password'); $share->method('getPermissions')->willReturn(Constants::PERMISSION_READ); $share->method('getShareOwner')->willReturn('owner'); $share->method('getAttributes')->willReturn(null); + $share->method('canSeeContent')->willReturn($canSeeContent); return $share; } diff --git a/tests/unit/Service/ApiServiceTest.php b/tests/unit/Service/ApiServiceTest.php index 3bfebec3a1e..483a4f143a4 100644 --- a/tests/unit/Service/ApiServiceTest.php +++ b/tests/unit/Service/ApiServiceTest.php @@ -9,6 +9,8 @@ use OCA\Text\Service\DocumentService; use OCA\Text\Service\EncodingService; use OCA\Text\Service\SessionService; +use OCP\AppFramework\Http; +use OCP\Files\NotPermittedException; use OCP\IL10N; use OCP\IRequest; use Psr\Log\LoggerInterface; @@ -71,6 +73,18 @@ public function testCreateNewSessionWithoutOwner() { self::assertFalse($actual->getData()['hasOwner']); } + public function testCreateWithShareContentHidden() { + $file = $this->mockFile(1234, 'admin'); + $this->documentService->method('getFileByShareToken')->willReturn($file); + $this->documentService->method('checkShareCanSeeContent') + ->with('token') + ->willThrowException(new NotPermittedException()); + $this->sessionService->expects($this->never())->method('initSession'); + + $actual = $this->apiService->create(null, null, null, 'token'); + self::assertEquals(Http::STATUS_FORBIDDEN, $actual->getStatus()); + } + public function testSaveWithNotPermittedException() { $session = new Session(); $session->setDocumentId(123); diff --git a/tests/unit/Service/AttachmentServiceTest.php b/tests/unit/Service/AttachmentServiceTest.php index 2d9d70aca66..c67415306ce 100755 --- a/tests/unit/Service/AttachmentServiceTest.php +++ b/tests/unit/Service/AttachmentServiceTest.php @@ -2,18 +2,24 @@ namespace OCA\Text\Tests; -use OCA\Text\AppInfo\Application; use OCA\Text\Service\AttachmentService; use OCP\Files\File; use OCP\Files\Folder; use OCP\Files\IFilenameValidator; use OCP\Files\IMimeTypeDetector; use OCP\Files\IRootFolder; +use OCP\Files\NotFoundException; +use OCP\Files\SimpleFS\ISimpleFile; +use OCP\Files\Storage\ISharedStorage; +use OCP\Files\Storage\IStorage; use OCP\FilesMetadata\IFilesMetadataManager; use OCP\IPreview; use OCP\ISession; use OCP\IURLGenerator; +use OCP\IUser; +use OCP\Share\IAttributes; use OCP\Share\IManager as ShareManager; +use OCP\Share\IShare; use PHPUnit\Framework\TestCase; class AttachmentServiceTest extends TestCase { @@ -31,9 +37,47 @@ class AttachmentServiceTest extends TestCase { 'a`a`.png', ]; - public function testDummy(): void { - $app = new Application(); - $this->assertEquals('text', $app::APP_NAME); + private function createService(?IRootFolder $rootFolder = null, ?ShareManager $shareManager = null, ?IPreview $previewManager = null): AttachmentService { + return new AttachmentService( + $rootFolder ?? $this->createMock(IRootFolder::class), + $shareManager ?? $this->createMock(ShareManager::class), + $previewManager ?? $this->createMock(IPreview::class), + $this->createMock(IMimeTypeDetector::class), + $this->createMock(IURLGenerator::class), + $this->createMock(IFilenameValidator::class), + $this->createMock(IFilesMetadataManager::class), + $this->createMock(ISession::class), + ); + } + + private function createFile(int $id, ?bool $download = null): File { + if ($download === null) { + $storage = $this->createMock(IStorage::class); + $storage->method('instanceOfStorage')->willReturn(false); + } else { + $attributes = $this->createMock(IAttributes::class); + $attributes->method('getAttribute') + ->with('permissions', 'download') + ->willReturn($download); + $share = $this->createMock(IShare::class); + $share->method('getAttributes')->willReturn($attributes); + $share->method('canSeeContent')->willReturn(true); + $storage = $this->createMock(ISharedStorage::class); + $storage->method('instanceOfStorage')->willReturn(true); + $storage->method('getShare')->willReturn($share); + } + $file = $this->createMock(File::class); + $file->method('getId')->willReturn($id); + $file->method('getStorage')->willReturn($storage); + return $file; + } + + private function createRootFolder(File $textFile): IRootFolder { + $userFolder = $this->createMock(Folder::class); + $userFolder->method('getFirstNodeById')->with($textFile->getId())->willReturn($textFile); + $rootFolder = $this->createMock(IRootFolder::class); + $rootFolder->method('getUserFolder')->with('user')->willReturn($userFolder); + return $rootFolder; } public function testGetAttachmentNamesFromContent(): void { @@ -277,16 +321,7 @@ public function testReplaceAttachmentFileIdNoReplace(string $sourceContent): voi } public function testCopyAttachmentsInFolderRewritesFolderAndFileIds(): void { - $service = new AttachmentService( - $this->createMock(IRootFolder::class), - $this->createMock(ShareManager::class), - $this->createMock(IPreview::class), - $this->createMock(IMimeTypeDetector::class), - $this->createMock(IURLGenerator::class), - $this->createMock(IFilenameValidator::class), - $this->createMock(IFilesMetadataManager::class), - $this->createMock(ISession::class), - ); + $service = $this->createService(); $sourceMd = $this->createMock(File::class); $sourceMd->method('getId')->willReturn(1); @@ -333,4 +368,89 @@ public function testCopyAttachmentsInFolderRewritesFolderAndFileIds(): void { $this->assertEquals("![a.png](.attachments.2/a.png)\n\n[board](https://localhost/f/20 (preview))\n", $content); } + + public function testGetMediaFileWithDownloadDisabled(): void { + $textFile = $this->createFile(1, false); + $textFile->expects($this->never())->method('getOwner'); + $service = $this->createService($this->createRootFolder($textFile)); + + $this->assertNull($service->getMediaFile(1, 'media.zip', 'user')); + } + + public function testGetMediaFileWithLinkShareDownloadDisabled(): void { + $textFile = $this->createFile(1); + $textFile->expects($this->never())->method('getOwner'); + $share = $this->createMock(IShare::class); + $share->method('getShareType')->willReturn(IShare::TYPE_LINK); + $share->method('getNodeType')->willReturn('file'); + $share->method('getNode')->willReturn($textFile); + $share->method('canDownload')->willReturn(false); + $shareManager = $this->createMock(ShareManager::class); + $shareManager->method('getShareByToken')->with('token')->willReturn($share); + $service = $this->createService(shareManager: $shareManager); + + $this->assertNull($service->getMediaFilePublic(1, 'media.zip', 'token')); + } + + public function testInsertAttachmentFileWithDownloadDisabled(): void { + $textFile = $this->createFile(1); + $textFile->method('isUpdateable')->willReturn(true); + $textFile->expects($this->never())->method('getOwner'); + $userFolder = $this->createMock(Folder::class); + $userFolder->method('getFirstNodeById')->with(1)->willReturn($textFile); + $userFolder->method('nodeExists')->with('/shared.png')->willReturn(true); + $userFolder->method('get')->with('/shared.png')->willReturn($this->createFile(2, false)); + $rootFolder = $this->createMock(IRootFolder::class); + $rootFolder->method('getUserFolder')->with('user')->willReturn($userFolder); + $service = $this->createService($rootFolder); + + $this->expectException(NotFoundException::class); + $service->insertAttachmentFile(1, '/shared.png', 'user'); + } + + public static function dataGetImageFilePreferRawImage(): array { + return [ + 'download allowed' => [true, true], + 'download disabled' => [false, false], + ]; + } + + /** + * @dataProvider dataGetImageFilePreferRawImage + */ + public function testGetImageFilePreferRawImage(bool $download, bool $expectRaw): void { + $imageFile = $this->createMock(File::class); + $imageFile->method('getMimeType')->willReturn('image/jpeg'); + $attachmentFolder = $this->createMock(Folder::class); + $attachmentFolder->method('get')->with('photo.jpg')->willReturn($imageFile); + $parentFolder = $this->createMock(Folder::class); + $parentFolder->method('nodeExists')->with('.attachments.1')->willReturn(true); + $parentFolder->method('get')->with('.attachments.1')->willReturn($attachmentFolder); + $ownerTextFile = $this->createMock(File::class); + $ownerTextFile->method('getParent')->willReturn($parentFolder); + $ownerFolder = $this->createMock(Folder::class); + $ownerFolder->method('getFirstNodeById')->with(1)->willReturn($ownerTextFile); + + $owner = $this->createMock(IUser::class); + $owner->method('getUID')->willReturn('owner'); + $textFile = $this->createFile(1, $download); + $textFile->method('getOwner')->willReturn($owner); + $userFolder = $this->createMock(Folder::class); + $userFolder->method('getFirstNodeById')->with(1)->willReturn($textFile); + + $rootFolder = $this->createMock(IRootFolder::class); + $rootFolder->method('getUserFolder')->willReturnMap([ + ['user', $userFolder], + ['owner', $ownerFolder], + ]); + + $preview = $this->createMock(ISimpleFile::class); + $previewManager = $this->createMock(IPreview::class); + $previewManager->method('isMimeSupported')->with('image/jpeg')->willReturn(true); + $previewManager->method('getPreview')->with($imageFile, 1024, 1024)->willReturn($preview); + $service = $this->createService($rootFolder, previewManager: $previewManager); + + $result = $service->getImageFile(1, 'photo.jpg', 'user', true); + $this->assertSame($expectRaw ? $imageFile : $preview, $result); + } } diff --git a/tests/unit/Service/DocumentServiceTest.php b/tests/unit/Service/DocumentServiceTest.php index 71c10fa3033..b3e3c8db6a3 100644 --- a/tests/unit/Service/DocumentServiceTest.php +++ b/tests/unit/Service/DocumentServiceTest.php @@ -338,4 +338,22 @@ public function testManualSaveChecksForConflictsWithinAutosaveDelay(): void { $this->expectException(DocumentSaveConflictException::class); $this->documentService->autosave($document, $file, 3, 'new content', 'doc state', false, true); } + + public function testCheckShareCanSeeContent(): void { + $share = $this->createMock(IShare::class); + $share->method('canSeeContent')->willReturn(true); + $this->shareManager->method('getShareByToken')->with('token')->willReturn($share); + + $this->documentService->checkShareCanSeeContent('token'); + $this->addToAssertionCount(1); + } + + public function testCheckShareCanSeeContentHidden(): void { + $share = $this->createMock(IShare::class); + $share->method('canSeeContent')->willReturn(false); + $this->shareManager->method('getShareByToken')->with('token')->willReturn($share); + + $this->expectException(NotPermittedException::class); + $this->documentService->checkShareCanSeeContent('token'); + } }