diff --git a/lib/Listener/MailNotifyListener.php b/lib/Listener/MailNotifyListener.php index 4c17b5f1b2..9f2d690b4a 100644 --- a/lib/Listener/MailNotifyListener.php +++ b/lib/Listener/MailNotifyListener.php @@ -22,13 +22,11 @@ use OCP\EventDispatcher\IEventListener; use OCP\IUser; use OCP\IUserManager; -use OCP\IUserSession; use Psr\Log\LoggerInterface; /** @template-implements IEventListener */ class MailNotifyListener implements IEventListener { public function __construct( - protected IUserSession $userSession, protected IUserManager $userManager, protected IdentifyService $identifyService, protected MailService $mail, @@ -65,34 +63,11 @@ protected function sendSignMailNotification( IIdentifyMethod $identifyMethod, ): void { try { - if ($identifyMethod->getEntity()->isDeletedAccount()) { - return; - } - $email = ''; - if ($identifyMethod->getName() === 'account') { - $userId = $identifyMethod->getEntity()->getIdentifierValue(); - $email = $this->userManager - ->get($userId) - ->getEMailAddress(); - } elseif ($identifyMethod->getName() === 'email') { - $email = $identifyMethod->getEntity()->getIdentifierValue(); - } - if (empty($email)) { + $email = $this->resolveEligibleRecipientEmail($identifyMethod, SendSignNotificationEvent::FILE_TO_SIGN); + if ($email === null) { return; } - $users = $this->userManager->getByEmail($email); - if (count($users) === 1) { - $userId = $users[0]->getUID(); - if ($this->notificationPreferenceResolver->isEmailNotificationDisabled( - $userId, - SendSignNotificationEvent::FILE_TO_SIGN, - true, - )) { - return; - } - } - $isFirstNotification = $this->signRequestMapper->incrementNotificationCounter($signRequest, 'mail'); if ($isFirstNotification) { $this->mail->notifyUnsignedUser($signRequest, $email, $signRequest->getDescription()); @@ -146,33 +121,11 @@ protected function sendCanceledMailNotification( FileEntity $libreSignFile, ): void { try { - if ($identifyMethod->getEntity()->isDeletedAccount()) { - return; - } - - $email = ''; - if ($identifyMethod->getName() === 'account') { - $userId = $identifyMethod->getEntity()->getIdentifierValue(); - $user = $this->userManager->get($userId); - if ($user) { - $email = $user->getEMailAddress(); - } - } elseif ($identifyMethod->getName() === 'email') { - $email = $identifyMethod->getEntity()->getIdentifierValue(); - } - - if (empty($email)) { + $email = $this->resolveEligibleRecipientEmail($identifyMethod, SignRequestCanceledEvent::SIGN_REQUEST_CANCELED); + if ($email === null) { return; } - $users = $this->userManager->getByEmail($email); - if (count($users) === 1) { - $userId = $users[0]->getUID(); - if ($this->notificationPreferenceResolver->isEmailNotificationDisabled($userId, SignRequestCanceledEvent::SIGN_REQUEST_CANCELED, true)) { - return; - } - } - $this->mail->notifyCanceledRequest($signRequest, $email, $libreSignFile); } catch (\InvalidArgumentException $e) { @@ -180,4 +133,62 @@ protected function sendCanceledMailNotification( return; } } + + private function resolveEligibleRecipientEmail(IIdentifyMethod $identifyMethod, string $notificationType): ?string { + $entity = $identifyMethod->getEntity(); + if ($entity->isDeletedAccount()) { + return null; + } + + return match ($identifyMethod->getName()) { + 'email' => $this->resolveEmailIdentifiedRecipient($entity->getIdentifierValue(), $notificationType), + 'account' => $this->resolveAccountIdentifiedRecipient($entity->getIdentifierValue(), $notificationType), + default => null, + }; + } + + private function resolveEmailIdentifiedRecipient(string $email, string $notificationType): ?string { + if ($email === '') { + return null; + } + + $disabled = match ($notificationType) { + SendSignNotificationEvent::FILE_TO_SIGN + => $this->notificationPreferenceResolver->isEmailNotificationGloballyDisabled($notificationType), + SignRequestCanceledEvent::SIGN_REQUEST_CANCELED + => $this->isCancellationDisabledForUniqueLinkedAccount($email), + default => true, + }; + + return $disabled ? null : $email; + } + + private function resolveAccountIdentifiedRecipient(string $uid, string $notificationType): ?string { + $user = $this->userManager->get($uid); + if (!$user instanceof IUser) { + return null; + } + $email = $user->getEMailAddress(); + if (empty($email) || $this->notificationPreferenceResolver->isEmailNotificationDisabled( + $user->getUID(), + $notificationType, + true, + )) { + return null; + } + return $email; + } + + private function isCancellationDisabledForUniqueLinkedAccount(string $email): bool { + $users = $this->userManager->getByEmail($email); + if (count($users) !== 1) { + return false; + } + + return $this->notificationPreferenceResolver->isEmailNotificationDisabled( + $users[0]->getUID(), + SignRequestCanceledEvent::SIGN_REQUEST_CANCELED, + true, + ); + } } diff --git a/lib/Service/NotificationPreferenceResolver.php b/lib/Service/NotificationPreferenceResolver.php index a4700025b4..e6e7328d90 100644 --- a/lib/Service/NotificationPreferenceResolver.php +++ b/lib/Service/NotificationPreferenceResolver.php @@ -27,6 +27,25 @@ public function isEmailNotificationDisabled( return $this->isNotificationDisabled($userId, 'email', $type, $requireKnownActivitySetting); } + /** + * Apply the administrator's mail policy without consulting a linked user's opt-out. + */ + public function isEmailNotificationGloballyDisabled( + string $type, + bool $requireKnownActivitySetting = true, + ): bool { + if ($this->activitySettingsStore->isAvailable()) { + if ($requireKnownActivitySetting && !$this->activitySettingsStore->hasSetting($type)) { + return false; + } + return !$this->isActivitySettingEnabled($this->activitySettingsStore->getAdminSetting('email', $type)); + } + + return !$this->isActivitySettingEnabled( + $this->appConfig->getValueString('activity', sprintf('notify_email_%s', $type), '1'), + ); + } + public function isInAppNotificationDisabled( string $userId, string $type, diff --git a/tests/integration/features/identify-account/search.feature b/tests/integration/features/identify-account/search.feature index 82a80f068b..3d36a20fb9 100644 --- a/tests/integration/features/identify-account/search.feature +++ b/tests/integration/features/identify-account/search.feature @@ -173,3 +173,4 @@ Feature: search | (jq).ocs.data[0].identify | notification-global-off | | (jq).ocs.data[0].method | account | | (jq).ocs.data[0].acceptsEmailNotifications | false | + And run the command "config:app:set activity notify_email_libresign_file_to_sign --value=1" with result code 0 diff --git a/tests/integration/features/page/validate.feature b/tests/integration/features/page/validate.feature index 8dab524ea9..a0f0536a58 100644 --- a/tests/integration/features/page/validate.feature +++ b/tests/integration/features/page/validate.feature @@ -74,6 +74,7 @@ Feature: page/validate Scenario: Unauthenticated email signer can fetch PDF and gets controlled error after source deletion Given as user "admin" + And run the command "config:app:set activity notify_email_libresign_file_to_sign --value=1" with result code 0 And sending "post" to ocs "/apps/libresign/api/v1/policies/system/identify_methods" | value | (string){"can_create_account":false,"factors":[{"name":"email","enabled":true,"requirement":"required","signatureMethods":{"clickToSign":{"enabled":true}}}]} | And my inbox is empty diff --git a/tests/php/Unit/Listener/MailNotifyListenerTest.php b/tests/php/Unit/Listener/MailNotifyListenerTest.php index bdb002722c..c362938edd 100644 --- a/tests/php/Unit/Listener/MailNotifyListenerTest.php +++ b/tests/php/Unit/Listener/MailNotifyListenerTest.php @@ -12,7 +12,9 @@ use OCA\Libresign\Db\IdentifyMethod as IdentifyMethodEntity; use OCA\Libresign\Db\SignRequest; use OCA\Libresign\Db\SignRequestMapper; +use OCA\Libresign\Events\SendSignNotificationEvent; use OCA\Libresign\Events\SignedEvent; +use OCA\Libresign\Events\SignRequestCanceledEvent; use OCA\Libresign\Listener\MailNotifyListener; use OCA\Libresign\Service\IdentifyMethod\IdentifyService; use OCA\Libresign\Service\IdentifyMethod\IIdentifyMethod; @@ -21,7 +23,6 @@ use OCP\Files\File; use OCP\IUser; use OCP\IUserManager; -use OCP\IUserSession; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -30,84 +31,266 @@ class MailNotifyListenerTest extends TestCase { private MailService&MockObject $mailService; private IUserManager&MockObject $userManager; - private NotificationPreferenceResolver&MockObject $notificationPreferenceResolver; + private NotificationPreferenceResolver&MockObject $preferences; + private SignRequestMapper&MockObject $signRequestMapper; private MailNotifyListener $listener; + private bool $firstNotification = true; - public function setUp(): void { + protected function setUp(): void { $this->mailService = $this->createMock(MailService::class); $this->userManager = $this->createMock(IUserManager::class); - $this->notificationPreferenceResolver = $this->createMock(NotificationPreferenceResolver::class); - $userSession = $this->createMock(IUserSession::class); - $identifyService = $this->createMock(IdentifyService::class); - $signRequestMapper = $this->createMock(SignRequestMapper::class); - $logger = $this->createMock(LoggerInterface::class); + $this->preferences = $this->createMock(NotificationPreferenceResolver::class); + $this->signRequestMapper = $this->createMock(SignRequestMapper::class); + $this->signRequestMapper->method('incrementNotificationCounter') + ->willReturnCallback(fn (): bool => $this->firstNotification); $this->listener = new MailNotifyListener( - $userSession, $this->userManager, - $identifyService, + $this->createMock(IdentifyService::class), $this->mailService, - $signRequestMapper, - $logger, - $this->notificationPreferenceResolver, + $this->signRequestMapper, + $this->createMock(LoggerInterface::class), + $this->preferences, ); } - public static function provideSignedMailPreferenceScenarios(): array { + public function testEmailInvitationIgnoresLinkedAccountOptOut(): void { + $this->userManager->expects($this->never())->method('getByEmail'); + $this->userManager->expects($this->never())->method('get'); + $this->preferences->expects($this->never())->method('isEmailNotificationDisabled'); + $this->preferences->expects($this->once()) + ->method('isEmailNotificationGloballyDisabled') + ->with(SendSignNotificationEvent::FILE_TO_SIGN) + ->willReturn(false); + $this->mailService->expects($this->once()) + ->method('notifyUnsignedUser') + ->with($this->isInstanceOf(SignRequest::class), 'bob@example.org', 'Review document'); + + $this->listener->handle($this->invitation('email', 'bob@example.org')); + } + + public function testEmailInvitationHonorsAdminDisabledChannel(): void { + $this->preferences->expects($this->once()) + ->method('isEmailNotificationGloballyDisabled') + ->with(SendSignNotificationEvent::FILE_TO_SIGN) + ->willReturn(true); + $this->userManager->expects($this->never())->method('getByEmail'); + $this->signRequestMapper->expects($this->never())->method('getById'); + $this->mailService->expects($this->never())->method('notifyUnsignedUser'); + $this->mailService->expects($this->never())->method('notifySignDataUpdated'); + + $this->listener->handle($this->invitation('email', 'bob@example.org')); + } + + public function testExternalEmailInvitationIsSentWithoutAccountLookup(): void { + $this->userManager->expects($this->never())->method('getByEmail'); + $this->mailService->expects($this->once()) + ->method('notifyUnsignedUser') + ->with($this->isInstanceOf(SignRequest::class), 'external@example.org', 'Review document'); + + $this->listener->handle($this->invitation('email', 'external@example.org')); + } + + public function testReminderUsesUpdatedMailTemplate(): void { + $this->firstNotification = false; + $this->mailService->expects($this->never())->method('notifyUnsignedUser'); + $this->mailService->expects($this->once()) + ->method('notifySignDataUpdated') + ->with($this->isInstanceOf(SignRequest::class), 'bob@example.org', 'Review document'); + + $this->listener->handle($this->invitation('email', 'bob@example.org')); + } + + public static function accountPreferences(): array { return [ - 'notification disabled' => [true, false], - 'notification enabled' => [false, true], + 'account allows email' => [false, true], + 'account disables email' => [true, false], ]; } - #[DataProvider('provideSignedMailPreferenceScenarios')] - public function testSignedMailRespectsNotificationPreference( - bool $notificationDisabled, - bool $shouldSend, - ): void { - $this->notificationPreferenceResolver->expects($this->once()) + #[DataProvider('accountPreferences')] + public function testAccountInvitationUsesUidAndItsPreference(bool $disabled, bool $shouldSend): void { + $this->userManager->method('get')->with('account-uid') + ->willReturn($this->account('account-uid', 'shared@example.org')); + $this->userManager->expects($this->never())->method('getByEmail'); + $this->preferences->expects($this->once()) ->method('isEmailNotificationDisabled') - ->with('admin', SignedEvent::FILE_SIGNED, true) - ->willReturn($notificationDisabled); + ->with('account-uid', SendSignNotificationEvent::FILE_TO_SIGN, true) + ->willReturn($disabled); + $this->mailService->expects($shouldSend ? $this->once() : $this->never()) + ->method('notifyUnsignedUser') + ->with($this->anything(), 'shared@example.org', 'Review document'); - $owner = $this->createMock(IUser::class); - $owner->method('getEMailAddress')->willReturn('admin@email.tld'); - $owner->method('getDisplayName')->willReturn('Admin'); + $this->listener->handle($this->invitation('account', 'account-uid')); + } - $expectation = $shouldSend ? $this->once() : $this->never(); - $this->mailService->expects($expectation) - ->method('notifySignedUser'); + public function testMissingAccountIsSkippedWithoutDereference(): void { + $this->userManager->method('get')->with('absent-uid')->willReturn(null); + $this->mailService->expects($this->never())->method('notifyUnsignedUser'); - $this->listener->handle($this->createSignedEvent($owner)); + $this->listener->handle($this->invitation('account', 'absent-uid')); } - private function createSignedEvent(IUser $owner): SignedEvent { - $signRequest = new SignRequest(); - $signRequest->setId(42); - $signRequest->setFileId(10); - $signRequest->setDisplayName('Signer Name'); + public function testAccountWithoutEmailIsSkipped(): void { + $this->userManager->method('get')->with('account-uid') + ->willReturn($this->account('account-uid', '')); + $this->mailService->expects($this->never())->method('notifyUnsignedUser'); - $libreSignFile = new FileEntity(); - $libreSignFile->setId(10); - $libreSignFile->setUuid('file-uuid'); - $libreSignFile->setName('Contract.pdf'); - $libreSignFile->setUserId('admin'); + $this->listener->handle($this->invitation('account', 'account-uid')); + } + + public function testEmptyAndUnsupportedDestinationsAreSkipped(): void { + $this->mailService->expects($this->never())->method('notifyUnsignedUser'); + + $this->listener->handle($this->invitation('email', '')); + $this->listener->handle($this->invitation('phone', '+1234567890')); + } + + public function testDeletedIdentityDoesNotReceiveInvitationOrCancellation(): void { + $this->mailService->expects($this->never())->method('notifyUnsignedUser'); + $this->mailService->expects($this->never())->method('notifyCanceledRequest'); + + $this->listener->handle($this->invitation('account', 'deleted-uid', true)); + $this->listener->handle($this->cancellation('account', 'deleted-uid', true)); + } - $identifyEntity = new IdentifyMethodEntity(); - $identifyEntity->setIdentifierKey('account'); - $identifyEntity->setIdentifierValue('signer1'); + public static function cancellationPreferences(): array { + return [ + 'linked account allows cancellation email' => [false, true], + 'linked account disables cancellation email' => [true, false], + ]; + } - $identifyMethod = $this->createMock(IIdentifyMethod::class); - $identifyMethod->method('getEntity')->willReturn($identifyEntity); + #[DataProvider('cancellationPreferences')] + public function testEmailCancellationRetainsUniqueLinkedAccountPreference(bool $disabled, bool $shouldSend): void { + $this->userManager->method('getByEmail')->with('linked@example.org') + ->willReturn([$this->account('account-uid', 'linked@example.org')]); + $this->preferences->expects($this->once()) + ->method('isEmailNotificationDisabled') + ->with('account-uid', SignRequestCanceledEvent::SIGN_REQUEST_CANCELED, true) + ->willReturn($disabled); + $this->mailService->expects($shouldSend ? $this->once() : $this->never()) + ->method('notifyCanceledRequest') + ->with($this->anything(), 'linked@example.org', $this->isInstanceOf(FileEntity::class)); - $signedFile = $this->createMock(File::class); + $this->listener->handle($this->cancellation('email', 'linked@example.org')); + } + + public function testExternalEmailCancellationIsSent(): void { + $this->userManager->method('getByEmail')->with('external@example.org')->willReturn([]); + $this->preferences->expects($this->never())->method('isEmailNotificationDisabled'); + $this->mailService->expects($this->once()) + ->method('notifyCanceledRequest') + ->with($this->anything(), 'external@example.org', $this->isInstanceOf(FileEntity::class)); - return new SignedEvent( - $signRequest, - $libreSignFile, - $identifyMethod, + $this->listener->handle($this->cancellation('email', 'external@example.org')); + } + + public function testSharedEmailCancellationIsNotSuppressedByOneUser(): void { + $this->userManager->method('getByEmail')->with('shared@example.org') + ->willReturn([ + $this->account('first', 'shared@example.org'), + $this->account('second', 'shared@example.org'), + ]); + $this->preferences->expects($this->never())->method('isEmailNotificationDisabled'); + $this->mailService->expects($this->once()) + ->method('notifyCanceledRequest') + ->with($this->anything(), 'shared@example.org', $this->isInstanceOf(FileEntity::class)); + + $this->listener->handle($this->cancellation('email', 'shared@example.org')); + } + + #[DataProvider('accountPreferences')] + public function testAccountCancellationChecksSelectedUid(bool $disabled, bool $shouldSend): void { + $this->userManager->method('get')->with('account-uid') + ->willReturn($this->account('account-uid', 'shared@example.org')); + $this->userManager->expects($this->never())->method('getByEmail'); + $this->preferences->expects($this->once()) + ->method('isEmailNotificationDisabled') + ->with('account-uid', SignRequestCanceledEvent::SIGN_REQUEST_CANCELED, true) + ->willReturn($disabled); + $this->mailService->expects($shouldSend ? $this->once() : $this->never()) + ->method('notifyCanceledRequest') + ->with($this->anything(), 'shared@example.org', $this->isInstanceOf(FileEntity::class)); + + $this->listener->handle($this->cancellation('account', 'account-uid')); + } + + public static function signedMailPreferences(): array { + return [ + 'owner enables signed mail' => [false, true], + 'owner disables signed mail' => [true, false], + ]; + } + + #[DataProvider('signedMailPreferences')] + public function testSignedFileMailStillUsesOwnerPreference(bool $disabled, bool $shouldSend): void { + $this->preferences->expects($this->once()) + ->method('isEmailNotificationDisabled') + ->with('admin', SignedEvent::FILE_SIGNED, true) + ->willReturn($disabled); + $owner = $this->account('admin', 'admin@example.org'); + $owner->method('getDisplayName')->willReturn('Admin'); + $this->mailService->expects($shouldSend ? $this->once() : $this->never()) + ->method('notifySignedUser') + ->with($this->anything(), 'admin@example.org', $this->anything(), 'Admin'); + $this->listener->handle(new SignedEvent( + $this->request(), + $this->file(), + $this->identifyMethod('account', 'signer-uid'), $owner, - $signedFile, + $this->createMock(File::class), + )); + } + + private function invitation(string $method, string $value, bool $deleted = false): SendSignNotificationEvent { + return new SendSignNotificationEvent( + $this->request(), $this->file(), $this->identifyMethod($method, $value, $deleted), ); } + + private function cancellation(string $method, string $value, bool $deleted = false): SignRequestCanceledEvent { + return new SignRequestCanceledEvent( + $this->request(), $this->file(), $this->identifyMethod($method, $value, $deleted), + ); + } + + private function request(): SignRequest { + $request = new SignRequest(); + $request->setId(42); + $request->setFileId(10); + $request->setDescription('Review document'); + return $request; + } + + private function file(): FileEntity { + $file = new FileEntity(); + $file->setId(10); + $file->setUserId('admin'); + $file->setName('Contract.pdf'); + return $file; + } + + private function identifyMethod(string $method, string $value, bool $deleted = false): IIdentifyMethod { + $entity = new IdentifyMethodEntity(); + $entity->setIdentifierKey($method); + $entity->setIdentifierValue($value); + if ($deleted) { + $entity->setMetadata(['deleted_account' => [ + 'account' => $value, + 'display_name' => 'Deleted user', + ]]); + } + $identify = $this->createMock(IIdentifyMethod::class); + $identify->method('getName')->willReturn($method); + $identify->method('getEntity')->willReturn($entity); + return $identify; + } + + private function account(string $uid, string $email): IUser&MockObject { + $user = $this->createMock(IUser::class); + $user->method('getUID')->willReturn($uid); + $user->method('getEMailAddress')->willReturn($email); + return $user; + } } diff --git a/tests/php/Unit/Service/NotificationPreferenceResolverTest.php b/tests/php/Unit/Service/NotificationPreferenceResolverTest.php index 7251e16b6c..7656a98e81 100644 --- a/tests/php/Unit/Service/NotificationPreferenceResolverTest.php +++ b/tests/php/Unit/Service/NotificationPreferenceResolverTest.php @@ -8,6 +8,7 @@ namespace OCA\Libresign\Tests\Unit\Service; +use OCA\Libresign\Events\SendSignNotificationEvent; use OCA\Libresign\Events\SignedEvent; use OCA\Libresign\Service\ActivitySettingsStore; use OCA\Libresign\Service\NotificationPreferenceResolver; @@ -70,6 +71,43 @@ public function testEmailFallbackUsesMockedConfigValues( ); } + public static function globalEmailSettings(): array { + return [ + 'admin permits email' => ['1', false], + 'admin disables email' => ['0', true], + ]; + } + + #[DataProvider('globalEmailSettings')] + public function testGlobalEmailPreferenceUsesActivityAdminSetting(string $value, bool $disabled): void { + $this->activitySettingsStore->method('isAvailable')->willReturn(true); + $this->activitySettingsStore->method('hasSetting') + ->with(SendSignNotificationEvent::FILE_TO_SIGN)->willReturn(true); + $this->activitySettingsStore->method('getAdminSetting') + ->with('email', SendSignNotificationEvent::FILE_TO_SIGN)->willReturn($value); + $this->activitySettingsStore->expects($this->never())->method('getUserSetting'); + + $this->assertSame($disabled, $this->resolver->isEmailNotificationGloballyDisabled(SendSignNotificationEvent::FILE_TO_SIGN)); + } + + #[DataProvider('globalEmailSettings')] + public function testGlobalEmailPreferenceUsesAppConfigFallback(string $value, bool $disabled): void { + $this->activitySettingsStore->method('isAvailable')->willReturn(false); + $this->appConfig->method('getValueString') + ->with('activity', 'notify_email_libresign_file_to_sign', '1')->willReturn($value); + $this->userConfig->expects($this->never())->method('getValueString'); + + $this->assertSame($disabled, $this->resolver->isEmailNotificationGloballyDisabled(SendSignNotificationEvent::FILE_TO_SIGN)); + } + + public function testGlobalEmailPreferenceIgnoresUnregisteredActivitySetting(): void { + $this->activitySettingsStore->method('isAvailable')->willReturn(true); + $this->activitySettingsStore->method('hasSetting')->willReturn(false); + $this->activitySettingsStore->expects($this->never())->method('getAdminSetting'); + + $this->assertFalse($this->resolver->isEmailNotificationGloballyDisabled(SendSignNotificationEvent::FILE_TO_SIGN)); + } + public function testInAppFallbackUsesNotificationChannel(): void { $this->activitySettingsStore->expects($this->once()) ->method('isAvailable')