Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions lib/Controller/AttachmentController.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use OCA\Text\Middleware\Attribute\RequireDocumentSession;
use OCA\Text\Middleware\Attribute\RequireDocumentSessionOrUserOrShareToken;
use OCA\Text\Service\AttachmentService;
use OCA\Text\Service\FileService;
use OCP\AppFramework\ApiController;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Http;
Expand Down Expand Up @@ -77,6 +78,7 @@ public function __construct(
private ShareManager $shareManager,
private DocumentMapper $documentMapper,
private ContextManager $contextManager,
private FileService $fileService,
) {
parent::__construct($appName, $request);
}
Expand Down Expand Up @@ -212,8 +214,8 @@ public function getImageFile(
int $preferRawImage = 0,
int $fileId = 0,
): DataResponse|DataDownloadResponse {
$auth = $this->getAuth($shareToken, false);
try {
$auth = $this->getAuth($shareToken, false);
$context = $this->getContext($auth, $fileId);
$imageFile = $this->attachmentService->getImageFile($context, $imageFileName, $preferRawImage === 1, $auth);
if ($imageFile !== null) {
Expand Down Expand Up @@ -249,8 +251,8 @@ public function getMediaFile(
string $shareToken = '',
int $fileId = 0,
): DataResponse|DataDownloadResponse {
$auth = $this->getAuth($shareToken, false);
try {
$auth = $this->getAuth($shareToken, false);
$context = $this->getContext($auth, $fileId);
$mediaFile = $this->attachmentService->getMediaFile($context, $mediaFileName, $auth);
return $mediaFile !== null
Expand All @@ -275,8 +277,8 @@ public function getMediaFile(
#[NoCSRFRequired]
#[RequireDocumentSessionOrUserOrShareToken]
public function getMediaFilePreview(string $mediaFileName, string $shareToken = '', int $fileId = 0) {
$auth = $this->getAuth($shareToken, false);
try {
$auth = $this->getAuth($shareToken, false);
$context = $this->getContext($auth, $fileId);
$preview = $this->attachmentService->getMediaFilePreview($context, $mediaFileName);
if ($preview === null) {
Expand Down Expand Up @@ -320,6 +322,9 @@ private function getAuth(string $shareToken, bool $updatePermissionRequired = tr
if ($shareToken !== '') {
try {
$share = $this->shareManager->getShareByToken($shareToken);
if ($share->getPassword() !== null && !$this->fileService->isShareAuthenticated($share)) {
throw new InvalidSessionException();
}
if ($updatePermissionRequired && !$this->hasUpdatePermissions($share)) {
throw new NotPermittedException('No write permissions');
}
Expand Down
13 changes: 4 additions & 9 deletions lib/Controller/WorkspaceController.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use Exception;
use OCA\Text\AppInfo\Application;
use OCA\Text\DirectEditing\TextDocumentCreator;
use OCA\Text\Service\FileService;
use OCA\Text\Service\WorkspaceService;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\Attribute\NoAdminRequired;
Expand All @@ -27,7 +28,6 @@
use OCP\Files\NotFoundException;
use OCP\Files\NotPermittedException;
use OCP\IRequest;
use OCP\ISession;
use OCP\IURLGenerator;
use OCP\Share\Exceptions\ShareNotFound;
use OCP\Share\IManager;
Expand All @@ -44,7 +44,7 @@ public function __construct(
private readonly WorkspaceService $workspaceService,
private readonly IEventDispatcher $eventDispatcher,
private readonly LoggerInterface $logger,
private readonly ISession $session,
private readonly FileService $fileService,
private readonly ?string $userId,
) {
parent::__construct($appName, $request);
Expand Down Expand Up @@ -114,13 +114,8 @@ public function publicFolder(string $shareToken, string $path = '/'): DataRespon
throw new ShareNotFound();
}
/** @psalm-suppress RedundantConditionGivenDocblockType */
if ($share->getPassword() !== null) {
$shareIds = $this->session->get('public_link_authenticated');
$shareIds = is_array($shareIds) ? $shareIds : [$shareIds];

if (!in_array($share->getId(), $shareIds, true)) {
throw new ShareNotFound();
}
if ($share->getPassword() !== null && !$this->fileService->isShareAuthenticated($share)) {
throw new ShareNotFound();
}

$shareNode = $share->getNode();
Expand Down
20 changes: 0 additions & 20 deletions lib/Service/AttachmentService.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@

namespace OCA\Text\Service;

use OCA\DAV\Connector\Sabre\PublicAuth;
use OCA\Text\Context\IContext;
use OCA\Text\Controller\AttachmentController;
use OCA\Text\Db\Session;
Expand All @@ -24,7 +23,6 @@
use OCP\Files\SimpleFS\ISimpleFile;
use OCP\FilesMetadata\IFilesMetadataManager;
use OCP\IPreview;
use OCP\ISession;
use OCP\IURLGenerator;
use OCP\IUser;
use OCP\Lock\LockedException;
Expand All @@ -43,7 +41,6 @@ public function __construct(
private IURLGenerator $urlGenerator,
private IFilenameValidator $filenameValidator,
private IFilesMetadataManager $filesMetadataManager,
private ISession $session,
private FileService $fileService,
) {
}
Expand Down Expand Up @@ -250,23 +247,6 @@ public function getAttachmentList(IContext $context, IShare|IUser $auth, ?Sessio
* @throws UserNotFoundException
*/
public function uploadAttachment(IContext $context, string $newFileName, $newFileResource, IShare|IUser $auth): array {
if ($auth instanceof IShare && $auth->getPassword() !== null) {
$key = PublicAuth::DAV_AUTHENTICATED;

if (!$this->session->exists($key)) {
throw new NotPermittedException('Share not authenticated');
}

$allowedShareIds = $this->session->get($key);
if (!is_array($allowedShareIds)) {
throw new NotPermittedException('Share not authenticated');
}

if (!in_array($auth->getId(), $allowedShareIds, true)) {
throw new NotPermittedException('Share not authenticated');
}
}

$textFile = $this->getTextFile($context);
if (!$textFile->isUpdateable()) {
throw new NotPermittedException('No write permissions');
Expand Down
28 changes: 19 additions & 9 deletions lib/Service/FileService.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

namespace OCA\Text\Service;

use OCA\DAV\Connector\Sabre\PublicAuth;
use OCA\Text\Exception\InvalidSessionException;
use OCP\Constants;
use OCP\Files\File;
Expand Down Expand Up @@ -173,6 +174,10 @@ public function checkFileAccessFromShare(int $fileId, string $shareToken): void
throw new InvalidSessionException();
}

if ($share->getPassword() !== null && !$this->isShareAuthenticated($share)) {
throw new InvalidSessionException();
}

$node = $this->rootFolder->getUserFolder($share->getShareOwner())->getFirstNodeById($fileId);
if ($node === null) {
throw new InvalidSessionException();
Expand All @@ -189,15 +194,6 @@ public function checkFileAccessFromShare(int $fileId, string $shareToken): void
}
}

if ($share->getPassword() !== null) {
$shareIds = $this->session->get('public_link_authenticated');
$shareIds = is_array($shareIds) ? $shareIds : [$shareIds];

if (!in_array($share->getId(), $shareIds, true)) {
throw new InvalidSessionException();
}
}

if (($share->getPermissions() & Constants::PERMISSION_READ) !== Constants::PERMISSION_READ) {
throw new InvalidSessionException();
}
Expand All @@ -207,6 +203,20 @@ public function checkFileAccessFromShare(int $fileId, string $shareToken): void
}
}

/**
* Whether the password of the share was verified in the current session
*/
public function isShareAuthenticated(IShare $share): bool {
// Older server releases lack the public helper
if (!is_callable(PublicAuth::class . '::isShareInSession')) {
$shareIds = $this->session->get(PublicAuth::DAV_AUTHENTICATED);
$shareIds = is_array($shareIds) ? $shareIds : [$shareIds];
return in_array($share->getId(), $shareIds, true);
}

return PublicAuth::isShareInSession($this->session, $share);
}

public function checkFileAccessForUser(int $fileId, string $userId): void {
if ($this->rootFolder->getUserFolder($userId)->getFirstNodeById($fileId) === null) {
throw new InvalidSessionException();
Expand Down
3 changes: 3 additions & 0 deletions tests/stub.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,5 +84,8 @@ abstract public function getSourceFile(): \OCP\Files\File;
namespace OCA\DAV\Connector\Sabre {
class PublicAuth {
public const DAV_AUTHENTICATED = '';

public static function isShareInSession(\OCP\ISession $session, \OCP\Share\IShare $share): bool {
}
}
}
2 changes: 0 additions & 2 deletions tests/unit/CleanupTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
use OCP\Files\NotPermittedException;
use OCP\FilesMetadata\IFilesMetadataManager;
use OCP\IPreview;
use OCP\ISession;
use OCP\IURLGenerator;
use OCP\Share\IManager;
use Psr\Log\LoggerInterface;
Expand Down Expand Up @@ -54,7 +53,6 @@ public function setUp(): void {
$this->createMock(IURLGenerator::class),
$this->createMock(IFilenameValidator::class),
$this->createMock(IFilesMetadataManager::class),
$this->createMock(ISession::class),
$this->createMock(FileService::class),
);
$this->sessionService = $this->createMock(SessionService::class);
Expand Down
127 changes: 127 additions & 0 deletions tests/unit/Controller/AttachmentControllerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\Text\Tests\Controller;

use OCA\Text\Context\ContextManager;
use OCA\Text\Controller\AttachmentController;
use OCA\Text\Db\DocumentMapper;
use OCA\Text\Exception\InvalidSessionException;
use OCA\Text\Service\AttachmentService;
use OCA\Text\Service\FileService;
use OCP\AppFramework\Http;
use OCP\Constants;
use OCP\Files\File;
use OCP\Files\IFilenameValidator;
use OCP\Files\IMimeTypeDetector;
use OCP\Files\IRootFolder;
use OCP\Files\NotFoundException;
use OCP\FilesMetadata\IFilesMetadataManager;
use OCP\IL10N;
use OCP\IPreview;
use OCP\IRequest;
use OCP\IURLGenerator;
use OCP\Share\IManager as ShareManager;
use OCP\Share\IShare;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;

class AttachmentControllerTest extends TestCase {
private IRequest&MockObject $request;
private ShareManager&MockObject $shareManager;
private ContextManager&MockObject $contextManager;
private FileService&MockObject $fileService;
private AttachmentController $controller;

protected function setUp(): void {
$this->request = $this->createMock(IRequest::class);
$this->shareManager = $this->createMock(ShareManager::class);
$this->contextManager = $this->createMock(ContextManager::class);
$this->fileService = $this->createMock(FileService::class);
$this->controller = new AttachmentController(
'text',
$this->request,
$this->createMock(IL10N::class),
$this->createMock(LoggerInterface::class),
$this->createMock(IMimeTypeDetector::class),
new AttachmentService(
$this->createMock(IRootFolder::class),
$this->shareManager,
$this->createMock(IPreview::class),
$this->createMock(IMimeTypeDetector::class),
$this->createMock(IURLGenerator::class),
$this->createMock(IFilenameValidator::class),
$this->createMock(IFilesMetadataManager::class),
$this->fileService,
),
$this->shareManager,
$this->createMock(DocumentMapper::class),
$this->contextManager,
$this->fileService,
);
}

public function testAttachmentListForAuthenticatedPasswordShare(): void {
$share = $this->createPasswordShare();
$this->fileService->method('isShareAuthenticated')->with($share)->willReturn(true);
$this->contextManager->expects($this->once())->method('getContext')->willThrowException(new NotFoundException());

$this->expectException(NotFoundException::class);
$this->controller->getAttachmentList(42, 'token');
}

public function testAttachmentListForUnauthenticatedPasswordShare(): void {
$share = $this->createPasswordShare();
$this->fileService->method('isShareAuthenticated')->with($share)->willReturn(false);
$this->contextManager->expects($this->never())->method('getContext');

$this->expectException(InvalidSessionException::class);
$this->controller->getAttachmentList(42, 'token');
}

public function testUploadAttachmentForUnauthenticatedPasswordShare(): void {
$share = $this->createPasswordShare();
$this->fileService->method('isShareAuthenticated')->with($share)->willReturn(false);
// The controller catches all exceptions, so a never() expectation would be swallowed
$contextRequested = false;
$this->contextManager->method('getContext')->willReturnCallback(function () use (&$contextRequested): never {
$contextRequested = true;
throw new NotFoundException();
});
$tmpFile = tempnam(sys_get_temp_dir(), 'text');
$this->request->method('getUploadedFile')->with('file')->willReturn([
'tmp_name' => $tmpFile,
'name' => 'image.png',
'type' => 'image/png',
'error' => UPLOAD_ERR_OK,
]);

try {
$response = $this->controller->uploadAttachment('token');
} finally {
unlink($tmpFile);
}

$this->assertSame(Http::STATUS_BAD_REQUEST, $response->getStatus());
$this->assertFalse($contextRequested);
}

private function createPasswordShare(): IShare {
$share = $this->createMock(IShare::class);
$share->method('getPassword')->willReturn('hash');
$share->method('getShareType')->willReturn(IShare::TYPE_LINK);
$share->method('getPermissions')->willReturn(Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE);
$node = $this->createMock(File::class);
$node->method('getPermissions')->willReturn(Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE);
$share->method('getNode')->willReturn($node);
$this->shareManager->method('getShareByToken')->with('token')->willReturn($share);
return $share;
}
}
Loading
Loading