From 6003dad799f3fb871b013240846875cb17c7f6be Mon Sep 17 00:00:00 2001 From: Julius Knorr Date: Wed, 18 Nov 2026 22:05:45 +0100 Subject: [PATCH] fix(share): check the share password hash for authenticated public shares Use PublicAuth::isShareInSession() from the server when available, so access follows the current share password. Older server releases without the helper keep using the list of authenticated share ids. Signed-off-by: Julius Knorr Assisted-by: ClaudeCode:claude-opus-5-5 --- lib/Controller/AttachmentController.php | 11 +- lib/Controller/WorkspaceController.php | 13 +- lib/Service/AttachmentService.php | 20 --- lib/Service/FileService.php | 28 ++-- tests/stub.php | 3 + tests/unit/CleanupTest.php | 2 - .../Controller/AttachmentControllerTest.php | 127 ++++++++++++++++++ .../Controller/WorkspaceControllerTest.php | 89 ++++++++++++ tests/unit/Service/AttachmentServiceTest.php | 2 - tests/unit/Service/FileServiceTest.php | 56 ++++++++ 10 files changed, 306 insertions(+), 45 deletions(-) create mode 100644 tests/unit/Controller/AttachmentControllerTest.php create mode 100644 tests/unit/Controller/WorkspaceControllerTest.php diff --git a/lib/Controller/AttachmentController.php b/lib/Controller/AttachmentController.php index 72ed82d5e26..c4556d645f7 100644 --- a/lib/Controller/AttachmentController.php +++ b/lib/Controller/AttachmentController.php @@ -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; @@ -77,6 +78,7 @@ public function __construct( private ShareManager $shareManager, private DocumentMapper $documentMapper, private ContextManager $contextManager, + private FileService $fileService, ) { parent::__construct($appName, $request); } @@ -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) { @@ -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 @@ -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) { @@ -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'); } diff --git a/lib/Controller/WorkspaceController.php b/lib/Controller/WorkspaceController.php index 7e590ab8cef..0d487100d19 100644 --- a/lib/Controller/WorkspaceController.php +++ b/lib/Controller/WorkspaceController.php @@ -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; @@ -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; @@ -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); @@ -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(); diff --git a/lib/Service/AttachmentService.php b/lib/Service/AttachmentService.php index 38c20707b26..80961df47f2 100755 --- a/lib/Service/AttachmentService.php +++ b/lib/Service/AttachmentService.php @@ -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; @@ -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; @@ -43,7 +41,6 @@ public function __construct( private IURLGenerator $urlGenerator, private IFilenameValidator $filenameValidator, private IFilesMetadataManager $filesMetadataManager, - private ISession $session, private FileService $fileService, ) { } @@ -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'); diff --git a/lib/Service/FileService.php b/lib/Service/FileService.php index c578e6e2721..b41033b9ec8 100644 --- a/lib/Service/FileService.php +++ b/lib/Service/FileService.php @@ -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; @@ -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(); @@ -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(); } @@ -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(); diff --git a/tests/stub.php b/tests/stub.php index c694ab91430..03cfbfb78e8 100644 --- a/tests/stub.php +++ b/tests/stub.php @@ -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 { + } } } diff --git a/tests/unit/CleanupTest.php b/tests/unit/CleanupTest.php index 59102b839f3..9b1849adb8f 100644 --- a/tests/unit/CleanupTest.php +++ b/tests/unit/CleanupTest.php @@ -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; @@ -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); diff --git a/tests/unit/Controller/AttachmentControllerTest.php b/tests/unit/Controller/AttachmentControllerTest.php new file mode 100644 index 00000000000..4d31bf1b8af --- /dev/null +++ b/tests/unit/Controller/AttachmentControllerTest.php @@ -0,0 +1,127 @@ +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; + } +} diff --git a/tests/unit/Controller/WorkspaceControllerTest.php b/tests/unit/Controller/WorkspaceControllerTest.php new file mode 100644 index 00000000000..7d6d8244767 --- /dev/null +++ b/tests/unit/Controller/WorkspaceControllerTest.php @@ -0,0 +1,89 @@ +shareManager = $this->createMock(ShareManager::class); + $this->workspaceService = $this->createMock(WorkspaceService::class); + $this->fileService = $this->createMock(FileService::class); + $this->controller = new WorkspaceController( + 'text', + $this->createMock(IRequest::class), + $this->createMock(IRootFolder::class), + $this->shareManager, + $this->createMock(IDirectEditingManager::class), + $this->createMock(IURLGenerator::class), + $this->workspaceService, + $this->createMock(IEventDispatcher::class), + $this->createMock(LoggerInterface::class), + $this->fileService, + null, + ); + } + + public function testPublicFolderForAuthenticatedPasswordShare(): void { + $share = $this->createPasswordShare(); + $this->fileService->method('isShareAuthenticated')->with($share)->willReturn(true); + $file = $this->createMock(File::class); + $file->method('getId')->willReturn(42); + $file->method('getName')->willReturn('Readme.md'); + $this->workspaceService->method('getFile')->willReturn($file); + + $response = $this->controller->publicFolder('token'); + + $this->assertSame(Http::STATUS_OK, $response->getStatus()); + $this->assertSame(42, $response->getData()['file']['id']); + } + + public function testPublicFolderForUnauthenticatedPasswordShare(): void { + $share = $this->createPasswordShare(); + $this->fileService->method('isShareAuthenticated')->with($share)->willReturn(false); + $this->workspaceService->expects($this->never())->method('getFile'); + + $response = $this->controller->publicFolder('token'); + + $this->assertSame(Http::STATUS_NOT_FOUND, $response->getStatus()); + } + + private function createPasswordShare(): IShare { + $share = $this->createMock(IShare::class); + $share->method('getPassword')->willReturn('hash'); + $share->method('getPermissions')->willReturn(Constants::PERMISSION_READ); + $folder = $this->createMock(Folder::class); + $folder->method('get')->willReturn($folder); + $share->method('getNode')->willReturn($folder); + $this->shareManager->method('getShareByToken')->with('token')->willReturn($share); + return $share; + } +} diff --git a/tests/unit/Service/AttachmentServiceTest.php b/tests/unit/Service/AttachmentServiceTest.php index 5fbc307937e..5666496aab3 100755 --- a/tests/unit/Service/AttachmentServiceTest.php +++ b/tests/unit/Service/AttachmentServiceTest.php @@ -15,7 +15,6 @@ use OCP\Files\SimpleFS\ISimpleFile; use OCP\FilesMetadata\IFilesMetadataManager; use OCP\IPreview; -use OCP\ISession; use OCP\IURLGenerator; use OCP\IUser; use OCP\Share\IManager as ShareManager; @@ -46,7 +45,6 @@ private function createService(?IRootFolder $rootFolder = null, ?FileService $fi $this->createMock(IURLGenerator::class), $this->createMock(IFilenameValidator::class), $this->createMock(IFilesMetadataManager::class), - $this->createMock(ISession::class), $fileService ?? $this->createMock(FileService::class), ); } diff --git a/tests/unit/Service/FileServiceTest.php b/tests/unit/Service/FileServiceTest.php index ca8e23abbef..c339bfbe6cc 100644 --- a/tests/unit/Service/FileServiceTest.php +++ b/tests/unit/Service/FileServiceTest.php @@ -2,10 +2,12 @@ namespace OCA\Text\Tests; +use OCA\DAV\Connector\Sabre\PublicAuth; use OCA\Text\Exception\InvalidSessionException; use OCA\Text\Service\EncodingService; use OCA\Text\Service\FileService; use OCA\Text\Service\LockService; +use OCP\AppFramework\PublicShareController; use OCP\Constants; use OCP\Files\File; use OCP\Files\IRootFolder; @@ -92,6 +94,7 @@ public function testValidTokenWithoutPassword(): void { } public function testValidTokenMissingPassword(): void { + $this->skipIfServerChecksPasswordHash(); $this->expectException(InvalidSessionException::class); $share = $this->createShare('protected-share', 'password'); @@ -101,6 +104,7 @@ public function testValidTokenMissingPassword(): void { } public function testValidTokenWithPasswordArray(): void { + $this->skipIfServerChecksPasswordHash(); $share = $this->createShare('42', 'password'); $this->session->method('get')->with('public_link_authenticated')->willReturn(['1', '42']); @@ -108,6 +112,7 @@ public function testValidTokenWithPasswordArray(): void { } public function testValidTokenWithSinglePassword(): void { + $this->skipIfServerChecksPasswordHash(); $share = $this->createShare('42', 'password'); $this->session->method('get')->with('public_link_authenticated')->willReturn('42'); @@ -115,6 +120,7 @@ public function testValidTokenWithSinglePassword(): void { } public function testValidTokenWithOtherPassword(): void { + $this->skipIfServerChecksPasswordHash(); $this->expectException(InvalidSessionException::class); $share = $this->createShare('42', 'password'); @@ -124,6 +130,7 @@ public function testValidTokenWithOtherPassword(): void { } public function testValidTokenWithOtherPasswords(): void { + $this->skipIfServerChecksPasswordHash(); $this->expectException(InvalidSessionException::class); $share = $this->createShare('42', 'password'); @@ -140,6 +147,54 @@ public function testValidTokenContentHidden(): void { $this->invokeCheckFileAccessFromShare(123, $share); } + public function testPasswordShareWithCurrentPasswordHashInSession(): void { + $this->skipIfServerOnlyStoresShareIds(); + + $share = $this->createShare('42', 'current-hash'); + $this->mockAuthenticatedSession(['42'], ['token' => 'current-hash']); + + $this->invokeCheckFileAccessFromShare(123, $share); + } + + public function testPasswordShareWithPreviousPasswordHashInSession(): void { + $this->skipIfServerOnlyStoresShareIds(); + $this->expectException(InvalidSessionException::class); + + $share = $this->createShare('42', 'current-hash'); + $this->mockAuthenticatedSession(['42'], ['token' => 'previous-hash']); + + $this->invokeCheckFileAccessFromShare(123, $share); + } + + public function testPasswordShareWithoutAuthenticatedSession(): void { + $this->skipIfServerOnlyStoresShareIds(); + $this->expectException(InvalidSessionException::class); + + $share = $this->createShare('42', 'current-hash'); + $this->mockAuthenticatedSession(null, null); + + $this->invokeCheckFileAccessFromShare(123, $share); + } + + private function mockAuthenticatedSession(?array $shareIds, ?array $tokenHashes): void { + $this->session->method('get')->willReturnMap([ + [PublicAuth::DAV_AUTHENTICATED, $shareIds], + [PublicShareController::DAV_AUTHENTICATED_FRONTEND, $tokenHashes === null ? null : json_encode($tokenHashes)], + ]); + } + + private function skipIfServerChecksPasswordHash(): void { + if (is_callable(PublicAuth::class . '::isShareInSession')) { + $this->markTestSkipped('Server checks the share password hash'); + } + } + + private function skipIfServerOnlyStoresShareIds(): void { + if (!is_callable(PublicAuth::class . '::isShareInSession')) { + $this->markTestSkipped('Server only stores authenticated share ids'); + } + } + private function invokeCheckFileAccessFromShare(int $fileId, IShare $share): void { $this->shareManager->expects($this->once())->method('getShareByToken')->willReturn($share); @@ -153,6 +208,7 @@ private function invokeCheckFileAccessFromShare(int $fileId, IShare $share): voi private function createShare(string $id, ?string $password = null, bool $canSeeContent = true): IShare { $share = $this->createMock(IShare::class); $share->method('getId')->willReturn($id); + $share->method('getToken')->willReturn('token'); $share->method('getPassword')->willReturn($password); $share->method('getPermissions')->willReturn(Constants::PERMISSION_READ); $share->method('getShareOwner')->willReturn('owner');