From 1650c77c9ba3edb3fed7ee0924c991b5cc677cb4 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Mon, 9 Nov 2026 15:39:07 +0000 Subject: [PATCH 01/23] feat: expose signer and workflow transitions as native webhooks Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- lib/Events/SignerRejectedWebhookEvent.php | 64 +++++++++++++++++++ lib/Events/SignerSignedWebhookEvent.php | 62 ++++++++++++++++++ lib/Events/SigningRequestCanceledEvent.php | 48 ++++++++++++++ lib/Events/SigningRequestReadyEvent.php | 48 ++++++++++++++ lib/Service/FileStatusService.php | 16 +++++ lib/Service/RequestSignatureService.php | 10 ++- lib/Service/SignFileService.php | 6 ++ .../SignatureRejectionService.php | 43 +++++++++++++ .../Unit/Service/FileStatusServiceTest.php | 20 +++++- .../SignatureRejectionServiceTest.php | 45 +++++++++++++ 10 files changed, 359 insertions(+), 3 deletions(-) create mode 100644 lib/Events/SignerRejectedWebhookEvent.php create mode 100644 lib/Events/SignerSignedWebhookEvent.php create mode 100644 lib/Events/SigningRequestCanceledEvent.php create mode 100644 lib/Events/SigningRequestReadyEvent.php diff --git a/lib/Events/SignerRejectedWebhookEvent.php b/lib/Events/SignerRejectedWebhookEvent.php new file mode 100644 index 0000000000..b685c8e9fc --- /dev/null +++ b/lib/Events/SignerRejectedWebhookEvent.php @@ -0,0 +1,64 @@ +getUuid() === '' || $document->getUuid() === '' + || $signer->getId() === null + || $signer->getStatusEnum() !== SignRequestStatus::REJECTED + || $signer->getRejectedAt() === null) { + return null; + } + + $identity = implode(':', [$root->getUuid(), $document->getUuid(), $signer->getId(), $signer->getRejectedAt()->format('U.u')]); + return new self( + $root->getUuid(), + $root->isEnvelope() ? 'envelope' : 'document', + $document->getUuid(), + $signer->getId(), + $workflowCanceled, + 'libresign.signer.rejected.v1:' . hash('sha256', $identity), + ); + } + + #[\Override] + public function getWebhookSerializable(): array { + return [ + 'contractVersion' => self::CONTRACT_VERSION, + 'eventId' => $this->eventId, + 'requestUuid' => $this->requestUuid, + 'requestType' => $this->requestType, + 'documentUuid' => $this->documentUuid, + 'signerId' => $this->signerId, + 'status' => 'rejected', + 'workflowCanceled' => $this->workflowCanceled, + ]; + } +} diff --git a/lib/Events/SignerSignedWebhookEvent.php b/lib/Events/SignerSignedWebhookEvent.php new file mode 100644 index 0000000000..2925082c8a --- /dev/null +++ b/lib/Events/SignerSignedWebhookEvent.php @@ -0,0 +1,62 @@ +getUuid() === '' || $document->getUuid() === '' + || $signer->getId() === null || $signer->getSigned() === null + || !is_string($signer->getSignedHash()) || $signer->getSignedHash() === '') { + return null; + } + + $identity = implode(':', [$root->getUuid(), $document->getUuid(), $signer->getId(), $signer->getSignedHash()]); + return new self( + $root->getUuid(), + $root->isEnvelope() ? 'envelope' : 'document', + $document->getUuid(), + $signer->getId(), + 'libresign.signer.signed.v1:' . hash('sha256', $identity), + ); + } + + #[\Override] + public function getWebhookSerializable(): array { + return [ + 'contractVersion' => self::CONTRACT_VERSION, + 'eventId' => $this->eventId, + 'requestUuid' => $this->requestUuid, + 'requestType' => $this->requestType, + 'documentUuid' => $this->documentUuid, + 'signerId' => $this->signerId, + 'status' => 'signed', + ]; + } +} diff --git a/lib/Events/SigningRequestCanceledEvent.php b/lib/Events/SigningRequestCanceledEvent.php new file mode 100644 index 0000000000..ac2b3eb416 --- /dev/null +++ b/lib/Events/SigningRequestCanceledEvent.php @@ -0,0 +1,48 @@ +hasParent() + || $previousStatus === FileStatus::CANCELED->value + || $file->getStatus() !== FileStatus::CANCELED->value + || $file->getUuid() === '') { + return null; + } + + return new self($file->getUuid(), $file->isEnvelope() ? 'envelope' : 'document'); + } + + #[\Override] + public function getWebhookSerializable(): array { + return [ + 'contractVersion' => self::CONTRACT_VERSION, + 'eventId' => 'libresign.workflow.canceled.v1:' . $this->requestUuid, + 'requestUuid' => $this->requestUuid, + 'requestType' => $this->requestType, + 'status' => 'canceled', + ]; + } +} diff --git a/lib/Events/SigningRequestReadyEvent.php b/lib/Events/SigningRequestReadyEvent.php new file mode 100644 index 0000000000..5a184f4262 --- /dev/null +++ b/lib/Events/SigningRequestReadyEvent.php @@ -0,0 +1,48 @@ +hasParent() + || $previousStatus !== FileStatus::DRAFT->value + || $file->getStatus() !== FileStatus::ABLE_TO_SIGN->value + || $file->getUuid() === '') { + return null; + } + + return new self($file->getUuid(), $file->isEnvelope() ? 'envelope' : 'document'); + } + + #[\Override] + public function getWebhookSerializable(): array { + return [ + 'contractVersion' => self::CONTRACT_VERSION, + 'eventId' => 'libresign.workflow.ready.v1:' . $this->requestUuid, + 'requestUuid' => $this->requestUuid, + 'requestType' => $this->requestType, + 'status' => 'ready_to_sign', + ]; + } +} diff --git a/lib/Service/FileStatusService.php b/lib/Service/FileStatusService.php index b95bca2457..832bdd224b 100644 --- a/lib/Service/FileStatusService.php +++ b/lib/Service/FileStatusService.php @@ -13,8 +13,10 @@ use OCA\Libresign\Db\File as FileEntity; use OCA\Libresign\Db\FileMapper; use OCA\Libresign\Enum\FileStatus; +use OCA\Libresign\Events\SigningRequestReadyEvent; use OCA\Libresign\Service\SignRequest\StatusCacheService; use OCP\AppFramework\Db\DoesNotExistException; +use OCP\EventDispatcher\IEventDispatcher; class FileStatusService { public const POLICY_SNAPSHOT_FROZEN_AT = 'policy_snapshot_frozen_at'; @@ -22,6 +24,7 @@ class FileStatusService { public function __construct( private FileMapper $fileMapper, private StatusCacheService $statusCacheService, + private IEventDispatcher $eventDispatcher, ) { } @@ -33,6 +36,7 @@ public function updateFileStatusIfUpgrade(FileEntity $file, int $newStatus): Fil $this->touchStatusChangedAt($file); $this->fileMapper->update($file); $this->statusCacheService->setStatus($file->getUuid(), $newStatus); + $this->dispatchReadyTransition($file, $currentStatus); if ($file->hasParent()) { $this->propagateStatusToParent($file->getParentFileId()); @@ -42,6 +46,18 @@ public function updateFileStatusIfUpgrade(FileEntity $file, int $newStatus): Fil return $file; } + /** Called after creating a ready request and persisting its signers. */ + public function dispatchCreatedReadyRequest(FileEntity $file): void { + $this->dispatchReadyTransition($file, FileStatus::DRAFT->value); + } + + private function dispatchReadyTransition(FileEntity $file, int $previousStatus): void { + $event = SigningRequestReadyEvent::fromTransition($file, $previousStatus); + if ($event !== null) { + $this->eventDispatcher->dispatchTyped($event); + } + } + public function invalidateCachedStatus(FileEntity $file): void { $this->statusCacheService->invalidateStatus($file->getUuid()); } diff --git a/lib/Service/RequestSignatureService.php b/lib/Service/RequestSignatureService.php index 35009a3fe4..5e1f5df258 100644 --- a/lib/Service/RequestSignatureService.php +++ b/lib/Service/RequestSignatureService.php @@ -139,7 +139,8 @@ public function saveFiles(array $data): array { } public function save(array $data): FileEntity { - $file = $this->saveFile($data); + $newlyCreated = false; + $file = $this->saveFile($data, $newlyCreated); if (!isset($data['status'])) { $data['status'] = $file->getStatus(); } @@ -149,6 +150,9 @@ public function save(array $data): FileEntity { $this->propagateSignersToChildren($file, $data); $this->saveVisibleElements($data, $file); }, $this->db); + if ($newlyCreated) { + $this->fileStatusService->dispatchCreatedReadyRequest($file); + } $this->notifications->flushCommitted(); return $file; @@ -363,7 +367,8 @@ private function createFileForEnvelope( * uploadedFile?: array * } $data */ - public function saveFile(array $data): FileEntity { + public function saveFile(array $data, ?bool &$newlyCreated = null): FileEntity { + $newlyCreated = false; if (!empty($data['uuid'])) { $file = $this->fileMapper->getByUuid($data['uuid']); $this->filePolicyApplier->syncCoreFlowPolicies($file, $data); @@ -433,6 +438,7 @@ public function saveFile(array $data): FileEntity { $this->filePolicyApplier->applyAll($file, $data); $this->fileMapper->insert($file); + $newlyCreated = true; return $file; } diff --git a/lib/Service/SignFileService.php b/lib/Service/SignFileService.php index a230d1a5df..7a7395955d 100644 --- a/lib/Service/SignFileService.php +++ b/lib/Service/SignFileService.php @@ -31,6 +31,7 @@ use OCA\Libresign\Enum\IdentifyMethodRequirement; use OCA\Libresign\Enum\SignRequestStatus; use OCA\Libresign\Events\SignedEventFactory; +use OCA\Libresign\Events\SignerSignedWebhookEvent; use OCA\Libresign\Events\SigningRequestCompletedEvent; use OCA\Libresign\Exception\FooterStampUnavailableException; use OCA\Libresign\Exception\LibresignException; @@ -1018,6 +1019,11 @@ protected function dispatchSignedEvent(): void { $certificateSerialNumber, ); $this->eventDispatcher->dispatchTyped($event); + $root = $this->getCompletionTarget($this->libreSignFile); + $publicEvent = SignerSignedWebhookEvent::afterSigning($root, $this->libreSignFile, $this->signRequest); + if ($publicEvent !== null) { + $this->eventDispatcher->dispatchTyped($publicEvent); + } } protected function identifyEngine(File $file): ISignEngineHandler { diff --git a/lib/Service/SignatureRejection/SignatureRejectionService.php b/lib/Service/SignatureRejection/SignatureRejectionService.php index b5de4b2282..70f086a14a 100644 --- a/lib/Service/SignatureRejection/SignatureRejectionService.php +++ b/lib/Service/SignatureRejection/SignatureRejectionService.php @@ -16,6 +16,9 @@ use OCA\Libresign\Enum\SignatureRejectionCommentMode; use OCA\Libresign\Enum\SignRequestStatus; use OCA\Libresign\Events\SignatureRejectedEvent; +use OCA\Libresign\Events\SignerRejectedWebhookEvent; +use OCA\Libresign\Events\SigningRequestCanceledEvent; +use OCA\Libresign\Events\SigningRequestCompletedEvent; use OCA\Libresign\Exception\LibresignException; use OCA\Libresign\Service\File\SigningWorkflowStatusResolver; use OCA\Libresign\Service\FileStatusService; @@ -77,7 +80,12 @@ public function reject( // always the signer's call and no policy can take that choice away. $commentIsPrivate = $normalizedComment !== null && $privateComment; + $root = $libreSignFile->hasParent() + ? $this->fileMapper->getById($libreSignFile->getParentFileId()) + : $libreSignFile; + $previousRootStatus = $root->getStatus(); $activatedSigners = $this->persistRejection($libreSignFile, $signRequest, $normalizedComment, $commentIsPrivate, $config->cancelsWorkflow()); + $this->dispatchPublicRejectionEvents($libreSignFile, $signRequest, $previousRootStatus); // Record the committed rejection before notification errors can interrupt this flow. // The event reports the status the rejection left, as the API does: a workflow that // continues after rejections is still canceled once every signer rejected. @@ -357,6 +365,41 @@ private function normalizeComment(?string $comment, SignatureRejectionCommentMod return $trimmed; } + private function dispatchPublicRejectionEvents( + FileEntity $document, + SignRequestEntity $signer, + int $previousRootStatus, + ): void { + // Signing-state transactions have committed. A webhook scheduling failure + // must not undo a persisted rejection. + try { + $root = $document->hasParent() + ? $this->fileMapper->getById($document->getParentFileId()) + : $document; + $rejected = SignerRejectedWebhookEvent::afterRejection( + $root, $document, $signer, $this->isWorkflowCanceled($root), + ); + if ($rejected !== null) { + $this->eventDispatcher->dispatchTyped($rejected); + } + $canceled = SigningRequestCanceledEvent::fromTransition($root, $previousRootStatus); + if ($canceled !== null) { + $this->eventDispatcher->dispatchTyped($canceled); + } + // Under a continue-on-rejection policy, the final rejection may + // finish a workflow that already contains a valid signature. + $completed = SigningRequestCompletedEvent::fromTransition($root, $previousRootStatus); + if ($completed !== null) { + $this->eventDispatcher->dispatchTyped($completed); + } + } catch (\Throwable $e) { + $this->logger->error('Unable to enqueue LibreSign rejection webhook', [ + 'exception' => $e, + 'fileId' => $document->getId(), + ]); + } + } + private function dispatchRejectedEvent( SignRequestEntity $signRequest, FileEntity $libreSignFile, diff --git a/tests/php/Unit/Service/FileStatusServiceTest.php b/tests/php/Unit/Service/FileStatusServiceTest.php index 6bbe403d11..a8bbcac8a6 100644 --- a/tests/php/Unit/Service/FileStatusServiceTest.php +++ b/tests/php/Unit/Service/FileStatusServiceTest.php @@ -12,8 +12,10 @@ use OCA\Libresign\Db\File as FileEntity; use OCA\Libresign\Db\FileMapper; use OCA\Libresign\Enum\FileStatus; +use OCA\Libresign\Events\SigningRequestReadyEvent; use OCA\Libresign\Service\FileStatusService; use OCA\Libresign\Service\SignRequest\StatusCacheService; +use OCP\EventDispatcher\IEventDispatcher; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -22,11 +24,13 @@ class FileStatusServiceTest extends TestCase { private FileMapper|MockObject $fileMapper; private StatusCacheService|MockObject $statusCacheService; private FileStatusService $service; + private IEventDispatcher&MockObject $eventDispatcher; protected function setUp(): void { $this->fileMapper = $this->createMock(FileMapper::class); $this->statusCacheService = $this->createMock(StatusCacheService::class); - $this->service = new FileStatusService($this->fileMapper, $this->statusCacheService); + $this->eventDispatcher = $this->createMock(IEventDispatcher::class); + $this->service = new FileStatusService($this->fileMapper, $this->statusCacheService, $this->eventDispatcher); } public function testQueuedSigningStatusIsNotPublishedBeforeCommit(): void { @@ -49,6 +53,20 @@ public function testCommittedEnqueueDoesNotOverwriteNewerSigningProgress(): void $this->service->onQueuedJobCommitted($file); } + public function testReadyWebhookIsEmittedOnceForRootDraftTransition(): void { + $file = new FileEntity(); + $file->setId(11); + $file->setUuid('ready-uuid'); + $file->setStatus(FileStatus::DRAFT->value); + $this->eventDispatcher->expects($this->once())->method('dispatchTyped') + ->with($this->callback(static function ($event): bool { + return $event instanceof SigningRequestReadyEvent + && $event->getWebhookSerializable()['status'] === 'ready_to_sign'; + })); + $this->service->updateFileStatusIfUpgrade($file, FileStatus::ABLE_TO_SIGN->value); + $this->service->updateFileStatusIfUpgrade($file, FileStatus::ABLE_TO_SIGN->value); + } + #[DataProvider('dataFileStatusUpgrade')] public function testUpdateFileStatusIfUpgrade(int $currentStatus, int $newStatus, bool $shouldUpdate): void { $file = new FileEntity(); diff --git a/tests/php/Unit/Service/SignatureRejection/SignatureRejectionServiceTest.php b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionServiceTest.php index 6d34ac914a..74c66c3533 100644 --- a/tests/php/Unit/Service/SignatureRejection/SignatureRejectionServiceTest.php +++ b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionServiceTest.php @@ -15,6 +15,9 @@ use OCA\Libresign\Enum\FileStatus; use OCA\Libresign\Enum\SignRequestStatus; use OCA\Libresign\Events\SignatureRejectedEvent; +use OCA\Libresign\Events\SignerRejectedWebhookEvent; +use OCA\Libresign\Events\SigningRequestCanceledEvent; +use OCA\Libresign\Events\SigningRequestCompletedEvent; use OCA\Libresign\Exception\LibresignException; use OCA\Libresign\Service\File\SigningWorkflowStatusResolver; use OCA\Libresign\Service\FileStatusService; @@ -285,6 +288,48 @@ public function testPrivateFlagIsIgnoredWhenThereIsNoComment(): void { $this->assertFalse($signRequest->getRejectionCommentPrivate()); } + #[DataProvider('publicRejectionOutcomes')] + public function testCommittedRejectionEmitsOnePublicBusinessEvent(bool $cancel): void { + $this->withPolicy(self::policy($cancel ? 'cancel' : 'continue', 'optional')); + $file = $this->file(); + $file->setUuid('request-uuid'); + $signer = $this->signRequest(); + $signer->setUuid('secret-invitation'); + $events = []; + $this->eventDispatcher->method('dispatchTyped')->willReturnCallback(static function ($event) use (&$events): void { + $events[] = $event; + }); + $this->getService()->reject($file, $signer, 'private explanation', true); + $rejections = array_values(array_filter($events, static fn ($event): bool => $event instanceof SignerRejectedWebhookEvent)); + $cancellations = array_values(array_filter($events, static fn ($event): bool => $event instanceof SigningRequestCanceledEvent)); + $this->assertCount(1, $rejections); + $this->assertCount($cancel ? 1 : 0, $cancellations); + $this->assertSame($cancel, $rejections[0]->getWebhookSerializable()['workflowCanceled']); + $this->assertStringNotContainsString('private explanation', json_encode($rejections[0]->getWebhookSerializable())); + } + + /** @return array */ + public static function publicRejectionOutcomes(): array { + return [ + 'continue' => [false], + 'cancel' => [true], + ]; + } + + public function testRejectionCanCompletePreviouslySignedWorkflow(): void { + $this->withPolicy(self::policy('continue')); + $file = $this->file(FileStatus::PARTIAL_SIGNED->value); + $file->setUuid('completed-by-rejection'); + $this->signingWorkflowStatusResolver->method('resolve')->willReturn(FileStatus::SIGNED); + $events = []; + $this->eventDispatcher->method('dispatchTyped')->willReturnCallback(static function ($event) use (&$events): void { + $events[] = $event; + }); + $this->getService()->reject($file, $this->signRequest()); + $this->assertSame(FileStatus::SIGNED->value, $file->getStatus()); + $this->assertCount(1, array_filter($events, static fn ($event): bool => $event instanceof SigningRequestCompletedEvent)); + } + public function testRejectionIsPersistedWithItsTimestampAndComment(): void { $this->withPolicy(self::policy(commentMode: 'optional')); $signRequest = $this->signRequest(); From 75a368c8be367dc58b1e2d4e500f3a5b4523f49c Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Mon, 9 Nov 2026 15:39:23 +0000 Subject: [PATCH 02/23] feat: publish persisted notification channel outcomes via webhook Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- ...NotificationDeliveryStatusChangedEvent.php | 65 +++++++ .../NotificationSubmissionService.php | 27 +++ .../Unit/Events/NativeWebhookEventsTest.php | 177 ++++++++++++++++++ .../NotificationSubmissionServiceTest.php | 4 +- .../NotificationDeliveryServiceTest.php | 4 + 5 files changed, 276 insertions(+), 1 deletion(-) create mode 100644 lib/Events/NotificationDeliveryStatusChangedEvent.php create mode 100644 tests/php/Unit/Events/NativeWebhookEventsTest.php diff --git a/lib/Events/NotificationDeliveryStatusChangedEvent.php b/lib/Events/NotificationDeliveryStatusChangedEvent.php new file mode 100644 index 0000000000..3f0393d395 --- /dev/null +++ b/lib/Events/NotificationDeliveryStatusChangedEvent.php @@ -0,0 +1,65 @@ +getState()); + if ($root->getUuid() === '' || $delivery->getId() === null || $delivery->getAttemptCount() < 1 + || $state === null + || in_array($state, [NotificationDeliveryState::PENDING, NotificationDeliveryState::SENDING], true)) { + return null; + } + + return new self( + $root->getUuid(), + $root->isEnvelope() ? 'envelope' : 'document', + $delivery->getId(), + $delivery->getChannel(), + $state->value, + $delivery->getAttemptCount(), + 'libresign.notification.delivery.v1:' . $delivery->getId() . ':' . $delivery->getAttemptCount() . ':' . $state->value, + ); + } + + #[\Override] + public function getWebhookSerializable(): array { + return [ + 'contractVersion' => self::CONTRACT_VERSION, + 'eventId' => $this->eventId, + 'requestUuid' => $this->requestUuid, + 'requestType' => $this->requestType, + 'deliveryId' => $this->deliveryId, + 'channel' => $this->channel, + 'state' => $this->state, + 'attempt' => $this->attempt, + ]; + } +} diff --git a/lib/Service/Notification/NotificationSubmissionService.php b/lib/Service/Notification/NotificationSubmissionService.php index d9702450c0..a08f4072ea 100644 --- a/lib/Service/Notification/NotificationSubmissionService.php +++ b/lib/Service/Notification/NotificationSubmissionService.php @@ -8,12 +8,15 @@ namespace OCA\Libresign\Service\Notification; +use OCA\Libresign\Db\FileMapper; use OCA\Libresign\Db\NotificationAttemptMapper; use OCA\Libresign\Db\NotificationDelivery; use OCA\Libresign\Db\NotificationDeliveryMapper; use OCA\Libresign\Enum\NotificationDeliveryState; +use OCA\Libresign\Events\NotificationDeliveryStatusChangedEvent; use OCA\Libresign\Exception\NotificationPreparationException; use OCP\AppFramework\Db\TTransactional; +use OCP\EventDispatcher\IEventDispatcher; use OCP\IDBConnection; use Psr\Log\LoggerInterface; @@ -29,6 +32,8 @@ public function __construct( private NotificationFailureClassifier $failureClassifier, private NotificationHistoryService $history, private LoggerInterface $logger, + private FileMapper $fileMapper, + private IEventDispatcher $eventDispatcher, ) { } @@ -90,7 +95,29 @@ public function submit(NotificationDelivery $delivery, NotificationMessage $mess $this->attempts->finish($attempt->getId(), $outcome, $reason); $this->deliveries->finish($delivery->getId(), $outcome, $retryAt); }, $this->db); + $this->dispatchDeliveryStatusWebhook($delivery); } return true; } + + private function dispatchDeliveryStatusWebhook(NotificationDelivery $delivery): void { + // A webhook failure must not mask a persisted provider result or its original error. + try { + $persisted = $this->deliveries->findById($delivery->getId()); + $file = $this->fileMapper->getById($persisted->getFileId()); + $root = $file->hasParent() + ? $this->fileMapper->getById($file->getParentFileId()) + : $file; + $event = NotificationDeliveryStatusChangedEvent::fromPersistedDelivery($root, $persisted); + if ($event !== null) { + $this->eventDispatcher->dispatchTyped($event); + } + } catch (\Throwable $e) { + $this->logger->warning('Unable to enqueue notification outcome webhook', [ + 'exception' => $e, + 'deliveryId' => $delivery->getId(), + ]); + } + } + } diff --git a/tests/php/Unit/Events/NativeWebhookEventsTest.php b/tests/php/Unit/Events/NativeWebhookEventsTest.php new file mode 100644 index 0000000000..1998f504c2 --- /dev/null +++ b/tests/php/Unit/Events/NativeWebhookEventsTest.php @@ -0,0 +1,177 @@ +setUuid($uuid); + $file->setNodeType($envelope ? 'envelope' : 'file'); + return $file; + } + + /** @return array */ + public static function readyTransitions(): array { + return [ + 'draft to ready' => [FileStatus::DRAFT, FileStatus::ABLE_TO_SIGN, false, true], + 'repeated ready' => [FileStatus::ABLE_TO_SIGN, FileStatus::ABLE_TO_SIGN, false, false], + 'draft to signed' => [FileStatus::DRAFT, FileStatus::SIGNED, false, false], + 'child draft to ready' => [FileStatus::DRAFT, FileStatus::ABLE_TO_SIGN, true, false], + ]; + } + + #[DataProvider('readyTransitions')] + public function testReadyRequiresRealRootTransition(FileStatus $previous, FileStatus $next, bool $child, bool $emitted): void { + $file = self::file(); + $file->setStatus($next->value); + if ($child) { + $file->setParentFileId(42); + } + $event = SigningRequestReadyEvent::fromTransition($file, $previous->value); + if (!$emitted) { + self::assertNull($event); + return; + } + self::assertInstanceOf(IWebhookCompatibleEvent::class, $event); + self::assertSame([ + 'contractVersion' => 1, + 'eventId' => 'libresign.workflow.ready.v1:workflow-uuid', + 'requestUuid' => 'workflow-uuid', + 'requestType' => 'document', + 'status' => 'ready_to_sign', + ], $event->getWebhookSerializable()); + } + + /** @return array */ + public static function canceledTransitions(): array { + return [ + 'ready to canceled' => [FileStatus::ABLE_TO_SIGN, FileStatus::CANCELED, false, true], + 'already canceled' => [FileStatus::CANCELED, FileStatus::CANCELED, false, false], + 'not canceled' => [FileStatus::ABLE_TO_SIGN, FileStatus::PARTIAL_SIGNED, false, false], + 'canceled envelope child' => [FileStatus::ABLE_TO_SIGN, FileStatus::CANCELED, true, false], + ]; + } + + #[DataProvider('canceledTransitions')] + public function testCanceledRequiresAggregateTransition(FileStatus $previous, FileStatus $next, bool $child, bool $emitted): void { + $file = self::file('envelope-uuid', true); + $file->setStatus($next->value); + if ($child) { + $file->setParentFileId(42); + } + $event = SigningRequestCanceledEvent::fromTransition($file, $previous->value); + if (!$emitted) { + self::assertNull($event); + return; + } + self::assertInstanceOf(IWebhookCompatibleEvent::class, $event); + self::assertSame([ + 'contractVersion' => 1, + 'eventId' => 'libresign.workflow.canceled.v1:envelope-uuid', + 'requestUuid' => 'envelope-uuid', + 'requestType' => 'envelope', + 'status' => 'canceled', + ], $event->getWebhookSerializable()); + } + + public function testSignerSignedHasStableNonSecretCorrelation(): void { + $root = self::file('envelope-uuid', true); + $document = self::file('child-uuid'); + $document->setParentFileId(42); + $signer = new SignRequest(); + $signer->setId(52); + $signer->setUuid('SECRET-INVITATION-UUID'); + $signer->setSigned(new \DateTime('2026-11-09T11:00:00Z')); + $signer->setSignedHash('content-hash'); + $event = SignerSignedWebhookEvent::afterSigning($root, $document, $signer); + self::assertInstanceOf(IWebhookCompatibleEvent::class, $event); + $payload = $event->getWebhookSerializable(); + self::assertSame('envelope', $payload['requestType']); + self::assertSame('envelope-uuid', $payload['requestUuid']); + self::assertSame('child-uuid', $payload['documentUuid']); + self::assertSame(52, $payload['signerId']); + self::assertSame('signed', $payload['status']); + self::assertSame($payload, SignerSignedWebhookEvent::afterSigning($root, $document, $signer)->getWebhookSerializable()); + self::assertStringNotContainsString('SECRET-INVITATION-UUID', json_encode($payload)); + $signer->setSignedHash(null); + self::assertNull(SignerSignedWebhookEvent::afterSigning($root, $document, $signer)); + } + + public function testRejectedEventDoesNotDiscloseCommentsOrInvitation(): void { + $root = self::file('workflow-uuid'); + $signer = new SignRequest(); + $signer->setId(9); + $signer->setUuid('SECRET-INVITATION'); + $signer->setRejectedAt(new \DateTime('2026-11-09T11:00:00Z')); + $signer->setStatusEnum(SignRequestStatus::REJECTED); + $signer->setRejectionComment('PRIVATE CASE DETAILS'); + $signer->setRejectionCommentPrivate(true); + $event = SignerRejectedWebhookEvent::afterRejection($root, $root, $signer, true); + self::assertInstanceOf(IWebhookCompatibleEvent::class, $event); + $p = $event->getWebhookSerializable(); + self::assertSame(true, $p['workflowCanceled']); + self::assertSame('rejected', $p['status']); + self::assertSame(9, $p['signerId']); + self::assertSame($p, SignerRejectedWebhookEvent::afterRejection($root, $root, $signer, true)->getWebhookSerializable()); + self::assertStringNotContainsString('PRIVATE CASE DETAILS', json_encode($p)); + self::assertStringNotContainsString('SECRET-INVITATION', json_encode($p)); + $signer->setStatusEnum(SignRequestStatus::SIGNED); + self::assertNull(SignerRejectedWebhookEvent::afterRejection($root, $root, $signer, false)); + } + + /** @return array */ + public static function persistedDeliveryOutcomes(): array { + return [ + 'pending' => [NotificationDeliveryState::PENDING, 0, false], + 'claimed' => [NotificationDeliveryState::SENDING, 1, false], + 'accepted by adapter' => [NotificationDeliveryState::ACCEPTED, 1, true], + 'unknown result' => [NotificationDeliveryState::UNKNOWN, 2, true], + 'failed' => [NotificationDeliveryState::FAILED, 2, true], + 'temporary failure' => [NotificationDeliveryState::TEMPORARY_FAILURE, 2, true], + ]; + } + + #[DataProvider('persistedDeliveryOutcomes')] + public function testDeliveryReportsOnlyPersistedAttemptOutcomes(NotificationDeliveryState $state, int $attempt, bool $emitted): void { + $delivery = new NotificationDelivery(); + $delivery->setId(15); + $delivery->setEventKey(str_repeat('a', 64)); + $delivery->setRecipientEnc('ENCRYPTED_RECIPIENT'); + $delivery->setChannel('mail'); + $delivery->setState($state->value); + $delivery->setAttemptCount($attempt); + $event = NotificationDeliveryStatusChangedEvent::fromPersistedDelivery(self::file(), $delivery); + if (!$emitted) { + self::assertNull($event); + return; + } + self::assertInstanceOf(IWebhookCompatibleEvent::class, $event); + $p = $event->getWebhookSerializable(); + self::assertSame($state->value, $p['state']); + self::assertSame($attempt, $p['attempt']); + self::assertSame(15, $p['deliveryId']); + self::assertSame('mail', $p['channel']); + self::assertStringNotContainsString('ENCRYPTED_RECIPIENT', json_encode($p)); + } +} diff --git a/tests/php/Unit/Service/Notification/NotificationSubmissionServiceTest.php b/tests/php/Unit/Service/Notification/NotificationSubmissionServiceTest.php index 32c82fc91d..be5d824d45 100644 --- a/tests/php/Unit/Service/Notification/NotificationSubmissionServiceTest.php +++ b/tests/php/Unit/Service/Notification/NotificationSubmissionServiceTest.php @@ -9,6 +9,7 @@ namespace OCA\Libresign\Tests\Unit\Service\Notification; use OCA\Libresign\Db\File; +use OCA\Libresign\Db\FileMapper; use OCA\Libresign\Db\NotificationAttempt; use OCA\Libresign\Db\NotificationAttemptMapper; use OCA\Libresign\Db\NotificationDelivery; @@ -24,6 +25,7 @@ use OCA\Libresign\Service\Notification\NotificationHistoryService; use OCA\Libresign\Service\Notification\NotificationMessage; use OCA\Libresign\Service\Notification\NotificationSubmissionService; +use OCP\EventDispatcher\IEventDispatcher; use OCP\IDBConnection; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; @@ -65,7 +67,7 @@ static function (?\DateTime $due) use ($expectRetry, $attemptNumber): bool { $db->expects($this->never())->method('rollBack'); $channel = $this->createMock(NotificationChannel::class); $channel->method('deliver')->willThrowException($failure); - $service = new NotificationSubmissionService($deliveries, $attempts, $db, new NotificationFailureClassifier(), new NotificationHistoryService($this->createMock(SignRequestMapper::class)), $this->createMock(LoggerInterface::class)); + $service = new NotificationSubmissionService($deliveries, $attempts, $db, new NotificationFailureClassifier(), new NotificationHistoryService($this->createMock(SignRequestMapper::class)), $this->createMock(LoggerInterface::class), $this->createMock(FileMapper::class), $this->createMock(IEventDispatcher::class)); $this->expectException(get_class($failure)); $service->submit($delivery, $this->message(), $channel); } diff --git a/tests/php/Unit/Service/NotificationDeliveryServiceTest.php b/tests/php/Unit/Service/NotificationDeliveryServiceTest.php index fbd8fae78d..e0af462066 100644 --- a/tests/php/Unit/Service/NotificationDeliveryServiceTest.php +++ b/tests/php/Unit/Service/NotificationDeliveryServiceTest.php @@ -10,6 +10,7 @@ use OCA\Libresign\BackgroundJob\DeliverNotification; use OCA\Libresign\Db\File; +use OCA\Libresign\Db\FileMapper; use OCA\Libresign\Db\NotificationAttempt; use OCA\Libresign\Db\NotificationAttemptMapper; use OCA\Libresign\Db\NotificationDelivery; @@ -31,6 +32,7 @@ use OCA\Libresign\Service\NotificationDeliveryService; use OCA\Libresign\Service\Worker\WorkerActivationService; use OCP\BackgroundJob\IJobList; +use OCP\EventDispatcher\IEventDispatcher; use OCP\IConfig; use OCP\IDBConnection; use OCP\Notification\IManager; @@ -79,6 +81,8 @@ protected function setUp(): void { new NotificationFailureClassifier(), new NotificationHistoryService($this->createMock(\OCA\Libresign\Db\SignRequestMapper::class)), $this->createMock(LoggerInterface::class), + $this->createMock(FileMapper::class), + $this->createMock(IEventDispatcher::class), ), new NotificationEnvelopeCodec($handoffCrypto, $this->createMock(IManager::class)), $this->mode, From 2b7705b860cd9f71a3ad8f941bd1918171cf0c47 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Mon, 9 Nov 2026 15:45:39 +0000 Subject: [PATCH 03/23] test: verify notification outcome event follows persisted submission Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- .../NotificationSubmissionServiceTest.php | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/tests/php/Unit/Service/Notification/NotificationSubmissionServiceTest.php b/tests/php/Unit/Service/Notification/NotificationSubmissionServiceTest.php index be5d824d45..5ffae31b82 100644 --- a/tests/php/Unit/Service/Notification/NotificationSubmissionServiceTest.php +++ b/tests/php/Unit/Service/Notification/NotificationSubmissionServiceTest.php @@ -17,6 +17,7 @@ use OCA\Libresign\Db\SignRequest; use OCA\Libresign\Db\SignRequestMapper; use OCA\Libresign\Enum\NotificationDeliveryState; +use OCA\Libresign\Events\NotificationDeliveryStatusChangedEvent; use OCA\Libresign\Exception\NotificationPreparationException; use OCA\Libresign\Exception\NotificationTransportException; use OCA\Libresign\Service\Notification\MailPayload; @@ -105,4 +106,55 @@ public function testGenericTransportWrapperCannotMakeNestedPreparationSafe(): vo public function testNestedPreparationFailureCannotMakeTransportOutcomeSafe(): void { $this->executeFailure(new NotificationTransportException('synthetic uncertain outcome', NotificationDeliveryState::UNKNOWN, 'smtp_outcome_unknown', new NotificationPreparationException('preparation')), 1, NotificationDeliveryState::UNKNOWN, false); } + + public function testAcceptedOutcomeWebhookIsDispatchedOnlyAfterLedgerCommit(): void { + $delivery = new NotificationDelivery(); + $delivery->setId(9); + $delivery->setFileId(25); + $delivery->setChannel('mail'); + $delivery->setAttemptCount(1); + $persisted = new NotificationDelivery(); + $persisted->setId(9); + $persisted->setFileId(25); + $persisted->setChannel('mail'); + $persisted->setAttemptCount(1); + $persisted->setState(NotificationDeliveryState::ACCEPTED->value); + $attempt = new NotificationAttempt(); + $attempt->setId(28); + + $deliveries = $this->createMock(NotificationDeliveryMapper::class); + $deliveries->method('claim')->with(9)->willReturn(true); + $deliveries->method('findById')->with(9)->willReturn($persisted); + $deliveries->expects($this->once())->method('finish')->with(9, NotificationDeliveryState::ACCEPTED, null); + $attempts = $this->createMock(NotificationAttemptMapper::class); + $attempts->method('begin')->willReturn($attempt); + $attempts->expects($this->once())->method('finish')->with(28, NotificationDeliveryState::ACCEPTED, null); + $db = $this->createMock(IDBConnection::class); + $committed = 0; + $db->expects($this->exactly(2))->method('commit')->willReturnCallback(static function () use (&$committed): void { + $committed++; + }); + $root = new File(); + $root->setUuid('public-workflow-uuid'); + $files = $this->createMock(FileMapper::class); + $files->method('getById')->with(25)->willReturn($root); + $dispatcher = $this->createMock(IEventDispatcher::class); + $dispatcher->expects($this->once())->method('dispatchTyped')->with($this->callback( + static function ($event) use (&$committed): bool { + return $committed === 2 + && $event instanceof NotificationDeliveryStatusChangedEvent + && $event->getWebhookSerializable()['state'] === 'accepted' + && $event->getWebhookSerializable()['requestUuid'] === 'public-workflow-uuid'; + }, + )); + $channel = $this->createMock(NotificationChannel::class); + $channel->expects($this->once())->method('deliver'); + $history = new NotificationHistoryService($this->createMock(SignRequestMapper::class)); + $service = new NotificationSubmissionService( + $deliveries, $attempts, $db, new NotificationFailureClassifier(), + $history, $this->createMock(LoggerInterface::class), $files, $dispatcher, + ); + $this->assertTrue($service->submit($delivery, $this->message(), $channel)); + } + } From f95997c75309a9a75934390754886e65654cb4aa Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Mon, 9 Nov 2026 18:06:15 +0000 Subject: [PATCH 04/23] refactor: isolate persisted notification webhook publishing Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- .../NotificationDeliveryEventPublisher.php | 44 +++++++++ .../NotificationSubmissionService.php | 28 +----- ...NotificationDeliveryEventPublisherTest.php | 98 +++++++++++++++++++ .../NotificationSubmissionServiceTest.php | 66 ++++++------- .../NotificationDeliveryServiceTest.php | 5 +- 5 files changed, 177 insertions(+), 64 deletions(-) create mode 100644 lib/Service/Notification/NotificationDeliveryEventPublisher.php create mode 100644 tests/php/Unit/Service/Notification/NotificationDeliveryEventPublisherTest.php diff --git a/lib/Service/Notification/NotificationDeliveryEventPublisher.php b/lib/Service/Notification/NotificationDeliveryEventPublisher.php new file mode 100644 index 0000000000..8b1b764b0b --- /dev/null +++ b/lib/Service/Notification/NotificationDeliveryEventPublisher.php @@ -0,0 +1,44 @@ +deliveries->findById($deliveryId); + $file = $this->files->getById($delivery->getFileId()); + $root = $file->hasParent() + ? $this->files->getById($file->getParentFileId()) + : $file; + $event = NotificationDeliveryStatusChangedEvent::fromPersistedDelivery($root, $delivery); + if ($event !== null) { + $this->events->dispatchTyped($event); + } + } catch (\Exception $e) { + $this->logger->warning('Unable to publish persisted notification outcome', [ + 'deliveryId' => $deliveryId, + 'errorType' => get_debug_type($e), + ]); + } + } +} diff --git a/lib/Service/Notification/NotificationSubmissionService.php b/lib/Service/Notification/NotificationSubmissionService.php index a08f4072ea..20105dfacc 100644 --- a/lib/Service/Notification/NotificationSubmissionService.php +++ b/lib/Service/Notification/NotificationSubmissionService.php @@ -8,15 +8,12 @@ namespace OCA\Libresign\Service\Notification; -use OCA\Libresign\Db\FileMapper; use OCA\Libresign\Db\NotificationAttemptMapper; use OCA\Libresign\Db\NotificationDelivery; use OCA\Libresign\Db\NotificationDeliveryMapper; use OCA\Libresign\Enum\NotificationDeliveryState; -use OCA\Libresign\Events\NotificationDeliveryStatusChangedEvent; use OCA\Libresign\Exception\NotificationPreparationException; use OCP\AppFramework\Db\TTransactional; -use OCP\EventDispatcher\IEventDispatcher; use OCP\IDBConnection; use Psr\Log\LoggerInterface; @@ -32,8 +29,7 @@ public function __construct( private NotificationFailureClassifier $failureClassifier, private NotificationHistoryService $history, private LoggerInterface $logger, - private FileMapper $fileMapper, - private IEventDispatcher $eventDispatcher, + private NotificationDeliveryEventPublisher $eventPublisher, ) { } @@ -95,29 +91,9 @@ public function submit(NotificationDelivery $delivery, NotificationMessage $mess $this->attempts->finish($attempt->getId(), $outcome, $reason); $this->deliveries->finish($delivery->getId(), $outcome, $retryAt); }, $this->db); - $this->dispatchDeliveryStatusWebhook($delivery); + $this->eventPublisher->publish($delivery->getId()); } return true; } - private function dispatchDeliveryStatusWebhook(NotificationDelivery $delivery): void { - // A webhook failure must not mask a persisted provider result or its original error. - try { - $persisted = $this->deliveries->findById($delivery->getId()); - $file = $this->fileMapper->getById($persisted->getFileId()); - $root = $file->hasParent() - ? $this->fileMapper->getById($file->getParentFileId()) - : $file; - $event = NotificationDeliveryStatusChangedEvent::fromPersistedDelivery($root, $persisted); - if ($event !== null) { - $this->eventDispatcher->dispatchTyped($event); - } - } catch (\Throwable $e) { - $this->logger->warning('Unable to enqueue notification outcome webhook', [ - 'exception' => $e, - 'deliveryId' => $delivery->getId(), - ]); - } - } - } diff --git a/tests/php/Unit/Service/Notification/NotificationDeliveryEventPublisherTest.php b/tests/php/Unit/Service/Notification/NotificationDeliveryEventPublisherTest.php new file mode 100644 index 0000000000..733deb1727 --- /dev/null +++ b/tests/php/Unit/Service/Notification/NotificationDeliveryEventPublisherTest.php @@ -0,0 +1,98 @@ +deliveries = $this->createMock(NotificationDeliveryMapper::class); + $this->files = $this->createMock(FileMapper::class); + $this->dispatcher = $this->createMock(IEventDispatcher::class); + $this->logger = $this->createMock(LoggerInterface::class); + $this->publisher = new NotificationDeliveryEventPublisher( + $this->deliveries, $this->files, $this->dispatcher, $this->logger, + ); + } + + private function delivery(string $state = 'accepted'): NotificationDelivery { + $delivery = new NotificationDelivery(); + $delivery->setId(9); + $delivery->setFileId(25); + $delivery->setState($state); + $delivery->setAttemptCount(1); + $delivery->setChannel('mail'); + $delivery->setRecipientEnc('PRIVATE_RECIPIENT'); + return $delivery; + } + + public function testPublishedOutcomeUsesRootOfEnvelopeWithoutDisclosingRecipient(): void { + $this->deliveries->method('findById')->with(9)->willReturn($this->delivery()); + $child = new File(); + $child->setParentFileId(10); + $root = new File(); + $root->setUuid('root-uuid'); + $root->setNodeType('envelope'); + $this->files->method('getById')->willReturnMap([[25, $child], [10, $root]]); + $this->dispatcher->expects($this->once())->method('dispatchTyped') + ->with($this->callback(static function ($event): bool { + if (!$event instanceof NotificationDeliveryStatusChangedEvent) { + return false; + } + $payload = $event->getWebhookSerializable(); + return $payload['requestUuid'] === 'root-uuid' + && $payload['requestType'] === 'envelope' + && !str_contains(json_encode($payload), 'PRIVATE_RECIPIENT'); + })); + $this->publisher->publish(9); + } + + public function testPendingDeliveryCannotPublishAnOutcome(): void { + $this->deliveries->method('findById')->willReturn($this->delivery(NotificationDeliveryState::PENDING->value)); + $root = new File(); + $root->setUuid('root-uuid'); + $this->files->method('getById')->willReturn($root); + $this->dispatcher->expects($this->never())->method('dispatchTyped'); + $this->publisher->publish(9); + } + + public function testExpectedRepositoryFailureIsLoggedWithoutSensitiveData(): void { + $this->deliveries->method('findById') + ->willThrowException(new \RuntimeException('PRIVATE_RECIPIENT')); + $this->dispatcher->expects($this->never())->method('dispatchTyped'); + $this->logger->expects($this->once())->method('warning') + ->with($this->anything(), $this->callback(static function (array $context): bool { + return !str_contains(json_encode($context), 'PRIVATE_RECIPIENT') + && $context['deliveryId'] === 9; + })); + $this->publisher->publish(9); + } + + public function testProgrammingErrorIsNotSwallowed(): void { + $this->deliveries->method('findById')->willThrowException(new \TypeError('programming error')); + $this->expectException(\TypeError::class); + $this->publisher->publish(9); + } +} diff --git a/tests/php/Unit/Service/Notification/NotificationSubmissionServiceTest.php b/tests/php/Unit/Service/Notification/NotificationSubmissionServiceTest.php index 5ffae31b82..e8c98ee46d 100644 --- a/tests/php/Unit/Service/Notification/NotificationSubmissionServiceTest.php +++ b/tests/php/Unit/Service/Notification/NotificationSubmissionServiceTest.php @@ -9,7 +9,6 @@ namespace OCA\Libresign\Tests\Unit\Service\Notification; use OCA\Libresign\Db\File; -use OCA\Libresign\Db\FileMapper; use OCA\Libresign\Db\NotificationAttempt; use OCA\Libresign\Db\NotificationAttemptMapper; use OCA\Libresign\Db\NotificationDelivery; @@ -17,16 +16,15 @@ use OCA\Libresign\Db\SignRequest; use OCA\Libresign\Db\SignRequestMapper; use OCA\Libresign\Enum\NotificationDeliveryState; -use OCA\Libresign\Events\NotificationDeliveryStatusChangedEvent; use OCA\Libresign\Exception\NotificationPreparationException; use OCA\Libresign\Exception\NotificationTransportException; use OCA\Libresign\Service\Notification\MailPayload; use OCA\Libresign\Service\Notification\NotificationChannel; +use OCA\Libresign\Service\Notification\NotificationDeliveryEventPublisher; use OCA\Libresign\Service\Notification\NotificationFailureClassifier; use OCA\Libresign\Service\Notification\NotificationHistoryService; use OCA\Libresign\Service\Notification\NotificationMessage; use OCA\Libresign\Service\Notification\NotificationSubmissionService; -use OCP\EventDispatcher\IEventDispatcher; use OCP\IDBConnection; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; @@ -68,7 +66,7 @@ static function (?\DateTime $due) use ($expectRetry, $attemptNumber): bool { $db->expects($this->never())->method('rollBack'); $channel = $this->createMock(NotificationChannel::class); $channel->method('deliver')->willThrowException($failure); - $service = new NotificationSubmissionService($deliveries, $attempts, $db, new NotificationFailureClassifier(), new NotificationHistoryService($this->createMock(SignRequestMapper::class)), $this->createMock(LoggerInterface::class), $this->createMock(FileMapper::class), $this->createMock(IEventDispatcher::class)); + $service = new NotificationSubmissionService($deliveries, $attempts, $db, new NotificationFailureClassifier(), new NotificationHistoryService($this->createMock(SignRequestMapper::class)), $this->createMock(LoggerInterface::class), $this->createMock(NotificationDeliveryEventPublisher::class)); $this->expectException(get_class($failure)); $service->submit($delivery, $this->message(), $channel); } @@ -107,54 +105,54 @@ public function testNestedPreparationFailureCannotMakeTransportOutcomeSafe(): vo $this->executeFailure(new NotificationTransportException('synthetic uncertain outcome', NotificationDeliveryState::UNKNOWN, 'smtp_outcome_unknown', new NotificationPreparationException('preparation')), 1, NotificationDeliveryState::UNKNOWN, false); } - public function testAcceptedOutcomeWebhookIsDispatchedOnlyAfterLedgerCommit(): void { + public function testSuccessfulSubmissionPublishesAfterLedgerCommit(): void { $delivery = new NotificationDelivery(); $delivery->setId(9); - $delivery->setFileId(25); - $delivery->setChannel('mail'); - $delivery->setAttemptCount(1); - $persisted = new NotificationDelivery(); - $persisted->setId(9); - $persisted->setFileId(25); - $persisted->setChannel('mail'); - $persisted->setAttemptCount(1); - $persisted->setState(NotificationDeliveryState::ACCEPTED->value); $attempt = new NotificationAttempt(); $attempt->setId(28); $deliveries = $this->createMock(NotificationDeliveryMapper::class); - $deliveries->method('claim')->with(9)->willReturn(true); - $deliveries->method('findById')->with(9)->willReturn($persisted); + $deliveries->method('claim')->willReturn(true); $deliveries->expects($this->once())->method('finish')->with(9, NotificationDeliveryState::ACCEPTED, null); $attempts = $this->createMock(NotificationAttemptMapper::class); $attempts->method('begin')->willReturn($attempt); $attempts->expects($this->once())->method('finish')->with(28, NotificationDeliveryState::ACCEPTED, null); $db = $this->createMock(IDBConnection::class); - $committed = 0; - $db->expects($this->exactly(2))->method('commit')->willReturnCallback(static function () use (&$committed): void { - $committed++; + $commits = 0; + $db->method('commit')->willReturnCallback(static function () use (&$commits): void { + $commits++; }); - $root = new File(); - $root->setUuid('public-workflow-uuid'); - $files = $this->createMock(FileMapper::class); - $files->method('getById')->with(25)->willReturn($root); - $dispatcher = $this->createMock(IEventDispatcher::class); - $dispatcher->expects($this->once())->method('dispatchTyped')->with($this->callback( - static function ($event) use (&$committed): bool { - return $committed === 2 - && $event instanceof NotificationDeliveryStatusChangedEvent - && $event->getWebhookSerializable()['state'] === 'accepted' - && $event->getWebhookSerializable()['requestUuid'] === 'public-workflow-uuid'; - }, - )); + $publisher = $this->createMock(NotificationDeliveryEventPublisher::class); + $publisher->expects($this->once())->method('publish')->with(9) + ->willReturnCallback(function () use (&$commits): void { + $this->assertSame(2, $commits); + }); $channel = $this->createMock(NotificationChannel::class); $channel->expects($this->once())->method('deliver'); - $history = new NotificationHistoryService($this->createMock(SignRequestMapper::class)); $service = new NotificationSubmissionService( $deliveries, $attempts, $db, new NotificationFailureClassifier(), - $history, $this->createMock(LoggerInterface::class), $files, $dispatcher, + new NotificationHistoryService($this->createMock(SignRequestMapper::class)), + $this->createMock(LoggerInterface::class), $publisher, ); $this->assertTrue($service->submit($delivery, $this->message(), $channel)); } + public function testAlreadyClaimedDeliveryNeverSubmitsOrPublishes(): void { + $delivery = new NotificationDelivery(); + $delivery->setId(9); + $deliveries = $this->createMock(NotificationDeliveryMapper::class); + $deliveries->method('claim')->willReturn(false); + $channel = $this->createMock(NotificationChannel::class); + $channel->expects($this->never())->method('deliver'); + $publisher = $this->createMock(NotificationDeliveryEventPublisher::class); + $publisher->expects($this->never())->method('publish'); + $service = new NotificationSubmissionService( + $deliveries, $this->createMock(NotificationAttemptMapper::class), + $this->createMock(IDBConnection::class), new NotificationFailureClassifier(), + new NotificationHistoryService($this->createMock(SignRequestMapper::class)), + $this->createMock(LoggerInterface::class), $publisher, + ); + $this->assertFalse($service->submit($delivery, $this->message(), $channel)); + } + } diff --git a/tests/php/Unit/Service/NotificationDeliveryServiceTest.php b/tests/php/Unit/Service/NotificationDeliveryServiceTest.php index e0af462066..2e6bbff6f0 100644 --- a/tests/php/Unit/Service/NotificationDeliveryServiceTest.php +++ b/tests/php/Unit/Service/NotificationDeliveryServiceTest.php @@ -10,7 +10,6 @@ use OCA\Libresign\BackgroundJob\DeliverNotification; use OCA\Libresign\Db\File; -use OCA\Libresign\Db\FileMapper; use OCA\Libresign\Db\NotificationAttempt; use OCA\Libresign\Db\NotificationAttemptMapper; use OCA\Libresign\Db\NotificationDelivery; @@ -32,7 +31,6 @@ use OCA\Libresign\Service\NotificationDeliveryService; use OCA\Libresign\Service\Worker\WorkerActivationService; use OCP\BackgroundJob\IJobList; -use OCP\EventDispatcher\IEventDispatcher; use OCP\IConfig; use OCP\IDBConnection; use OCP\Notification\IManager; @@ -81,8 +79,7 @@ protected function setUp(): void { new NotificationFailureClassifier(), new NotificationHistoryService($this->createMock(\OCA\Libresign\Db\SignRequestMapper::class)), $this->createMock(LoggerInterface::class), - $this->createMock(FileMapper::class), - $this->createMock(IEventDispatcher::class), + $this->createMock(\OCA\Libresign\Service\Notification\NotificationDeliveryEventPublisher::class), ), new NotificationEnvelopeCodec($handoffCrypto, $this->createMock(IManager::class)), $this->mode, From 569f720234d32579b44e07ce7515808a5dfa1688 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Mon, 9 Nov 2026 18:07:43 +0000 Subject: [PATCH 05/23] fix: publish ready workflow events after signer persistence Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- lib/Service/FileStatusService.php | 15 +++---- lib/Service/RequestSignatureService.php | 41 ++++++++++++------- .../Unit/Service/FileStatusServiceTest.php | 11 +++++ .../Service/RequestSignatureServiceTest.php | 33 +++++++++++++++ 4 files changed, 76 insertions(+), 24 deletions(-) diff --git a/lib/Service/FileStatusService.php b/lib/Service/FileStatusService.php index 832bdd224b..6070e1cc71 100644 --- a/lib/Service/FileStatusService.php +++ b/lib/Service/FileStatusService.php @@ -28,7 +28,7 @@ public function __construct( ) { } - public function updateFileStatusIfUpgrade(FileEntity $file, int $newStatus): FileEntity { + public function updateFileStatusIfUpgrade(FileEntity $file, int $newStatus, bool $publishReady = true): FileEntity { $currentStatus = $file->getStatus(); if ($newStatus > $currentStatus) { $this->markPolicySnapshotFrozen($file, $newStatus); @@ -36,7 +36,9 @@ public function updateFileStatusIfUpgrade(FileEntity $file, int $newStatus): Fil $this->touchStatusChangedAt($file); $this->fileMapper->update($file); $this->statusCacheService->setStatus($file->getUuid(), $newStatus); - $this->dispatchReadyTransition($file, $currentStatus); + if ($publishReady && $currentStatus === FileStatus::DRAFT->value) { + $this->dispatchReadyRequest($file); + } if ($file->hasParent()) { $this->propagateStatusToParent($file->getParentFileId()); @@ -46,13 +48,8 @@ public function updateFileStatusIfUpgrade(FileEntity $file, int $newStatus): Fil return $file; } - /** Called after creating a ready request and persisting its signers. */ - public function dispatchCreatedReadyRequest(FileEntity $file): void { - $this->dispatchReadyTransition($file, FileStatus::DRAFT->value); - } - - private function dispatchReadyTransition(FileEntity $file, int $previousStatus): void { - $event = SigningRequestReadyEvent::fromTransition($file, $previousStatus); + public function dispatchReadyRequest(FileEntity $file): void { + $event = SigningRequestReadyEvent::fromTransition($file, FileStatus::DRAFT->value); if ($event !== null) { $this->eventDispatcher->dispatchTyped($event); } diff --git a/lib/Service/RequestSignatureService.php b/lib/Service/RequestSignatureService.php index 5e1f5df258..18017bd84b 100644 --- a/lib/Service/RequestSignatureService.php +++ b/lib/Service/RequestSignatureService.php @@ -139,8 +139,8 @@ public function saveFiles(array $data): array { } public function save(array $data): FileEntity { - $newlyCreated = false; - $file = $this->saveFile($data, $newlyCreated); + $becameReady = false; + $file = $this->saveFile($data, $becameReady); if (!isset($data['status'])) { $data['status'] = $file->getStatus(); } @@ -150,10 +150,10 @@ public function save(array $data): FileEntity { $this->propagateSignersToChildren($file, $data); $this->saveVisibleElements($data, $file); }, $this->db); - if ($newlyCreated) { - $this->fileStatusService->dispatchCreatedReadyRequest($file); - } $this->notifications->flushCommitted(); + if ($becameReady) { + $this->fileStatusService->dispatchReadyRequest($file); + } return $file; } @@ -227,15 +227,18 @@ public function saveEnvelope(array $data): array { }, $this->db); $this->notifications->flushCommitted(); } - - return [ - 'envelope' => $envelope, - 'files' => $files, - ]; } catch (\Throwable $e) { $this->rollbackEnvelopeCreation($envelope, $files, $createdNodes); throw $e; } + + if ($envelope->getStatus() === FileStatus::ABLE_TO_SIGN->value) { + $this->fileStatusService->dispatchReadyRequest($envelope); + } + return [ + 'envelope' => $envelope, + 'files' => $files, + ]; } private function processFileData(array $fileData, ?IUser $userManager, array $settings): Node { @@ -367,16 +370,20 @@ private function createFileForEnvelope( * uploadedFile?: array * } $data */ - public function saveFile(array $data, ?bool &$newlyCreated = null): FileEntity { - $newlyCreated = false; + public function saveFile(array $data, ?bool &$becameReady = null): FileEntity { + $becameReady = false; if (!empty($data['uuid'])) { $file = $this->fileMapper->getByUuid($data['uuid']); $this->filePolicyApplier->syncCoreFlowPolicies($file, $data); + $previousStatus = $file->getStatus(); if (!empty($data['name'])) { $file->setName($data['name']); $this->fileService->update($file); } - return $this->fileStatusService->updateFileStatusIfUpgrade($file, $data['status'] ?? 0); + $updated = $this->fileStatusService->updateFileStatusIfUpgrade($file, $data['status'] ?? 0, false); + $becameReady = $previousStatus === FileStatus::DRAFT->value + && $updated->getStatus() === FileStatus::ABLE_TO_SIGN->value; + return $updated; } $nodeId = null; if (isset($data['file']['fileNode']) && $data['file']['fileNode'] instanceof Node) { @@ -395,7 +402,11 @@ public function saveFile(array $data, ?bool &$newlyCreated = null): FileEntity { } if ($file !== null) { $this->filePolicyApplier->syncAllPolicies($file, $data); - return $this->fileStatusService->updateFileStatusIfUpgrade($file, $data['status'] ?? 0); + $previousStatus = $file->getStatus(); + $updated = $this->fileStatusService->updateFileStatusIfUpgrade($file, $data['status'] ?? 0, false); + $becameReady = $previousStatus === FileStatus::DRAFT->value + && $updated->getStatus() === FileStatus::ABLE_TO_SIGN->value; + return $updated; } } @@ -438,7 +449,7 @@ public function saveFile(array $data, ?bool &$newlyCreated = null): FileEntity { $this->filePolicyApplier->applyAll($file, $data); $this->fileMapper->insert($file); - $newlyCreated = true; + $becameReady = $file->getStatus() === FileStatus::ABLE_TO_SIGN->value; return $file; } diff --git a/tests/php/Unit/Service/FileStatusServiceTest.php b/tests/php/Unit/Service/FileStatusServiceTest.php index a8bbcac8a6..b262ebeac7 100644 --- a/tests/php/Unit/Service/FileStatusServiceTest.php +++ b/tests/php/Unit/Service/FileStatusServiceTest.php @@ -67,6 +67,17 @@ public function testReadyWebhookIsEmittedOnceForRootDraftTransition(): void { $this->service->updateFileStatusIfUpgrade($file, FileStatus::ABLE_TO_SIGN->value); } + public function testReadyEventCanBeDeferredUntilSignerPersistenceFinishes(): void { + $file = new FileEntity(); + $file->setId(11); + $file->setUuid('ready-uuid'); + $file->setStatus(FileStatus::DRAFT->value); + $this->service->updateFileStatusIfUpgrade($file, FileStatus::ABLE_TO_SIGN->value, false); + $this->eventDispatcher->expects($this->once())->method('dispatchTyped') + ->with($this->isInstanceOf(SigningRequestReadyEvent::class)); + $this->service->dispatchReadyRequest($file); + } + #[DataProvider('dataFileStatusUpgrade')] public function testUpdateFileStatusIfUpgrade(int $currentStatus, int $newStatus, bool $shouldUpdate): void { $file = new FileEntity(); diff --git a/tests/php/Unit/Service/RequestSignatureServiceTest.php b/tests/php/Unit/Service/RequestSignatureServiceTest.php index 7af9e9f6de..b1ff72a24e 100644 --- a/tests/php/Unit/Service/RequestSignatureServiceTest.php +++ b/tests/php/Unit/Service/RequestSignatureServiceTest.php @@ -318,6 +318,39 @@ public function testANewRequestCreatedReadyToSignStartsWithItsPolicySnapshotFroz $this->assertSame(['freeze:' . \OCA\Libresign\Enum\FileStatus::ABLE_TO_SIGN->value, 'insert'], $calls); } + public function testReadyRequestEventIsPublishedAfterSignerTransaction(): void { + $file = new \OCA\Libresign\Db\File(); + $file->setUuid('ready-uuid'); + $file->setStatus(\OCA\Libresign\Enum\FileStatus::ABLE_TO_SIGN->value); + $service = $this->getService(['saveFile']); + $service->method('saveFile')->willReturnCallback( + static function (array $data, ?bool &$becameReady) use ($file): \OCA\Libresign\Db\File { + $becameReady = true; + return $file; + }, + ); + $this->fileStatusService->expects($this->once())->method('dispatchReadyRequest')->with($file); + $this->assertSame($file, $service->save(['status' => $file->getStatus()])); + } + + public function testReadyRequestEventIsNotPublishedWhenSignerPersistenceFails(): void { + $file = new \OCA\Libresign\Db\File(); + $file->setUuid('ready-uuid'); + $file->setStatus(\OCA\Libresign\Enum\FileStatus::ABLE_TO_SIGN->value); + $service = $this->getService(['saveFile']); + $service->method('saveFile')->willReturnCallback( + static function (array $data, ?bool &$becameReady) use ($file): \OCA\Libresign\Db\File { + $becameReady = true; + return $file; + }, + ); + $this->signerValidator->method('normalizeRequestSigners') + ->willThrowException(new \RuntimeException('invalid signer')); + $this->fileStatusService->expects($this->never())->method('dispatchReadyRequest'); + $this->expectException(\RuntimeException::class); + $service->save(['status' => $file->getStatus(), 'signers' => [['identifyMethods' => []]]]); + } + public function testSaveFilesUsesSaveForSingleFile(): void { $service = $this->getService(['save']); From 1dd4f1d47788ebb1e6bc218589cb8f3d4d0146f6 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Mon, 9 Nov 2026 18:08:02 +0000 Subject: [PATCH 06/23] refactor: narrow rejection error handling and isolate event failures Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- .../SignatureRejectionService.php | 77 +++++++++++-------- .../SignatureRejectionServiceTest.php | 50 ++++++++++++ 2 files changed, 97 insertions(+), 30 deletions(-) diff --git a/lib/Service/SignatureRejection/SignatureRejectionService.php b/lib/Service/SignatureRejection/SignatureRejectionService.php index 70f086a14a..d8562e8285 100644 --- a/lib/Service/SignatureRejection/SignatureRejectionService.php +++ b/lib/Service/SignatureRejection/SignatureRejectionService.php @@ -24,6 +24,7 @@ use OCA\Libresign\Service\FileStatusService; use OCA\Libresign\Service\IdentifyMethodService; use OCA\Libresign\Service\SequentialSigningService; +use OCP\AppFramework\Db\DoesNotExistException; use OCP\AppFramework\Utility\ITimeFactory; use OCP\EventDispatcher\IEventDispatcher; use OCP\IDBConnection; @@ -144,16 +145,18 @@ private function persistRejection( } $this->db->commit(); - } catch (\Throwable $e) { - $this->db->rollBack(); - $this->restoreState($libreSignFile, $signRequests, $previousSignerStatuses, $previousFileStatus); - $this->logger->error('Failed to register the signature rejection: ' . $e->getMessage(), [ - 'exception' => $e, + } catch (\Exception $e) { + $this->rollBackRejection($libreSignFile, $signRequests, $previousSignerStatuses, $previousFileStatus); + $this->logger->error('Failed to register the signature rejection', [ + 'errorType' => get_debug_type($e), 'signRequestId' => $signRequest->getId(), ]); // TRANSLATORS Error shown when the rejection could not be saved and nothing was changed. throw new LibresignException($this->l10n->t('It was not possible to register the rejection. Nothing was changed.')); + } catch (\Error $e) { + $this->rollBackRejection($libreSignFile, $signRequests, $previousSignerStatuses, $previousFileStatus); + throw $e; } return $activatedSigners; @@ -188,8 +191,7 @@ private function collectSignRequestsToReject(FileEntity $libreSignFile, SignRequ $envelopeId, ); $collected[$envelopeSignRequest->getId()] ??= $envelopeSignRequest; - } catch (\Throwable) { - // The envelope itself carries no signature request for this signer. + } catch (DoesNotExistException) { } // A document this signer already signed keeps its signature. @@ -293,6 +295,16 @@ private function cancelWorkflow(FileEntity $libreSignFile): void { * @param list $signRequests * @param list $previousSignerStatuses */ + private function rollBackRejection( + FileEntity $file, + array $signRequests, + array $previousSignerStatuses, + int $previousFileStatus, + ): void { + $this->db->rollBack(); + $this->restoreState($file, $signRequests, $previousSignerStatuses, $previousFileStatus); + } + private function restoreState( FileEntity $libreSignFile, array $signRequests, @@ -370,33 +382,36 @@ private function dispatchPublicRejectionEvents( SignRequestEntity $signer, int $previousRootStatus, ): void { - // Signing-state transactions have committed. A webhook scheduling failure - // must not undo a persisted rejection. try { $root = $document->hasParent() ? $this->fileMapper->getById($document->getParentFileId()) : $document; - $rejected = SignerRejectedWebhookEvent::afterRejection( - $root, $document, $signer, $this->isWorkflowCanceled($root), - ); - if ($rejected !== null) { - $this->eventDispatcher->dispatchTyped($rejected); - } - $canceled = SigningRequestCanceledEvent::fromTransition($root, $previousRootStatus); - if ($canceled !== null) { - $this->eventDispatcher->dispatchTyped($canceled); - } - // Under a continue-on-rejection policy, the final rejection may - // finish a workflow that already contains a valid signature. - $completed = SigningRequestCompletedEvent::fromTransition($root, $previousRootStatus); - if ($completed !== null) { - $this->eventDispatcher->dispatchTyped($completed); - } - } catch (\Throwable $e) { - $this->logger->error('Unable to enqueue LibreSign rejection webhook', [ - 'exception' => $e, + $events = [ + SignerRejectedWebhookEvent::afterRejection($root, $document, $signer, $this->isWorkflowCanceled($root)), + SigningRequestCanceledEvent::fromTransition($root, $previousRootStatus), + SigningRequestCompletedEvent::fromTransition($root, $previousRootStatus), + ]; + } catch (\Exception $e) { + $this->logger->warning('Unable to prepare LibreSign rejection events', [ 'fileId' => $document->getId(), + 'errorType' => get_debug_type($e), ]); + return; + } + + foreach ($events as $event) { + if ($event === null) { + continue; + } + try { + $this->eventDispatcher->dispatchTyped($event); + } catch (\Exception $e) { + $this->logger->warning('Unable to publish LibreSign rejection event', [ + 'fileId' => $document->getId(), + 'eventType' => $event::class, + 'errorType' => get_debug_type($e), + ]); + } } } @@ -419,8 +434,10 @@ private function dispatchRejectedEvent( )); } } - } catch (\Throwable $e) { - $this->logger->error('Error dispatching SignatureRejectedEvent: ' . $e->getMessage(), ['exception' => $e]); + } catch (\Exception $e) { + $this->logger->error('Error dispatching SignatureRejectedEvent', [ + 'errorType' => get_debug_type($e), + ]); } } } diff --git a/tests/php/Unit/Service/SignatureRejection/SignatureRejectionServiceTest.php b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionServiceTest.php index 74c66c3533..aa801dd53c 100644 --- a/tests/php/Unit/Service/SignatureRejection/SignatureRejectionServiceTest.php +++ b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionServiceTest.php @@ -316,6 +316,56 @@ public static function publicRejectionOutcomes(): array { ]; } + public function testProgrammingErrorDuringRejectionRollsBackAndRemainsVisible(): void { + $this->withPolicy(self::policy('cancel')); + $signer = $this->signRequest(); + $this->signRequestMapper->method('update') + ->willThrowException(new \TypeError('programming error')); + $this->db->expects($this->once())->method('rollBack'); + $this->db->expects($this->never())->method('commit'); + $this->eventDispatcher->expects($this->never())->method('dispatchTyped'); + $this->expectException(\TypeError::class); + try { + $this->getService()->reject($this->file(), $signer); + } finally { + $this->assertSame(SignRequestStatus::ABLE_TO_SIGN, $signer->getStatusEnum()); + } + } + + public function testFailedPublicRejectionEventDoesNotSuppressCancellationEvent(): void { + $this->withPolicy(self::policy('cancel')); + $file = $this->file(); + $file->setUuid('workflow-uuid'); + $signer = $this->signRequest(); + $events = []; + $this->eventDispatcher->method('dispatchTyped')->willReturnCallback( + static function ($event) use (&$events): void { + $events[] = $event; + if ($event instanceof SignerRejectedWebhookEvent) { + throw new \RuntimeException('private recipient information'); + } + }, + ); + $this->logger->expects($this->once())->method('warning') + ->with($this->anything(), $this->callback(static function (array $context): bool { + return $context['errorType'] === 'RuntimeException' + && !str_contains(json_encode($context), 'private recipient information'); + })); + $this->getService()->reject($file, $signer); + $this->assertCount(1, array_filter($events, static fn ($event): bool => $event instanceof SigningRequestCanceledEvent)); + } + + public function testProgrammingErrorDuringPublicEventDispatchIsNotSuppressed(): void { + $this->withPolicy(self::policy('cancel')); + $file = $this->file(); + $file->setUuid('workflow-uuid'); + $this->db->expects($this->once())->method('commit'); + $this->db->expects($this->never())->method('rollBack'); + $this->eventDispatcher->method('dispatchTyped')->willThrowException(new \TypeError('programming error')); + $this->expectException(\TypeError::class); + $this->getService()->reject($file, $this->signRequest()); + } + public function testRejectionCanCompletePreviouslySignedWorkflow(): void { $this->withPolicy(self::policy('continue')); $file = $this->file(FileStatus::PARTIAL_SIGNED->value); From 1f04265fc75190c1b0da0a51dbe4537e6b8e7378 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Tue, 10 Nov 2026 01:30:16 +0000 Subject: [PATCH 07/23] test: verify notification outcomes through persisted ledger Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- .../NotificationDeliveryServiceTest.php | 67 +++++++++++++++++++ .../NotificationSubmissionServiceTest.php | 18 ++--- 2 files changed, 72 insertions(+), 13 deletions(-) diff --git a/tests/php/Integration/Service/NotificationDeliveryServiceTest.php b/tests/php/Integration/Service/NotificationDeliveryServiceTest.php index 439efad08b..ce25508582 100644 --- a/tests/php/Integration/Service/NotificationDeliveryServiceTest.php +++ b/tests/php/Integration/Service/NotificationDeliveryServiceTest.php @@ -10,18 +10,23 @@ use OCA\Libresign\BackgroundJob\DeliverNotification; use OCA\Libresign\Db\File; +use OCA\Libresign\Db\FileMapper; use OCA\Libresign\Db\NotificationAttemptMapper; use OCA\Libresign\Db\NotificationDeliveryMapper; use OCA\Libresign\Db\SignRequest; +use OCA\Libresign\Enum\FileStatus; use OCA\Libresign\Enum\NotificationDeliveryState; +use OCA\Libresign\Events\NotificationDeliveryStatusChangedEvent; use OCA\Libresign\Exception\MailTransportException; use OCA\Libresign\Service\Notification\GatewayPayload; use OCA\Libresign\Service\Notification\MailPayload; use OCA\Libresign\Service\Notification\NotificationChannel; use OCA\Libresign\Service\Notification\NotificationMessage; +use OCA\Libresign\Service\Notification\NotificationSubmissionService; use OCA\Libresign\Service\NotificationDeliveryService; use OCP\AppFramework\Db\DoesNotExistException; use OCP\BackgroundJob\IJobList; +use OCP\EventDispatcher\IEventDispatcher; use OCP\IDBConnection; use OCP\Server; @@ -180,6 +185,68 @@ public function testRealDatabaseMakesOneSmtpSubmissionAndRecordsAcceptance(): vo $this->assertSame(NotificationDeliveryState::ACCEPTED->value, $attempts[0]->getState()); } + public function testSubmittedOutcomeEventReflectsCommittedLedgerWithoutRecipientData(): void { + $fileMapper = Server::get(FileMapper::class); + $file = new File(); + $file->setUuid('notification-workflow-' . bin2hex(random_bytes(12))); + $file->setNodeId(random_int(1000000, 1999999)); + $file->setUserId('synthetic-owner'); + $file->setName('notification-contract.pdf'); + $file->setCreatedAt(new \DateTime('now', new \DateTimeZone('UTC'))); + $file->setStatus(FileStatus::ABLE_TO_SIGN->value); + $file = $fileMapper->insert($file); + + $source = 'committed-event-' . bin2hex(random_bytes(10)); + $key = hash('sha256', 'outcome-' . $source); + $dispatcher = Server::get(IEventDispatcher::class); + $db = Server::get(IDBConnection::class); + $observed = []; + $listener = function (NotificationDeliveryStatusChangedEvent $event) use (&$observed, $db, $key): void { + $delivery = $this->deliveries->findByEventKey($key); + $attempts = $this->attempts->findForDelivery($delivery->getId()); + $observed[] = [ + 'inTransaction' => $db->inTransaction(), + 'ledgerState' => $delivery->getState(), + 'attemptStates' => array_map(static fn ($attempt): string => $attempt->getState(), $attempts), + 'payload' => $event->getWebhookSerializable(), + ]; + }; + $dispatcher->addListener(NotificationDeliveryStatusChangedEvent::class, $listener); + + try { + $delivery = $this->deliveries->register( + $key, hash('sha256', 'correlation-' . $source), 'sign_request', 'mail', + $file->getId(), null, 'synthetic-owner', 'PRIVATE_ENCRYPTED_RECIPIENT', + ); + $this->keys[] = $key; + $channel = new class implements NotificationChannel { + public function supports(string $channel): bool { + return $channel === 'mail'; + } + public function deliver(NotificationMessage $message): void { + } + }; + $this->assertTrue(Server::get(NotificationSubmissionService::class)->submit( + $delivery, + new NotificationMessage($source, 'sign_request', 'mail', $file, $this->request(), 'synthetic@example.invalid', new MailPayload()), + $channel, + )); + $this->assertCount(1, $observed); + $this->assertFalse($observed[0]['inTransaction']); + $this->assertSame(NotificationDeliveryState::ACCEPTED->value, $observed[0]['ledgerState']); + $this->assertSame([NotificationDeliveryState::ACCEPTED->value], $observed[0]['attemptStates']); + $this->assertSame($file->getUuid(), $observed[0]['payload']['requestUuid']); + $this->assertSame(NotificationDeliveryState::ACCEPTED->value, $observed[0]['payload']['state']); + $this->assertSame(1, $observed[0]['payload']['attempt']); + $serialized = json_encode($observed[0]['payload'], JSON_THROW_ON_ERROR); + $this->assertStringNotContainsString('synthetic@example.invalid', $serialized); + $this->assertStringNotContainsString('PRIVATE_ENCRYPTED_RECIPIENT', $serialized); + } finally { + $dispatcher->removeListener(NotificationDeliveryStatusChangedEvent::class, $listener); + $fileMapper->delete($file); + } + } + public function testAmbiguousSubmissionNeverRetriesEvenWhenEventReplayed(): void { $source = 'integration-unknown-' . bin2hex(random_bytes(8)); $key = $this->recordKey(101, 201, $source); diff --git a/tests/php/Unit/Service/Notification/NotificationSubmissionServiceTest.php b/tests/php/Unit/Service/Notification/NotificationSubmissionServiceTest.php index e8c98ee46d..0f21d47fac 100644 --- a/tests/php/Unit/Service/Notification/NotificationSubmissionServiceTest.php +++ b/tests/php/Unit/Service/Notification/NotificationSubmissionServiceTest.php @@ -105,7 +105,7 @@ public function testNestedPreparationFailureCannotMakeTransportOutcomeSafe(): vo $this->executeFailure(new NotificationTransportException('synthetic uncertain outcome', NotificationDeliveryState::UNKNOWN, 'smtp_outcome_unknown', new NotificationPreparationException('preparation')), 1, NotificationDeliveryState::UNKNOWN, false); } - public function testSuccessfulSubmissionPublishesAfterLedgerCommit(): void { + public function testSuccessfulSubmissionRequestsOutcomePublication(): void { $delivery = new NotificationDelivery(); $delivery->setId(9); $attempt = new NotificationAttempt(); @@ -113,27 +113,19 @@ public function testSuccessfulSubmissionPublishesAfterLedgerCommit(): void { $deliveries = $this->createMock(NotificationDeliveryMapper::class); $deliveries->method('claim')->willReturn(true); - $deliveries->expects($this->once())->method('finish')->with(9, NotificationDeliveryState::ACCEPTED, null); $attempts = $this->createMock(NotificationAttemptMapper::class); $attempts->method('begin')->willReturn($attempt); - $attempts->expects($this->once())->method('finish')->with(28, NotificationDeliveryState::ACCEPTED, null); - $db = $this->createMock(IDBConnection::class); - $commits = 0; - $db->method('commit')->willReturnCallback(static function () use (&$commits): void { - $commits++; - }); $publisher = $this->createMock(NotificationDeliveryEventPublisher::class); - $publisher->expects($this->once())->method('publish')->with(9) - ->willReturnCallback(function () use (&$commits): void { - $this->assertSame(2, $commits); - }); + $publisher->expects($this->once())->method('publish')->with(9); $channel = $this->createMock(NotificationChannel::class); $channel->expects($this->once())->method('deliver'); + $service = new NotificationSubmissionService( - $deliveries, $attempts, $db, new NotificationFailureClassifier(), + $deliveries, $attempts, $this->createMock(IDBConnection::class), new NotificationFailureClassifier(), new NotificationHistoryService($this->createMock(SignRequestMapper::class)), $this->createMock(LoggerInterface::class), $publisher, ); + $this->assertTrue($service->submit($delivery, $this->message(), $channel)); } From 2a149945a0e3f1ae2583714c5d4b2100e13ac93a Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Tue, 10 Nov 2026 01:35:56 +0000 Subject: [PATCH 08/23] test: keep notification workflow fixture UUID within SQL schema Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- .../php/Integration/Service/NotificationDeliveryServiceTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/php/Integration/Service/NotificationDeliveryServiceTest.php b/tests/php/Integration/Service/NotificationDeliveryServiceTest.php index ce25508582..926af12a62 100644 --- a/tests/php/Integration/Service/NotificationDeliveryServiceTest.php +++ b/tests/php/Integration/Service/NotificationDeliveryServiceTest.php @@ -188,7 +188,7 @@ public function testRealDatabaseMakesOneSmtpSubmissionAndRecordsAcceptance(): vo public function testSubmittedOutcomeEventReflectsCommittedLedgerWithoutRecipientData(): void { $fileMapper = Server::get(FileMapper::class); $file = new File(); - $file->setUuid('notification-workflow-' . bin2hex(random_bytes(12))); + $file->setUuid(bin2hex(random_bytes(16))); $file->setNodeId(random_int(1000000, 1999999)); $file->setUserId('synthetic-owner'); $file->setName('notification-contract.pdf'); From 0db6c0e5419707e864a15ab3a7f67e2346773bef Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Tue, 10 Nov 2026 23:13:44 +0000 Subject: [PATCH 09/23] fix: isolate native signed events from legacy listener failures Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- lib/Service/SignFileService.php | 39 ++++++++++----- .../php/Unit/Service/SignFileServiceTest.php | 50 +++++++++++++++++++ 2 files changed, 77 insertions(+), 12 deletions(-) diff --git a/lib/Service/SignFileService.php b/lib/Service/SignFileService.php index 7a7395955d..71e6602a04 100644 --- a/lib/Service/SignFileService.php +++ b/lib/Service/SignFileService.php @@ -1011,18 +1011,33 @@ protected function dispatchSignedEvent(): void { } } - $event = $this->signedEventFactory->make( - $this->signRequest, - $this->libreSignFile, - $this->getEngine()->getInputFile(), - $this->signWithoutPassword, - $certificateSerialNumber, - ); - $this->eventDispatcher->dispatchTyped($event); - $root = $this->getCompletionTarget($this->libreSignFile); - $publicEvent = SignerSignedWebhookEvent::afterSigning($root, $this->libreSignFile, $this->signRequest); - if ($publicEvent !== null) { - $this->eventDispatcher->dispatchTyped($publicEvent); + try { + $event = $this->signedEventFactory->make( + $this->signRequest, + $this->libreSignFile, + $this->getEngine()->getInputFile(), + $this->signWithoutPassword, + $certificateSerialNumber, + ); + $this->eventDispatcher->dispatchTyped($event); + } catch (\Exception $e) { + $this->logger->warning('Unable to dispatch legacy signed event', [ + 'signRequestId' => $this->signRequest->getId(), + 'errorType' => get_debug_type($e), + ]); + } + + try { + $root = $this->getCompletionTarget($this->libreSignFile); + $publicEvent = SignerSignedWebhookEvent::afterSigning($root, $this->libreSignFile, $this->signRequest); + if ($publicEvent !== null) { + $this->eventDispatcher->dispatchTyped($publicEvent); + } + } catch (\Exception $e) { + $this->logger->warning('Unable to dispatch signer signed webhook event', [ + 'signRequestId' => $this->signRequest->getId(), + 'errorType' => get_debug_type($e), + ]); } } diff --git a/tests/php/Unit/Service/SignFileServiceTest.php b/tests/php/Unit/Service/SignFileServiceTest.php index 9da9d45bc3..cdf8156642 100644 --- a/tests/php/Unit/Service/SignFileServiceTest.php +++ b/tests/php/Unit/Service/SignFileServiceTest.php @@ -30,6 +30,7 @@ use OCA\Libresign\Enum\SignRequestStatus; use OCA\Libresign\Events\SignedEvent; use OCA\Libresign\Events\SignedEventFactory; +use OCA\Libresign\Events\SignerSignedWebhookEvent; use OCA\Libresign\Events\SigningRequestCompletedEvent; use OCA\Libresign\Exception\LibresignException; use OCA\Libresign\Handler\DocMdpHandler; @@ -878,6 +879,55 @@ public function testNativeWebhookOnlyForCompletedDocumentWorkflow(?int $id, File )); } + public function testLegacyListenerFailureDoesNotSuppressNativeSigningEvent(): void { + $service = $this->getService([ + 'getEngine', 'computeHash', 'validateDocMdpAllowsSignatures', + 'updateSignRequest', 'updateLibreSignFile', + ]); + $file = new File(); + $file->setId(17); + $file->setUuid('document-uuid'); + $file->setStatus(FileStatus::ABLE_TO_SIGN->value); + $signer = new SignRequest(); + $signer->setId(31); + $signer->setSigned(new DateTime('2026-11-09T11:00:00Z')); + $signer->setSignedHash('signed-content-hash'); + + $signedFile = $this->createMock(\OCP\Files\File::class); + $signedFile->method('getId')->willReturn(123); + $engine = $this->createMock(Pkcs12Handler::class); + $engine->method('sign')->willReturn($signedFile); + $engine->method('getInputFile')->willReturn($signedFile); + $service->method('getEngine')->willReturn($engine); + $service->method('computeHash')->willReturn('signed-content-hash'); + $this->fileMapper->method('getById')->willReturn($file); + $this->signedEventFactory->method('make')->willReturn($this->createMock(SignedEvent::class)); + + $events = []; + $this->eventDispatcher->method('dispatchTyped')->willReturnCallback( + static function ($event) use (&$events): void { + $events[] = $event; + if ($event instanceof SignedEvent) { + throw new \RuntimeException('private callback details'); + } + }, + ); + $this->logger->expects($this->once())->method('warning') + ->with('Unable to dispatch legacy signed event', $this->callback( + static fn (array $context): bool => $context['errorType'] === 'RuntimeException' + && !str_contains(json_encode($context), 'private callback details'), + )); + + $service->signSingleFile($file, $signer); + + $published = array_values(array_filter( + $events, + static fn ($event): bool => $event instanceof SignerSignedWebhookEvent, + )); + $this->assertCount(1, $published); + $this->assertSame('document-uuid', $published[0]->getWebhookSerializable()['requestUuid']); + } + public function testUpdateEnvelopeStatusAddsStatusChangedAt(): void { $service = $this->getService(); From ff9311f57d8c123b0d733f258fd70b96bd5506e2 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Tue, 10 Nov 2026 23:20:00 +0000 Subject: [PATCH 10/23] refactor: publish ready events after atomic signer persistence Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- lib/Service/FileStatusService.php | 9 +-- lib/Service/RequestSignatureService.php | 52 ++++++++------ .../Unit/Service/FileStatusServiceTest.php | 22 +++--- .../Service/RequestSignatureServiceTest.php | 67 +++++++++++++------ 4 files changed, 89 insertions(+), 61 deletions(-) diff --git a/lib/Service/FileStatusService.php b/lib/Service/FileStatusService.php index 6070e1cc71..4ce9e6e834 100644 --- a/lib/Service/FileStatusService.php +++ b/lib/Service/FileStatusService.php @@ -28,18 +28,13 @@ public function __construct( ) { } - public function updateFileStatusIfUpgrade(FileEntity $file, int $newStatus, bool $publishReady = true): FileEntity { - $currentStatus = $file->getStatus(); - if ($newStatus > $currentStatus) { + public function updateFileStatusIfUpgrade(FileEntity $file, int $newStatus): FileEntity { + if ($newStatus > $file->getStatus()) { $this->markPolicySnapshotFrozen($file, $newStatus); $file->setStatus($newStatus); $this->touchStatusChangedAt($file); $this->fileMapper->update($file); $this->statusCacheService->setStatus($file->getUuid(), $newStatus); - if ($publishReady && $currentStatus === FileStatus::DRAFT->value) { - $this->dispatchReadyRequest($file); - } - if ($file->hasParent()) { $this->propagateStatusToParent($file->getParentFileId()); } diff --git a/lib/Service/RequestSignatureService.php b/lib/Service/RequestSignatureService.php index 18017bd84b..6f2d0c6eb6 100644 --- a/lib/Service/RequestSignatureService.php +++ b/lib/Service/RequestSignatureService.php @@ -139,23 +139,23 @@ public function saveFiles(array $data): array { } public function save(array $data): FileEntity { - $becameReady = false; - $file = $this->saveFile($data, $becameReady); - if (!isset($data['status'])) { - $data['status'] = $file->getStatus(); - } - $this->atomic(function () use ($file, $data): void { + $result = $this->atomic(function () use ($data): array { + $result = $this->persistFile($data); + $file = $result['file']; + $data['status'] ??= $file->getStatus(); $this->sequentialSigningService->setFile($file); $this->associateToSigners($data, $file); $this->propagateSignersToChildren($file, $data); $this->saveVisibleElements($data, $file); + return $result; }, $this->db); + $this->notifications->flushCommitted(); - if ($becameReady) { - $this->fileStatusService->dispatchReadyRequest($file); + if ($result['becameReady']) { + $this->fileStatusService->dispatchReadyRequest($result['file']); } - return $file; + return $result['file']; } private function propagateSignersToChildren(FileEntity $envelope, array $data): void { @@ -370,8 +370,12 @@ private function createFileForEnvelope( * uploadedFile?: array * } $data */ - public function saveFile(array $data, ?bool &$becameReady = null): FileEntity { - $becameReady = false; + public function saveFile(array $data): FileEntity { + return $this->persistFile($data)['file']; + } + + /** @return array{file: FileEntity, becameReady: bool} */ + private function persistFile(array $data): array { if (!empty($data['uuid'])) { $file = $this->fileMapper->getByUuid($data['uuid']); $this->filePolicyApplier->syncCoreFlowPolicies($file, $data); @@ -380,10 +384,12 @@ public function saveFile(array $data, ?bool &$becameReady = null): FileEntity { $file->setName($data['name']); $this->fileService->update($file); } - $updated = $this->fileStatusService->updateFileStatusIfUpgrade($file, $data['status'] ?? 0, false); - $becameReady = $previousStatus === FileStatus::DRAFT->value - && $updated->getStatus() === FileStatus::ABLE_TO_SIGN->value; - return $updated; + $updated = $this->fileStatusService->updateFileStatusIfUpgrade($file, $data['status'] ?? 0); + return [ + 'file' => $updated, + 'becameReady' => $previousStatus === FileStatus::DRAFT->value + && $updated->getStatus() === FileStatus::ABLE_TO_SIGN->value, + ]; } $nodeId = null; if (isset($data['file']['fileNode']) && $data['file']['fileNode'] instanceof Node) { @@ -403,10 +409,12 @@ public function saveFile(array $data, ?bool &$becameReady = null): FileEntity { if ($file !== null) { $this->filePolicyApplier->syncAllPolicies($file, $data); $previousStatus = $file->getStatus(); - $updated = $this->fileStatusService->updateFileStatusIfUpgrade($file, $data['status'] ?? 0, false); - $becameReady = $previousStatus === FileStatus::DRAFT->value - && $updated->getStatus() === FileStatus::ABLE_TO_SIGN->value; - return $updated; + $updated = $this->fileStatusService->updateFileStatusIfUpgrade($file, $data['status'] ?? 0); + return [ + 'file' => $updated, + 'becameReady' => $previousStatus === FileStatus::DRAFT->value + && $updated->getStatus() === FileStatus::ABLE_TO_SIGN->value, + ]; } } @@ -449,8 +457,10 @@ public function saveFile(array $data, ?bool &$becameReady = null): FileEntity { $this->filePolicyApplier->applyAll($file, $data); $this->fileMapper->insert($file); - $becameReady = $file->getStatus() === FileStatus::ABLE_TO_SIGN->value; - return $file; + return [ + 'file' => $file, + 'becameReady' => !$file->hasParent() && $file->getStatus() === FileStatus::ABLE_TO_SIGN->value, + ]; } private function getFileMetadata(\OCP\Files\Node $node): array { diff --git a/tests/php/Unit/Service/FileStatusServiceTest.php b/tests/php/Unit/Service/FileStatusServiceTest.php index b262ebeac7..d3efe3b272 100644 --- a/tests/php/Unit/Service/FileStatusServiceTest.php +++ b/tests/php/Unit/Service/FileStatusServiceTest.php @@ -53,28 +53,28 @@ public function testCommittedEnqueueDoesNotOverwriteNewerSigningProgress(): void $this->service->onQueuedJobCommitted($file); } - public function testReadyWebhookIsEmittedOnceForRootDraftTransition(): void { + public function testStatusPersistenceDoesNotPublishBeforeSignerTransactionCommits(): void { $file = new FileEntity(); $file->setId(11); $file->setUuid('ready-uuid'); $file->setStatus(FileStatus::DRAFT->value); - $this->eventDispatcher->expects($this->once())->method('dispatchTyped') - ->with($this->callback(static function ($event): bool { - return $event instanceof SigningRequestReadyEvent - && $event->getWebhookSerializable()['status'] === 'ready_to_sign'; - })); - $this->service->updateFileStatusIfUpgrade($file, FileStatus::ABLE_TO_SIGN->value); + $this->eventDispatcher->expects($this->never())->method('dispatchTyped'); + $this->service->updateFileStatusIfUpgrade($file, FileStatus::ABLE_TO_SIGN->value); + + $this->assertSame(FileStatus::ABLE_TO_SIGN->value, $file->getStatus()); } - public function testReadyEventCanBeDeferredUntilSignerPersistenceFinishes(): void { + public function testReadyEventIsPublishedWhenExplicitlyRequestedAfterPersistence(): void { $file = new FileEntity(); $file->setId(11); $file->setUuid('ready-uuid'); - $file->setStatus(FileStatus::DRAFT->value); - $this->service->updateFileStatusIfUpgrade($file, FileStatus::ABLE_TO_SIGN->value, false); + $file->setStatus(FileStatus::ABLE_TO_SIGN->value); $this->eventDispatcher->expects($this->once())->method('dispatchTyped') - ->with($this->isInstanceOf(SigningRequestReadyEvent::class)); + ->with($this->callback(static function ($event): bool { + return $event instanceof SigningRequestReadyEvent + && $event->getWebhookSerializable()['status'] === 'ready_to_sign'; + })); $this->service->dispatchReadyRequest($file); } diff --git a/tests/php/Unit/Service/RequestSignatureServiceTest.php b/tests/php/Unit/Service/RequestSignatureServiceTest.php index b1ff72a24e..f744d7fd0b 100644 --- a/tests/php/Unit/Service/RequestSignatureServiceTest.php +++ b/tests/php/Unit/Service/RequestSignatureServiceTest.php @@ -85,6 +85,8 @@ final class RequestSignatureServiceTest extends \OCA\Libresign\Tests\Unit\TestCa private SignRequestService&MockObject $signRequestService; private FilePolicyApplier&MockObject $filePolicyApplier; private SignerGeolocationPolicyService&MockObject $signerGeolocationPolicyService; + private \OCP\IDBConnection&MockObject $db; + private \OCA\Libresign\Service\NotificationDeliveryService&MockObject $notifications; public function setUp(): void { parent::setUp(); @@ -123,6 +125,8 @@ public function setUp(): void { $this->signRequestService = $this->createMock(SignRequestService::class); $this->filePolicyApplier = $this->createMock(FilePolicyApplier::class); $this->signerGeolocationPolicyService = $this->createMock(SignerGeolocationPolicyService::class); + $this->db = $this->createMock(\OCP\IDBConnection::class); + $this->notifications = $this->createMock(\OCA\Libresign\Service\NotificationDeliveryService::class); } private function getService(array $methods = []): RequestSignatureService|MockObject { @@ -158,8 +162,8 @@ private function getService(array $methods = []): RequestSignatureService|MockOb $this->filePolicyApplier, $this->signerGeolocationPolicyService, $this->signerRemovalService, - $this->createMock(\OCP\IDBConnection::class), - $this->createMock(\OCA\Libresign\Service\NotificationDeliveryService::class), + $this->db, + $this->notifications, ]) ->onlyMethods($methods) ->getMock(); @@ -195,8 +199,8 @@ private function getService(array $methods = []): RequestSignatureService|MockOb $this->filePolicyApplier, $this->signerGeolocationPolicyService, $this->signerRemovalService, - $this->createMock(\OCP\IDBConnection::class), - $this->createMock(\OCA\Libresign\Service\NotificationDeliveryService::class), + $this->db, + $this->notifications, ); } @@ -318,37 +322,56 @@ public function testANewRequestCreatedReadyToSignStartsWithItsPolicySnapshotFroz $this->assertSame(['freeze:' . \OCA\Libresign\Enum\FileStatus::ABLE_TO_SIGN->value, 'insert'], $calls); } - public function testReadyRequestEventIsPublishedAfterSignerTransaction(): void { + public function testReadyRequestEventIsPublishedOnlyAfterSignerTransactionCommits(): void { $file = new \OCA\Libresign\Db\File(); $file->setUuid('ready-uuid'); - $file->setStatus(\OCA\Libresign\Enum\FileStatus::ABLE_TO_SIGN->value); - $service = $this->getService(['saveFile']); - $service->method('saveFile')->willReturnCallback( - static function (array $data, ?bool &$becameReady) use ($file): \OCA\Libresign\Db\File { - $becameReady = true; + $file->setStatus(\OCA\Libresign\Enum\FileStatus::DRAFT->value); + $this->fileMapper->method('getByUuid')->with('ready-uuid')->willReturn($file); + $this->fileStatusService->method('updateFileStatusIfUpgrade') + ->willReturnCallback(static function ($file, int $status) { + $file->setStatus($status); return $file; - }, - ); - $this->fileStatusService->expects($this->once())->method('dispatchReadyRequest')->with($file); - $this->assertSame($file, $service->save(['status' => $file->getStatus()])); + }); + + $committed = false; + $this->db->expects($this->once())->method('commit') + ->willReturnCallback(static function () use (&$committed): void { + $committed = true; + }); + $this->fileStatusService->expects($this->once())->method('dispatchReadyRequest') + ->with($this->callback(static function ($published) use (&$committed, $file): bool { + return $committed && $published === $file + && $file->getStatus() === \OCA\Libresign\Enum\FileStatus::ABLE_TO_SIGN->value; + })); + + $this->assertSame($file, $this->getService()->save([ + 'uuid' => 'ready-uuid', + 'status' => \OCA\Libresign\Enum\FileStatus::ABLE_TO_SIGN->value, + ])); } public function testReadyRequestEventIsNotPublishedWhenSignerPersistenceFails(): void { $file = new \OCA\Libresign\Db\File(); $file->setUuid('ready-uuid'); - $file->setStatus(\OCA\Libresign\Enum\FileStatus::ABLE_TO_SIGN->value); - $service = $this->getService(['saveFile']); - $service->method('saveFile')->willReturnCallback( - static function (array $data, ?bool &$becameReady) use ($file): \OCA\Libresign\Db\File { - $becameReady = true; + $file->setStatus(\OCA\Libresign\Enum\FileStatus::DRAFT->value); + $this->fileMapper->method('getByUuid')->with('ready-uuid')->willReturn($file); + $this->fileStatusService->method('updateFileStatusIfUpgrade') + ->willReturnCallback(static function ($file, int $status) { + $file->setStatus($status); return $file; - }, - ); + }); $this->signerValidator->method('normalizeRequestSigners') ->willThrowException(new \RuntimeException('invalid signer')); + $this->db->expects($this->once())->method('rollBack'); + $this->db->expects($this->never())->method('commit'); $this->fileStatusService->expects($this->never())->method('dispatchReadyRequest'); $this->expectException(\RuntimeException::class); - $service->save(['status' => $file->getStatus(), 'signers' => [['identifyMethods' => []]]]); + + $this->getService()->save([ + 'uuid' => 'ready-uuid', + 'status' => \OCA\Libresign\Enum\FileStatus::ABLE_TO_SIGN->value, + 'signers' => [['identifyMethods' => []]], + ]); } public function testSaveFilesUsesSaveForSingleFile(): void { From bee9ff882767ca9106b3b2c32130794d4b82a3db Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Tue, 10 Nov 2026 23:26:50 +0000 Subject: [PATCH 11/23] test: verify committed notification outcomes and preserve signed event failures Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- lib/Service/RequestSignatureService.php | 13 ++- lib/Service/SignFileService.php | 29 +++---- .../NotificationSubmissionServiceTest.php | 85 +++++++++++++++---- .../php/Unit/Service/SignFileServiceTest.php | 24 +++--- 4 files changed, 96 insertions(+), 55 deletions(-) diff --git a/lib/Service/RequestSignatureService.php b/lib/Service/RequestSignatureService.php index 6f2d0c6eb6..37be3d8940 100644 --- a/lib/Service/RequestSignatureService.php +++ b/lib/Service/RequestSignatureService.php @@ -139,23 +139,22 @@ public function saveFiles(array $data): array { } public function save(array $data): FileEntity { - $result = $this->atomic(function () use ($data): array { - $result = $this->persistFile($data); - $file = $result['file']; - $data['status'] ??= $file->getStatus(); + $result = $this->persistFile($data); + $file = $result['file']; + $data['status'] ??= $file->getStatus(); + $this->atomic(function () use ($file, $data): void { $this->sequentialSigningService->setFile($file); $this->associateToSigners($data, $file); $this->propagateSignersToChildren($file, $data); $this->saveVisibleElements($data, $file); - return $result; }, $this->db); $this->notifications->flushCommitted(); if ($result['becameReady']) { - $this->fileStatusService->dispatchReadyRequest($result['file']); + $this->fileStatusService->dispatchReadyRequest($file); } - return $result['file']; + return $file; } private function propagateSignersToChildren(FileEntity $envelope, array $data): void { diff --git a/lib/Service/SignFileService.php b/lib/Service/SignFileService.php index 71e6602a04..0f2e94b3ad 100644 --- a/lib/Service/SignFileService.php +++ b/lib/Service/SignFileService.php @@ -1020,24 +1020,19 @@ protected function dispatchSignedEvent(): void { $certificateSerialNumber, ); $this->eventDispatcher->dispatchTyped($event); - } catch (\Exception $e) { - $this->logger->warning('Unable to dispatch legacy signed event', [ - 'signRequestId' => $this->signRequest->getId(), - 'errorType' => get_debug_type($e), - ]); - } - - try { - $root = $this->getCompletionTarget($this->libreSignFile); - $publicEvent = SignerSignedWebhookEvent::afterSigning($root, $this->libreSignFile, $this->signRequest); - if ($publicEvent !== null) { - $this->eventDispatcher->dispatchTyped($publicEvent); + } finally { + try { + $root = $this->getCompletionTarget($this->libreSignFile); + $publicEvent = SignerSignedWebhookEvent::afterSigning($root, $this->libreSignFile, $this->signRequest); + if ($publicEvent !== null) { + $this->eventDispatcher->dispatchTyped($publicEvent); + } + } catch (\Exception $e) { + $this->logger->warning('Unable to dispatch signer signed webhook event', [ + 'signRequestId' => $this->signRequest->getId(), + 'errorType' => get_debug_type($e), + ]); } - } catch (\Exception $e) { - $this->logger->warning('Unable to dispatch signer signed webhook event', [ - 'signRequestId' => $this->signRequest->getId(), - 'errorType' => get_debug_type($e), - ]); } } diff --git a/tests/php/Unit/Service/Notification/NotificationSubmissionServiceTest.php b/tests/php/Unit/Service/Notification/NotificationSubmissionServiceTest.php index 0f21d47fac..e33764297b 100644 --- a/tests/php/Unit/Service/Notification/NotificationSubmissionServiceTest.php +++ b/tests/php/Unit/Service/Notification/NotificationSubmissionServiceTest.php @@ -35,6 +35,23 @@ private function message(): NotificationMessage { return new NotificationMessage('test-event', 'sign_request', 'mail', new File(), new SignRequest(), 'test@example.invalid', new MailPayload(firstNotification: true)); } + private function service( + NotificationDeliveryMapper $deliveries, + NotificationAttemptMapper $attempts, + NotificationDeliveryEventPublisher $publisher, + ?IDBConnection $db = null, + ): NotificationSubmissionService { + return new NotificationSubmissionService( + $deliveries, + $attempts, + $db ?? $this->createMock(IDBConnection::class), + new NotificationFailureClassifier(), + new NotificationHistoryService($this->createMock(SignRequestMapper::class)), + $this->createMock(LoggerInterface::class), + $publisher, + ); + } + private function executeFailure(\Exception $failure, int $attemptNumber, NotificationDeliveryState $expected, bool $expectRetry): void { $delivery = new NotificationDelivery(); $delivery->setId(9); @@ -66,7 +83,9 @@ static function (?\DateTime $due) use ($expectRetry, $attemptNumber): bool { $db->expects($this->never())->method('rollBack'); $channel = $this->createMock(NotificationChannel::class); $channel->method('deliver')->willThrowException($failure); - $service = new NotificationSubmissionService($deliveries, $attempts, $db, new NotificationFailureClassifier(), new NotificationHistoryService($this->createMock(SignRequestMapper::class)), $this->createMock(LoggerInterface::class), $this->createMock(NotificationDeliveryEventPublisher::class)); + $publisher = $this->createMock(NotificationDeliveryEventPublisher::class); + $publisher->expects($this->once())->method('publish')->with(9); + $service = $this->service($deliveries, $attempts, $publisher, $db); $this->expectException(get_class($failure)); $service->submit($delivery, $this->message(), $channel); } @@ -105,28 +124,60 @@ public function testNestedPreparationFailureCannotMakeTransportOutcomeSafe(): vo $this->executeFailure(new NotificationTransportException('synthetic uncertain outcome', NotificationDeliveryState::UNKNOWN, 'smtp_outcome_unknown', new NotificationPreparationException('preparation')), 1, NotificationDeliveryState::UNKNOWN, false); } - public function testSuccessfulSubmissionRequestsOutcomePublication(): void { + public function testPublishedOutcomeFollowsFinalLedgerCommit(): void { $delivery = new NotificationDelivery(); $delivery->setId(9); $attempt = new NotificationAttempt(); $attempt->setId(28); + $deliveries = $this->createMock(NotificationDeliveryMapper::class); + $deliveries->method('claim')->willReturn(true); + $attempts = $this->createMock(NotificationAttemptMapper::class); + $attempts->method('begin')->willReturn($attempt); + $commits = 0; + $db = $this->createMock(IDBConnection::class); + $db->expects($this->exactly(2))->method('commit') + ->willReturnCallback(static function () use (&$commits): void { + $commits++; + }); + $channel = $this->createMock(NotificationChannel::class); + $channel->expects($this->once())->method('deliver') + ->willReturnCallback(function () use (&$commits): void { + $this->assertSame(1, $commits, 'The attempt must be claimed before sending.'); + }); + $publisher = $this->createMock(NotificationDeliveryEventPublisher::class); + $publisher->expects($this->once())->method('publish')->with(9) + ->willReturnCallback(function () use (&$commits): void { + $this->assertSame(2, $commits, 'Publication must follow the committed ledger outcome.'); + }); + + $this->assertTrue($this->service($deliveries, $attempts, $publisher, $db) + ->submit($delivery, $this->message(), $channel)); + } + + public function testFailedLedgerPersistenceDoesNotPublishOutcome(): void { + $delivery = new NotificationDelivery(); + $delivery->setId(9); + $attempt = new NotificationAttempt(); + $attempt->setId(28); $deliveries = $this->createMock(NotificationDeliveryMapper::class); $deliveries->method('claim')->willReturn(true); $attempts = $this->createMock(NotificationAttemptMapper::class); $attempts->method('begin')->willReturn($attempt); + $attempts->method('finish')->willThrowException(new \RuntimeException('ledger write failed')); + + $db = $this->createMock(IDBConnection::class); + $db->expects($this->once())->method('rollBack'); $publisher = $this->createMock(NotificationDeliveryEventPublisher::class); - $publisher->expects($this->once())->method('publish')->with(9); - $channel = $this->createMock(NotificationChannel::class); - $channel->expects($this->once())->method('deliver'); + $publisher->expects($this->never())->method('publish'); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('ledger write failed'); - $service = new NotificationSubmissionService( - $deliveries, $attempts, $this->createMock(IDBConnection::class), new NotificationFailureClassifier(), - new NotificationHistoryService($this->createMock(SignRequestMapper::class)), - $this->createMock(LoggerInterface::class), $publisher, + $this->service($deliveries, $attempts, $publisher, $db)->submit( + $delivery, + $this->message(), + $this->createMock(NotificationChannel::class), ); - - $this->assertTrue($service->submit($delivery, $this->message(), $channel)); } public function testAlreadyClaimedDeliveryNeverSubmitsOrPublishes(): void { @@ -138,13 +189,11 @@ public function testAlreadyClaimedDeliveryNeverSubmitsOrPublishes(): void { $channel->expects($this->never())->method('deliver'); $publisher = $this->createMock(NotificationDeliveryEventPublisher::class); $publisher->expects($this->never())->method('publish'); - $service = new NotificationSubmissionService( - $deliveries, $this->createMock(NotificationAttemptMapper::class), - $this->createMock(IDBConnection::class), new NotificationFailureClassifier(), - new NotificationHistoryService($this->createMock(SignRequestMapper::class)), - $this->createMock(LoggerInterface::class), $publisher, - ); - $this->assertFalse($service->submit($delivery, $this->message(), $channel)); + $this->assertFalse($this->service( + $deliveries, + $this->createMock(NotificationAttemptMapper::class), + $publisher, + )->submit($delivery, $this->message(), $channel)); } } diff --git a/tests/php/Unit/Service/SignFileServiceTest.php b/tests/php/Unit/Service/SignFileServiceTest.php index cdf8156642..4b8cd40c1f 100644 --- a/tests/php/Unit/Service/SignFileServiceTest.php +++ b/tests/php/Unit/Service/SignFileServiceTest.php @@ -912,20 +912,18 @@ static function ($event) use (&$events): void { } }, ); - $this->logger->expects($this->once())->method('warning') - ->with('Unable to dispatch legacy signed event', $this->callback( - static fn (array $context): bool => $context['errorType'] === 'RuntimeException' - && !str_contains(json_encode($context), 'private callback details'), + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('private callback details'); + try { + $service->signSingleFile($file, $signer); + } finally { + $published = array_values(array_filter( + $events, + static fn ($event): bool => $event instanceof SignerSignedWebhookEvent, )); - - $service->signSingleFile($file, $signer); - - $published = array_values(array_filter( - $events, - static fn ($event): bool => $event instanceof SignerSignedWebhookEvent, - )); - $this->assertCount(1, $published); - $this->assertSame('document-uuid', $published[0]->getWebhookSerializable()['requestUuid']); + $this->assertCount(1, $published); + $this->assertSame('document-uuid', $published[0]->getWebhookSerializable()['requestUuid']); + } } public function testUpdateEnvelopeStatusAddsStatusChangedAt(): void { From 8d968b05e05e348776c8828bc5e00418a9aa293c Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Tue, 10 Nov 2026 23:46:54 +0000 Subject: [PATCH 12/23] fix: sanitize unexpected rejection errors in public API Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- lib/Controller/SignFileController.php | 13 +++++- .../Controller/SignFileControllerTest.php | 40 ++++++++++++++++++- 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/lib/Controller/SignFileController.php b/lib/Controller/SignFileController.php index 0ee2d0b4b3..fa5ddceefd 100644 --- a/lib/Controller/SignFileController.php +++ b/lib/Controller/SignFileController.php @@ -386,9 +386,20 @@ private function reject( $comment, $privateComment, ); + } catch (LibresignException $e) { + return new DataResponse( + ['message' => $e->getMessage()], + Http::STATUS_UNPROCESSABLE_ENTITY, + ); } catch (\Throwable $th) { + // Reject is public and persistence can throw internal errors. Never + // reveal exception details to an unauthenticated signing client. + $this->logger->error('Unable to process signature rejection', [ + 'errorType' => get_debug_type($th), + ]); return new DataResponse( - ['message' => $th->getMessage()], + // TRANSLATORS Error shown when a signature rejection fails unexpectedly. + ['message' => $this->l10n->t('Unable to process signature rejection.')], Http::STATUS_UNPROCESSABLE_ENTITY, ); } diff --git a/tests/php/Unit/Controller/SignFileControllerTest.php b/tests/php/Unit/Controller/SignFileControllerTest.php index 23472bcd77..2a52a51157 100644 --- a/tests/php/Unit/Controller/SignFileControllerTest.php +++ b/tests/php/Unit/Controller/SignFileControllerTest.php @@ -50,6 +50,7 @@ final class SignFileControllerTest extends TestCase { private SignerValidator&MockObject $signerValidator; private WorkerConfiguration&MockObject $workerConfiguration; private AsyncSigningService&MockObject $asyncSigningService; + private SignatureRejectionService&MockObject $signatureRejectionService; protected function setUp(): void { $this->request = $this->createMock(IRequest::class); @@ -64,6 +65,7 @@ protected function setUp(): void { $this->signerValidator = $this->createMock(SignerValidator::class); $this->workerConfiguration = $this->createMock(WorkerConfiguration::class); $this->asyncSigningService = $this->createMock(AsyncSigningService::class); + $this->signatureRejectionService = $this->createMock(SignatureRejectionService::class); } private function getController(): SignFileController { @@ -86,7 +88,7 @@ private function getController(): SignFileController { $this->createMock(SignerGeolocationMetadataValidator::class), $this->createMock(SignerIpGeolocationPolicyService::class), $this->createMock(SigningErrorHandler::class), - $this->createMock(SignatureRejectionService::class), + $this->signatureRejectionService, $this->emailSignerElementsService, $this->logger, ); @@ -241,6 +243,42 @@ public function testRequestCodeDoesNotExposeInternalExceptionMessage(): void { $response->getData()['message'], ); } + public function testRejectPublicApiDoesNotExposeUnexpectedServerError(): void { + $file = new FileEntity(); + $file->setId(10); + $signer = new SignRequest(); + $signer->setId(12); + $signer->setFileId(10); + $this->signFileService->method('getLibresignFile')->willReturn($file); + $this->signFileService->method('getSignRequestToSign')->willReturn($signer); + $this->signatureRejectionService->method('reject')->willThrowException( + new \TypeError('internal signing key path: /private/not-for-client'), + ); + $this->logger->expects($this->once())->method('error')->with( + 'Unable to process signature rejection', + $this->callback(static fn (array $context): bool + => ($context['errorType'] ?? null) === \TypeError::class + && !str_contains(json_encode($context), '/private/not-for-client') + ), + ); + + $response = $this->getController()->rejectBySignerUuid('signer-uuid'); + + $this->assertSame(Http::STATUS_UNPROCESSABLE_ENTITY, $response->getStatus()); + $this->assertSame('Unable to process signature rejection.', $response->getData()['message']); + } + + public function testRejectPublicApiKeepsExpectedDomainError(): void { + $this->signFileService->method('getLibresignFile')->willThrowException( + new \OCA\Libresign\Exception\LibresignException('Signature request is closed'), + ); + + $response = $this->getController()->rejectBySignerUuid('signer-uuid'); + + $this->assertSame(Http::STATUS_UNPROCESSABLE_ENTITY, $response->getStatus()); + $this->assertSame('Signature request is closed', $response->getData()['message']); + } + private function prepareSigning(bool $prepareSignature = true): SignRequest { if ($prepareSignature) { $this->emailSignerElementsService->method('prepareSignature') From 2c424061025201ab089b04db209ab091581029e5 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Tue, 10 Nov 2026 23:47:09 +0000 Subject: [PATCH 13/23] fix: isolate native webhook listener failures from committed workflows Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- .../NotificationDeliveryEventPublisher.php | 3 +- lib/Service/RequestSignatureService.php | 17 ++++++- lib/Service/SignFileService.php | 2 +- .../SignatureRejectionService.php | 5 +- ...NotificationDeliveryEventPublisherTest.php | 20 ++++++-- .../Service/RequestSignatureServiceTest.php | 32 ++++++++++++ .../php/Unit/Service/SignFileServiceTest.php | 51 +++++++++++++++++++ .../SignatureRejectionServiceTest.php | 25 +++++++-- 8 files changed, 142 insertions(+), 13 deletions(-) diff --git a/lib/Service/Notification/NotificationDeliveryEventPublisher.php b/lib/Service/Notification/NotificationDeliveryEventPublisher.php index 8b1b764b0b..7b6fba94a5 100644 --- a/lib/Service/Notification/NotificationDeliveryEventPublisher.php +++ b/lib/Service/Notification/NotificationDeliveryEventPublisher.php @@ -34,7 +34,8 @@ public function publish(int $deliveryId): void { if ($event !== null) { $this->events->dispatchTyped($event); } - } catch (\Exception $e) { + } catch (\Throwable $e) { + // The delivery has already been committed: webhook listeners are best effort. $this->logger->warning('Unable to publish persisted notification outcome', [ 'deliveryId' => $deliveryId, 'errorType' => get_debug_type($e), diff --git a/lib/Service/RequestSignatureService.php b/lib/Service/RequestSignatureService.php index 37be3d8940..a624346508 100644 --- a/lib/Service/RequestSignatureService.php +++ b/lib/Service/RequestSignatureService.php @@ -151,12 +151,25 @@ public function save(array $data): FileEntity { $this->notifications->flushCommitted(); if ($result['becameReady']) { - $this->fileStatusService->dispatchReadyRequest($file); + $this->publishReadyRequest($file); } return $file; } + private function publishReadyRequest(FileEntity $file): void { + try { + $this->fileStatusService->dispatchReadyRequest($file); + } catch (\Throwable $e) { + // The database write already committed. Do not turn a successful + // signing request into a failed API response due to a webhook listener. + $this->logger->warning('Unable to publish signing request ready event', [ + 'fileId' => $file->getId(), + 'errorType' => get_debug_type($e), + ]); + } + } + private function propagateSignersToChildren(FileEntity $envelope, array $data): void { if ($envelope->getNodeType() !== 'envelope' || empty($data['signers'])) { return; @@ -232,7 +245,7 @@ public function saveEnvelope(array $data): array { } if ($envelope->getStatus() === FileStatus::ABLE_TO_SIGN->value) { - $this->fileStatusService->dispatchReadyRequest($envelope); + $this->publishReadyRequest($envelope); } return [ 'envelope' => $envelope, diff --git a/lib/Service/SignFileService.php b/lib/Service/SignFileService.php index 0f2e94b3ad..5b98bbbb05 100644 --- a/lib/Service/SignFileService.php +++ b/lib/Service/SignFileService.php @@ -1027,7 +1027,7 @@ protected function dispatchSignedEvent(): void { if ($publicEvent !== null) { $this->eventDispatcher->dispatchTyped($publicEvent); } - } catch (\Exception $e) { + } catch (\Throwable $e) { $this->logger->warning('Unable to dispatch signer signed webhook event', [ 'signRequestId' => $this->signRequest->getId(), 'errorType' => get_debug_type($e), diff --git a/lib/Service/SignatureRejection/SignatureRejectionService.php b/lib/Service/SignatureRejection/SignatureRejectionService.php index d8562e8285..a37485fa1a 100644 --- a/lib/Service/SignatureRejection/SignatureRejectionService.php +++ b/lib/Service/SignatureRejection/SignatureRejectionService.php @@ -391,7 +391,7 @@ private function dispatchPublicRejectionEvents( SigningRequestCanceledEvent::fromTransition($root, $previousRootStatus), SigningRequestCompletedEvent::fromTransition($root, $previousRootStatus), ]; - } catch (\Exception $e) { + } catch (\Throwable $e) { $this->logger->warning('Unable to prepare LibreSign rejection events', [ 'fileId' => $document->getId(), 'errorType' => get_debug_type($e), @@ -405,7 +405,8 @@ private function dispatchPublicRejectionEvents( } try { $this->eventDispatcher->dispatchTyped($event); - } catch (\Exception $e) { + } catch (\Throwable $e) { + // Listener errors cannot undo a persisted rejection or suppress later events. $this->logger->warning('Unable to publish LibreSign rejection event', [ 'fileId' => $document->getId(), 'eventType' => $event::class, diff --git a/tests/php/Unit/Service/Notification/NotificationDeliveryEventPublisherTest.php b/tests/php/Unit/Service/Notification/NotificationDeliveryEventPublisherTest.php index 733deb1727..66d35caf3e 100644 --- a/tests/php/Unit/Service/Notification/NotificationDeliveryEventPublisherTest.php +++ b/tests/php/Unit/Service/Notification/NotificationDeliveryEventPublisherTest.php @@ -90,9 +90,23 @@ public function testExpectedRepositoryFailureIsLoggedWithoutSensitiveData(): voi $this->publisher->publish(9); } - public function testProgrammingErrorIsNotSwallowed(): void { - $this->deliveries->method('findById')->willThrowException(new \TypeError('programming error')); - $this->expectException(\TypeError::class); + public function testListenerProgrammingErrorCannotInterruptCommittedDelivery(): void { + $this->deliveries->method('findById')->willReturn($this->delivery()); + $root = new File(); + $root->setUuid('root-uuid'); + $this->files->method('getById')->willReturn($root); + $this->dispatcher->method('dispatchTyped')->willThrowException( + new \TypeError('PRIVATE_WEBHOOK_DETAILS'), + ); + $this->logger->expects($this->once())->method('warning')->with( + 'Unable to publish persisted notification outcome', + $this->callback(static fn (array $context): bool + => ($context['deliveryId'] ?? null) === 9 + && ($context['errorType'] ?? null) === \TypeError::class + && !str_contains(json_encode($context), 'PRIVATE_WEBHOOK_DETAILS') + ), + ); + $this->publisher->publish(9); } } diff --git a/tests/php/Unit/Service/RequestSignatureServiceTest.php b/tests/php/Unit/Service/RequestSignatureServiceTest.php index f744d7fd0b..e4cbf25dd9 100644 --- a/tests/php/Unit/Service/RequestSignatureServiceTest.php +++ b/tests/php/Unit/Service/RequestSignatureServiceTest.php @@ -350,6 +350,38 @@ public function testReadyRequestEventIsPublishedOnlyAfterSignerTransactionCommit ])); } + public function testReadyWebhookFailureDoesNotInvalidateCommittedRequest(): void { + $file = new \OCA\Libresign\Db\File(); + $file->setUuid('ready-uuid'); + $file->setStatus(\OCA\Libresign\Enum\FileStatus::DRAFT->value); + $this->fileMapper->method('getByUuid')->with('ready-uuid')->willReturn($file); + $this->fileStatusService->method('updateFileStatusIfUpgrade') + ->willReturnCallback(static function ($file, int $status) { + $file->setStatus($status); + return $file; + }); + $committed = false; + $this->db->expects($this->once())->method('commit') + ->willReturnCallback(static function () use (&$committed): void { + $committed = true; + }); + $this->fileStatusService->method('dispatchReadyRequest') + ->willThrowException(new \TypeError('PRIVATE_WEBHOOK_DETAILS')); + $this->loggerInterface->expects($this->once())->method('warning')->with( + 'Unable to publish signing request ready event', + $this->callback(static fn (array $context): bool + => ($context['errorType'] ?? null) === \TypeError::class + && !str_contains(json_encode($context), 'PRIVATE_WEBHOOK_DETAILS') + ), + ); + + $this->assertSame($file, $this->getService()->save([ + 'uuid' => 'ready-uuid', + 'status' => \OCA\Libresign\Enum\FileStatus::ABLE_TO_SIGN->value, + ])); + $this->assertTrue($committed); + } + public function testReadyRequestEventIsNotPublishedWhenSignerPersistenceFails(): void { $file = new \OCA\Libresign\Db\File(); $file->setUuid('ready-uuid'); diff --git a/tests/php/Unit/Service/SignFileServiceTest.php b/tests/php/Unit/Service/SignFileServiceTest.php index 4b8cd40c1f..42e1944b42 100644 --- a/tests/php/Unit/Service/SignFileServiceTest.php +++ b/tests/php/Unit/Service/SignFileServiceTest.php @@ -926,6 +926,57 @@ static function ($event) use (&$events): void { } } + public function testNativeWebhookListenerErrorCannotInterruptCommittedSigning(): void { + $service = $this->getService([ + 'getEngine', 'computeHash', 'validateDocMdpAllowsSignatures', + 'updateSignRequest', 'updateLibreSignFile', + ]); + $file = new File(); + $file->setId(17); + $file->setUuid('document-uuid'); + $file->setStatus(FileStatus::ABLE_TO_SIGN->value); + $signer = new SignRequest(); + $signer->setId(31); + $signer->setSigned(new DateTime('2026-11-09T11:00:00Z')); + $signer->setSignedHash('signed-content-hash'); + + $signedFile = $this->createMock(\OCP\Files\File::class); + $signedFile->method('getId')->willReturn(123); + $engine = $this->createMock(Pkcs12Handler::class); + $engine->method('sign')->willReturn($signedFile); + $engine->method('getInputFile')->willReturn($signedFile); + $service->method('getEngine')->willReturn($engine); + $service->method('computeHash')->willReturn('signed-content-hash'); + $service->method('updateLibreSignFile')->willReturnCallback( + static function (File $file): void { + $file->setStatus(FileStatus::SIGNED->value); + }, + ); + $this->fileMapper->method('getById')->willReturn($file); + $this->signedEventFactory->method('make')->willReturn($this->createMock(SignedEvent::class)); + $events = []; + $this->eventDispatcher->method('dispatchTyped')->willReturnCallback( + static function ($event) use (&$events): void { + $events[] = $event; + if ($event instanceof SignerSignedWebhookEvent) { + throw new \TypeError('PRIVATE_WEBHOOK_DETAILS'); + } + }, + ); + $this->logger->expects($this->once())->method('warning')->with( + 'Unable to dispatch signer signed webhook event', + $this->callback(static fn (array $context): bool + => ($context['errorType'] ?? null) === \TypeError::class + && !str_contains(json_encode($context), 'PRIVATE_WEBHOOK_DETAILS') + ), + ); + + $service->signSingleFile($file, $signer); + + $this->assertSame(FileStatus::SIGNED->value, $file->getStatus()); + $this->assertCount(1, array_filter($events, static fn ($event): bool => $event instanceof SigningRequestCompletedEvent)); + } + public function testUpdateEnvelopeStatusAddsStatusChangedAt(): void { $service = $this->getService(); diff --git a/tests/php/Unit/Service/SignatureRejection/SignatureRejectionServiceTest.php b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionServiceTest.php index aa801dd53c..eb3f7cefa0 100644 --- a/tests/php/Unit/Service/SignatureRejection/SignatureRejectionServiceTest.php +++ b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionServiceTest.php @@ -355,15 +355,32 @@ static function ($event) use (&$events): void { $this->assertCount(1, array_filter($events, static fn ($event): bool => $event instanceof SigningRequestCanceledEvent)); } - public function testProgrammingErrorDuringPublicEventDispatchIsNotSuppressed(): void { + public function testPublicWebhookErrorCannotInterruptCommittedRejection(): void { $this->withPolicy(self::policy('cancel')); $file = $this->file(); $file->setUuid('workflow-uuid'); + $signer = $this->signRequest(); $this->db->expects($this->once())->method('commit'); $this->db->expects($this->never())->method('rollBack'); - $this->eventDispatcher->method('dispatchTyped')->willThrowException(new \TypeError('programming error')); - $this->expectException(\TypeError::class); - $this->getService()->reject($file, $this->signRequest()); + $events = []; + $this->eventDispatcher->method('dispatchTyped')->willReturnCallback( + static function ($event) use (&$events): void { + $events[] = $event; + if ($event instanceof SignerRejectedWebhookEvent) { + throw new \TypeError('PRIVATE_WEBHOOK_DETAILS'); + } + }, + ); + $this->logger->expects($this->once())->method('warning')->with( + 'Unable to publish LibreSign rejection event', + $this->callback(static fn (array $context): bool + => ($context['errorType'] ?? null) === \TypeError::class + && !str_contains(json_encode($context), 'PRIVATE_WEBHOOK_DETAILS') + ), + ); + + $this->assertSame($signer, $this->getService()->reject($file, $signer)); + $this->assertCount(1, array_filter($events, static fn ($event): bool => $event instanceof SigningRequestCanceledEvent)); } public function testRejectionCanCompletePreviouslySignedWorkflow(): void { From 2dcc2e93f9310e74c0c7362c2706e1b5b5bb9ae2 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Wed, 11 Nov 2026 00:17:09 +0000 Subject: [PATCH 14/23] refactor: centralize native webhook publishing and simplify lifecycle tests Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- lib/Service/FileStatusService.php | 10 - .../NotificationDeliveryEventPublisher.php | 45 ---- .../NotificationSubmissionService.php | 5 +- lib/Service/RequestSignatureService.php | 19 +- lib/Service/SignFileService.php | 28 +- .../SignatureRejectionService.php | 46 +--- .../Webhook/NativeWebhookEventPublisher.php | 141 ++++++++++ .../Unit/Service/FileStatusServiceTest.php | 22 +- ...NotificationDeliveryEventPublisherTest.php | 112 -------- .../NotificationSubmissionServiceTest.php | 20 +- .../NotificationDeliveryServiceTest.php | 2 +- .../Service/RequestSignatureServiceTest.php | 43 +-- .../php/Unit/Service/SignFileServiceTest.php | 121 ++------- .../SignatureRejectionServiceTest.php | 87 +------ .../NativeWebhookEventPublisherTest.php | 246 ++++++++++++++++++ 15 files changed, 450 insertions(+), 497 deletions(-) delete mode 100644 lib/Service/Notification/NotificationDeliveryEventPublisher.php create mode 100644 lib/Service/Webhook/NativeWebhookEventPublisher.php delete mode 100644 tests/php/Unit/Service/Notification/NotificationDeliveryEventPublisherTest.php create mode 100644 tests/php/Unit/Service/Webhook/NativeWebhookEventPublisherTest.php diff --git a/lib/Service/FileStatusService.php b/lib/Service/FileStatusService.php index 4ce9e6e834..a4b37fa47b 100644 --- a/lib/Service/FileStatusService.php +++ b/lib/Service/FileStatusService.php @@ -13,10 +13,8 @@ use OCA\Libresign\Db\File as FileEntity; use OCA\Libresign\Db\FileMapper; use OCA\Libresign\Enum\FileStatus; -use OCA\Libresign\Events\SigningRequestReadyEvent; use OCA\Libresign\Service\SignRequest\StatusCacheService; use OCP\AppFramework\Db\DoesNotExistException; -use OCP\EventDispatcher\IEventDispatcher; class FileStatusService { public const POLICY_SNAPSHOT_FROZEN_AT = 'policy_snapshot_frozen_at'; @@ -24,7 +22,6 @@ class FileStatusService { public function __construct( private FileMapper $fileMapper, private StatusCacheService $statusCacheService, - private IEventDispatcher $eventDispatcher, ) { } @@ -43,13 +40,6 @@ public function updateFileStatusIfUpgrade(FileEntity $file, int $newStatus): Fil return $file; } - public function dispatchReadyRequest(FileEntity $file): void { - $event = SigningRequestReadyEvent::fromTransition($file, FileStatus::DRAFT->value); - if ($event !== null) { - $this->eventDispatcher->dispatchTyped($event); - } - } - public function invalidateCachedStatus(FileEntity $file): void { $this->statusCacheService->invalidateStatus($file->getUuid()); } diff --git a/lib/Service/Notification/NotificationDeliveryEventPublisher.php b/lib/Service/Notification/NotificationDeliveryEventPublisher.php deleted file mode 100644 index 7b6fba94a5..0000000000 --- a/lib/Service/Notification/NotificationDeliveryEventPublisher.php +++ /dev/null @@ -1,45 +0,0 @@ -deliveries->findById($deliveryId); - $file = $this->files->getById($delivery->getFileId()); - $root = $file->hasParent() - ? $this->files->getById($file->getParentFileId()) - : $file; - $event = NotificationDeliveryStatusChangedEvent::fromPersistedDelivery($root, $delivery); - if ($event !== null) { - $this->events->dispatchTyped($event); - } - } catch (\Throwable $e) { - // The delivery has already been committed: webhook listeners are best effort. - $this->logger->warning('Unable to publish persisted notification outcome', [ - 'deliveryId' => $deliveryId, - 'errorType' => get_debug_type($e), - ]); - } - } -} diff --git a/lib/Service/Notification/NotificationSubmissionService.php b/lib/Service/Notification/NotificationSubmissionService.php index 20105dfacc..e48c46bfdb 100644 --- a/lib/Service/Notification/NotificationSubmissionService.php +++ b/lib/Service/Notification/NotificationSubmissionService.php @@ -13,6 +13,7 @@ use OCA\Libresign\Db\NotificationDeliveryMapper; use OCA\Libresign\Enum\NotificationDeliveryState; use OCA\Libresign\Exception\NotificationPreparationException; +use OCA\Libresign\Service\Webhook\NativeWebhookEventPublisher; use OCP\AppFramework\Db\TTransactional; use OCP\IDBConnection; use Psr\Log\LoggerInterface; @@ -29,7 +30,7 @@ public function __construct( private NotificationFailureClassifier $failureClassifier, private NotificationHistoryService $history, private LoggerInterface $logger, - private NotificationDeliveryEventPublisher $eventPublisher, + private NativeWebhookEventPublisher $webhooks, ) { } @@ -91,7 +92,7 @@ public function submit(NotificationDelivery $delivery, NotificationMessage $mess $this->attempts->finish($attempt->getId(), $outcome, $reason); $this->deliveries->finish($delivery->getId(), $outcome, $retryAt); }, $this->db); - $this->eventPublisher->publish($delivery->getId()); + $this->webhooks->notificationOutcome($delivery->getId()); } return true; } diff --git a/lib/Service/RequestSignatureService.php b/lib/Service/RequestSignatureService.php index a624346508..0a8f4a3037 100644 --- a/lib/Service/RequestSignatureService.php +++ b/lib/Service/RequestSignatureService.php @@ -30,6 +30,7 @@ use OCA\Libresign\Service\Validation\FileInputValidator; use OCA\Libresign\Service\Validation\SignerValidator; use OCA\Libresign\Service\Validation\SigningRequestValidator; +use OCA\Libresign\Service\Webhook\NativeWebhookEventPublisher; use OCP\AppFramework\Db\DoesNotExistException; use OCP\AppFramework\Db\MultipleObjectsReturnedException; use OCP\AppFramework\Db\TTransactional; @@ -79,6 +80,7 @@ public function __construct( protected SignerRemovalService $signerRemovalService, protected IDBConnection $db, protected NotificationDeliveryService $notifications, + protected NativeWebhookEventPublisher $webhooks, ) { } @@ -151,25 +153,12 @@ public function save(array $data): FileEntity { $this->notifications->flushCommitted(); if ($result['becameReady']) { - $this->publishReadyRequest($file); + $this->webhooks->requestReady($file); } return $file; } - private function publishReadyRequest(FileEntity $file): void { - try { - $this->fileStatusService->dispatchReadyRequest($file); - } catch (\Throwable $e) { - // The database write already committed. Do not turn a successful - // signing request into a failed API response due to a webhook listener. - $this->logger->warning('Unable to publish signing request ready event', [ - 'fileId' => $file->getId(), - 'errorType' => get_debug_type($e), - ]); - } - } - private function propagateSignersToChildren(FileEntity $envelope, array $data): void { if ($envelope->getNodeType() !== 'envelope' || empty($data['signers'])) { return; @@ -245,7 +234,7 @@ public function saveEnvelope(array $data): array { } if ($envelope->getStatus() === FileStatus::ABLE_TO_SIGN->value) { - $this->publishReadyRequest($envelope); + $this->webhooks->requestReady($envelope); } return [ 'envelope' => $envelope, diff --git a/lib/Service/SignFileService.php b/lib/Service/SignFileService.php index 5b98bbbb05..ad7852b129 100644 --- a/lib/Service/SignFileService.php +++ b/lib/Service/SignFileService.php @@ -31,8 +31,6 @@ use OCA\Libresign\Enum\IdentifyMethodRequirement; use OCA\Libresign\Enum\SignRequestStatus; use OCA\Libresign\Events\SignedEventFactory; -use OCA\Libresign\Events\SignerSignedWebhookEvent; -use OCA\Libresign\Events\SigningRequestCompletedEvent; use OCA\Libresign\Exception\FooterStampUnavailableException; use OCA\Libresign\Exception\LibresignException; use OCA\Libresign\Handler\DocMdpHandler; @@ -57,6 +55,7 @@ use OCA\Libresign\Service\Validation\IdentityDocumentValidator; use OCA\Libresign\Service\Validation\SignerValidator; use OCA\Libresign\Service\Validation\SigningRequestValidator; +use OCA\Libresign\Service\Webhook\NativeWebhookEventPublisher; use OCP\AppFramework\Db\DoesNotExistException; use OCP\AppFramework\Db\MultipleObjectsReturnedException; use OCP\AppFramework\Utility\ITimeFactory; @@ -144,6 +143,7 @@ public function __construct( private TemporarySignatureImageService $temporarySignatureImageService, private NotificationDeliveryMapper $notificationDeliveries, private SigningWorkflowStatusResolver $signingWorkflowStatusResolver, + private NativeWebhookEventPublisher $webhooks, ) { } @@ -981,16 +981,7 @@ private function getCompletionTarget(FileEntity $file): FileEntity { } private function dispatchCompletionIfTransition(FileEntity $request, int $previousStatus): void { - $requestId = $request->getId(); - if ($requestId === null) { - return; - } - - $request = $this->fileMapper->getById($requestId); - $event = SigningRequestCompletedEvent::fromTransition($request, $previousStatus); - if ($event !== null) { - $this->eventDispatcher->dispatchTyped($event); - } + $this->webhooks->requestCompleted($request, $previousStatus); } protected function dispatchSignedEvent(): void { @@ -1021,18 +1012,7 @@ protected function dispatchSignedEvent(): void { ); $this->eventDispatcher->dispatchTyped($event); } finally { - try { - $root = $this->getCompletionTarget($this->libreSignFile); - $publicEvent = SignerSignedWebhookEvent::afterSigning($root, $this->libreSignFile, $this->signRequest); - if ($publicEvent !== null) { - $this->eventDispatcher->dispatchTyped($publicEvent); - } - } catch (\Throwable $e) { - $this->logger->warning('Unable to dispatch signer signed webhook event', [ - 'signRequestId' => $this->signRequest->getId(), - 'errorType' => get_debug_type($e), - ]); - } + $this->webhooks->signerSigned($this->libreSignFile, $this->signRequest); } } diff --git a/lib/Service/SignatureRejection/SignatureRejectionService.php b/lib/Service/SignatureRejection/SignatureRejectionService.php index a37485fa1a..27dda32c4e 100644 --- a/lib/Service/SignatureRejection/SignatureRejectionService.php +++ b/lib/Service/SignatureRejection/SignatureRejectionService.php @@ -16,14 +16,12 @@ use OCA\Libresign\Enum\SignatureRejectionCommentMode; use OCA\Libresign\Enum\SignRequestStatus; use OCA\Libresign\Events\SignatureRejectedEvent; -use OCA\Libresign\Events\SignerRejectedWebhookEvent; -use OCA\Libresign\Events\SigningRequestCanceledEvent; -use OCA\Libresign\Events\SigningRequestCompletedEvent; use OCA\Libresign\Exception\LibresignException; use OCA\Libresign\Service\File\SigningWorkflowStatusResolver; use OCA\Libresign\Service\FileStatusService; use OCA\Libresign\Service\IdentifyMethodService; use OCA\Libresign\Service\SequentialSigningService; +use OCA\Libresign\Service\Webhook\NativeWebhookEventPublisher; use OCP\AppFramework\Db\DoesNotExistException; use OCP\AppFramework\Utility\ITimeFactory; use OCP\EventDispatcher\IEventDispatcher; @@ -54,6 +52,7 @@ public function __construct( private ITimeFactory $timeFactory, private IL10N $l10n, private LoggerInterface $logger, + private NativeWebhookEventPublisher $webhooks, ) { } @@ -86,7 +85,7 @@ public function reject( : $libreSignFile; $previousRootStatus = $root->getStatus(); $activatedSigners = $this->persistRejection($libreSignFile, $signRequest, $normalizedComment, $commentIsPrivate, $config->cancelsWorkflow()); - $this->dispatchPublicRejectionEvents($libreSignFile, $signRequest, $previousRootStatus); + $this->webhooks->signerRejected($libreSignFile, $signRequest, $previousRootStatus); // Record the committed rejection before notification errors can interrupt this flow. // The event reports the status the rejection left, as the API does: a workflow that // continues after rejections is still canceled once every signer rejected. @@ -377,45 +376,6 @@ private function normalizeComment(?string $comment, SignatureRejectionCommentMod return $trimmed; } - private function dispatchPublicRejectionEvents( - FileEntity $document, - SignRequestEntity $signer, - int $previousRootStatus, - ): void { - try { - $root = $document->hasParent() - ? $this->fileMapper->getById($document->getParentFileId()) - : $document; - $events = [ - SignerRejectedWebhookEvent::afterRejection($root, $document, $signer, $this->isWorkflowCanceled($root)), - SigningRequestCanceledEvent::fromTransition($root, $previousRootStatus), - SigningRequestCompletedEvent::fromTransition($root, $previousRootStatus), - ]; - } catch (\Throwable $e) { - $this->logger->warning('Unable to prepare LibreSign rejection events', [ - 'fileId' => $document->getId(), - 'errorType' => get_debug_type($e), - ]); - return; - } - - foreach ($events as $event) { - if ($event === null) { - continue; - } - try { - $this->eventDispatcher->dispatchTyped($event); - } catch (\Throwable $e) { - // Listener errors cannot undo a persisted rejection or suppress later events. - $this->logger->warning('Unable to publish LibreSign rejection event', [ - 'fileId' => $document->getId(), - 'eventType' => $event::class, - 'errorType' => get_debug_type($e), - ]); - } - } - } - private function dispatchRejectedEvent( SignRequestEntity $signRequest, FileEntity $libreSignFile, diff --git a/lib/Service/Webhook/NativeWebhookEventPublisher.php b/lib/Service/Webhook/NativeWebhookEventPublisher.php new file mode 100644 index 0000000000..e495264f3a --- /dev/null +++ b/lib/Service/Webhook/NativeWebhookEventPublisher.php @@ -0,0 +1,141 @@ +publish('request.ready', ['fileId' => $request->getId()], + static fn (): ?Event => SigningRequestReadyEvent::fromTransition($request, FileStatus::DRAFT->value)); + } + + public function signerSigned(FileEntity $document, SignRequestEntity $signer): void { + $this->publish('signer.signed', [ + 'fileId' => $document->getId(), + 'signRequestId' => $signer->getId(), + ], fn (): ?Event => SignerSignedWebhookEvent::afterSigning( + $this->rootOf($document), $document, $signer, + )); + } + + public function signerRejected(FileEntity $document, SignRequestEntity $signer, int $previousRootStatus): void { + $context = ['fileId' => $document->getId(), 'signRequestId' => $signer->getId()]; + try { + $root = $this->rootOf($document); + } catch (\Throwable $e) { + $this->reportFailure($e, 'prepare', 'signer.rejected', $context); + return; + } + + // A listener failure cannot suppress later aggregate transitions. + $this->publish('signer.rejected', $context, + static fn (): ?Event => SignerRejectedWebhookEvent::afterRejection( + $root, $document, $signer, $root->getStatus() === FileStatus::CANCELED->value, + )); + $this->publish('request.canceled', $context, + static fn (): ?Event => SigningRequestCanceledEvent::fromTransition($root, $previousRootStatus)); + $this->publish('request.completed', $context, + static fn (): ?Event => SigningRequestCompletedEvent::fromTransition($root, $previousRootStatus)); + } + + public function requestCompleted(FileEntity $request, int $previousStatus): void { + $this->publish('request.completed', ['fileId' => $request->getId()], + function () use ($request, $previousStatus): ?Event { + $id = $request->getId(); + if ($id === null) { + return null; + } + return SigningRequestCompletedEvent::fromTransition($this->files->getById($id), $previousStatus); + }); + } + + public function notificationOutcome(int $deliveryId): void { + $this->publish('notification.outcome', ['deliveryId' => $deliveryId], + function () use ($deliveryId): ?Event { + $delivery = $this->deliveries->findById($deliveryId); + $document = $this->files->getById($delivery->getFileId()); + return NotificationDeliveryStatusChangedEvent::fromPersistedDelivery( + $this->rootOf($document), $delivery, + ); + }); + } + + /** @param \Closure(): ?Event $eventFactory */ + private function publish(string $eventName, array $context, \Closure $eventFactory): void { + try { + $event = $eventFactory(); + } catch (\Throwable $e) { + $this->reportFailure($e, 'prepare', $eventName, $context); + return; + } + if ($event === null) { + return; + } + + try { + $this->dispatcher->dispatchTyped($event); + } catch (\Throwable $e) { + $this->reportFailure($e, 'dispatch', $eventName, $context); + } + } + + private function rootOf(FileEntity $document): FileEntity { + return $document->hasParent() + ? $this->files->getById($document->getParentFileId()) + : $document; + } + + private function reportFailure(\Throwable $error, string $phase, string $eventName, array $context): void { + // Listener exceptions may contain private comments, tokens or recipients. + // Keep the type and source location, never the message or stack trace. + $details = $context + [ + 'event' => $eventName, + 'phase' => $phase, + 'errorType' => get_debug_type($error), + 'errorFile' => $error->getFile(), + 'errorLine' => $error->getLine(), + ]; + if ($phase === 'prepare' || $error instanceof \Error) { + $this->logger->error('Native webhook publication failed after commit', $details); + } else { + $this->logger->warning('Native webhook listener failed after commit', $details); + } + } +} diff --git a/tests/php/Unit/Service/FileStatusServiceTest.php b/tests/php/Unit/Service/FileStatusServiceTest.php index d3efe3b272..c0c39159a6 100644 --- a/tests/php/Unit/Service/FileStatusServiceTest.php +++ b/tests/php/Unit/Service/FileStatusServiceTest.php @@ -12,10 +12,8 @@ use OCA\Libresign\Db\File as FileEntity; use OCA\Libresign\Db\FileMapper; use OCA\Libresign\Enum\FileStatus; -use OCA\Libresign\Events\SigningRequestReadyEvent; use OCA\Libresign\Service\FileStatusService; use OCA\Libresign\Service\SignRequest\StatusCacheService; -use OCP\EventDispatcher\IEventDispatcher; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -24,13 +22,11 @@ class FileStatusServiceTest extends TestCase { private FileMapper|MockObject $fileMapper; private StatusCacheService|MockObject $statusCacheService; private FileStatusService $service; - private IEventDispatcher&MockObject $eventDispatcher; protected function setUp(): void { $this->fileMapper = $this->createMock(FileMapper::class); $this->statusCacheService = $this->createMock(StatusCacheService::class); - $this->eventDispatcher = $this->createMock(IEventDispatcher::class); - $this->service = new FileStatusService($this->fileMapper, $this->statusCacheService, $this->eventDispatcher); + $this->service = new FileStatusService($this->fileMapper, $this->statusCacheService); } public function testQueuedSigningStatusIsNotPublishedBeforeCommit(): void { @@ -53,31 +49,17 @@ public function testCommittedEnqueueDoesNotOverwriteNewerSigningProgress(): void $this->service->onQueuedJobCommitted($file); } - public function testStatusPersistenceDoesNotPublishBeforeSignerTransactionCommits(): void { + public function testStatusPersistenceDoesNotDispatchEvents(): void { $file = new FileEntity(); $file->setId(11); $file->setUuid('ready-uuid'); $file->setStatus(FileStatus::DRAFT->value); - $this->eventDispatcher->expects($this->never())->method('dispatchTyped'); $this->service->updateFileStatusIfUpgrade($file, FileStatus::ABLE_TO_SIGN->value); $this->assertSame(FileStatus::ABLE_TO_SIGN->value, $file->getStatus()); } - public function testReadyEventIsPublishedWhenExplicitlyRequestedAfterPersistence(): void { - $file = new FileEntity(); - $file->setId(11); - $file->setUuid('ready-uuid'); - $file->setStatus(FileStatus::ABLE_TO_SIGN->value); - $this->eventDispatcher->expects($this->once())->method('dispatchTyped') - ->with($this->callback(static function ($event): bool { - return $event instanceof SigningRequestReadyEvent - && $event->getWebhookSerializable()['status'] === 'ready_to_sign'; - })); - $this->service->dispatchReadyRequest($file); - } - #[DataProvider('dataFileStatusUpgrade')] public function testUpdateFileStatusIfUpgrade(int $currentStatus, int $newStatus, bool $shouldUpdate): void { $file = new FileEntity(); diff --git a/tests/php/Unit/Service/Notification/NotificationDeliveryEventPublisherTest.php b/tests/php/Unit/Service/Notification/NotificationDeliveryEventPublisherTest.php deleted file mode 100644 index 66d35caf3e..0000000000 --- a/tests/php/Unit/Service/Notification/NotificationDeliveryEventPublisherTest.php +++ /dev/null @@ -1,112 +0,0 @@ -deliveries = $this->createMock(NotificationDeliveryMapper::class); - $this->files = $this->createMock(FileMapper::class); - $this->dispatcher = $this->createMock(IEventDispatcher::class); - $this->logger = $this->createMock(LoggerInterface::class); - $this->publisher = new NotificationDeliveryEventPublisher( - $this->deliveries, $this->files, $this->dispatcher, $this->logger, - ); - } - - private function delivery(string $state = 'accepted'): NotificationDelivery { - $delivery = new NotificationDelivery(); - $delivery->setId(9); - $delivery->setFileId(25); - $delivery->setState($state); - $delivery->setAttemptCount(1); - $delivery->setChannel('mail'); - $delivery->setRecipientEnc('PRIVATE_RECIPIENT'); - return $delivery; - } - - public function testPublishedOutcomeUsesRootOfEnvelopeWithoutDisclosingRecipient(): void { - $this->deliveries->method('findById')->with(9)->willReturn($this->delivery()); - $child = new File(); - $child->setParentFileId(10); - $root = new File(); - $root->setUuid('root-uuid'); - $root->setNodeType('envelope'); - $this->files->method('getById')->willReturnMap([[25, $child], [10, $root]]); - $this->dispatcher->expects($this->once())->method('dispatchTyped') - ->with($this->callback(static function ($event): bool { - if (!$event instanceof NotificationDeliveryStatusChangedEvent) { - return false; - } - $payload = $event->getWebhookSerializable(); - return $payload['requestUuid'] === 'root-uuid' - && $payload['requestType'] === 'envelope' - && !str_contains(json_encode($payload), 'PRIVATE_RECIPIENT'); - })); - $this->publisher->publish(9); - } - - public function testPendingDeliveryCannotPublishAnOutcome(): void { - $this->deliveries->method('findById')->willReturn($this->delivery(NotificationDeliveryState::PENDING->value)); - $root = new File(); - $root->setUuid('root-uuid'); - $this->files->method('getById')->willReturn($root); - $this->dispatcher->expects($this->never())->method('dispatchTyped'); - $this->publisher->publish(9); - } - - public function testExpectedRepositoryFailureIsLoggedWithoutSensitiveData(): void { - $this->deliveries->method('findById') - ->willThrowException(new \RuntimeException('PRIVATE_RECIPIENT')); - $this->dispatcher->expects($this->never())->method('dispatchTyped'); - $this->logger->expects($this->once())->method('warning') - ->with($this->anything(), $this->callback(static function (array $context): bool { - return !str_contains(json_encode($context), 'PRIVATE_RECIPIENT') - && $context['deliveryId'] === 9; - })); - $this->publisher->publish(9); - } - - public function testListenerProgrammingErrorCannotInterruptCommittedDelivery(): void { - $this->deliveries->method('findById')->willReturn($this->delivery()); - $root = new File(); - $root->setUuid('root-uuid'); - $this->files->method('getById')->willReturn($root); - $this->dispatcher->method('dispatchTyped')->willThrowException( - new \TypeError('PRIVATE_WEBHOOK_DETAILS'), - ); - $this->logger->expects($this->once())->method('warning')->with( - 'Unable to publish persisted notification outcome', - $this->callback(static fn (array $context): bool - => ($context['deliveryId'] ?? null) === 9 - && ($context['errorType'] ?? null) === \TypeError::class - && !str_contains(json_encode($context), 'PRIVATE_WEBHOOK_DETAILS') - ), - ); - - $this->publisher->publish(9); - } -} diff --git a/tests/php/Unit/Service/Notification/NotificationSubmissionServiceTest.php b/tests/php/Unit/Service/Notification/NotificationSubmissionServiceTest.php index e33764297b..724ba62735 100644 --- a/tests/php/Unit/Service/Notification/NotificationSubmissionServiceTest.php +++ b/tests/php/Unit/Service/Notification/NotificationSubmissionServiceTest.php @@ -20,11 +20,11 @@ use OCA\Libresign\Exception\NotificationTransportException; use OCA\Libresign\Service\Notification\MailPayload; use OCA\Libresign\Service\Notification\NotificationChannel; -use OCA\Libresign\Service\Notification\NotificationDeliveryEventPublisher; use OCA\Libresign\Service\Notification\NotificationFailureClassifier; use OCA\Libresign\Service\Notification\NotificationHistoryService; use OCA\Libresign\Service\Notification\NotificationMessage; use OCA\Libresign\Service\Notification\NotificationSubmissionService; +use OCA\Libresign\Service\Webhook\NativeWebhookEventPublisher; use OCP\IDBConnection; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; @@ -38,7 +38,7 @@ private function message(): NotificationMessage { private function service( NotificationDeliveryMapper $deliveries, NotificationAttemptMapper $attempts, - NotificationDeliveryEventPublisher $publisher, + NativeWebhookEventPublisher $publisher, ?IDBConnection $db = null, ): NotificationSubmissionService { return new NotificationSubmissionService( @@ -83,8 +83,8 @@ static function (?\DateTime $due) use ($expectRetry, $attemptNumber): bool { $db->expects($this->never())->method('rollBack'); $channel = $this->createMock(NotificationChannel::class); $channel->method('deliver')->willThrowException($failure); - $publisher = $this->createMock(NotificationDeliveryEventPublisher::class); - $publisher->expects($this->once())->method('publish')->with(9); + $publisher = $this->createMock(NativeWebhookEventPublisher::class); + $publisher->expects($this->once())->method('notificationOutcome')->with(9); $service = $this->service($deliveries, $attempts, $publisher, $db); $this->expectException(get_class($failure)); $service->submit($delivery, $this->message(), $channel); @@ -145,8 +145,8 @@ public function testPublishedOutcomeFollowsFinalLedgerCommit(): void { ->willReturnCallback(function () use (&$commits): void { $this->assertSame(1, $commits, 'The attempt must be claimed before sending.'); }); - $publisher = $this->createMock(NotificationDeliveryEventPublisher::class); - $publisher->expects($this->once())->method('publish')->with(9) + $publisher = $this->createMock(NativeWebhookEventPublisher::class); + $publisher->expects($this->once())->method('notificationOutcome')->with(9) ->willReturnCallback(function () use (&$commits): void { $this->assertSame(2, $commits, 'Publication must follow the committed ledger outcome.'); }); @@ -168,8 +168,8 @@ public function testFailedLedgerPersistenceDoesNotPublishOutcome(): void { $db = $this->createMock(IDBConnection::class); $db->expects($this->once())->method('rollBack'); - $publisher = $this->createMock(NotificationDeliveryEventPublisher::class); - $publisher->expects($this->never())->method('publish'); + $publisher = $this->createMock(NativeWebhookEventPublisher::class); + $publisher->expects($this->never())->method('notificationOutcome'); $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('ledger write failed'); @@ -187,8 +187,8 @@ public function testAlreadyClaimedDeliveryNeverSubmitsOrPublishes(): void { $deliveries->method('claim')->willReturn(false); $channel = $this->createMock(NotificationChannel::class); $channel->expects($this->never())->method('deliver'); - $publisher = $this->createMock(NotificationDeliveryEventPublisher::class); - $publisher->expects($this->never())->method('publish'); + $publisher = $this->createMock(NativeWebhookEventPublisher::class); + $publisher->expects($this->never())->method('notificationOutcome'); $this->assertFalse($this->service( $deliveries, $this->createMock(NotificationAttemptMapper::class), diff --git a/tests/php/Unit/Service/NotificationDeliveryServiceTest.php b/tests/php/Unit/Service/NotificationDeliveryServiceTest.php index 2e6bbff6f0..134418473a 100644 --- a/tests/php/Unit/Service/NotificationDeliveryServiceTest.php +++ b/tests/php/Unit/Service/NotificationDeliveryServiceTest.php @@ -79,7 +79,7 @@ protected function setUp(): void { new NotificationFailureClassifier(), new NotificationHistoryService($this->createMock(\OCA\Libresign\Db\SignRequestMapper::class)), $this->createMock(LoggerInterface::class), - $this->createMock(\OCA\Libresign\Service\Notification\NotificationDeliveryEventPublisher::class), + $this->createMock(\OCA\Libresign\Service\Webhook\NativeWebhookEventPublisher::class), ), new NotificationEnvelopeCodec($handoffCrypto, $this->createMock(IManager::class)), $this->mode, diff --git a/tests/php/Unit/Service/RequestSignatureServiceTest.php b/tests/php/Unit/Service/RequestSignatureServiceTest.php index e4cbf25dd9..be289f0b48 100644 --- a/tests/php/Unit/Service/RequestSignatureServiceTest.php +++ b/tests/php/Unit/Service/RequestSignatureServiceTest.php @@ -41,6 +41,7 @@ use OCA\Libresign\Service\Validation\FileInputValidator; use OCA\Libresign\Service\Validation\SignerValidator; use OCA\Libresign\Service\Validation\SigningRequestValidator; +use OCA\Libresign\Service\Webhook\NativeWebhookEventPublisher; use OCP\Files\Folder; use OCP\Files\IMimeTypeDetector; use OCP\Http\Client\IClient; @@ -87,6 +88,7 @@ final class RequestSignatureServiceTest extends \OCA\Libresign\Tests\Unit\TestCa private SignerGeolocationPolicyService&MockObject $signerGeolocationPolicyService; private \OCP\IDBConnection&MockObject $db; private \OCA\Libresign\Service\NotificationDeliveryService&MockObject $notifications; + private NativeWebhookEventPublisher&MockObject $webhooks; public function setUp(): void { parent::setUp(); @@ -127,6 +129,7 @@ public function setUp(): void { $this->signerGeolocationPolicyService = $this->createMock(SignerGeolocationPolicyService::class); $this->db = $this->createMock(\OCP\IDBConnection::class); $this->notifications = $this->createMock(\OCA\Libresign\Service\NotificationDeliveryService::class); + $this->webhooks = $this->createMock(NativeWebhookEventPublisher::class); } private function getService(array $methods = []): RequestSignatureService|MockObject { @@ -164,6 +167,7 @@ private function getService(array $methods = []): RequestSignatureService|MockOb $this->signerRemovalService, $this->db, $this->notifications, + $this->webhooks, ]) ->onlyMethods($methods) ->getMock(); @@ -201,6 +205,7 @@ private function getService(array $methods = []): RequestSignatureService|MockOb $this->signerRemovalService, $this->db, $this->notifications, + $this->webhooks, ); } @@ -338,7 +343,7 @@ public function testReadyRequestEventIsPublishedOnlyAfterSignerTransactionCommit ->willReturnCallback(static function () use (&$committed): void { $committed = true; }); - $this->fileStatusService->expects($this->once())->method('dispatchReadyRequest') + $this->webhooks->expects($this->once())->method('requestReady') ->with($this->callback(static function ($published) use (&$committed, $file): bool { return $committed && $published === $file && $file->getStatus() === \OCA\Libresign\Enum\FileStatus::ABLE_TO_SIGN->value; @@ -350,38 +355,6 @@ public function testReadyRequestEventIsPublishedOnlyAfterSignerTransactionCommit ])); } - public function testReadyWebhookFailureDoesNotInvalidateCommittedRequest(): void { - $file = new \OCA\Libresign\Db\File(); - $file->setUuid('ready-uuid'); - $file->setStatus(\OCA\Libresign\Enum\FileStatus::DRAFT->value); - $this->fileMapper->method('getByUuid')->with('ready-uuid')->willReturn($file); - $this->fileStatusService->method('updateFileStatusIfUpgrade') - ->willReturnCallback(static function ($file, int $status) { - $file->setStatus($status); - return $file; - }); - $committed = false; - $this->db->expects($this->once())->method('commit') - ->willReturnCallback(static function () use (&$committed): void { - $committed = true; - }); - $this->fileStatusService->method('dispatchReadyRequest') - ->willThrowException(new \TypeError('PRIVATE_WEBHOOK_DETAILS')); - $this->loggerInterface->expects($this->once())->method('warning')->with( - 'Unable to publish signing request ready event', - $this->callback(static fn (array $context): bool - => ($context['errorType'] ?? null) === \TypeError::class - && !str_contains(json_encode($context), 'PRIVATE_WEBHOOK_DETAILS') - ), - ); - - $this->assertSame($file, $this->getService()->save([ - 'uuid' => 'ready-uuid', - 'status' => \OCA\Libresign\Enum\FileStatus::ABLE_TO_SIGN->value, - ])); - $this->assertTrue($committed); - } - public function testReadyRequestEventIsNotPublishedWhenSignerPersistenceFails(): void { $file = new \OCA\Libresign\Db\File(); $file->setUuid('ready-uuid'); @@ -396,7 +369,7 @@ public function testReadyRequestEventIsNotPublishedWhenSignerPersistenceFails(): ->willThrowException(new \RuntimeException('invalid signer')); $this->db->expects($this->once())->method('rollBack'); $this->db->expects($this->never())->method('commit'); - $this->fileStatusService->expects($this->never())->method('dispatchReadyRequest'); + $this->webhooks->expects($this->never())->method('requestReady'); $this->expectException(\RuntimeException::class); $this->getService()->save([ @@ -968,6 +941,7 @@ public function testDeleteIdentifyMethodIfNotExitsKeepsMatchingIdentifyMethods() $this->signerRemovalService, $this->createMock(\OCP\IDBConnection::class), $this->createMock(\OCA\Libresign\Service\NotificationDeliveryService::class), + $this->webhooks, ]) ->onlyMethods(['unassociateToUser']) ->getMock(); @@ -1046,6 +1020,7 @@ public function testDeleteIdentifyMethodIfNotExitsRemovesMissingIdentifyMethods( $this->signerRemovalService, $this->createMock(\OCP\IDBConnection::class), $this->createMock(\OCA\Libresign\Service\NotificationDeliveryService::class), + $this->webhooks, ]) ->onlyMethods(['unassociateToUser']) ->getMock(); diff --git a/tests/php/Unit/Service/SignFileServiceTest.php b/tests/php/Unit/Service/SignFileServiceTest.php index 42e1944b42..ffd2cf76de 100644 --- a/tests/php/Unit/Service/SignFileServiceTest.php +++ b/tests/php/Unit/Service/SignFileServiceTest.php @@ -30,8 +30,6 @@ use OCA\Libresign\Enum\SignRequestStatus; use OCA\Libresign\Events\SignedEvent; use OCA\Libresign\Events\SignedEventFactory; -use OCA\Libresign\Events\SignerSignedWebhookEvent; -use OCA\Libresign\Events\SigningRequestCompletedEvent; use OCA\Libresign\Exception\LibresignException; use OCA\Libresign\Handler\DocMdpHandler; use OCA\Libresign\Handler\FooterHandler; @@ -69,6 +67,7 @@ use OCA\Libresign\Service\Validation\IdentityDocumentValidator; use OCA\Libresign\Service\Validation\SignerValidator; use OCA\Libresign\Service\Validation\SigningRequestValidator; +use OCA\Libresign\Service\Webhook\NativeWebhookEventPublisher; use OCP\AppFramework\Db\DoesNotExistException; use OCP\AppFramework\Utility\ITimeFactory; use OCP\BackgroundJob\IJobList; @@ -109,6 +108,7 @@ final class SignFileServiceTest extends \OCA\Libresign\Tests\Unit\TestCase { private FileElementMapper&MockObject $fileElementMapper; private UserElementMapper&MockObject $userElementMapper; private IEventDispatcher&MockObject $eventDispatcher; + private NativeWebhookEventPublisher&MockObject $webhooks; private ISecureRandom&MockObject $secureRandom; private IURLGenerator&MockObject $urlGenerator; private IdentifyMethodMapper&MockObject $identifyMethodMapper; @@ -164,6 +164,7 @@ public function setUp(): void { $this->fileElementMapper = $this->createMock(FileElementMapper::class); $this->userElementMapper = $this->createMock(UserElementMapper::class); $this->eventDispatcher = $this->createMock(IEventDispatcher::class); + $this->webhooks = $this->createMock(NativeWebhookEventPublisher::class); $this->secureRandom = $this->createMock(ISecureRandom::class); $this->secureRandom->method('generate')->willReturn('temporary-password'); $this->urlGenerator = $this->createMock(IURLGenerator::class); @@ -543,6 +544,7 @@ private function getService(array $methods = []): SignFileService|MockObject { new TemporarySignatureImageService($this->tempManager, $this->l10n), $this->notificationDeliveries, new SigningWorkflowStatusResolver($this->idDocsMapper, $this->signatureRejectionPolicyService), + $this->webhooks, ]) ->onlyMethods($methods) ->getMock(); @@ -592,6 +594,7 @@ private function getService(array $methods = []): SignFileService|MockObject { new TemporarySignatureImageService($this->tempManager, $this->l10n), $this->notificationDeliveries, new SigningWorkflowStatusResolver($this->idDocsMapper, $this->signatureRejectionPolicyService), + $this->webhooks, ); } @@ -826,57 +829,24 @@ public function testDispatchEventWhenSign(): void { ->sign(); } - public static function nativeCompletionCases(): array { - return [ - 'partial workflow' => [33, FileStatus::ABLE_TO_SIGN, FileStatus::PARTIAL_SIGNED, false], - 'document completed' => [33, FileStatus::PARTIAL_SIGNED, FileStatus::SIGNED, true], - 'already completed' => [33, FileStatus::SIGNED, FileStatus::SIGNED, false], - 'unpersisted request' => [null, FileStatus::PARTIAL_SIGNED, FileStatus::SIGNED, false], - ]; - } - - #[DataProvider('nativeCompletionCases')] - public function testNativeWebhookOnlyForCompletedDocumentWorkflow(?int $id, FileStatus $before, FileStatus $after, bool $completed): void { + public function testSigningDelegatesCompletionAfterPersistence(): void { $service = $this->getService([ 'getEngine', 'computeHash', 'validateDocMdpAllowsSignatures', 'updateSignRequest', 'updateLibreSignFile', 'dispatchSignedEvent', ]); $file = new File(); - if ($id !== null) { - $file->setId($id); - } + $file->setId(33); $file->setUuid('workflow-uuid'); - $file->setStatus($before->value); - - $saved = new File(); - $saved->setUuid('workflow-uuid'); - $saved->setStatus($after->value); - $this->fileMapper->method('getById')->willReturn($saved); - - $nextcloudFile = $this->createMock(\OCP\Files\File::class); - $nextcloudFile->method('getId')->willReturn(999); + $file->setStatus(FileStatus::PARTIAL_SIGNED->value); + $signedFile = $this->createMock(\OCP\Files\File::class); + $signedFile->method('getId')->willReturn(999); $engine = $this->createMock(Pkcs12Handler::class); - $engine->method('sign')->willReturn($nextcloudFile); + $engine->method('sign')->willReturn($signedFile); $service->method('getEngine')->willReturn($engine); $service->method('computeHash')->willReturn('hash'); - - $events = []; - $this->eventDispatcher->method('dispatchTyped') - ->willReturnCallback(static function ($event) use (&$events): void { - $events[] = $event; - }); - + $this->webhooks->expects($this->once())->method('requestCompleted') + ->with($file, FileStatus::PARTIAL_SIGNED->value); $service->signSingleFile($file, new SignRequest()); - $this->assertSame($completed ? [[ - 'contractVersion' => 1, - 'eventId' => 'libresign.workflow.completed.v1:workflow-uuid', - 'requestUuid' => 'workflow-uuid', - 'requestType' => 'document', - 'status' => 'completed', - ]] : [], array_map( - static fn (SigningRequestCompletedEvent $event): array => $event->getWebhookSerializable(), - $events, - )); } public function testLegacyListenerFailureDoesNotSuppressNativeSigningEvent(): void { @@ -903,10 +873,9 @@ public function testLegacyListenerFailureDoesNotSuppressNativeSigningEvent(): vo $this->fileMapper->method('getById')->willReturn($file); $this->signedEventFactory->method('make')->willReturn($this->createMock(SignedEvent::class)); - $events = []; + $this->webhooks->expects($this->once())->method('signerSigned')->with($file, $signer); $this->eventDispatcher->method('dispatchTyped')->willReturnCallback( - static function ($event) use (&$events): void { - $events[] = $event; + static function ($event): void { if ($event instanceof SignedEvent) { throw new \RuntimeException('private callback details'); } @@ -914,67 +883,7 @@ static function ($event) use (&$events): void { ); $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('private callback details'); - try { - $service->signSingleFile($file, $signer); - } finally { - $published = array_values(array_filter( - $events, - static fn ($event): bool => $event instanceof SignerSignedWebhookEvent, - )); - $this->assertCount(1, $published); - $this->assertSame('document-uuid', $published[0]->getWebhookSerializable()['requestUuid']); - } - } - - public function testNativeWebhookListenerErrorCannotInterruptCommittedSigning(): void { - $service = $this->getService([ - 'getEngine', 'computeHash', 'validateDocMdpAllowsSignatures', - 'updateSignRequest', 'updateLibreSignFile', - ]); - $file = new File(); - $file->setId(17); - $file->setUuid('document-uuid'); - $file->setStatus(FileStatus::ABLE_TO_SIGN->value); - $signer = new SignRequest(); - $signer->setId(31); - $signer->setSigned(new DateTime('2026-11-09T11:00:00Z')); - $signer->setSignedHash('signed-content-hash'); - - $signedFile = $this->createMock(\OCP\Files\File::class); - $signedFile->method('getId')->willReturn(123); - $engine = $this->createMock(Pkcs12Handler::class); - $engine->method('sign')->willReturn($signedFile); - $engine->method('getInputFile')->willReturn($signedFile); - $service->method('getEngine')->willReturn($engine); - $service->method('computeHash')->willReturn('signed-content-hash'); - $service->method('updateLibreSignFile')->willReturnCallback( - static function (File $file): void { - $file->setStatus(FileStatus::SIGNED->value); - }, - ); - $this->fileMapper->method('getById')->willReturn($file); - $this->signedEventFactory->method('make')->willReturn($this->createMock(SignedEvent::class)); - $events = []; - $this->eventDispatcher->method('dispatchTyped')->willReturnCallback( - static function ($event) use (&$events): void { - $events[] = $event; - if ($event instanceof SignerSignedWebhookEvent) { - throw new \TypeError('PRIVATE_WEBHOOK_DETAILS'); - } - }, - ); - $this->logger->expects($this->once())->method('warning')->with( - 'Unable to dispatch signer signed webhook event', - $this->callback(static fn (array $context): bool - => ($context['errorType'] ?? null) === \TypeError::class - && !str_contains(json_encode($context), 'PRIVATE_WEBHOOK_DETAILS') - ), - ); - $service->signSingleFile($file, $signer); - - $this->assertSame(FileStatus::SIGNED->value, $file->getStatus()); - $this->assertCount(1, array_filter($events, static fn ($event): bool => $event instanceof SigningRequestCompletedEvent)); } public function testUpdateEnvelopeStatusAddsStatusChangedAt(): void { diff --git a/tests/php/Unit/Service/SignatureRejection/SignatureRejectionServiceTest.php b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionServiceTest.php index eb3f7cefa0..14384d81c2 100644 --- a/tests/php/Unit/Service/SignatureRejection/SignatureRejectionServiceTest.php +++ b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionServiceTest.php @@ -15,9 +15,6 @@ use OCA\Libresign\Enum\FileStatus; use OCA\Libresign\Enum\SignRequestStatus; use OCA\Libresign\Events\SignatureRejectedEvent; -use OCA\Libresign\Events\SignerRejectedWebhookEvent; -use OCA\Libresign\Events\SigningRequestCanceledEvent; -use OCA\Libresign\Events\SigningRequestCompletedEvent; use OCA\Libresign\Exception\LibresignException; use OCA\Libresign\Service\File\SigningWorkflowStatusResolver; use OCA\Libresign\Service\FileStatusService; @@ -27,6 +24,7 @@ use OCA\Libresign\Service\SequentialSigningService; use OCA\Libresign\Service\SignatureRejection\SignatureRejectionPolicyService; use OCA\Libresign\Service\SignatureRejection\SignatureRejectionService; +use OCA\Libresign\Service\Webhook\NativeWebhookEventPublisher; use OCP\AppFramework\Db\DoesNotExistException; use OCP\AppFramework\Utility\ITimeFactory; use OCP\EventDispatcher\IEventDispatcher; @@ -52,6 +50,7 @@ final class SignatureRejectionServiceTest extends TestCase { private ITimeFactory&MockObject $timeFactory; private IL10N&MockObject $l10n; private LoggerInterface&MockObject $logger; + private NativeWebhookEventPublisher&MockObject $webhooks; /** @var list */ private array $envelopeChildSignRequests = []; private ?SignRequest $envelopeSignRequest = null; @@ -72,6 +71,7 @@ protected function setUp(): void { $this->timeFactory = $this->createMock(ITimeFactory::class); $this->l10n = $this->createMock(IL10N::class); $this->logger = $this->createMock(LoggerInterface::class); + $this->webhooks = $this->createMock(NativeWebhookEventPublisher::class); $this->l10n->method('t')->willReturnArgument(0); $this->timeFactory->method('getDateTime') @@ -116,6 +116,7 @@ private function getService(): SignatureRejectionService { $this->timeFactory, $this->l10n, $this->logger, + $this->webhooks, ); } @@ -289,31 +290,22 @@ public function testPrivateFlagIsIgnoredWhenThereIsNoComment(): void { } #[DataProvider('publicRejectionOutcomes')] - public function testCommittedRejectionEmitsOnePublicBusinessEvent(bool $cancel): void { + public function testCommittedRejectionDelegatesBusinessEvent(bool $cancel): void { $this->withPolicy(self::policy($cancel ? 'cancel' : 'continue', 'optional')); $file = $this->file(); $file->setUuid('request-uuid'); $signer = $this->signRequest(); - $signer->setUuid('secret-invitation'); - $events = []; - $this->eventDispatcher->method('dispatchTyped')->willReturnCallback(static function ($event) use (&$events): void { - $events[] = $event; - }); + $this->db->expects($this->once())->method('commit'); + $this->webhooks->expects($this->once())->method('signerRejected') + ->with($file, $signer, FileStatus::ABLE_TO_SIGN->value); $this->getService()->reject($file, $signer, 'private explanation', true); - $rejections = array_values(array_filter($events, static fn ($event): bool => $event instanceof SignerRejectedWebhookEvent)); - $cancellations = array_values(array_filter($events, static fn ($event): bool => $event instanceof SigningRequestCanceledEvent)); - $this->assertCount(1, $rejections); - $this->assertCount($cancel ? 1 : 0, $cancellations); - $this->assertSame($cancel, $rejections[0]->getWebhookSerializable()['workflowCanceled']); - $this->assertStringNotContainsString('private explanation', json_encode($rejections[0]->getWebhookSerializable())); + $this->assertSame(SignRequestStatus::REJECTED, $signer->getStatusEnum()); + $this->assertTrue($signer->getRejectionCommentPrivate()); } /** @return array */ public static function publicRejectionOutcomes(): array { - return [ - 'continue' => [false], - 'cancel' => [true], - ]; + return ['continue' => [false], 'cancel' => [true]]; } public function testProgrammingErrorDuringRejectionRollsBackAndRemainsVisible(): void { @@ -332,69 +324,14 @@ public function testProgrammingErrorDuringRejectionRollsBackAndRemainsVisible(): } } - public function testFailedPublicRejectionEventDoesNotSuppressCancellationEvent(): void { - $this->withPolicy(self::policy('cancel')); - $file = $this->file(); - $file->setUuid('workflow-uuid'); - $signer = $this->signRequest(); - $events = []; - $this->eventDispatcher->method('dispatchTyped')->willReturnCallback( - static function ($event) use (&$events): void { - $events[] = $event; - if ($event instanceof SignerRejectedWebhookEvent) { - throw new \RuntimeException('private recipient information'); - } - }, - ); - $this->logger->expects($this->once())->method('warning') - ->with($this->anything(), $this->callback(static function (array $context): bool { - return $context['errorType'] === 'RuntimeException' - && !str_contains(json_encode($context), 'private recipient information'); - })); - $this->getService()->reject($file, $signer); - $this->assertCount(1, array_filter($events, static fn ($event): bool => $event instanceof SigningRequestCanceledEvent)); - } - - public function testPublicWebhookErrorCannotInterruptCommittedRejection(): void { - $this->withPolicy(self::policy('cancel')); - $file = $this->file(); - $file->setUuid('workflow-uuid'); - $signer = $this->signRequest(); - $this->db->expects($this->once())->method('commit'); - $this->db->expects($this->never())->method('rollBack'); - $events = []; - $this->eventDispatcher->method('dispatchTyped')->willReturnCallback( - static function ($event) use (&$events): void { - $events[] = $event; - if ($event instanceof SignerRejectedWebhookEvent) { - throw new \TypeError('PRIVATE_WEBHOOK_DETAILS'); - } - }, - ); - $this->logger->expects($this->once())->method('warning')->with( - 'Unable to publish LibreSign rejection event', - $this->callback(static fn (array $context): bool - => ($context['errorType'] ?? null) === \TypeError::class - && !str_contains(json_encode($context), 'PRIVATE_WEBHOOK_DETAILS') - ), - ); - - $this->assertSame($signer, $this->getService()->reject($file, $signer)); - $this->assertCount(1, array_filter($events, static fn ($event): bool => $event instanceof SigningRequestCanceledEvent)); - } - public function testRejectionCanCompletePreviouslySignedWorkflow(): void { $this->withPolicy(self::policy('continue')); $file = $this->file(FileStatus::PARTIAL_SIGNED->value); $file->setUuid('completed-by-rejection'); $this->signingWorkflowStatusResolver->method('resolve')->willReturn(FileStatus::SIGNED); - $events = []; - $this->eventDispatcher->method('dispatchTyped')->willReturnCallback(static function ($event) use (&$events): void { - $events[] = $event; - }); + $this->webhooks->expects($this->once())->method('signerRejected')->with($file, $this->anything(), FileStatus::PARTIAL_SIGNED->value); $this->getService()->reject($file, $this->signRequest()); $this->assertSame(FileStatus::SIGNED->value, $file->getStatus()); - $this->assertCount(1, array_filter($events, static fn ($event): bool => $event instanceof SigningRequestCompletedEvent)); } public function testRejectionIsPersistedWithItsTimestampAndComment(): void { diff --git a/tests/php/Unit/Service/Webhook/NativeWebhookEventPublisherTest.php b/tests/php/Unit/Service/Webhook/NativeWebhookEventPublisherTest.php new file mode 100644 index 0000000000..aa17d23ef4 --- /dev/null +++ b/tests/php/Unit/Service/Webhook/NativeWebhookEventPublisherTest.php @@ -0,0 +1,246 @@ +files = $this->createMock(FileMapper::class); + $this->deliveries = $this->createMock(NotificationDeliveryMapper::class); + $this->dispatcher = $this->createMock(IEventDispatcher::class); + $this->logger = $this->createMock(LoggerInterface::class); + $this->publisher = new NativeWebhookEventPublisher( + $this->dispatcher, $this->logger, $this->files, $this->deliveries, + ); + } + + private static function file(int $id, string $uuid, FileStatus $status): File { + $file = new File(); + $file->setId($id); + $file->setUuid($uuid); + $file->setStatus($status->value); + return $file; + } + + private static function signer(bool $rejected = false): SignRequest { + $signer = new SignRequest(); + $signer->setId(17); + $signer->setUuid('SECRET_INVITATION'); + if ($rejected) { + $signer->setStatusEnum(SignRequestStatus::REJECTED); + $signer->setRejectedAt(new \DateTime('2026-11-10T10:00:00Z')); + $signer->setRejectionComment('PRIVATE_REJECTION_COMMENT'); + $signer->setRejectionCommentPrivate(true); + } else { + $signer->setSigned(new \DateTime('2026-11-10T10:00:00Z')); + $signer->setSignedHash('signed-hash'); + } + return $signer; + } + + private static function delivery(NotificationDeliveryState $state): NotificationDelivery { + $delivery = new NotificationDelivery(); + $delivery->setId(9); + $delivery->setFileId(25); + $delivery->setState($state->value); + $delivery->setAttemptCount(1); + $delivery->setChannel('mail'); + $delivery->setRecipientEnc('PRIVATE_RECIPIENT'); + return $delivery; + } + + public function testReadyEventIsPublishedForReadyRoot(): void { + $root = self::file(13, 'request-uuid', FileStatus::ABLE_TO_SIGN); + $this->dispatcher->expects($this->once())->method('dispatchTyped') + ->with($this->callback(static fn ($event): bool + => $event instanceof SigningRequestReadyEvent + && $event->getWebhookSerializable()['requestUuid'] === 'request-uuid')); + $this->publisher->requestReady($root); + } + + public function testReadyChildIsNotPublished(): void { + $child = self::file(25, 'child-uuid', FileStatus::ABLE_TO_SIGN); + $child->setParentFileId(13); + $this->dispatcher->expects($this->never())->method('dispatchTyped'); + $this->publisher->requestReady($child); + } + + public function testSignerSignedEventUsesEnvelopeRootAndNeverExposesInvitation(): void { + $child = self::file(25, 'child-uuid', FileStatus::SIGNED); + $child->setParentFileId(13); + $root = self::file(13, 'root-uuid', FileStatus::PARTIAL_SIGNED); + $root->setNodeType('envelope'); + $this->files->method('getById')->with(13)->willReturn($root); + $this->dispatcher->expects($this->once())->method('dispatchTyped') + ->with($this->callback(static function ($event): bool { + if (!$event instanceof SignerSignedWebhookEvent) { + return false; + } + $payload = $event->getWebhookSerializable(); + return $payload['requestUuid'] === 'root-uuid' + && $payload['documentUuid'] === 'child-uuid' + && $payload['requestType'] === 'envelope' + && !str_contains(json_encode($payload), 'SECRET_INVITATION'); + })); + $this->publisher->signerSigned($child, self::signer()); + } + + public function testFailedRejectionListenerDoesNotSuppressCancellation(): void { + $root = self::file(13, 'root-uuid', FileStatus::CANCELED); + $root->setNodeType('envelope'); + $child = self::file(25, 'child-uuid', FileStatus::CANCELED); + $child->setParentFileId(13); + $this->files->method('getById')->with(13)->willReturn($root); + $published = []; + $this->dispatcher->method('dispatchTyped')->willReturnCallback( + static function ($event) use (&$published): void { + $published[] = $event; + if ($event instanceof SignerRejectedWebhookEvent) { + throw new \RuntimeException('PRIVATE_REJECTION_COMMENT'); + } + }); + $this->logger->expects($this->once())->method('warning') + ->with('Native webhook listener failed after commit', $this->callback( + static fn (array $context): bool + => ($context['phase'] ?? null) === 'dispatch' + && ($context['event'] ?? null) === 'signer.rejected' + && !str_contains(json_encode($context), 'PRIVATE_REJECTION_COMMENT'), + )); + $this->publisher->signerRejected($child, self::signer(true), FileStatus::ABLE_TO_SIGN->value); + $this->assertCount(1, array_filter($published, static fn ($event): bool => $event instanceof SigningRequestCanceledEvent)); + $this->assertCount(1, array_filter($published, static fn ($event): bool => $event instanceof SignerRejectedWebhookEvent)); + } + + public function testRejectionCanCompletePreviouslyPartiallySignedWorkflow(): void { + $root = self::file(13, 'root-uuid', FileStatus::SIGNED); + $published = []; + $this->dispatcher->method('dispatchTyped')->willReturnCallback( + static function ($event) use (&$published): void { + $published[] = $event; + }); + $this->publisher->signerRejected($root, self::signer(true), FileStatus::PARTIAL_SIGNED->value); + $this->assertCount(1, array_filter($published, static fn ($event): bool => $event instanceof SigningRequestCompletedEvent)); + $this->assertCount(0, array_filter($published, static fn ($event): bool => $event instanceof SigningRequestCanceledEvent)); + $rejection = array_values(array_filter($published, static fn ($event): bool => $event instanceof SignerRejectedWebhookEvent))[0]; + $this->assertFalse($rejection->getWebhookSerializable()['workflowCanceled']); + $this->assertStringNotContainsString('PRIVATE_REJECTION_COMMENT', json_encode($rejection->getWebhookSerializable())); + } + + /** @return array */ + public static function completionStates(): array { + return [ + 'just signed' => [FileStatus::PARTIAL_SIGNED, FileStatus::SIGNED, true], + 'already signed' => [FileStatus::SIGNED, FileStatus::SIGNED, false], + 'not complete' => [FileStatus::ABLE_TO_SIGN, FileStatus::PARTIAL_SIGNED, false], + ]; + } + + #[DataProvider('completionStates')] + public function testCompletionUsesPersistedStatus(FileStatus $before, FileStatus $after, bool $shouldPublish): void { + $root = self::file(13, 'request-uuid', $before); + $this->files->method('getById')->with(13)->willReturn(self::file(13, 'request-uuid', $after)); + $this->dispatcher->expects($shouldPublish ? $this->once() : $this->never()) + ->method('dispatchTyped'); + $this->publisher->requestCompleted($root, $before->value); + } + + public function testUnpersistedRequestDoesNotPublishCompletion(): void { + $request = new File(); + $request->setUuid('uuid'); + $request->setStatus(FileStatus::SIGNED->value); + $this->dispatcher->expects($this->never())->method('dispatchTyped'); + $this->publisher->requestCompleted($request, FileStatus::PARTIAL_SIGNED->value); + } + + public function testDeliveryEventUsesEnvelopeRootAndHidesRecipient(): void { + $this->deliveries->method('findById')->with(9)->willReturn(self::delivery(NotificationDeliveryState::ACCEPTED)); + $child = self::file(25, 'child', FileStatus::ABLE_TO_SIGN); + $child->setParentFileId(13); + $root = self::file(13, 'root-uuid', FileStatus::ABLE_TO_SIGN); + $root->setNodeType('envelope'); + $this->files->method('getById')->willReturnMap([[25, $child], [13, $root]]); + $this->dispatcher->expects($this->once())->method('dispatchTyped') + ->with($this->callback(static function ($event): bool { + if (!$event instanceof NotificationDeliveryStatusChangedEvent) { + return false; + } + $payload = $event->getWebhookSerializable(); + return $payload['requestUuid'] === 'root-uuid' + && $payload['state'] === NotificationDeliveryState::ACCEPTED->value + && !str_contains(json_encode($payload), 'PRIVATE_RECIPIENT'); + })); + $this->publisher->notificationOutcome(9); + } + + public function testPendingDeliveryCannotPublishOutcome(): void { + $this->deliveries->method('findById')->willReturn(self::delivery(NotificationDeliveryState::PENDING)); + $this->files->method('getById')->willReturn(self::file(13, 'uuid', FileStatus::ABLE_TO_SIGN)); + $this->dispatcher->expects($this->never())->method('dispatchTyped'); + $this->publisher->notificationOutcome(9); + } + + public function testRepositoryFailureIsLoggedAsAnErrorWithoutPrivateMessage(): void { + $this->deliveries->method('findById')->willThrowException( + new \RuntimeException('PRIVATE_RECIPIENT')); + $this->dispatcher->expects($this->never())->method('dispatchTyped'); + $this->logger->expects($this->once())->method('error') + ->with('Native webhook publication failed after commit', $this->callback( + static fn (array $context): bool + => ($context['phase'] ?? null) === 'prepare' + && ($context['deliveryId'] ?? null) === 9 + && ($context['errorType'] ?? null) === \RuntimeException::class + && is_string($context['errorFile'] ?? null) + && is_int($context['errorLine'] ?? null) + && !str_contains(json_encode($context), 'PRIVATE_RECIPIENT'), + )); + $this->publisher->notificationOutcome(9); + } + + public function testListenerProgrammingErrorIsLoggedAsErrorAndCannotUndoCommittedState(): void { + $root = self::file(13, 'ready-uuid', FileStatus::ABLE_TO_SIGN); + $this->dispatcher->method('dispatchTyped')->willThrowException( + new \TypeError('PRIVATE_WEBHOOK_DETAILS')); + $this->logger->expects($this->once())->method('error') + ->with('Native webhook publication failed after commit', $this->callback( + static fn (array $context): bool + => ($context['phase'] ?? null) === 'dispatch' + && ($context['event'] ?? null) === 'request.ready' + && ($context['errorType'] ?? null) === \TypeError::class + && !str_contains(json_encode($context), 'PRIVATE_WEBHOOK_DETAILS'), + )); + $this->publisher->requestReady($root); + $this->assertSame(FileStatus::ABLE_TO_SIGN->value, $root->getStatus()); + } +} From f7f997b7940f1ac5f990fd73b692ccc3d4785d8e Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Wed, 11 Nov 2026 02:04:11 +0000 Subject: [PATCH 15/23] refactor: narrow webhook preparation failures and reuse committed root state Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- .../SignatureRejectionService.php | 19 +++- .../Webhook/NativeWebhookEventPublisher.php | 22 ++-- .../SignatureRejectionServiceTest.php | 102 +++++++++++++++++- .../NativeWebhookEventPublisherTest.php | 29 +++-- 4 files changed, 148 insertions(+), 24 deletions(-) diff --git a/lib/Service/SignatureRejection/SignatureRejectionService.php b/lib/Service/SignatureRejection/SignatureRejectionService.php index 27dda32c4e..99541b8bfb 100644 --- a/lib/Service/SignatureRejection/SignatureRejectionService.php +++ b/lib/Service/SignatureRejection/SignatureRejectionService.php @@ -85,7 +85,24 @@ public function reject( : $libreSignFile; $previousRootStatus = $root->getStatus(); $activatedSigners = $this->persistRejection($libreSignFile, $signRequest, $normalizedComment, $commentIsPrivate, $config->cancelsWorkflow()); - $this->webhooks->signerRejected($libreSignFile, $signRequest, $previousRootStatus); + // The envelope can change during the transaction. The earlier snapshot is + // needed for the transition, but must not be reused as the final status. + if ($libreSignFile->hasParent()) { + try { + $root = $this->fileMapper->getById($libreSignFile->getParentFileId()); + } catch (DoesNotExistException $e) { + // The rejection committed, but its envelope no longer exists. + // Do not publish a webhook with the stale pre-commit status. + $root = null; + $this->logger->error('Committed rejection envelope missing during webhook publication', [ + 'fileId' => $libreSignFile->getId(), + 'errorType' => get_debug_type($e), + ]); + } + } + if ($root !== null) { + $this->webhooks->signerRejected($root, $libreSignFile, $signRequest, $previousRootStatus); + } // Record the committed rejection before notification errors can interrupt this flow. // The event reports the status the rejection left, as the API does: a workflow that // continues after rejections is still canceled once every signer rejected. diff --git a/lib/Service/Webhook/NativeWebhookEventPublisher.php b/lib/Service/Webhook/NativeWebhookEventPublisher.php index e495264f3a..0bf6eb7145 100644 --- a/lib/Service/Webhook/NativeWebhookEventPublisher.php +++ b/lib/Service/Webhook/NativeWebhookEventPublisher.php @@ -19,6 +19,7 @@ use OCA\Libresign\Events\SigningRequestCanceledEvent; use OCA\Libresign\Events\SigningRequestCompletedEvent; use OCA\Libresign\Events\SigningRequestReadyEvent; +use OCP\AppFramework\Db\DoesNotExistException; use OCP\EventDispatcher\Event; use OCP\EventDispatcher\IEventDispatcher; use Psr\Log\LoggerInterface; @@ -27,10 +28,11 @@ * Publishes native webhook events after the business operation has committed. * * Publication is best effort: it cannot reverse a persisted operation. - * Preparation errors and listener programming errors are logged as errors; - * listener exceptions are logged as warnings. Nextcloud Webhook Listeners - * enqueues HTTP delivery jobs when enabled, but LibreSign does not persist - * failed event dispatches for replay. + * Missing persisted records and listener programming errors are logged as errors; + * listener exceptions are logged as warnings. Unexpected preparation failures + * are not swallowed: they indicate a fault in the application or database path. + * Nextcloud Webhook Listeners enqueues HTTP delivery jobs when enabled, but + * LibreSign does not persist failed event dispatches for replay. */ class NativeWebhookEventPublisher { public function __construct( @@ -55,14 +57,8 @@ public function signerSigned(FileEntity $document, SignRequestEntity $signer): v )); } - public function signerRejected(FileEntity $document, SignRequestEntity $signer, int $previousRootStatus): void { + public function signerRejected(FileEntity $root, FileEntity $document, SignRequestEntity $signer, int $previousRootStatus): void { $context = ['fileId' => $document->getId(), 'signRequestId' => $signer->getId()]; - try { - $root = $this->rootOf($document); - } catch (\Throwable $e) { - $this->reportFailure($e, 'prepare', 'signer.rejected', $context); - return; - } // A listener failure cannot suppress later aggregate transitions. $this->publish('signer.rejected', $context, @@ -101,7 +97,9 @@ function () use ($deliveryId): ?Event { private function publish(string $eventName, array $context, \Closure $eventFactory): void { try { $event = $eventFactory(); - } catch (\Throwable $e) { + } catch (DoesNotExistException $e) { + // A row missing after a commit is an explicit data-integrity failure. + // Do not turn unrelated database or programming faults into success. $this->reportFailure($e, 'prepare', $eventName, $context); return; } diff --git a/tests/php/Unit/Service/SignatureRejection/SignatureRejectionServiceTest.php b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionServiceTest.php index 14384d81c2..5cc0bf97ff 100644 --- a/tests/php/Unit/Service/SignatureRejection/SignatureRejectionServiceTest.php +++ b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionServiceTest.php @@ -54,8 +54,9 @@ final class SignatureRejectionServiceTest extends TestCase { /** @var list */ private array $envelopeChildSignRequests = []; private ?SignRequest $envelopeSignRequest = null; - /** @var array */ + /** @var array */ private array $filesById = []; + private bool $detachedFileReads = false; protected function setUp(): void { parent::setUp(); @@ -84,8 +85,11 @@ protected function setUp(): void { // without the default stub masking it. $this->fileMapper->method('getById') ->willReturnCallback(function (int $id): File { - if (isset($this->filesById[$id])) { - return $this->filesById[$id]; + if (array_key_exists($id, $this->filesById)) { + if ($this->filesById[$id] === null) { + throw new DoesNotExistException('Synthetic missing committed envelope'); + } + return $this->detachedFileReads ? clone $this->filesById[$id] : $this->filesById[$id]; } $file = $this->file(); $file->setId($id); @@ -297,7 +301,7 @@ public function testCommittedRejectionDelegatesBusinessEvent(bool $cancel): void $signer = $this->signRequest(); $this->db->expects($this->once())->method('commit'); $this->webhooks->expects($this->once())->method('signerRejected') - ->with($file, $signer, FileStatus::ABLE_TO_SIGN->value); + ->with($file, $file, $signer, FileStatus::ABLE_TO_SIGN->value); $this->getService()->reject($file, $signer, 'private explanation', true); $this->assertSame(SignRequestStatus::REJECTED, $signer->getStatusEnum()); $this->assertTrue($signer->getRejectionCommentPrivate()); @@ -308,6 +312,94 @@ public static function publicRejectionOutcomes(): array { return ['continue' => [false], 'cancel' => [true]]; } + public function testEnvelopeWebhookReceivesTheCommittedRootStatus(): void { + $this->withPolicy(self::policy('cancel')); + $document = $this->file(); + $document->setId(21); + $document->setParentFileId(1); + $document->setUuid('child-uuid'); + $signer = $this->signRequest(); + $signer->setFileId(21); + + $persistedRoot = $this->envelope(); + $persistedRoot->setUuid('root-uuid'); + $this->filesById[1] = $persistedRoot; + // Mapper reads are detached entities: the pre-commit root object is stale + // after the transaction updates the envelope row. + $this->detachedFileReads = true; + $this->fileStatusService->method('update') + ->willReturnCallback(function (File $updated): File { + $this->filesById[$updated->getId()] = clone $updated; + return $updated; + }); + $committed = false; + $this->db->expects($this->once())->method('commit') + ->willReturnCallback(static function () use (&$committed): void { + $committed = true; + }); + $this->webhooks->expects($this->once())->method('signerRejected') + ->with( + $this->callback(static function (File $root) use (&$committed): bool { + return $committed + && $root->getUuid() === 'root-uuid' + && $root->getStatus() === FileStatus::CANCELED->value; + }), + $document, + $signer, + FileStatus::ABLE_TO_SIGN->value, + ); + + $this->getService()->reject($document, $signer); + + $this->assertSame(FileStatus::CANCELED->value, $this->filesById[1]->getStatus()); + $this->assertSame(SignRequestStatus::REJECTED, $signer->getStatusEnum()); + } + + public function testMissingEnvelopeAfterCommitDoesNotTurnRejectionIntoFailedRequest(): void { + $this->withPolicy(self::policy('cancel')); + $document = $this->file(); + $document->setId(21); + $document->setParentFileId(1); + $signer = $this->signRequest(); + $signer->setFileId(21); + $this->filesById[1] = $this->envelope(); + $this->db->expects($this->once())->method('commit') + ->willReturnCallback(function (): void { + $this->filesById[1] = null; + }); + $this->logger->expects($this->once())->method('error') + ->with('Committed rejection envelope missing during webhook publication', [ + 'fileId' => 21, + 'errorType' => DoesNotExistException::class, + ]); + $this->webhooks->expects($this->never())->method('signerRejected'); + $this->eventDispatcher->expects($this->once())->method('dispatchTyped') + ->with($this->isInstanceOf(SignatureRejectedEvent::class)); + + $result = $this->getService()->reject($document, $signer); + $this->assertSame($signer, $result); + $this->assertSame(SignRequestStatus::REJECTED, $result->getStatusEnum()); + } + + public function testMissingEnvelopeBeforeCommitPreventsTheRejection(): void { + $this->withPolicy(self::policy('cancel')); + $document = $this->file(); + $document->setId(21); + $document->setParentFileId(1); + $signer = $this->signRequest(); + $this->filesById[1] = null; + $this->db->expects($this->never())->method('beginTransaction'); + $this->db->expects($this->never())->method('commit'); + $this->webhooks->expects($this->never())->method('signerRejected'); + + $this->expectException(DoesNotExistException::class); + try { + $this->getService()->reject($document, $signer); + } finally { + $this->assertSame(SignRequestStatus::ABLE_TO_SIGN, $signer->getStatusEnum()); + } + } + public function testProgrammingErrorDuringRejectionRollsBackAndRemainsVisible(): void { $this->withPolicy(self::policy('cancel')); $signer = $this->signRequest(); @@ -329,7 +421,7 @@ public function testRejectionCanCompletePreviouslySignedWorkflow(): void { $file = $this->file(FileStatus::PARTIAL_SIGNED->value); $file->setUuid('completed-by-rejection'); $this->signingWorkflowStatusResolver->method('resolve')->willReturn(FileStatus::SIGNED); - $this->webhooks->expects($this->once())->method('signerRejected')->with($file, $this->anything(), FileStatus::PARTIAL_SIGNED->value); + $this->webhooks->expects($this->once())->method('signerRejected')->with($file, $file, $this->anything(), FileStatus::PARTIAL_SIGNED->value); $this->getService()->reject($file, $this->signRequest()); $this->assertSame(FileStatus::SIGNED->value, $file->getStatus()); } diff --git a/tests/php/Unit/Service/Webhook/NativeWebhookEventPublisherTest.php b/tests/php/Unit/Service/Webhook/NativeWebhookEventPublisherTest.php index aa17d23ef4..fac8cc9a95 100644 --- a/tests/php/Unit/Service/Webhook/NativeWebhookEventPublisherTest.php +++ b/tests/php/Unit/Service/Webhook/NativeWebhookEventPublisherTest.php @@ -23,6 +23,7 @@ use OCA\Libresign\Events\SigningRequestCompletedEvent; use OCA\Libresign\Events\SigningRequestReadyEvent; use OCA\Libresign\Service\Webhook\NativeWebhookEventPublisher; +use OCP\AppFramework\Db\DoesNotExistException; use OCP\EventDispatcher\IEventDispatcher; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\MockObject\MockObject; @@ -122,7 +123,7 @@ public function testFailedRejectionListenerDoesNotSuppressCancellation(): void { $root->setNodeType('envelope'); $child = self::file(25, 'child-uuid', FileStatus::CANCELED); $child->setParentFileId(13); - $this->files->method('getById')->with(13)->willReturn($root); + $this->files->expects($this->never())->method('getById'); $published = []; $this->dispatcher->method('dispatchTyped')->willReturnCallback( static function ($event) use (&$published): void { @@ -138,7 +139,7 @@ static function ($event) use (&$published): void { && ($context['event'] ?? null) === 'signer.rejected' && !str_contains(json_encode($context), 'PRIVATE_REJECTION_COMMENT'), )); - $this->publisher->signerRejected($child, self::signer(true), FileStatus::ABLE_TO_SIGN->value); + $this->publisher->signerRejected($root, $child, self::signer(true), FileStatus::ABLE_TO_SIGN->value); $this->assertCount(1, array_filter($published, static fn ($event): bool => $event instanceof SigningRequestCanceledEvent)); $this->assertCount(1, array_filter($published, static fn ($event): bool => $event instanceof SignerRejectedWebhookEvent)); } @@ -150,7 +151,7 @@ public function testRejectionCanCompletePreviouslyPartiallySignedWorkflow(): voi static function ($event) use (&$published): void { $published[] = $event; }); - $this->publisher->signerRejected($root, self::signer(true), FileStatus::PARTIAL_SIGNED->value); + $this->publisher->signerRejected($root, $root, self::signer(true), FileStatus::PARTIAL_SIGNED->value); $this->assertCount(1, array_filter($published, static fn ($event): bool => $event instanceof SigningRequestCompletedEvent)); $this->assertCount(0, array_filter($published, static fn ($event): bool => $event instanceof SigningRequestCanceledEvent)); $rejection = array_values(array_filter($published, static fn ($event): bool => $event instanceof SignerRejectedWebhookEvent))[0]; @@ -211,16 +212,16 @@ public function testPendingDeliveryCannotPublishOutcome(): void { $this->publisher->notificationOutcome(9); } - public function testRepositoryFailureIsLoggedAsAnErrorWithoutPrivateMessage(): void { + public function testMissingPersistedDeliveryIsLoggedAsAnErrorWithoutPrivateMessage(): void { $this->deliveries->method('findById')->willThrowException( - new \RuntimeException('PRIVATE_RECIPIENT')); + new DoesNotExistException('PRIVATE_RECIPIENT')); $this->dispatcher->expects($this->never())->method('dispatchTyped'); $this->logger->expects($this->once())->method('error') ->with('Native webhook publication failed after commit', $this->callback( static fn (array $context): bool => ($context['phase'] ?? null) === 'prepare' && ($context['deliveryId'] ?? null) === 9 - && ($context['errorType'] ?? null) === \RuntimeException::class + && ($context['errorType'] ?? null) === DoesNotExistException::class && is_string($context['errorFile'] ?? null) && is_int($context['errorLine'] ?? null) && !str_contains(json_encode($context), 'PRIVATE_RECIPIENT'), @@ -228,6 +229,22 @@ public function testRepositoryFailureIsLoggedAsAnErrorWithoutPrivateMessage(): v $this->publisher->notificationOutcome(9); } + /** @return array */ + public static function unexpectedPreparationErrors(): array { + return [ + 'programming error' => [new \TypeError('INTERNAL_DETAILS')], + 'unexpected database failure' => [new \RuntimeException('INTERNAL_DETAILS')], + ]; + } + + #[DataProvider('unexpectedPreparationErrors')] + public function testUnexpectedPreparationErrorsRemainVisible(\Throwable $failure): void { + $this->deliveries->method('findById')->willThrowException($failure); + $this->dispatcher->expects($this->never())->method('dispatchTyped'); + $this->expectException($failure::class); + $this->publisher->notificationOutcome(9); + } + public function testListenerProgrammingErrorIsLoggedAsErrorAndCannotUndoCommittedState(): void { $root = self::file(13, 'ready-uuid', FileStatus::ABLE_TO_SIGN); $this->dispatcher->method('dispatchTyped')->willThrowException( From a25288bf3f6b8881a802ae704fc4ea04c0f7907e Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Wed, 11 Nov 2026 02:30:01 +0000 Subject: [PATCH 16/23] refactor: clarify webhook publication boundaries and observable tests Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- lib/Controller/SignFileController.php | 2 - lib/Service/RequestSignatureService.php | 27 +++-- .../SignatureRejectionService.php | 29 +---- .../Webhook/NativeWebhookEventPublisher.php | 23 ++-- .../SignatureRejectionServiceTest.php | 109 +++++++++++++----- .../NativeWebhookEventPublisherTest.php | 33 +++++- 6 files changed, 138 insertions(+), 85 deletions(-) diff --git a/lib/Controller/SignFileController.php b/lib/Controller/SignFileController.php index fa5ddceefd..e38a63503d 100644 --- a/lib/Controller/SignFileController.php +++ b/lib/Controller/SignFileController.php @@ -392,8 +392,6 @@ private function reject( Http::STATUS_UNPROCESSABLE_ENTITY, ); } catch (\Throwable $th) { - // Reject is public and persistence can throw internal errors. Never - // reveal exception details to an unauthenticated signing client. $this->logger->error('Unable to process signature rejection', [ 'errorType' => get_debug_type($th), ]); diff --git a/lib/Service/RequestSignatureService.php b/lib/Service/RequestSignatureService.php index 0a8f4a3037..3ef9da6a45 100644 --- a/lib/Service/RequestSignatureService.php +++ b/lib/Service/RequestSignatureService.php @@ -380,17 +380,11 @@ private function persistFile(array $data): array { if (!empty($data['uuid'])) { $file = $this->fileMapper->getByUuid($data['uuid']); $this->filePolicyApplier->syncCoreFlowPolicies($file, $data); - $previousStatus = $file->getStatus(); if (!empty($data['name'])) { $file->setName($data['name']); $this->fileService->update($file); } - $updated = $this->fileStatusService->updateFileStatusIfUpgrade($file, $data['status'] ?? 0); - return [ - 'file' => $updated, - 'becameReady' => $previousStatus === FileStatus::DRAFT->value - && $updated->getStatus() === FileStatus::ABLE_TO_SIGN->value, - ]; + return $this->upgradeExistingFileStatus($file, $data['status'] ?? 0); } $nodeId = null; if (isset($data['file']['fileNode']) && $data['file']['fileNode'] instanceof Node) { @@ -409,13 +403,7 @@ private function persistFile(array $data): array { } if ($file !== null) { $this->filePolicyApplier->syncAllPolicies($file, $data); - $previousStatus = $file->getStatus(); - $updated = $this->fileStatusService->updateFileStatusIfUpgrade($file, $data['status'] ?? 0); - return [ - 'file' => $updated, - 'becameReady' => $previousStatus === FileStatus::DRAFT->value - && $updated->getStatus() === FileStatus::ABLE_TO_SIGN->value, - ]; + return $this->upgradeExistingFileStatus($file, $data['status'] ?? 0); } } @@ -464,6 +452,17 @@ private function persistFile(array $data): array { ]; } + /** @return array{file: FileEntity, becameReady: bool} */ + private function upgradeExistingFileStatus(FileEntity $file, int $newStatus): array { + $wasDraft = $file->getStatus() === FileStatus::DRAFT->value; + $file = $this->fileStatusService->updateFileStatusIfUpgrade($file, $newStatus); + return [ + 'file' => $file, + 'becameReady' => $wasDraft && !$file->hasParent() + && $file->getStatus() === FileStatus::ABLE_TO_SIGN->value, + ]; + } + private function getFileMetadata(\OCP\Files\Node $node): array { $metadata = []; if ($extension = strtolower($node->getExtension())) { diff --git a/lib/Service/SignatureRejection/SignatureRejectionService.php b/lib/Service/SignatureRejection/SignatureRejectionService.php index 99541b8bfb..b2ee29b801 100644 --- a/lib/Service/SignatureRejection/SignatureRejectionService.php +++ b/lib/Service/SignatureRejection/SignatureRejectionService.php @@ -80,32 +80,11 @@ public function reject( // always the signer's call and no policy can take that choice away. $commentIsPrivate = $normalizedComment !== null && $privateComment; - $root = $libreSignFile->hasParent() - ? $this->fileMapper->getById($libreSignFile->getParentFileId()) - : $libreSignFile; - $previousRootStatus = $root->getStatus(); + $previousRootStatus = $libreSignFile->hasParent() + ? $this->fileMapper->getById($libreSignFile->getParentFileId())->getStatus() + : $libreSignFile->getStatus(); $activatedSigners = $this->persistRejection($libreSignFile, $signRequest, $normalizedComment, $commentIsPrivate, $config->cancelsWorkflow()); - // The envelope can change during the transaction. The earlier snapshot is - // needed for the transition, but must not be reused as the final status. - if ($libreSignFile->hasParent()) { - try { - $root = $this->fileMapper->getById($libreSignFile->getParentFileId()); - } catch (DoesNotExistException $e) { - // The rejection committed, but its envelope no longer exists. - // Do not publish a webhook with the stale pre-commit status. - $root = null; - $this->logger->error('Committed rejection envelope missing during webhook publication', [ - 'fileId' => $libreSignFile->getId(), - 'errorType' => get_debug_type($e), - ]); - } - } - if ($root !== null) { - $this->webhooks->signerRejected($root, $libreSignFile, $signRequest, $previousRootStatus); - } - // Record the committed rejection before notification errors can interrupt this flow. - // The event reports the status the rejection left, as the API does: a workflow that - // continues after rejections is still canceled once every signer rejected. + $this->webhooks->signerRejected($libreSignFile, $signRequest, $previousRootStatus); $this->dispatchRejectedEvent($signRequest, $libreSignFile, $this->isWorkflowCanceled($libreSignFile)); $this->sequentialSigningService->notifyActivatedSigners($activatedSigners); diff --git a/lib/Service/Webhook/NativeWebhookEventPublisher.php b/lib/Service/Webhook/NativeWebhookEventPublisher.php index 0bf6eb7145..f46ded3cea 100644 --- a/lib/Service/Webhook/NativeWebhookEventPublisher.php +++ b/lib/Service/Webhook/NativeWebhookEventPublisher.php @@ -25,14 +25,10 @@ use Psr\Log\LoggerInterface; /** - * Publishes native webhook events after the business operation has committed. + * Publishes native lifecycle events after business state has committed. * - * Publication is best effort: it cannot reverse a persisted operation. - * Missing persisted records and listener programming errors are logged as errors; - * listener exceptions are logged as warnings. Unexpected preparation failures - * are not swallowed: they indicate a fault in the application or database path. - * Nextcloud Webhook Listeners enqueues HTTP delivery jobs when enabled, but - * LibreSign does not persist failed event dispatches for replay. + * Listener failures cannot undo committed operations. Event dispatch is + * best-effort and LibreSign does not provide a replayable event outbox. */ class NativeWebhookEventPublisher { public function __construct( @@ -57,10 +53,15 @@ public function signerSigned(FileEntity $document, SignRequestEntity $signer): v )); } - public function signerRejected(FileEntity $root, FileEntity $document, SignRequestEntity $signer, int $previousRootStatus): void { + public function signerRejected(FileEntity $document, SignRequestEntity $signer, int $previousRootStatus): void { $context = ['fileId' => $document->getId(), 'signRequestId' => $signer->getId()]; + try { + $root = $this->rootOf($document); + } catch (DoesNotExistException $e) { + $this->reportFailure($e, 'prepare', 'signer.rejected', $context); + return; + } - // A listener failure cannot suppress later aggregate transitions. $this->publish('signer.rejected', $context, static fn (): ?Event => SignerRejectedWebhookEvent::afterRejection( $root, $document, $signer, $root->getStatus() === FileStatus::CANCELED->value, @@ -98,8 +99,6 @@ private function publish(string $eventName, array $context, \Closure $eventFacto try { $event = $eventFactory(); } catch (DoesNotExistException $e) { - // A row missing after a commit is an explicit data-integrity failure. - // Do not turn unrelated database or programming faults into success. $this->reportFailure($e, 'prepare', $eventName, $context); return; } @@ -121,8 +120,6 @@ private function rootOf(FileEntity $document): FileEntity { } private function reportFailure(\Throwable $error, string $phase, string $eventName, array $context): void { - // Listener exceptions may contain private comments, tokens or recipients. - // Keep the type and source location, never the message or stack trace. $details = $context + [ 'event' => $eventName, 'phase' => $phase, diff --git a/tests/php/Unit/Service/SignatureRejection/SignatureRejectionServiceTest.php b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionServiceTest.php index 5cc0bf97ff..8d141d075d 100644 --- a/tests/php/Unit/Service/SignatureRejection/SignatureRejectionServiceTest.php +++ b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionServiceTest.php @@ -10,11 +10,15 @@ use OCA\Libresign\Db\File; use OCA\Libresign\Db\FileMapper; +use OCA\Libresign\Db\NotificationDeliveryMapper; use OCA\Libresign\Db\SignRequest; use OCA\Libresign\Db\SignRequestMapper; use OCA\Libresign\Enum\FileStatus; use OCA\Libresign\Enum\SignRequestStatus; use OCA\Libresign\Events\SignatureRejectedEvent; +use OCA\Libresign\Events\SignerRejectedWebhookEvent; +use OCA\Libresign\Events\SigningRequestCanceledEvent; +use OCA\Libresign\Events\SigningRequestCompletedEvent; use OCA\Libresign\Exception\LibresignException; use OCA\Libresign\Service\File\SigningWorkflowStatusResolver; use OCA\Libresign\Service\FileStatusService; @@ -50,7 +54,7 @@ final class SignatureRejectionServiceTest extends TestCase { private ITimeFactory&MockObject $timeFactory; private IL10N&MockObject $l10n; private LoggerInterface&MockObject $logger; - private NativeWebhookEventPublisher&MockObject $webhooks; + private NativeWebhookEventPublisher $webhooks; /** @var list */ private array $envelopeChildSignRequests = []; private ?SignRequest $envelopeSignRequest = null; @@ -81,8 +85,6 @@ protected function setUp(): void { ->willReturn(['account' => [$this->createMock(IIdentifyMethod::class)]]); $this->sequentialSigningService->method('setFile')->willReturnSelf(); - // Backed by mutable properties so a test can widen the envelope fan-out - // without the default stub masking it. $this->fileMapper->method('getById') ->willReturnCallback(function (int $id): File { if (array_key_exists($id, $this->filesById)) { @@ -124,6 +126,15 @@ private function getService(): SignatureRejectionService { ); } + private function useNativeWebhookPublisher(): void { + $this->webhooks = new NativeWebhookEventPublisher( + $this->eventDispatcher, + $this->logger, + $this->fileMapper, + $this->createMock(NotificationDeliveryMapper::class), + ); + } + private function withPolicy(SignatureRejectionPolicyConfig $config): void { $this->rejectionPolicyService ->method('getConfig') @@ -294,15 +305,35 @@ public function testPrivateFlagIsIgnoredWhenThereIsNoComment(): void { } #[DataProvider('publicRejectionOutcomes')] - public function testCommittedRejectionDelegatesBusinessEvent(bool $cancel): void { + public function testCommittedRejectionPublishesSanitizedEvents(bool $cancel): void { $this->withPolicy(self::policy($cancel ? 'cancel' : 'continue', 'optional')); + $this->useNativeWebhookPublisher(); $file = $this->file(); $file->setUuid('request-uuid'); $signer = $this->signRequest(); - $this->db->expects($this->once())->method('commit'); - $this->webhooks->expects($this->once())->method('signerRejected') - ->with($file, $file, $signer, FileStatus::ABLE_TO_SIGN->value); + $published = []; + $committed = false; + $this->db->expects($this->once())->method('commit') + ->willReturnCallback(static function () use (&$committed): void { + $committed = true; + }); + $this->eventDispatcher->method('dispatchTyped') + ->willReturnCallback(function (object $event) use (&$published, &$committed): void { + $this->assertTrue($committed); + $published[] = $event; + }); + $this->getService()->reject($file, $signer, 'private explanation', true); + + $rejections = array_values(array_filter($published, + static fn (object $event): bool => $event instanceof SignerRejectedWebhookEvent)); + $this->assertCount(1, $rejections); + $payload = $rejections[0]->getWebhookSerializable(); + $this->assertSame('request-uuid', $payload['requestUuid']); + $this->assertSame($cancel, $payload['workflowCanceled']); + $this->assertStringNotContainsString('private explanation', json_encode($payload)); + $this->assertCount($cancel ? 1 : 0, array_filter($published, + static fn (object $event): bool => $event instanceof SigningRequestCanceledEvent)); $this->assertSame(SignRequestStatus::REJECTED, $signer->getStatusEnum()); $this->assertTrue($signer->getRejectionCommentPrivate()); } @@ -314,6 +345,7 @@ public static function publicRejectionOutcomes(): array { public function testEnvelopeWebhookReceivesTheCommittedRootStatus(): void { $this->withPolicy(self::policy('cancel')); + $this->useNativeWebhookPublisher(); $document = $this->file(); $document->setId(21); $document->setParentFileId(1); @@ -324,8 +356,6 @@ public function testEnvelopeWebhookReceivesTheCommittedRootStatus(): void { $persistedRoot = $this->envelope(); $persistedRoot->setUuid('root-uuid'); $this->filesById[1] = $persistedRoot; - // Mapper reads are detached entities: the pre-commit root object is stale - // after the transaction updates the envelope row. $this->detachedFileReads = true; $this->fileStatusService->method('update') ->willReturnCallback(function (File $updated): File { @@ -337,26 +367,30 @@ public function testEnvelopeWebhookReceivesTheCommittedRootStatus(): void { ->willReturnCallback(static function () use (&$committed): void { $committed = true; }); - $this->webhooks->expects($this->once())->method('signerRejected') - ->with( - $this->callback(static function (File $root) use (&$committed): bool { - return $committed - && $root->getUuid() === 'root-uuid' - && $root->getStatus() === FileStatus::CANCELED->value; - }), - $document, - $signer, - FileStatus::ABLE_TO_SIGN->value, - ); + $published = []; + $this->eventDispatcher->method('dispatchTyped') + ->willReturnCallback(function (object $event) use (&$published, &$committed): void { + $this->assertTrue($committed); + $published[] = $event; + }); $this->getService()->reject($document, $signer); + $rejections = array_values(array_filter($published, + static fn (object $event): bool => $event instanceof SignerRejectedWebhookEvent)); + $this->assertCount(1, $rejections); + $this->assertSame('root-uuid', $rejections[0]->getWebhookSerializable()['requestUuid']); + $this->assertSame('envelope', $rejections[0]->getWebhookSerializable()['requestType']); + $this->assertTrue($rejections[0]->getWebhookSerializable()['workflowCanceled']); + $this->assertCount(1, array_filter($published, + static fn (object $event): bool => $event instanceof SigningRequestCanceledEvent)); $this->assertSame(FileStatus::CANCELED->value, $this->filesById[1]->getStatus()); $this->assertSame(SignRequestStatus::REJECTED, $signer->getStatusEnum()); } public function testMissingEnvelopeAfterCommitDoesNotTurnRejectionIntoFailedRequest(): void { $this->withPolicy(self::policy('cancel')); + $this->useNativeWebhookPublisher(); $document = $this->file(); $document->setId(21); $document->setParentFileId(1); @@ -368,17 +402,25 @@ public function testMissingEnvelopeAfterCommitDoesNotTurnRejectionIntoFailedRequ $this->filesById[1] = null; }); $this->logger->expects($this->once())->method('error') - ->with('Committed rejection envelope missing during webhook publication', [ - 'fileId' => 21, - 'errorType' => DoesNotExistException::class, - ]); - $this->webhooks->expects($this->never())->method('signerRejected'); - $this->eventDispatcher->expects($this->once())->method('dispatchTyped') - ->with($this->isInstanceOf(SignatureRejectedEvent::class)); + ->with('Native webhook publication failed after commit', $this->callback( + static fn (array $context): bool + => ($context['fileId'] ?? null) === 21 + && ($context['event'] ?? null) === 'signer.rejected' + && ($context['phase'] ?? null) === 'prepare' + && ($context['errorType'] ?? null) === DoesNotExistException::class, + )); + $published = []; + $this->eventDispatcher->method('dispatchTyped') + ->willReturnCallback(static function (object $event) use (&$published): void { + $published[] = $event; + }); $result = $this->getService()->reject($document, $signer); + $this->assertSame($signer, $result); $this->assertSame(SignRequestStatus::REJECTED, $result->getStatusEnum()); + $this->assertCount(1, $published); + $this->assertInstanceOf(SignatureRejectedEvent::class, $published[0]); } public function testMissingEnvelopeBeforeCommitPreventsTheRejection(): void { @@ -418,11 +460,22 @@ public function testProgrammingErrorDuringRejectionRollsBackAndRemainsVisible(): public function testRejectionCanCompletePreviouslySignedWorkflow(): void { $this->withPolicy(self::policy('continue')); + $this->useNativeWebhookPublisher(); $file = $this->file(FileStatus::PARTIAL_SIGNED->value); $file->setUuid('completed-by-rejection'); $this->signingWorkflowStatusResolver->method('resolve')->willReturn(FileStatus::SIGNED); - $this->webhooks->expects($this->once())->method('signerRejected')->with($file, $file, $this->anything(), FileStatus::PARTIAL_SIGNED->value); + $published = []; + $this->eventDispatcher->method('dispatchTyped') + ->willReturnCallback(static function (object $event) use (&$published): void { + $published[] = $event; + }); + $this->getService()->reject($file, $this->signRequest()); + + $completed = array_values(array_filter($published, + static fn (object $event): bool => $event instanceof SigningRequestCompletedEvent)); + $this->assertCount(1, $completed); + $this->assertSame('completed-by-rejection', $completed[0]->getWebhookSerializable()['requestUuid']); $this->assertSame(FileStatus::SIGNED->value, $file->getStatus()); } diff --git a/tests/php/Unit/Service/Webhook/NativeWebhookEventPublisherTest.php b/tests/php/Unit/Service/Webhook/NativeWebhookEventPublisherTest.php index fac8cc9a95..2b8b7d9098 100644 --- a/tests/php/Unit/Service/Webhook/NativeWebhookEventPublisherTest.php +++ b/tests/php/Unit/Service/Webhook/NativeWebhookEventPublisherTest.php @@ -123,7 +123,7 @@ public function testFailedRejectionListenerDoesNotSuppressCancellation(): void { $root->setNodeType('envelope'); $child = self::file(25, 'child-uuid', FileStatus::CANCELED); $child->setParentFileId(13); - $this->files->expects($this->never())->method('getById'); + $this->files->method('getById')->with(13)->willReturn($root); $published = []; $this->dispatcher->method('dispatchTyped')->willReturnCallback( static function ($event) use (&$published): void { @@ -139,11 +139,38 @@ static function ($event) use (&$published): void { && ($context['event'] ?? null) === 'signer.rejected' && !str_contains(json_encode($context), 'PRIVATE_REJECTION_COMMENT'), )); - $this->publisher->signerRejected($root, $child, self::signer(true), FileStatus::ABLE_TO_SIGN->value); + $this->publisher->signerRejected($child, self::signer(true), FileStatus::ABLE_TO_SIGN->value); $this->assertCount(1, array_filter($published, static fn ($event): bool => $event instanceof SigningRequestCanceledEvent)); $this->assertCount(1, array_filter($published, static fn ($event): bool => $event instanceof SignerRejectedWebhookEvent)); } + public function testMissingEnvelopeDoesNotPublishARejectionOrTransitions(): void { + $child = self::file(25, 'child-uuid', FileStatus::CANCELED); + $child->setParentFileId(13); + $this->files->method('getById')->with(13)->willThrowException(new DoesNotExistException('PRIVATE_MESSAGE')); + $this->dispatcher->expects($this->never())->method('dispatchTyped'); + $this->logger->expects($this->once())->method('error') + ->with('Native webhook publication failed after commit', $this->callback( + static fn (array $context): bool + => ($context['phase'] ?? null) === 'prepare' + && ($context['event'] ?? null) === 'signer.rejected' + && ($context['errorType'] ?? null) === DoesNotExistException::class + && !str_contains(json_encode($context), 'PRIVATE_MESSAGE') + )); + + $this->publisher->signerRejected($child, self::signer(true), FileStatus::ABLE_TO_SIGN->value); + } + + public function testUnexpectedEnvelopeLookupErrorIsNotSuppressed(): void { + $child = self::file(25, 'child-uuid', FileStatus::CANCELED); + $child->setParentFileId(13); + $this->files->method('getById')->with(13)->willThrowException(new \TypeError('invalid mapper state')); + $this->dispatcher->expects($this->never())->method('dispatchTyped'); + $this->expectException(\TypeError::class); + + $this->publisher->signerRejected($child, self::signer(true), FileStatus::ABLE_TO_SIGN->value); + } + public function testRejectionCanCompletePreviouslyPartiallySignedWorkflow(): void { $root = self::file(13, 'root-uuid', FileStatus::SIGNED); $published = []; @@ -151,7 +178,7 @@ public function testRejectionCanCompletePreviouslyPartiallySignedWorkflow(): voi static function ($event) use (&$published): void { $published[] = $event; }); - $this->publisher->signerRejected($root, $root, self::signer(true), FileStatus::PARTIAL_SIGNED->value); + $this->publisher->signerRejected($root, self::signer(true), FileStatus::PARTIAL_SIGNED->value); $this->assertCount(1, array_filter($published, static fn ($event): bool => $event instanceof SigningRequestCompletedEvent)); $this->assertCount(0, array_filter($published, static fn ($event): bool => $event instanceof SigningRequestCanceledEvent)); $rejection = array_values(array_filter($published, static fn ($event): bool => $event instanceof SignerRejectedWebhookEvent))[0]; From 74ac021956f8308c3fcd05162fd5ce790bfe2d60 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Wed, 11 Nov 2026 02:53:08 +0000 Subject: [PATCH 17/23] refactor: decouple signature rejection rules, persistence and notifications Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- .../SignatureRejection/CommittedRejection.php | 20 + .../SignatureRejection/RejectionInput.php | 18 + .../SignatureRejectionNotifier.php | 62 + .../SignatureRejectionPersistence.php | 113 ++ .../SignatureRejectionRules.php | 103 ++ .../SignatureRejectionService.php | 368 +----- .../SignatureRejectionWorkflow.php | 162 +++ .../Service/SignatureRejectionWiringTest.php | 19 + .../SignatureRejectionNotifierTest.php | 144 +++ .../SignatureRejectionPersistenceTest.php | 243 ++++ .../SignatureRejectionRulesTest.php | 137 +++ .../SignatureRejectionSamples.php | 52 + .../SignatureRejectionServiceTest.php | 1096 +---------------- .../SignatureRejectionWorkflowTest.php | 217 ++++ 14 files changed, 1355 insertions(+), 1399 deletions(-) create mode 100644 lib/Service/SignatureRejection/CommittedRejection.php create mode 100644 lib/Service/SignatureRejection/RejectionInput.php create mode 100644 lib/Service/SignatureRejection/SignatureRejectionNotifier.php create mode 100644 lib/Service/SignatureRejection/SignatureRejectionPersistence.php create mode 100644 lib/Service/SignatureRejection/SignatureRejectionRules.php create mode 100644 lib/Service/SignatureRejection/SignatureRejectionWorkflow.php create mode 100644 tests/php/Integration/Service/SignatureRejectionWiringTest.php create mode 100644 tests/php/Unit/Service/SignatureRejection/SignatureRejectionNotifierTest.php create mode 100644 tests/php/Unit/Service/SignatureRejection/SignatureRejectionPersistenceTest.php create mode 100644 tests/php/Unit/Service/SignatureRejection/SignatureRejectionRulesTest.php create mode 100644 tests/php/Unit/Service/SignatureRejection/SignatureRejectionSamples.php create mode 100644 tests/php/Unit/Service/SignatureRejection/SignatureRejectionWorkflowTest.php diff --git a/lib/Service/SignatureRejection/CommittedRejection.php b/lib/Service/SignatureRejection/CommittedRejection.php new file mode 100644 index 0000000000..ae23335eec --- /dev/null +++ b/lib/Service/SignatureRejection/CommittedRejection.php @@ -0,0 +1,20 @@ + $activatedSigners */ + public function __construct( + public int $previousRootStatus, + public array $activatedSigners, + ) { + } +} diff --git a/lib/Service/SignatureRejection/RejectionInput.php b/lib/Service/SignatureRejection/RejectionInput.php new file mode 100644 index 0000000000..8ec4d44b48 --- /dev/null +++ b/lib/Service/SignatureRejection/RejectionInput.php @@ -0,0 +1,18 @@ +webhooks->signerRejected($file, $signer, $committed->previousRootStatus); + $this->dispatchRejectedEvent($signer, $file, $file->getStatus() === FileStatus::CANCELED->value); + $this->sequentialSigningService->notifyActivatedSigners($committed->activatedSigners); + } + + private function dispatchRejectedEvent( + SignRequestEntity $signRequest, + FileEntity $libreSignFile, + bool $workflowCanceled, + ): void { + // The rejection is already committed at this point: a failing listener must + // not turn a recorded rejection into an error for the signer. + try { + $groupedIdentifyMethods = $this->identifyMethodService->getIdentifyMethodsFromSignRequestId($signRequest->getId()); + foreach ($groupedIdentifyMethods as $identifyMethods) { + foreach ($identifyMethods as $identifyMethod) { + $this->eventDispatcher->dispatchTyped(new SignatureRejectedEvent( + $signRequest, + $libreSignFile, + $identifyMethod, + $workflowCanceled, + )); + } + } + } catch (\Exception $e) { + $this->logger->error('Error dispatching SignatureRejectedEvent', [ + 'errorType' => get_debug_type($e), + ]); + } + } +} diff --git a/lib/Service/SignatureRejection/SignatureRejectionPersistence.php b/lib/Service/SignatureRejection/SignatureRejectionPersistence.php new file mode 100644 index 0000000000..42812adfa0 --- /dev/null +++ b/lib/Service/SignatureRejection/SignatureRejectionPersistence.php @@ -0,0 +1,113 @@ +hasParent() + ? $this->fileMapper->getById($libreSignFile->getParentFileId())->getStatus() + : $libreSignFile->getStatus(); + $signRequests = $this->workflow->collectSignRequestsToReject($libreSignFile, $signRequest); + $previousSignerStatuses = array_map( + static fn (SignRequestEntity $each): int => $each->getStatus(), + $signRequests, + ); + $previousFileStatus = $libreSignFile->getStatus(); + $rejectedAt = $this->timeFactory->getDateTime(); + + $this->db->beginTransaction(); + try { + foreach ($signRequests as $each) { + $each->setStatusEnum(SignRequestStatus::REJECTED); + $each->setRejectedAt($rejectedAt); + $each->setRejectionComment($input->comment); + $each->setRejectionCommentPrivate($input->commentIsPrivate); + $this->signRequestMapper->update($each); + } + + if ($input->cancelsWorkflow) { + $this->workflow->cancelWorkflow($libreSignFile); + $activatedSigners = []; + } else { + $activatedSigners = $this->workflow->continueWorkflow($libreSignFile, $signRequests); + } + + $this->db->commit(); + } catch (\Exception $e) { + $this->rollBackRejection($libreSignFile, $signRequests, $previousSignerStatuses, $previousFileStatus); + $this->logger->error('Failed to register the signature rejection', [ + 'errorType' => get_debug_type($e), + 'signRequestId' => $signRequest->getId(), + ]); + + // TRANSLATORS Error shown when the rejection could not be saved and nothing was changed. + throw new LibresignException($this->l10n->t('It was not possible to register the rejection. Nothing was changed.')); + } catch (\Error $e) { + $this->rollBackRejection($libreSignFile, $signRequests, $previousSignerStatuses, $previousFileStatus); + throw $e; + } + + return new CommittedRejection($previousRootStatus, $activatedSigners); + } + + /** + * @param list $signRequests + * @param list $previousSignerStatuses + */ + private function rollBackRejection( + FileEntity $file, + array $signRequests, + array $previousSignerStatuses, + int $previousFileStatus, + ): void { + $this->db->rollBack(); + $this->restoreState($file, $signRequests, $previousSignerStatuses, $previousFileStatus); + } + + private function restoreState( + FileEntity $libreSignFile, + array $signRequests, + array $previousSignerStatuses, + int $previousFileStatus, + ): void { + foreach ($signRequests as $index => $signRequest) { + $signRequest->setStatus($previousSignerStatuses[$index]); + $signRequest->setRejectedAt(null); + $signRequest->setRejectionComment(null); + $signRequest->setRejectionCommentPrivate(false); + } + $libreSignFile->setStatus($previousFileStatus); + } +} diff --git a/lib/Service/SignatureRejection/SignatureRejectionRules.php b/lib/Service/SignatureRejection/SignatureRejectionRules.php new file mode 100644 index 0000000000..745999d2cb --- /dev/null +++ b/lib/Service/SignatureRejection/SignatureRejectionRules.php @@ -0,0 +1,103 @@ +policies->getConfig($file); + if (!$policy->isEnabled()) { + // TRANSLATORS Error shown when a signer tries to reject a document whose policy does not allow rejections. + throw new LibresignException($this->l10n->t('Signature rejection is not enabled for this document.')); + } + + $this->assertWorkflowIsOpen($file); + $this->assertSignerCanReject($signer); + $normalized = $this->normalizeComment($comment, $policy->getCommentMode()); + + return new RejectionInput($normalized, $normalized !== null && $privateComment, $policy->cancelsWorkflow()); + } + + private function assertWorkflowIsOpen(FileEntity $libreSignFile): void { + $openStatusList = [ + FileStatus::ABLE_TO_SIGN->value, + FileStatus::PARTIAL_SIGNED->value, + ]; + if (in_array($libreSignFile->getStatus(), $openStatusList, true)) { + return; + } + + if ($libreSignFile->getStatus() === FileStatus::CANCELED->value) { + // TRANSLATORS Error shown when an action is attempted on a document whose signing workflow was already closed by a rejection. + throw new LibresignException($this->l10n->t('The signing workflow of this document is already closed.')); + } + + // TRANSLATORS Error shown when a signer tries to reject a document that is not currently open for signing. + throw new LibresignException($this->l10n->t('This document is not open for signature rejection.')); + } + + private function assertSignerCanReject(SignRequestEntity $signRequest): void { + if ($signRequest->getSigned() !== null) { + // TRANSLATORS Error shown when the current user already signed this document. + throw new LibresignException($this->l10n->t('File already signed by you')); + } + + if ($signRequest->getStatusEnum() === SignRequestStatus::REJECTED) { + // TRANSLATORS Error shown when a signer tries to reject the same signature request twice. + throw new LibresignException($this->l10n->t('You already rejected this signature request.')); + } + } + + private function normalizeComment(?string $comment, SignatureRejectionCommentMode $mode): ?string { + $trimmed = $comment === null ? '' : trim($comment); + + if ($mode === SignatureRejectionCommentMode::DISABLED) { + if ($trimmed !== '') { + // TRANSLATORS Error shown when a signer sends a rejection comment but the document policy does not accept comments. + throw new LibresignException($this->l10n->t('Rejection comments are not allowed for this document.')); + } + return null; + } + + if ($trimmed === '') { + if ($mode === SignatureRejectionCommentMode::REQUIRED) { + // TRANSLATORS Error shown when the document policy requires a justification and the signer did not provide one. + throw new LibresignException($this->l10n->t('A comment is required to reject this signature request.')); + } + return null; + } + + if (mb_strlen($trimmed) > self::MAX_COMMENT_LENGTH) { + // TRANSLATORS Error shown when the rejection justification exceeds the maximum accepted length. %s is the maximum number of characters. + throw new LibresignException($this->l10n->t('The rejection comment must have at most %s characters.', [(string)self::MAX_COMMENT_LENGTH])); + } + + return $trimmed; + } +} diff --git a/lib/Service/SignatureRejection/SignatureRejectionService.php b/lib/Service/SignatureRejection/SignatureRejectionService.php index b2ee29b801..34e7b9907d 100644 --- a/lib/Service/SignatureRejection/SignatureRejectionService.php +++ b/lib/Service/SignatureRejection/SignatureRejectionService.php @@ -9,84 +9,31 @@ namespace OCA\Libresign\Service\SignatureRejection; use OCA\Libresign\Db\File as FileEntity; -use OCA\Libresign\Db\FileMapper; use OCA\Libresign\Db\SignRequest as SignRequestEntity; -use OCA\Libresign\Db\SignRequestMapper; use OCA\Libresign\Enum\FileStatus; -use OCA\Libresign\Enum\SignatureRejectionCommentMode; use OCA\Libresign\Enum\SignRequestStatus; -use OCA\Libresign\Events\SignatureRejectedEvent; use OCA\Libresign\Exception\LibresignException; -use OCA\Libresign\Service\File\SigningWorkflowStatusResolver; -use OCA\Libresign\Service\FileStatusService; -use OCA\Libresign\Service\IdentifyMethodService; -use OCA\Libresign\Service\SequentialSigningService; -use OCA\Libresign\Service\Webhook\NativeWebhookEventPublisher; -use OCP\AppFramework\Db\DoesNotExistException; -use OCP\AppFramework\Utility\ITimeFactory; -use OCP\EventDispatcher\IEventDispatcher; -use OCP\IDBConnection; -use OCP\IL10N; -use Psr\Log\LoggerInterface; -/** - * Records a signer's refusal to sign a document. - * - * The rules that govern a rejection (whether it is allowed at all, whether a - * comment is required, and whether the remaining workflow keeps running) come - * from the signature rejection policy frozen on the document. - */ class SignatureRejectionService { - public const MAX_COMMENT_LENGTH = 4096; + public const MAX_COMMENT_LENGTH = SignatureRejectionRules::MAX_COMMENT_LENGTH; public function __construct( - private SignRequestMapper $signRequestMapper, - private FileMapper $fileMapper, - private SignatureRejectionPolicyService $rejectionPolicyService, - private FileStatusService $fileStatusService, - private IdentifyMethodService $identifyMethodService, - private SequentialSigningService $sequentialSigningService, - private SigningWorkflowStatusResolver $signingWorkflowStatusResolver, - private IEventDispatcher $eventDispatcher, - private IDBConnection $db, - private ITimeFactory $timeFactory, - private IL10N $l10n, - private LoggerInterface $logger, - private NativeWebhookEventPublisher $webhooks, + private SignatureRejectionRules $rules, + private SignatureRejectionPersistence $persistence, + private SignatureRejectionNotifier $notifier, ) { } - /** - * @throws LibresignException when the policy or the current workflow state forbids the rejection - */ + /** @throws LibresignException when the policy or workflow state forbids rejection */ public function reject( FileEntity $libreSignFile, SignRequestEntity $signRequest, ?string $comment = null, bool $privateComment = false, ): SignRequestEntity { - $config = $this->rejectionPolicyService->getConfig($libreSignFile); - - if (!$config->isEnabled()) { - // TRANSLATORS Error shown when a signer tries to reject a document whose policy does not allow rejections. - throw new LibresignException($this->l10n->t('Signature rejection is not enabled for this document.')); - } - - $this->assertWorkflowIsOpen($libreSignFile); - $this->assertSignerCanReject($signRequest); - - $normalizedComment = $this->normalizeComment($comment, $config->getCommentMode()); - // A comment can carry personal or legal information, so keeping it private is - // always the signer's call and no policy can take that choice away. - $commentIsPrivate = $normalizedComment !== null && $privateComment; - - $previousRootStatus = $libreSignFile->hasParent() - ? $this->fileMapper->getById($libreSignFile->getParentFileId())->getStatus() - : $libreSignFile->getStatus(); - $activatedSigners = $this->persistRejection($libreSignFile, $signRequest, $normalizedComment, $commentIsPrivate, $config->cancelsWorkflow()); - $this->webhooks->signerRejected($libreSignFile, $signRequest, $previousRootStatus); - $this->dispatchRejectedEvent($signRequest, $libreSignFile, $this->isWorkflowCanceled($libreSignFile)); - $this->sequentialSigningService->notifyActivatedSigners($activatedSigners); + $input = $this->rules->validate($libreSignFile, $signRequest, $comment, $privateComment); + $committed = $this->persistence->commit($libreSignFile, $signRequest, $input); + $this->notifier->afterCommit($libreSignFile, $signRequest, $committed); return $signRequest; } @@ -98,303 +45,4 @@ public function isRejected(SignRequestEntity $signRequest): bool { public function isWorkflowCanceled(FileEntity $libreSignFile): bool { return $libreSignFile->getStatus() === FileStatus::CANCELED->value; } - - /** - * Marking the signer as rejected and closing the workflow describe a single - * decision, so they are written together: a failure must never leave a signer - * who already rejected on a document that stays open for everybody else. - * - * @return list Signers activated by the committed rejection. - */ - private function persistRejection( - FileEntity $libreSignFile, - SignRequestEntity $signRequest, - ?string $comment, - bool $commentIsPrivate, - bool $cancelWorkflow, - ): array { - $signRequests = $this->collectSignRequestsToReject($libreSignFile, $signRequest); - $previousSignerStatuses = array_map( - static fn (SignRequestEntity $each): int => $each->getStatus(), - $signRequests, - ); - $previousFileStatus = $libreSignFile->getStatus(); - $rejectedAt = $this->timeFactory->getDateTime(); - - $this->db->beginTransaction(); - try { - foreach ($signRequests as $each) { - $each->setStatusEnum(SignRequestStatus::REJECTED); - $each->setRejectedAt($rejectedAt); - $each->setRejectionComment($comment); - $each->setRejectionCommentPrivate($commentIsPrivate); - $this->signRequestMapper->update($each); - } - - if ($cancelWorkflow) { - $this->cancelWorkflow($libreSignFile); - $activatedSigners = []; - } else { - $activatedSigners = $this->releaseNextSigningOrders($libreSignFile, $signRequests); - $this->resolveStatusOfRejectedDocuments($libreSignFile, $signRequests); - } - - $this->db->commit(); - } catch (\Exception $e) { - $this->rollBackRejection($libreSignFile, $signRequests, $previousSignerStatuses, $previousFileStatus); - $this->logger->error('Failed to register the signature rejection', [ - 'errorType' => get_debug_type($e), - 'signRequestId' => $signRequest->getId(), - ]); - - // TRANSLATORS Error shown when the rejection could not be saved and nothing was changed. - throw new LibresignException($this->l10n->t('It was not possible to register the rejection. Nothing was changed.')); - } catch (\Error $e) { - $this->rollBackRejection($libreSignFile, $signRequests, $previousSignerStatuses, $previousFileStatus); - throw $e; - } - - return $activatedSigners; - } - - /** - * A signer of an envelope has one signature request per document it contains, - * plus one on the envelope itself. Signing closes all of them, so a rejection - * has to close all of them too: recording it on a single document would leave - * the refusal invisible to the person who requested the signature, whose view - * of the envelope is built from the envelope-level signature requests. - * - * @return list - */ - private function collectSignRequestsToReject(FileEntity $libreSignFile, SignRequestEntity $signRequest): array { - $envelopeId = $libreSignFile->isEnvelope() - ? $libreSignFile->getId() - : $libreSignFile->getParentFileId(); - if ($envelopeId === null) { - return [$signRequest]; - } - - $collected = [$signRequest->getId() => $signRequest]; - - foreach ($this->signRequestMapper->getByEnvelopeChildrenAndIdentifyMethod($envelopeId, $signRequest->getId()) as $childSignRequest) { - $collected[$childSignRequest->getId()] ??= $childSignRequest; - } - - try { - $envelopeSignRequest = $this->signRequestMapper->getByIdentifyMethodAndFileId( - $this->identifyMethodService->getIdentifiedMethod($signRequest->getId()), - $envelopeId, - ); - $collected[$envelopeSignRequest->getId()] ??= $envelopeSignRequest; - } catch (DoesNotExistException) { - } - - // A document this signer already signed keeps its signature. - return array_values(array_filter( - $collected, - static fn (SignRequestEntity $each): bool => $each->getSigned() === null, - )); - } - - /** - * When the workflow continues, a rejection ends the signer's turn just like a - * signature does, so in a sequential flow the next order must be released on - * every document the signer rejected, or the signers after them would wait - * forever. - * - * @param list $rejectedSignRequests - * @return list The signers activated on every document. - */ - private function releaseNextSigningOrders(FileEntity $libreSignFile, array $rejectedSignRequests): array { - $activatedSigners = []; - - foreach ($rejectedSignRequests as $rejected) { - $document = $rejected->getFileId() === $libreSignFile->getId() - ? $libreSignFile - : $this->fileMapper->getById($rejected->getFileId()); - foreach ($this->sequentialSigningService - ->setFile($document) - ->activateNextOrder( - $rejected->getFileId(), - $rejected->getSigningOrder() - ) as $activated) { - $activatedSigners[] = $activated; - } - } - - return $activatedSigners; - } - - /** - * A rejection ends the signer's turn just like a signature does, so it can be - * the last action a document was waiting for. Its status is then resolved by - * the same rule the signing flow uses, otherwise a document whose last signer - * rejected would stay partially signed forever. - * - * An envelope is not resolved here: its status follows the documents it - * contains, so it is read back once they are saved. - * - * @param list $rejectedSignRequests - */ - private function resolveStatusOfRejectedDocuments(FileEntity $libreSignFile, array $rejectedSignRequests): void { - foreach ($rejectedSignRequests as $rejected) { - $document = $rejected->getFileId() === $libreSignFile->getId() - ? $libreSignFile - : $this->fileMapper->getById($rejected->getFileId()); - if ($document->isEnvelope()) { - continue; - } - - $status = $this->signingWorkflowStatusResolver->resolve( - $document, - $this->signRequestMapper->getByFileId($document->getId()), - ); - if ($status === null || $status->value === $document->getStatus()) { - continue; - } - - $document->setStatusEnum($status); - $this->fileStatusService->update($document); - } - - if ($libreSignFile->isEnvelope()) { - $libreSignFile->setStatus($this->fileMapper->getById($libreSignFile->getId())->getStatus()); - } - } - - /** - * A rejection closes the whole envelope, not only the document that carried - * the rejected signature request. - */ - private function cancelWorkflow(FileEntity $libreSignFile): void { - $libreSignFile->setStatusEnum(FileStatus::CANCELED); - $this->fileStatusService->update($libreSignFile); - - $envelopeId = $libreSignFile->isEnvelope() - ? $libreSignFile->getId() - : $libreSignFile->getParentFileId(); - if ($envelopeId === null) { - return; - } - - $this->fileStatusService->propagateStatusToChildren($envelopeId, FileStatus::CANCELED->value); - - if (!$libreSignFile->isEnvelope()) { - $envelope = $this->fileMapper->getById($envelopeId); - $envelope->setStatusEnum(FileStatus::CANCELED); - $this->fileStatusService->update($envelope); - } - } - - /** - * @param list $signRequests - * @param list $previousSignerStatuses - */ - private function rollBackRejection( - FileEntity $file, - array $signRequests, - array $previousSignerStatuses, - int $previousFileStatus, - ): void { - $this->db->rollBack(); - $this->restoreState($file, $signRequests, $previousSignerStatuses, $previousFileStatus); - } - - private function restoreState( - FileEntity $libreSignFile, - array $signRequests, - array $previousSignerStatuses, - int $previousFileStatus, - ): void { - foreach ($signRequests as $index => $signRequest) { - $signRequest->setStatus($previousSignerStatuses[$index]); - $signRequest->setRejectedAt(null); - $signRequest->setRejectionComment(null); - $signRequest->setRejectionCommentPrivate(false); - } - $libreSignFile->setStatus($previousFileStatus); - } - - private function assertWorkflowIsOpen(FileEntity $libreSignFile): void { - $openStatusList = [ - FileStatus::ABLE_TO_SIGN->value, - FileStatus::PARTIAL_SIGNED->value, - ]; - if (in_array($libreSignFile->getStatus(), $openStatusList, true)) { - return; - } - - if ($libreSignFile->getStatus() === FileStatus::CANCELED->value) { - // TRANSLATORS Error shown when an action is attempted on a document whose signing workflow was already closed by a rejection. - throw new LibresignException($this->l10n->t('The signing workflow of this document is already closed.')); - } - - // TRANSLATORS Error shown when a signer tries to reject a document that is not currently open for signing. - throw new LibresignException($this->l10n->t('This document is not open for signature rejection.')); - } - - private function assertSignerCanReject(SignRequestEntity $signRequest): void { - if ($signRequest->getSigned() !== null) { - // TRANSLATORS Error shown when the current user already signed this document. - throw new LibresignException($this->l10n->t('File already signed by you')); - } - - if ($this->isRejected($signRequest)) { - // TRANSLATORS Error shown when a signer tries to reject the same signature request twice. - throw new LibresignException($this->l10n->t('You already rejected this signature request.')); - } - } - - private function normalizeComment(?string $comment, SignatureRejectionCommentMode $mode): ?string { - $trimmed = $comment === null ? '' : trim($comment); - - if ($mode === SignatureRejectionCommentMode::DISABLED) { - if ($trimmed !== '') { - // TRANSLATORS Error shown when a signer sends a rejection comment but the document policy does not accept comments. - throw new LibresignException($this->l10n->t('Rejection comments are not allowed for this document.')); - } - return null; - } - - if ($trimmed === '') { - if ($mode === SignatureRejectionCommentMode::REQUIRED) { - // TRANSLATORS Error shown when the document policy requires a justification and the signer did not provide one. - throw new LibresignException($this->l10n->t('A comment is required to reject this signature request.')); - } - return null; - } - - if (mb_strlen($trimmed) > self::MAX_COMMENT_LENGTH) { - // TRANSLATORS Error shown when the rejection justification exceeds the maximum accepted length. %s is the maximum number of characters. - throw new LibresignException($this->l10n->t('The rejection comment must have at most %s characters.', [(string)self::MAX_COMMENT_LENGTH])); - } - - return $trimmed; - } - - private function dispatchRejectedEvent( - SignRequestEntity $signRequest, - FileEntity $libreSignFile, - bool $workflowCanceled, - ): void { - // The rejection is already committed at this point: a failing listener must - // not turn a recorded rejection into an error for the signer. - try { - $groupedIdentifyMethods = $this->identifyMethodService->getIdentifyMethodsFromSignRequestId($signRequest->getId()); - foreach ($groupedIdentifyMethods as $identifyMethods) { - foreach ($identifyMethods as $identifyMethod) { - $this->eventDispatcher->dispatchTyped(new SignatureRejectedEvent( - $signRequest, - $libreSignFile, - $identifyMethod, - $workflowCanceled, - )); - } - } - } catch (\Exception $e) { - $this->logger->error('Error dispatching SignatureRejectedEvent', [ - 'errorType' => get_debug_type($e), - ]); - } - } } diff --git a/lib/Service/SignatureRejection/SignatureRejectionWorkflow.php b/lib/Service/SignatureRejection/SignatureRejectionWorkflow.php new file mode 100644 index 0000000000..409753da22 --- /dev/null +++ b/lib/Service/SignatureRejection/SignatureRejectionWorkflow.php @@ -0,0 +1,162 @@ + $signers + * @return list + */ + public function continueWorkflow(FileEntity $file, array $signers): array { + $activated = $this->releaseNextSigningOrders($file, $signers); + $this->resolveStatusOfRejectedDocuments($file, $signers); + return $activated; + } + + /** @return list */ + public function collectSignRequestsToReject(FileEntity $libreSignFile, SignRequestEntity $signRequest): array { + $envelopeId = $libreSignFile->isEnvelope() + ? $libreSignFile->getId() + : $libreSignFile->getParentFileId(); + if ($envelopeId === null) { + return [$signRequest]; + } + + $collected = [$signRequest->getId() => $signRequest]; + + foreach ($this->signRequestMapper->getByEnvelopeChildrenAndIdentifyMethod($envelopeId, $signRequest->getId()) as $childSignRequest) { + $collected[$childSignRequest->getId()] ??= $childSignRequest; + } + + try { + $envelopeSignRequest = $this->signRequestMapper->getByIdentifyMethodAndFileId( + $this->identifyMethodService->getIdentifiedMethod($signRequest->getId()), + $envelopeId, + ); + $collected[$envelopeSignRequest->getId()] ??= $envelopeSignRequest; + } catch (DoesNotExistException) { + } + + // A document this signer already signed keeps its signature. + return array_values(array_filter( + $collected, + static fn (SignRequestEntity $each): bool => $each->getSigned() === null, + )); + } + + /** + * When the workflow continues, a rejection ends the signer's turn just like a + * signature does, so in a sequential flow the next order must be released on + * every document the signer rejected, or the signers after them would wait + * forever. + * + * @param list $rejectedSignRequests + * @return list The signers activated on every document. + */ + private function releaseNextSigningOrders(FileEntity $libreSignFile, array $rejectedSignRequests): array { + $activatedSigners = []; + + foreach ($rejectedSignRequests as $rejected) { + $document = $rejected->getFileId() === $libreSignFile->getId() + ? $libreSignFile + : $this->fileMapper->getById($rejected->getFileId()); + foreach ($this->sequentialSigningService + ->setFile($document) + ->activateNextOrder( + $rejected->getFileId(), + $rejected->getSigningOrder() + ) as $activated) { + $activatedSigners[] = $activated; + } + } + + return $activatedSigners; + } + + /** + * A rejection ends the signer's turn just like a signature does, so it can be + * the last action a document was waiting for. Its status is then resolved by + * the same rule the signing flow uses, otherwise a document whose last signer + * rejected would stay partially signed forever. + * + * An envelope is not resolved here: its status follows the documents it + * contains, so it is read back once they are saved. + * + * @param list $rejectedSignRequests + */ + private function resolveStatusOfRejectedDocuments(FileEntity $libreSignFile, array $rejectedSignRequests): void { + foreach ($rejectedSignRequests as $rejected) { + $document = $rejected->getFileId() === $libreSignFile->getId() + ? $libreSignFile + : $this->fileMapper->getById($rejected->getFileId()); + if ($document->isEnvelope()) { + continue; + } + + $status = $this->signingWorkflowStatusResolver->resolve( + $document, + $this->signRequestMapper->getByFileId($document->getId()), + ); + if ($status === null || $status->value === $document->getStatus()) { + continue; + } + + $document->setStatusEnum($status); + $this->fileStatusService->update($document); + } + + if ($libreSignFile->isEnvelope()) { + $libreSignFile->setStatus($this->fileMapper->getById($libreSignFile->getId())->getStatus()); + } + } + + /** + * A rejection closes the whole envelope, not only the document that carried + * the rejected signature request. + */ + public function cancelWorkflow(FileEntity $libreSignFile): void { + $libreSignFile->setStatusEnum(FileStatus::CANCELED); + $this->fileStatusService->update($libreSignFile); + + $envelopeId = $libreSignFile->isEnvelope() + ? $libreSignFile->getId() + : $libreSignFile->getParentFileId(); + if ($envelopeId === null) { + return; + } + + $this->fileStatusService->propagateStatusToChildren($envelopeId, FileStatus::CANCELED->value); + + if (!$libreSignFile->isEnvelope()) { + $envelope = $this->fileMapper->getById($envelopeId); + $envelope->setStatusEnum(FileStatus::CANCELED); + $this->fileStatusService->update($envelope); + } + } +} diff --git a/tests/php/Integration/Service/SignatureRejectionWiringTest.php b/tests/php/Integration/Service/SignatureRejectionWiringTest.php new file mode 100644 index 0000000000..04dc41e078 --- /dev/null +++ b/tests/php/Integration/Service/SignatureRejectionWiringTest.php @@ -0,0 +1,19 @@ +assertInstanceOf(SignatureRejectionService::class, Server::get(SignatureRejectionService::class)); + } +} diff --git a/tests/php/Unit/Service/SignatureRejection/SignatureRejectionNotifierTest.php b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionNotifierTest.php new file mode 100644 index 0000000000..b46c083e70 --- /dev/null +++ b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionNotifierTest.php @@ -0,0 +1,144 @@ +webhooks = $this->createMock(NativeWebhookEventPublisher::class); + $this->identification = $this->createMock(IdentifyMethodService::class); + $this->events = $this->createMock(IEventDispatcher::class); + $this->sequential = $this->createMock(SequentialSigningService::class); + $this->logger = $this->createMock(LoggerInterface::class); + $this->notifier = new SignatureRejectionNotifier( + $this->webhooks, $this->identification, $this->events, $this->sequential, $this->logger, + ); + } + + public function testOneNativeEventAndLegacyEventPerIdentificationMethod(): void { + $file = $this->file(FileStatus::CANCELED->value); + $signer = $this->signer(); + $next = $this->signer(id: 99); + $methods = [$this->createMock(IIdentifyMethod::class), $this->createMock(IIdentifyMethod::class)]; + $this->identification->method('getIdentifyMethodsFromSignRequestId')->willReturn(['account' => $methods]); + $this->webhooks->expects($this->once())->method('signerRejected') + ->with($file, $signer, FileStatus::ABLE_TO_SIGN->value); + $legacy = []; + $this->events->method('dispatchTyped')->willReturnCallback( + static function ($event) use (&$legacy): void { + $legacy[] = $event; + }, + ); + $this->sequential->expects($this->once())->method('notifyActivatedSigners')->with([$next]); + + $this->notifier->afterCommit($file, $signer, new CommittedRejection(FileStatus::ABLE_TO_SIGN->value, [$next])); + + $this->assertCount(2, $legacy); + foreach ($legacy as $event) { + $this->assertInstanceOf(SignatureRejectedEvent::class, $event); + $this->assertTrue($event->wasWorkflowCanceled()); + } + } + + public function testListenerFailureDoesNotPreventPostCommitSignerNotification(): void { + $this->identification->method('getIdentifyMethodsFromSignRequestId')->willReturn([ + 'account' => [$this->createMock(IIdentifyMethod::class)], + ]); + $this->events->method('dispatchTyped')->willThrowException(new \RuntimeException('listener failed')); + $this->logger->expects($this->once())->method('error') + ->with('Error dispatching SignatureRejectedEvent', ['errorType' => \RuntimeException::class]); + $next = $this->signer(id: 77); + $this->sequential->expects($this->once())->method('notifyActivatedSigners')->with([$next]); + + $this->notifier->afterCommit($this->file(), $this->signer(), new CommittedRejection(1, [$next])); + } + + public function testNotificationFailureAfterCommitRemainsVisible(): void { + $this->identification->method('getIdentifyMethodsFromSignRequestId')->willReturn([]); + $this->sequential->method('notifyActivatedSigners') + ->willThrowException(new \RuntimeException('notification failure')); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('notification failure'); + + $this->notifier->afterCommit($this->file(), $this->signer(), new CommittedRejection(1, [])); + } + + public function testNativeWebhookIsAttemptedBeforeLegacyListeners(): void { + $calls = []; + $this->webhooks->method('signerRejected')->willReturnCallback( + static function () use (&$calls): void { + $calls[] = 'native'; + }, + ); + $this->identification->method('getIdentifyMethodsFromSignRequestId')->willReturn([ + 'account' => [$this->createMock(IIdentifyMethod::class)], + ]); + $this->events->method('dispatchTyped')->willReturnCallback( + static function () use (&$calls): void { + $calls[] = 'legacy'; + }, + ); + $this->sequential->method('notifyActivatedSigners')->willReturnCallback( + static function () use (&$calls): void { + $calls[] = 'notify'; + }, + ); + + $this->notifier->afterCommit($this->file(), $this->signer(), new CommittedRejection(1, [])); + $this->assertSame(['native', 'legacy', 'notify'], $calls); + } + + public function testUnexpectedNotificationProgrammingErrorIsNotHidden(): void { + $this->identification->method('getIdentifyMethodsFromSignRequestId')->willReturn([]); + $this->sequential->method('notifyActivatedSigners') + ->willThrowException(new \TypeError('incorrect notification dependency')); + $this->expectException(\TypeError::class); + + $this->notifier->afterCommit($this->file(), $this->signer(), new CommittedRejection(1, [])); + } + + public function testContinuingWorkflowIsNotReportedCanceled(): void { + $signer = $this->signer(); + $this->identification->method('getIdentifyMethodsFromSignRequestId')->willReturn([ + 'account' => [$this->createMock(IIdentifyMethod::class)], + ]); + $legacy = null; + $this->events->method('dispatchTyped')->willReturnCallback( + static function ($event) use (&$legacy): void { + $legacy = $event; + }, + ); + + $this->notifier->afterCommit($this->file(), $signer, new CommittedRejection(1, [])); + + $this->assertInstanceOf(SignatureRejectedEvent::class, $legacy); + $this->assertFalse($legacy->wasWorkflowCanceled()); + } +} diff --git a/tests/php/Unit/Service/SignatureRejection/SignatureRejectionPersistenceTest.php b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionPersistenceTest.php new file mode 100644 index 0000000000..30fa590ccf --- /dev/null +++ b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionPersistenceTest.php @@ -0,0 +1,243 @@ +signRequests = $this->createMock(SignRequestMapper::class); + $this->files = $this->createMock(FileMapper::class); + $this->workflow = $this->createMock(SignatureRejectionWorkflow::class); + $this->db = $this->createMock(IDBConnection::class); + $clock = $this->createMock(ITimeFactory::class); + $clock->method('getDateTime')->willReturn(new \DateTime(self::REJECTED_AT)); + $l10n = $this->createMock(IL10N::class); + $l10n->method('t')->willReturnArgument(0); + $logger = $this->createMock(LoggerInterface::class); + $this->persistence = new SignatureRejectionPersistence( + $this->signRequests, $this->files, $this->workflow, + $this->db, $clock, $l10n, $logger, + ); + } + + private function input(bool $cancel = false): RejectionInput { + return new RejectionInput('reason', true, $cancel); + } + + public function testCommitPersistsRejectionAndReturnsActivatedSigners(): void { + $file = $this->file(); + $signer = $this->signer(); + $next = $this->signer(id: 77); + $this->workflow->method('collectSignRequestsToReject')->willReturn([$signer]); + $this->workflow->method('continueWorkflow')->willReturn([$next]); + $this->db->expects($this->once())->method('commit'); + + $result = $this->persistence->commit($file, $signer, $this->input()); + + $this->assertSame(FileStatus::ABLE_TO_SIGN->value, $result->previousRootStatus); + $this->assertSame([$next], $result->activatedSigners); + $this->assertSame(SignRequestStatus::REJECTED, $signer->getStatusEnum()); + $this->assertSame(self::REJECTED_AT, $signer->getRejectedAt()?->format(\DateTimeInterface::ATOM)); + $this->assertSame('reason', $signer->getRejectionComment()); + $this->assertTrue($signer->getRejectionCommentPrivate()); + } + + public function testEnvelopePreviousStatusIsCapturedBeforeBusinessCommit(): void { + $document = $this->file(parentFileId: 1); + $signer = $this->signer(); + $envelope = $this->envelope(FileStatus::PARTIAL_SIGNED->value); + $this->files->method('getById')->with(1)->willReturn($envelope); + $this->workflow->method('collectSignRequestsToReject')->willReturn([$signer]); + $this->db->method('commit')->willReturnCallback( + static function () use ($envelope): void { + $envelope->setStatusEnum(FileStatus::CANCELED); + }, + ); + + $result = $this->persistence->commit($document, $signer, $this->input(true)); + + $this->assertSame(FileStatus::PARTIAL_SIGNED->value, $result->previousRootStatus); + $this->assertSame(FileStatus::CANCELED->value, $envelope->getStatus()); + } + + public function testMissingEnvelopeIsDetectedBeforeAnyWrites(): void { + $document = $this->file(parentFileId: 1); + $this->files->method('getById')->with(1) + ->willThrowException(new DoesNotExistException('missing')); + $this->db->expects($this->never())->method('beginTransaction'); + $this->expectException(DoesNotExistException::class); + + $this->persistence->commit($document, $this->signer(), $this->input()); + } + + public function testCancelPolicyUpdatesWorkflowWithoutActivatingNextSigners(): void { + $file = $this->file(); + $signer = $this->signer(); + $this->workflow->method('collectSignRequestsToReject')->willReturn([$signer]); + $this->workflow->expects($this->once())->method('cancelWorkflow') + ->willReturnCallback(static function ($file): void { + $file->setStatusEnum(FileStatus::CANCELED); + }); + $this->workflow->expects($this->never())->method('continueWorkflow'); + + $result = $this->persistence->commit($file, $signer, $this->input(true)); + + $this->assertSame([], $result->activatedSigners); + $this->assertSame(FileStatus::CANCELED->value, $file->getStatus()); + } + + public function testFailedWriteRollsBackAndRestoresMutatedSigner(): void { + $file = $this->file(); + $signer = $this->signer(); + $this->workflow->method('collectSignRequestsToReject')->willReturn([$signer]); + $this->signRequests->method('update')->willThrowException(new \RuntimeException('database error')); + $this->db->expects($this->never())->method('commit'); + $this->db->expects($this->once())->method('rollBack'); + $this->expectException(LibresignException::class); + + try { + $this->persistence->commit($file, $signer, $this->input()); + } finally { + $this->assertSame(SignRequestStatus::ABLE_TO_SIGN, $signer->getStatusEnum()); + $this->assertNull($signer->getRejectedAt()); + $this->assertNull($signer->getRejectionComment()); + $this->assertFalse($signer->getRejectionCommentPrivate()); + } + } + + public function testFailedWorkflowUpdateRollsBackPersistedRejectionAndFileStatus(): void { + $file = $this->file(); + $signer = $this->signer(); + $this->workflow->method('collectSignRequestsToReject')->willReturn([$signer]); + $this->workflow->method('continueWorkflow')->willReturnCallback( + static function ($file): array { + $file->setStatusEnum(FileStatus::SIGNED); + throw new \RuntimeException('signing status update failed'); + }, + ); + $this->db->expects($this->once())->method('rollBack'); + $this->db->expects($this->never())->method('commit'); + $this->expectException(LibresignException::class); + + try { + $this->persistence->commit($file, $signer, $this->input()); + } finally { + $this->assertSame(FileStatus::ABLE_TO_SIGN->value, $file->getStatus()); + $this->assertSame(SignRequestStatus::ABLE_TO_SIGN, $signer->getStatusEnum()); + } + } + + public function testProgrammingErrorRollsBackWithoutBeingConvertedIntoPolicyFailure(): void { + $signer = $this->signer(); + $this->workflow->method('collectSignRequestsToReject')->willReturn([$signer]); + $this->signRequests->method('update')->willThrowException(new \TypeError('bad state')); + $this->db->expects($this->once())->method('rollBack'); + $this->db->expects($this->never())->method('commit'); + $this->expectException(\TypeError::class); + + $this->persistence->commit($this->file(), $signer, $this->input()); + } + + public function testSecondSignerWriteFailureRestoresAllRejections(): void { + $first = $this->signer(id: 11); + $second = $this->signer(id: 12); + $this->workflow->method('collectSignRequestsToReject')->willReturn([$first, $second]); + $writes = []; + $this->signRequests->method('update')->willReturnCallback( + static function (SignRequest $signer) use (&$writes): SignRequest { + $writes[] = $signer->getId(); + if (count($writes) === 2) { + throw new \RuntimeException('second write failed'); + } + return $signer; + }, + ); + $this->db->expects($this->once())->method('rollBack'); + $this->db->expects($this->never())->method('commit'); + $this->expectException(LibresignException::class); + + try { + $this->persistence->commit($this->file(), $first, $this->input()); + } finally { + $this->assertSame([11, 12], $writes); + foreach ([$first, $second] as $signer) { + $this->assertSame(SignRequestStatus::ABLE_TO_SIGN, $signer->getStatusEnum()); + $this->assertNull($signer->getRejectedAt()); + $this->assertNull($signer->getRejectionComment()); + } + } + } + + public function testFailedCancellationRestoresFileAndSignerBeforeReturningError(): void { + $file = $this->file(FileStatus::PARTIAL_SIGNED->value); + $signer = $this->signer(); + $this->workflow->method('collectSignRequestsToReject')->willReturn([$signer]); + $this->workflow->method('cancelWorkflow')->willReturnCallback( + static function ($file): void { + $file->setStatusEnum(FileStatus::CANCELED); + throw new \RuntimeException('failed to update envelope'); + }, + ); + $this->db->expects($this->once())->method('rollBack'); + $this->db->expects($this->never())->method('commit'); + $this->expectException(LibresignException::class); + + try { + $this->persistence->commit($file, $signer, $this->input(true)); + } finally { + $this->assertSame(FileStatus::PARTIAL_SIGNED->value, $file->getStatus()); + $this->assertSame(SignRequestStatus::ABLE_TO_SIGN, $signer->getStatusEnum()); + } + } + + public function testWorkflowChangesOccurBeforeTransactionCommit(): void { + $file = $this->file(); + $signer = $this->signer(); + $this->workflow->method('collectSignRequestsToReject')->willReturn([$signer]); + $order = []; + $this->workflow->method('continueWorkflow')->willReturnCallback( + static function () use (&$order): array { + $order[] = 'status'; + return []; + }, + ); + $this->db->expects($this->once())->method('commit')->willReturnCallback( + static function () use (&$order): void { + $order[] = 'commit'; + }, + ); + + $this->persistence->commit($file, $signer, $this->input()); + $this->assertSame(['status', 'commit'], $order); + } +} diff --git a/tests/php/Unit/Service/SignatureRejection/SignatureRejectionRulesTest.php b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionRulesTest.php new file mode 100644 index 0000000000..31af16a6ba --- /dev/null +++ b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionRulesTest.php @@ -0,0 +1,137 @@ +policies = $this->createMock(\OCA\Libresign\Service\SignatureRejection\SignatureRejectionPolicyService::class); + $l10n = $this->createMock(IL10N::class); + $l10n->method('t')->willReturnArgument(0); + $this->rules = new SignatureRejectionRules($this->policies, $l10n); + } + + private function withPolicy(SignatureRejectionPolicyConfig $policy): void { + $this->policies->method('getConfig')->willReturn($policy); + } + + public function testDisabledPolicyPreventsRejection(): void { + $this->withPolicy(SignatureRejectionPolicyConfig::defaults()); + $this->expectException(LibresignException::class); + $this->expectExceptionMessage('Signature rejection is not enabled for this document.'); + + $this->rules->validate($this->file(), $this->signer(), null, false); + } + + /** @return array */ + public static function closedStatuses(): array { + return [ + 'already canceled' => [FileStatus::CANCELED->value, 'The signing workflow of this document is already closed.'], + 'draft' => [FileStatus::DRAFT->value, 'This document is not open for signature rejection.'], + 'signed' => [FileStatus::SIGNED->value, 'This document is not open for signature rejection.'], + 'deleted' => [FileStatus::DELETED->value, 'This document is not open for signature rejection.'], + ]; + } + + #[DataProvider('closedStatuses')] + public function testClosedWorkflowRejectsInput(int $status, string $message): void { + $this->withPolicy(self::policy()); + $this->expectException(LibresignException::class); + $this->expectExceptionMessage($message); + + $this->rules->validate($this->file($status), $this->signer(), null, false); + } + + public function testSignedSignerCannotReject(): void { + $this->withPolicy(self::policy()); + $signer = $this->signer(); + $signer->setSigned(new \DateTime(self::REJECTED_AT)); + $this->expectExceptionMessage('File already signed by you'); + + $this->rules->validate($this->file(), $signer, null, false); + } + + public function testAlreadyRejectedSignerCannotRejectAgain(): void { + $this->withPolicy(self::policy()); + $this->expectExceptionMessage('You already rejected this signature request.'); + + $this->rules->validate($this->file(), $this->signer(SignRequestStatus::REJECTED->value), null, false); + } + + public function testDisabledCommentsDoNotAcceptContent(): void { + $this->withPolicy(self::policy()); + $this->expectExceptionMessage('Rejection comments are not allowed for this document.'); + + $this->rules->validate($this->file(), $this->signer(), 'My private explanation', true); + } + + /** @return array */ + public static function absentComments(): array { + return ['null' => [null], 'empty' => [''], 'whitespace' => [' ']]; + } + + #[DataProvider('absentComments')] + public function testRequiredCommentCannotBeBlank(?string $comment): void { + $this->withPolicy(self::policy(commentMode: 'required')); + $this->expectExceptionMessage('A comment is required to reject this signature request.'); + + $this->rules->validate($this->file(), $this->signer(), $comment, false); + } + + public function testOverlongCommentIsRejected(): void { + $this->withPolicy(self::policy(commentMode: 'optional')); + $this->expectExceptionMessage('The rejection comment must have at most'); + + $this->rules->validate($this->file(), $this->signer(), str_repeat('a', SignatureRejectionRules::MAX_COMMENT_LENGTH + 1), false); + } + + /** @return array */ + public static function privacyChoices(): array { + return ['private' => [true], 'public' => [false]]; + } + + #[DataProvider('privacyChoices')] + public function testSignerControlsCommentPrivacy(bool $private): void { + $this->withPolicy(self::policy(behavior: 'cancel', commentMode: 'optional')); + $result = $this->rules->validate($this->file(), $this->signer(), ' reason ', $private); + + $this->assertSame('reason', $result->comment); + $this->assertSame($private, $result->commentIsPrivate); + $this->assertTrue($result->cancelsWorkflow); + } + + public function testEmptyCommentCannotBeMarkedPrivate(): void { + $this->withPolicy(self::policy(commentMode: 'optional')); + $result = $this->rules->validate($this->file(), $this->signer(), ' ', true); + + $this->assertNull($result->comment); + $this->assertFalse($result->commentIsPrivate); + $this->assertFalse($result->cancelsWorkflow); + } + + public function testMaximumLengthCommentIsAccepted(): void { + $this->withPolicy(self::policy(commentMode: 'required')); + $comment = str_repeat('x', SignatureRejectionRules::MAX_COMMENT_LENGTH); + $result = $this->rules->validate($this->file(), $this->signer(), $comment, false); + $this->assertSame($comment, $result->comment); + } +} diff --git a/tests/php/Unit/Service/SignatureRejection/SignatureRejectionSamples.php b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionSamples.php new file mode 100644 index 0000000000..ab59cfe257 --- /dev/null +++ b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionSamples.php @@ -0,0 +1,52 @@ +value, ?int $parentFileId = null): File { + $file = new File(); + $file->setId(10); + $file->setUserId('requester'); + $file->setUuid('doc-uuid'); + $file->setStatus($status); + if ($parentFileId !== null) { + $file->setParentFileId($parentFileId); + } + return $file; + } + + private function envelope(int $status = FileStatus::ABLE_TO_SIGN->value): File { + $envelope = $this->file($status); + $envelope->setId(1); + $envelope->setUuid('envelope-uuid'); + $envelope->setNodeType('envelope'); + return $envelope; + } + + private function signer(int $status = SignRequestStatus::ABLE_TO_SIGN->value, int $id = 1): SignRequest { + $signer = new SignRequest(); + $signer->setId($id); + $signer->setFileId(10); + $signer->setDisplayName('Signer'); + $signer->setStatus($status); + return $signer; + } + + private static function policy(string $behavior = 'continue', string $commentMode = 'disabled'): SignatureRejectionPolicyConfig { + return SignatureRejectionPolicyConfig::fromValues(enabled: true, behavior: $behavior, commentMode: $commentMode); + } +} diff --git a/tests/php/Unit/Service/SignatureRejection/SignatureRejectionServiceTest.php b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionServiceTest.php index 8d141d075d..d7cfa1e3af 100644 --- a/tests/php/Unit/Service/SignatureRejection/SignatureRejectionServiceTest.php +++ b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionServiceTest.php @@ -8,1071 +8,89 @@ namespace OCA\Libresign\Tests\Unit\Service\SignatureRejection; -use OCA\Libresign\Db\File; -use OCA\Libresign\Db\FileMapper; -use OCA\Libresign\Db\NotificationDeliveryMapper; -use OCA\Libresign\Db\SignRequest; -use OCA\Libresign\Db\SignRequestMapper; use OCA\Libresign\Enum\FileStatus; use OCA\Libresign\Enum\SignRequestStatus; -use OCA\Libresign\Events\SignatureRejectedEvent; -use OCA\Libresign\Events\SignerRejectedWebhookEvent; -use OCA\Libresign\Events\SigningRequestCanceledEvent; -use OCA\Libresign\Events\SigningRequestCompletedEvent; use OCA\Libresign\Exception\LibresignException; -use OCA\Libresign\Service\File\SigningWorkflowStatusResolver; -use OCA\Libresign\Service\FileStatusService; -use OCA\Libresign\Service\IdentifyMethod\IIdentifyMethod; -use OCA\Libresign\Service\IdentifyMethodService; -use OCA\Libresign\Service\Policy\Provider\SignatureRejection\SignatureRejectionPolicyConfig; -use OCA\Libresign\Service\SequentialSigningService; -use OCA\Libresign\Service\SignatureRejection\SignatureRejectionPolicyService; +use OCA\Libresign\Service\SignatureRejection\CommittedRejection; +use OCA\Libresign\Service\SignatureRejection\RejectionInput; +use OCA\Libresign\Service\SignatureRejection\SignatureRejectionNotifier; +use OCA\Libresign\Service\SignatureRejection\SignatureRejectionPersistence; +use OCA\Libresign\Service\SignatureRejection\SignatureRejectionRules; use OCA\Libresign\Service\SignatureRejection\SignatureRejectionService; -use OCA\Libresign\Service\Webhook\NativeWebhookEventPublisher; -use OCP\AppFramework\Db\DoesNotExistException; -use OCP\AppFramework\Utility\ITimeFactory; -use OCP\EventDispatcher\IEventDispatcher; -use OCP\IDBConnection; -use OCP\IL10N; -use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use Psr\Log\LoggerInterface; final class SignatureRejectionServiceTest extends TestCase { - private const REJECTED_AT = '2026-09-06T10:00:00+00:00'; + use SignatureRejectionSamples; - private SignRequestMapper&MockObject $signRequestMapper; - private FileMapper&MockObject $fileMapper; - private SignatureRejectionPolicyService&MockObject $rejectionPolicyService; - private FileStatusService&MockObject $fileStatusService; - private IdentifyMethodService&MockObject $identifyMethodService; - private SequentialSigningService&MockObject $sequentialSigningService; - private SigningWorkflowStatusResolver&MockObject $signingWorkflowStatusResolver; - private IEventDispatcher&MockObject $eventDispatcher; - private IDBConnection&MockObject $db; - private ITimeFactory&MockObject $timeFactory; - private IL10N&MockObject $l10n; - private LoggerInterface&MockObject $logger; - private NativeWebhookEventPublisher $webhooks; - /** @var list */ - private array $envelopeChildSignRequests = []; - private ?SignRequest $envelopeSignRequest = null; - /** @var array */ - private array $filesById = []; - private bool $detachedFileReads = false; + private SignatureRejectionRules&MockObject $rules; + private SignatureRejectionPersistence&MockObject $persistence; + private SignatureRejectionNotifier&MockObject $notifier; + private SignatureRejectionService $service; protected function setUp(): void { - parent::setUp(); - $this->signRequestMapper = $this->createMock(SignRequestMapper::class); - $this->fileMapper = $this->createMock(FileMapper::class); - $this->rejectionPolicyService = $this->createMock(SignatureRejectionPolicyService::class); - $this->fileStatusService = $this->createMock(FileStatusService::class); - $this->identifyMethodService = $this->createMock(IdentifyMethodService::class); - $this->sequentialSigningService = $this->createMock(SequentialSigningService::class); - $this->signingWorkflowStatusResolver = $this->createMock(SigningWorkflowStatusResolver::class); - $this->eventDispatcher = $this->createMock(IEventDispatcher::class); - $this->db = $this->createMock(IDBConnection::class); - $this->timeFactory = $this->createMock(ITimeFactory::class); - $this->l10n = $this->createMock(IL10N::class); - $this->logger = $this->createMock(LoggerInterface::class); - $this->webhooks = $this->createMock(NativeWebhookEventPublisher::class); - - $this->l10n->method('t')->willReturnArgument(0); - $this->timeFactory->method('getDateTime') - ->willReturn(new \DateTime(self::REJECTED_AT)); - $this->identifyMethodService->method('getIdentifyMethodsFromSignRequestId') - ->willReturn(['account' => [$this->createMock(IIdentifyMethod::class)]]); - $this->sequentialSigningService->method('setFile')->willReturnSelf(); - - $this->fileMapper->method('getById') - ->willReturnCallback(function (int $id): File { - if (array_key_exists($id, $this->filesById)) { - if ($this->filesById[$id] === null) { - throw new DoesNotExistException('Synthetic missing committed envelope'); - } - return $this->detachedFileReads ? clone $this->filesById[$id] : $this->filesById[$id]; - } - $file = $this->file(); - $file->setId($id); - return $file; - }); - $this->signRequestMapper->method('getByEnvelopeChildrenAndIdentifyMethod') - ->willReturnCallback(fn (): array => $this->envelopeChildSignRequests); - $this->signRequestMapper->method('getByIdentifyMethodAndFileId') - ->willReturnCallback(function (): SignRequest { - if (!$this->envelopeSignRequest instanceof SignRequest) { - throw new DoesNotExistException('the envelope has no signature request for this signer'); - } - return $this->envelopeSignRequest; - }); - } - - private function getService(): SignatureRejectionService { - return new SignatureRejectionService( - $this->signRequestMapper, - $this->fileMapper, - $this->rejectionPolicyService, - $this->fileStatusService, - $this->identifyMethodService, - $this->sequentialSigningService, - $this->signingWorkflowStatusResolver, - $this->eventDispatcher, - $this->db, - $this->timeFactory, - $this->l10n, - $this->logger, - $this->webhooks, - ); - } - - private function useNativeWebhookPublisher(): void { - $this->webhooks = new NativeWebhookEventPublisher( - $this->eventDispatcher, - $this->logger, - $this->fileMapper, - $this->createMock(NotificationDeliveryMapper::class), - ); - } - - private function withPolicy(SignatureRejectionPolicyConfig $config): void { - $this->rejectionPolicyService - ->method('getConfig') - ->willReturn($config); - } - - /** - * The rejection rules frozen on the document. The workflow keeps running by - * default here, so the tests about closing it say so explicitly. - */ - private static function policy(string $behavior = 'continue', string $commentMode = 'disabled'): SignatureRejectionPolicyConfig { - return SignatureRejectionPolicyConfig::fromValues( - enabled: true, - behavior: $behavior, - commentMode: $commentMode, - ); - } - - private function file(int $status = FileStatus::ABLE_TO_SIGN->value, ?int $parentFileId = null): File { - $file = new File(); - $file->setId(10); - $file->setUserId('requester'); - $file->setStatus($status); - if ($parentFileId !== null) { - $file->setParentFileId($parentFileId); - } - return $file; - } - - private function envelope(int $status = FileStatus::ABLE_TO_SIGN->value): File { - $envelope = $this->file($status); - $envelope->setId(1); - $envelope->setNodeType('envelope'); - return $envelope; - } - - private function signRequest(int $status = SignRequestStatus::ABLE_TO_SIGN->value, int $id = 1): SignRequest { - $signRequest = new SignRequest(); - $signRequest->setId($id); - $signRequest->setFileId(10); - $signRequest->setDisplayName('Signer'); - $signRequest->setStatus($status); - return $signRequest; - } - - public function testRejectionIsBlockedWhenThePolicyIsDisabled(): void { - $this->withPolicy(SignatureRejectionPolicyConfig::defaults()); - $this->signRequestMapper->expects($this->never())->method('update'); - $this->db->expects($this->never())->method('beginTransaction'); - - $this->expectException(LibresignException::class); - $this->expectExceptionMessage('Signature rejection is not enabled for this document.'); - - $this->getService()->reject($this->file(), $this->signRequest()); - } - - #[DataProvider('provideClosedWorkflowStatuses')] - public function testRejectionIsBlockedWhenTheWorkflowIsNotOpen(int $fileStatus, string $expectedMessage): void { - $this->withPolicy(self::policy()); - $this->signRequestMapper->expects($this->never())->method('update'); - - $this->expectException(LibresignException::class); - $this->expectExceptionMessage($expectedMessage); - - $this->getService()->reject($this->file($fileStatus), $this->signRequest()); - } - - /** - * @return iterable - */ - public static function provideClosedWorkflowStatuses(): iterable { - yield 'already canceled by a rejection' => [ - FileStatus::CANCELED->value, - 'The signing workflow of this document is already closed.', - ]; - yield 'draft' => [FileStatus::DRAFT->value, 'This document is not open for signature rejection.']; - yield 'signed' => [FileStatus::SIGNED->value, 'This document is not open for signature rejection.']; - yield 'deleted' => [FileStatus::DELETED->value, 'This document is not open for signature rejection.']; + $this->rules = $this->createMock(SignatureRejectionRules::class); + $this->persistence = $this->createMock(SignatureRejectionPersistence::class); + $this->notifier = $this->createMock(SignatureRejectionNotifier::class); + $this->service = new SignatureRejectionService($this->rules, $this->persistence, $this->notifier); } - public function testASignerWhoAlreadySignedCannotReject(): void { - $this->withPolicy(self::policy()); - $signRequest = $this->signRequest(SignRequestStatus::SIGNED->value); - $signRequest->setSigned(new \DateTime('2026-09-05T10:00:00+00:00')); - - $this->expectException(LibresignException::class); - $this->expectExceptionMessage('File already signed by you'); - - $this->getService()->reject($this->file(), $signRequest); - } - - public function testASignerCannotRejectTwice(): void { - $this->withPolicy(self::policy()); - - $this->expectException(LibresignException::class); - $this->expectExceptionMessage('You already rejected this signature request.'); - - $this->getService()->reject($this->file(), $this->signRequest(SignRequestStatus::REJECTED->value)); - } - - public function testCommentIsRefusedWhenThePolicyDoesNotAcceptComments(): void { - $this->withPolicy(self::policy(commentMode: 'disabled')); - + public function testSuccessfulRejectionReturnsSignerAndNotifiesCommittedResult(): void { + $file = $this->file(); + $signer = $this->signer(); + $input = new RejectionInput('reason', true, false); + $result = new CommittedRejection(FileStatus::ABLE_TO_SIGN->value, [$this->signer(id: 99)]); + $this->rules->expects($this->once())->method('validate') + ->with($file, $signer, 'reason', true)->willReturn($input); + $this->persistence->expects($this->once())->method('commit') + ->with($file, $signer, $input)->willReturn($result); + $this->notifier->expects($this->once())->method('afterCommit') + ->with($file, $signer, $result); + + $this->assertSame($signer, $this->service->reject($file, $signer, 'reason', true)); + } + + public function testInvalidInputDoesNotWriteOrNotify(): void { + $this->rules->method('validate')->willThrowException(new LibresignException('not allowed')); + $this->persistence->expects($this->never())->method('commit'); + $this->notifier->expects($this->never())->method('afterCommit'); $this->expectException(LibresignException::class); - $this->expectExceptionMessage('Rejection comments are not allowed for this document.'); - $this->getService()->reject($this->file(), $this->signRequest(), 'I do not agree'); + $this->service->reject($this->file(), $this->signer()); } - #[DataProvider('provideMissingRequiredComments')] - public function testCommentIsRequiredWhenThePolicySaysSo(?string $comment): void { - $this->withPolicy(self::policy(commentMode: 'required')); - - $this->expectException(LibresignException::class); - $this->expectExceptionMessage('A comment is required to reject this signature request.'); - - $this->getService()->reject($this->file(), $this->signRequest(), $comment); - } + public function testFailedWriteNeverDispatchesNotifications(): void { + $this->rules->method('validate')->willReturn(new RejectionInput(null, false, true)); + $this->persistence->method('commit')->willThrowException(new \RuntimeException('write failure')); + $this->notifier->expects($this->never())->method('afterCommit'); + $this->expectException(\RuntimeException::class); - /** - * @return iterable - */ - public static function provideMissingRequiredComments(): iterable { - yield 'null' => [null]; - yield 'empty string' => ['']; - yield 'only whitespace' => [" \n\t "]; + $this->service->reject($this->file(), $this->signer()); } - public function testCommentLongerThanTheLimitIsRefused(): void { - $this->withPolicy(self::policy(commentMode: 'optional')); - - $this->expectException(LibresignException::class); - $this->expectExceptionMessage('The rejection comment must have at most %s characters.'); - - $this->getService()->reject( - $this->file(), - $this->signRequest(), - str_repeat('a', SignatureRejectionService::MAX_COMMENT_LENGTH + 1), + public function testPostCommitNotificationFailureDoesNotChangePersistedSignerState(): void { + $signer = $this->signer(); + $this->rules->method('validate')->willReturn(new RejectionInput(null, false, true)); + $this->persistence->method('commit')->willReturnCallback( + static function ($file, $signer): CommittedRejection { + $signer->setStatusEnum(SignRequestStatus::REJECTED); + return new CommittedRejection($file->getStatus(), []); + }, ); - } - - public function testCommentAtTheLimitIsAccepted(): void { - $this->withPolicy(self::policy(commentMode: 'optional')); - $comment = str_repeat('a', SignatureRejectionService::MAX_COMMENT_LENGTH); - - $signRequest = $this->getService()->reject($this->file(), $this->signRequest(), $comment); - - $this->assertSame($comment, $signRequest->getRejectionComment()); - } - - public function testTheSignerAlwaysDecidesWhetherTheirCommentIsPrivate(): void { - // No policy option can take this choice away from the signer. - $this->withPolicy(self::policy(commentMode: 'optional')); - - $signRequest = $this->getService()->reject($this->file(), $this->signRequest(), 'Not my document', true); - - $this->assertSame('Not my document', $signRequest->getRejectionComment()); - $this->assertTrue($signRequest->getRejectionCommentPrivate()); - } - - public function testPrivateFlagIsIgnoredWhenThereIsNoComment(): void { - $this->withPolicy(self::policy(commentMode: 'optional')); - - $signRequest = $this->getService()->reject($this->file(), $this->signRequest(), null, true); - - $this->assertNull($signRequest->getRejectionComment()); - $this->assertFalse($signRequest->getRejectionCommentPrivate()); - } - - #[DataProvider('publicRejectionOutcomes')] - public function testCommittedRejectionPublishesSanitizedEvents(bool $cancel): void { - $this->withPolicy(self::policy($cancel ? 'cancel' : 'continue', 'optional')); - $this->useNativeWebhookPublisher(); - $file = $this->file(); - $file->setUuid('request-uuid'); - $signer = $this->signRequest(); - $published = []; - $committed = false; - $this->db->expects($this->once())->method('commit') - ->willReturnCallback(static function () use (&$committed): void { - $committed = true; - }); - $this->eventDispatcher->method('dispatchTyped') - ->willReturnCallback(function (object $event) use (&$published, &$committed): void { - $this->assertTrue($committed); - $published[] = $event; - }); - - $this->getService()->reject($file, $signer, 'private explanation', true); - - $rejections = array_values(array_filter($published, - static fn (object $event): bool => $event instanceof SignerRejectedWebhookEvent)); - $this->assertCount(1, $rejections); - $payload = $rejections[0]->getWebhookSerializable(); - $this->assertSame('request-uuid', $payload['requestUuid']); - $this->assertSame($cancel, $payload['workflowCanceled']); - $this->assertStringNotContainsString('private explanation', json_encode($payload)); - $this->assertCount($cancel ? 1 : 0, array_filter($published, - static fn (object $event): bool => $event instanceof SigningRequestCanceledEvent)); - $this->assertSame(SignRequestStatus::REJECTED, $signer->getStatusEnum()); - $this->assertTrue($signer->getRejectionCommentPrivate()); - } - - /** @return array */ - public static function publicRejectionOutcomes(): array { - return ['continue' => [false], 'cancel' => [true]]; - } - - public function testEnvelopeWebhookReceivesTheCommittedRootStatus(): void { - $this->withPolicy(self::policy('cancel')); - $this->useNativeWebhookPublisher(); - $document = $this->file(); - $document->setId(21); - $document->setParentFileId(1); - $document->setUuid('child-uuid'); - $signer = $this->signRequest(); - $signer->setFileId(21); - - $persistedRoot = $this->envelope(); - $persistedRoot->setUuid('root-uuid'); - $this->filesById[1] = $persistedRoot; - $this->detachedFileReads = true; - $this->fileStatusService->method('update') - ->willReturnCallback(function (File $updated): File { - $this->filesById[$updated->getId()] = clone $updated; - return $updated; - }); - $committed = false; - $this->db->expects($this->once())->method('commit') - ->willReturnCallback(static function () use (&$committed): void { - $committed = true; - }); - $published = []; - $this->eventDispatcher->method('dispatchTyped') - ->willReturnCallback(function (object $event) use (&$published, &$committed): void { - $this->assertTrue($committed); - $published[] = $event; - }); - - $this->getService()->reject($document, $signer); - - $rejections = array_values(array_filter($published, - static fn (object $event): bool => $event instanceof SignerRejectedWebhookEvent)); - $this->assertCount(1, $rejections); - $this->assertSame('root-uuid', $rejections[0]->getWebhookSerializable()['requestUuid']); - $this->assertSame('envelope', $rejections[0]->getWebhookSerializable()['requestType']); - $this->assertTrue($rejections[0]->getWebhookSerializable()['workflowCanceled']); - $this->assertCount(1, array_filter($published, - static fn (object $event): bool => $event instanceof SigningRequestCanceledEvent)); - $this->assertSame(FileStatus::CANCELED->value, $this->filesById[1]->getStatus()); - $this->assertSame(SignRequestStatus::REJECTED, $signer->getStatusEnum()); - } - - public function testMissingEnvelopeAfterCommitDoesNotTurnRejectionIntoFailedRequest(): void { - $this->withPolicy(self::policy('cancel')); - $this->useNativeWebhookPublisher(); - $document = $this->file(); - $document->setId(21); - $document->setParentFileId(1); - $signer = $this->signRequest(); - $signer->setFileId(21); - $this->filesById[1] = $this->envelope(); - $this->db->expects($this->once())->method('commit') - ->willReturnCallback(function (): void { - $this->filesById[1] = null; - }); - $this->logger->expects($this->once())->method('error') - ->with('Native webhook publication failed after commit', $this->callback( - static fn (array $context): bool - => ($context['fileId'] ?? null) === 21 - && ($context['event'] ?? null) === 'signer.rejected' - && ($context['phase'] ?? null) === 'prepare' - && ($context['errorType'] ?? null) === DoesNotExistException::class, - )); - $published = []; - $this->eventDispatcher->method('dispatchTyped') - ->willReturnCallback(static function (object $event) use (&$published): void { - $published[] = $event; - }); - - $result = $this->getService()->reject($document, $signer); - - $this->assertSame($signer, $result); - $this->assertSame(SignRequestStatus::REJECTED, $result->getStatusEnum()); - $this->assertCount(1, $published); - $this->assertInstanceOf(SignatureRejectedEvent::class, $published[0]); - } - - public function testMissingEnvelopeBeforeCommitPreventsTheRejection(): void { - $this->withPolicy(self::policy('cancel')); - $document = $this->file(); - $document->setId(21); - $document->setParentFileId(1); - $signer = $this->signRequest(); - $this->filesById[1] = null; - $this->db->expects($this->never())->method('beginTransaction'); - $this->db->expects($this->never())->method('commit'); - $this->webhooks->expects($this->never())->method('signerRejected'); - - $this->expectException(DoesNotExistException::class); - try { - $this->getService()->reject($document, $signer); - } finally { - $this->assertSame(SignRequestStatus::ABLE_TO_SIGN, $signer->getStatusEnum()); - } - } + $this->notifier->method('afterCommit')->willThrowException(new \RuntimeException('external notification failed')); + $this->expectException(\RuntimeException::class); - public function testProgrammingErrorDuringRejectionRollsBackAndRemainsVisible(): void { - $this->withPolicy(self::policy('cancel')); - $signer = $this->signRequest(); - $this->signRequestMapper->method('update') - ->willThrowException(new \TypeError('programming error')); - $this->db->expects($this->once())->method('rollBack'); - $this->db->expects($this->never())->method('commit'); - $this->eventDispatcher->expects($this->never())->method('dispatchTyped'); - $this->expectException(\TypeError::class); try { - $this->getService()->reject($this->file(), $signer); + $this->service->reject($this->file(), $signer); } finally { - $this->assertSame(SignRequestStatus::ABLE_TO_SIGN, $signer->getStatusEnum()); + $this->assertSame(SignRequestStatus::REJECTED, $signer->getStatusEnum()); } } - public function testRejectionCanCompletePreviouslySignedWorkflow(): void { - $this->withPolicy(self::policy('continue')); - $this->useNativeWebhookPublisher(); - $file = $this->file(FileStatus::PARTIAL_SIGNED->value); - $file->setUuid('completed-by-rejection'); - $this->signingWorkflowStatusResolver->method('resolve')->willReturn(FileStatus::SIGNED); - $published = []; - $this->eventDispatcher->method('dispatchTyped') - ->willReturnCallback(static function (object $event) use (&$published): void { - $published[] = $event; - }); - - $this->getService()->reject($file, $this->signRequest()); - - $completed = array_values(array_filter($published, - static fn (object $event): bool => $event instanceof SigningRequestCompletedEvent)); - $this->assertCount(1, $completed); - $this->assertSame('completed-by-rejection', $completed[0]->getWebhookSerializable()['requestUuid']); - $this->assertSame(FileStatus::SIGNED->value, $file->getStatus()); - } - - public function testRejectionIsPersistedWithItsTimestampAndComment(): void { - $this->withPolicy(self::policy(commentMode: 'optional')); - $signRequest = $this->signRequest(); - - $this->db->expects($this->once())->method('beginTransaction'); - $this->db->expects($this->once())->method('commit'); - $this->db->expects($this->never())->method('rollBack'); - $this->signRequestMapper - ->expects($this->once()) - ->method('update') - ->with($signRequest); - - $result = $this->getService()->reject($this->file(), $signRequest, ' I do not agree ', true); - - $this->assertSame(SignRequestStatus::REJECTED, $result->getStatusEnum()); - $this->assertSame(self::REJECTED_AT, $result->getRejectedAt()?->format(\DateTimeInterface::ATOM)); - $this->assertSame('I do not agree', $result->getRejectionComment()); - $this->assertTrue($result->getRejectionCommentPrivate()); - } - - public function testWorkflowKeepsRunningWhenThePolicyDoesNotCancelIt(): void { - $this->withPolicy(self::policy(behavior: 'continue')); - $file = $this->file(); - - $this->fileStatusService->expects($this->never())->method('update'); - - $this->getService()->reject($file, $this->signRequest()); - - $this->assertSame(FileStatus::ABLE_TO_SIGN->value, $file->getStatus()); - } - - public function testAContinuingRejectionReleasesTheNextSigningOrder(): void { - $this->withPolicy(self::policy(behavior: 'continue')); - $file = $this->file(); - $signRequest = $this->signRequest(); - $signRequest->setSigningOrder(2); - - $this->sequentialSigningService->expects($this->once()) - ->method('setFile') - ->with($file) - ->willReturnSelf(); - $this->sequentialSigningService->expects($this->once()) - ->method('activateNextOrder') - ->with(10, 2) - ->willReturn([]); - - $this->getService()->reject($file, $signRequest); - } - - public function testACancellingRejectionReleasesNobody(): void { - $this->withPolicy(self::policy(behavior: 'cancel')); - - $this->sequentialSigningService->expects($this->never())->method('activateNextOrder'); - - $this->getService()->reject($this->file(), $this->signRequest()); - } - - public function testRejectingAnEnvelopeReleasesTheNextOrderOfEveryDocument(): void { - $this->withPolicy(self::policy(behavior: 'continue')); - $envelope = $this->envelope(); - $onDoc1 = $this->signRequest(id: 11); - $onDoc1->setFileId(21); - $onDoc2 = $this->signRequest(id: 12); - $onDoc2->setFileId(22); - $onTheEnvelope = $this->signRequest(id: 13); - $onTheEnvelope->setFileId(1); - - $this->envelopeChildSignRequests = [$onDoc1, $onDoc2]; - $this->envelopeSignRequest = $onTheEnvelope; - - $released = []; - $this->sequentialSigningService->method('activateNextOrder') - ->willReturnCallback(function (int $fileId) use (&$released): array { - $released[] = $fileId; - return []; - }); - - $this->getService()->reject($envelope, $onDoc1); - - $this->assertSame([21, 22, 1], $released); - } - - public function testAFailedReleaseOfTheNextOrderLeavesNoPartiallyUpdatedWorkflow(): void { - $this->withPolicy(self::policy(behavior: 'continue')); - $signRequest = $this->signRequest(); - - $this->sequentialSigningService->method('activateNextOrder') - ->willThrowException(new \RuntimeException('database is down')); - $this->sequentialSigningService->expects($this->never())->method('notifyActivatedSigners'); - $this->db->expects($this->once())->method('rollBack'); - $this->db->expects($this->never())->method('commit'); - - try { - $this->getService()->reject($this->file(), $signRequest); - $this->fail('The rejection must fail when the next order cannot be released.'); - } catch (LibresignException) { - $this->assertSame(SignRequestStatus::ABLE_TO_SIGN, $signRequest->getStatusEnum()); - } - } - - public function testTheReleasedOrderIsNotifiedOnlyAfterTheRejectionIsCommitted(): void { - $this->withPolicy(self::policy(behavior: 'continue')); - $activated = $this->signRequest(id: 77); - $activated->setFileId(10); - - $this->sequentialSigningService->method('activateNextOrder') - ->willReturn([$activated]); - - $committed = false; - $eventDispatched = false; - $this->db->expects($this->once()) - ->method('commit') - ->willReturnCallback(function () use (&$committed): void { - $committed = true; - }); - $this->eventDispatcher->expects($this->once()) - ->method('dispatchTyped') - ->with($this->isInstanceOf(SignatureRejectedEvent::class)) - ->willReturnCallback(function () use (&$committed, &$eventDispatched): void { - $this->assertTrue($committed, 'The rejection event must follow the commit.'); - $eventDispatched = true; - }); - $this->sequentialSigningService->expects($this->once()) - ->method('notifyActivatedSigners') - ->with([$activated]) - ->willReturnCallback(function () use (&$committed, &$eventDispatched): void { - $this->assertTrue($eventDispatched, 'The rejection event must precede signer notifications.'); - $this->assertTrue( - $committed, - 'The released signers must only be notified once the rejection is committed.', - ); - }); - - $this->getService()->reject($this->file(), $this->signRequest()); - } - - public function testARolledBackRejectionDoesNotNotifyAnOrderReleasedForAnEarlierDocument(): void { - $this->withPolicy(self::policy(behavior: 'continue')); - $envelope = $this->envelope(); - $onDoc1 = $this->signRequest(id: 11); - $onDoc1->setFileId(21); - $onDoc2 = $this->signRequest(id: 12); - $onDoc2->setFileId(22); - $onTheEnvelope = $this->signRequest(id: 13); - $onTheEnvelope->setFileId(1); - - $this->envelopeChildSignRequests = [$onDoc1, $onDoc2]; - $this->envelopeSignRequest = $onTheEnvelope; - - $releasedForDoc1 = $this->signRequest(id: 71); - $this->sequentialSigningService->method('activateNextOrder') - ->willReturnCallback(function (int $fileId) use ($releasedForDoc1): array { - if ($fileId === 21) { - return [$releasedForDoc1]; - } - if ($fileId === 22) { - throw new \RuntimeException('the second document could not be updated'); - } - - return []; - }); - - $this->db->expects($this->once())->method('rollBack'); - $this->db->expects($this->never())->method('commit'); - $this->sequentialSigningService->expects($this->never())->method('notifyActivatedSigners'); - - try { - $this->getService()->reject($envelope, $onDoc1); - $this->fail('The rejection must fail when a later document cannot be released.'); - } catch (LibresignException) { - $this->assertSame(SignRequestStatus::ABLE_TO_SIGN, $onDoc1->getStatusEnum()); - $this->assertSame(SignRequestStatus::ABLE_TO_SIGN, $onDoc2->getStatusEnum()); - $this->assertSame(SignRequestStatus::ABLE_TO_SIGN, $onTheEnvelope->getStatusEnum()); - } - } - - public function testAnUnexpectedNotificationExceptionDoesNotRollBackACommittedRejection(): void { - $this->withPolicy(self::policy(behavior: 'continue')); - $signRequest = $this->signRequest(); - - $this->sequentialSigningService->method('activateNextOrder') - ->willReturn([$this->signRequest(id: 78)]); - $this->sequentialSigningService->method('notifyActivatedSigners') - ->willThrowException(new \RuntimeException('unexpected notification exception')); - $this->eventDispatcher->expects($this->once())->method('dispatchTyped') - ->with($this->isInstanceOf(SignatureRejectedEvent::class)); - $this->db->expects($this->once())->method('commit'); - $this->db->expects($this->never())->method('rollBack'); - $this->logger->expects($this->never())->method('error'); - - try { - $this->getService()->reject($this->file(), $signRequest); - $this->fail('Unexpected notification exceptions must propagate.'); - } catch (\RuntimeException $e) { - $this->assertSame('unexpected notification exception', $e->getMessage()); - $this->assertSame(SignRequestStatus::REJECTED, $signRequest->getStatusEnum()); - } - } - - public function testAProgrammingErrorWhileNotifyingIsNotConvertedIntoADeliveryFailure(): void { - $this->withPolicy(self::policy(behavior: 'continue')); - $signRequest = $this->signRequest(); - - $this->sequentialSigningService->method('activateNextOrder') - ->willReturn([$this->signRequest(id: 78)]); - $this->sequentialSigningService->method('notifyActivatedSigners') - ->willThrowException(new \TypeError('bug in the notification path')); - - $this->eventDispatcher->expects($this->once())->method('dispatchTyped') - ->with($this->isInstanceOf(SignatureRejectedEvent::class)); - $this->db->expects($this->once())->method('commit'); - $this->db->expects($this->never())->method('rollBack'); - $this->logger->expects($this->never())->method('error'); - - $this->expectException(\TypeError::class); - $this->expectExceptionMessage('bug in the notification path'); - - $this->getService()->reject($this->file(), $signRequest); - } - - public function testTheLastRejectionCompletesAWorkflowSomebodyAlreadySigned(): void { - $this->withPolicy(self::policy(behavior: 'continue')); - $file = $this->file(FileStatus::PARTIAL_SIGNED->value); - $signersOfTheDocument = [$this->signRequest(SignRequestStatus::SIGNED->value, id: 2)]; - $this->signRequestMapper->method('getByFileId') - ->with(10) - ->willReturn($signersOfTheDocument); - - $calls = []; - $this->signingWorkflowStatusResolver->expects($this->once()) - ->method('resolve') - ->with($file, $signersOfTheDocument) - ->willReturn(FileStatus::SIGNED); - $this->fileStatusService->expects($this->once()) - ->method('update') - ->with($file) - ->willReturnCallback(function (File $file) use (&$calls): File { - $calls[] = 'status'; - return $file; - }); - $this->db->method('commit') - ->willReturnCallback(function () use (&$calls): void { - $calls[] = 'commit'; - }); - - $this->getService()->reject($file, $this->signRequest()); - - $this->assertSame(FileStatus::SIGNED->value, $file->getStatus()); - $this->assertSame(['status', 'commit'], $calls); - } - - public function testARejectionThatLeavesSomebodyToSignKeepsTheStatus(): void { - $this->withPolicy(self::policy(behavior: 'continue')); - $file = $this->file(FileStatus::PARTIAL_SIGNED->value); - $this->signingWorkflowStatusResolver->method('resolve') - ->willReturn(FileStatus::PARTIAL_SIGNED); - - $this->fileStatusService->expects($this->never())->method('update'); - - $this->getService()->reject($file, $this->signRequest()); - - $this->assertSame(FileStatus::PARTIAL_SIGNED->value, $file->getStatus()); - } - - public function testRejectingAnEnvelopeResolvesTheStatusOfEveryDocumentButNotOfTheEnvelope(): void { - $this->withPolicy(self::policy(behavior: 'continue')); - $envelope = $this->envelope(FileStatus::PARTIAL_SIGNED->value); - $onDoc1 = $this->signRequest(id: 11); - $onDoc1->setFileId(21); - $onDoc2 = $this->signRequest(id: 12); - $onDoc2->setFileId(22); - $onTheEnvelope = $this->signRequest(id: 13); - $onTheEnvelope->setFileId(1); - $this->envelopeChildSignRequests = [$onDoc1, $onDoc2]; - $this->envelopeSignRequest = $onTheEnvelope; - $this->filesById[1] = $envelope; - - $resolved = []; - $this->signingWorkflowStatusResolver->method('resolve') - ->willReturnCallback(function (File $document) use (&$resolved): FileStatus { - $resolved[] = $document->getId(); - return FileStatus::SIGNED; - }); - $updated = []; - $this->fileStatusService->method('update') - ->willReturnCallback(function (File $document) use (&$updated): File { - $updated[] = $document->getId(); - return $document; - }); - - $this->getService()->reject($envelope, $onDoc1); - - $this->assertSame([21, 22], $resolved); - $this->assertSame([21, 22], $updated); - } - - public function testACancellingRejectionDoesNotResolveTheStatusFromTheSigners(): void { - $this->withPolicy(self::policy(behavior: 'cancel')); - - $this->signingWorkflowStatusResolver->expects($this->never())->method('resolve'); - - $this->getService()->reject($this->file(), $this->signRequest()); - } - - public function testAFailedStatusUpdateLeavesNoPartiallyUpdatedWorkflow(): void { - $this->withPolicy(self::policy(behavior: 'continue')); - $file = $this->file(FileStatus::PARTIAL_SIGNED->value); - $signRequest = $this->signRequest(); - $this->signingWorkflowStatusResolver->method('resolve') - ->willReturn(FileStatus::SIGNED); - $this->fileStatusService->method('update') - ->willThrowException(new \RuntimeException('database is down')); - $this->db->expects($this->once())->method('rollBack'); - $this->db->expects($this->never())->method('commit'); - - try { - $this->getService()->reject($file, $signRequest); - $this->fail('The rejection must fail when the document status cannot be saved.'); - } catch (LibresignException) { - $this->assertSame(FileStatus::PARTIAL_SIGNED->value, $file->getStatus()); - $this->assertSame(SignRequestStatus::ABLE_TO_SIGN, $signRequest->getStatusEnum()); - } - } - - public function testWorkflowIsClosedWhenThePolicyCancelsIt(): void { - $this->withPolicy(self::policy(behavior: 'cancel')); - $file = $this->file(FileStatus::PARTIAL_SIGNED->value); - - $this->fileStatusService - ->expects($this->once()) - ->method('update') - ->with($file); - $this->fileStatusService->expects($this->never())->method('propagateStatusToChildren'); - - $this->getService()->reject($file, $this->signRequest()); - - $this->assertSame(FileStatus::CANCELED->value, $file->getStatus()); - $this->assertTrue($this->getService()->isWorkflowCanceled($file)); - } - - public function testCancellingADocumentClosesTheWholeEnvelope(): void { - $this->withPolicy(self::policy(behavior: 'cancel')); - $child = $this->file(FileStatus::ABLE_TO_SIGN->value, parentFileId: 1); - $envelope = $this->envelope(); - - $this->filesById[1] = $envelope; - $this->fileStatusService - ->expects($this->once()) - ->method('propagateStatusToChildren') - ->with(1, FileStatus::CANCELED->value); - $this->fileStatusService->expects($this->exactly(2))->method('update'); - - $this->getService()->reject($child, $this->signRequest()); - - $this->assertSame(FileStatus::CANCELED->value, $child->getStatus()); - $this->assertSame(FileStatus::CANCELED->value, $envelope->getStatus()); - } - - public function testCancellingAnEnvelopeClosesEveryDocumentItContains(): void { - $this->withPolicy(self::policy(behavior: 'cancel')); - $envelope = $this->envelope(); - - $this->fileMapper->expects($this->never())->method('getById'); - $this->fileStatusService - ->expects($this->once()) - ->method('propagateStatusToChildren') - ->with(1, FileStatus::CANCELED->value); - - $this->getService()->reject($envelope, $this->signRequest()); - - $this->assertSame(FileStatus::CANCELED->value, $envelope->getStatus()); - } - - public function testAFailedCancellationLeavesNoPartiallyUpdatedWorkflow(): void { - $this->withPolicy(self::policy(behavior: 'cancel', commentMode: 'optional')); - $file = $this->file(); - $signRequest = $this->signRequest(); - - $this->signRequestMapper->expects($this->once())->method('update'); - $this->fileStatusService - ->method('update') - ->willThrowException(new \RuntimeException('database is gone')); - - $this->db->expects($this->once())->method('beginTransaction'); - $this->db->expects($this->never())->method('commit'); - $this->db->expects($this->once())->method('rollBack'); - $this->eventDispatcher->expects($this->never())->method('dispatchTyped'); - $this->logger->expects($this->once())->method('error'); - - try { - $this->getService()->reject($file, $signRequest, 'I do not agree'); - $this->fail('Expected the rejection to fail'); - } catch (LibresignException $e) { - $this->assertSame('It was not possible to register the rejection. Nothing was changed.', $e->getMessage()); - } - - $this->assertSame(SignRequestStatus::ABLE_TO_SIGN, $signRequest->getStatusEnum()); - $this->assertNull($signRequest->getRejectedAt()); - $this->assertNull($signRequest->getRejectionComment()); - $this->assertFalse($signRequest->getRejectionCommentPrivate()); - $this->assertSame(FileStatus::ABLE_TO_SIGN->value, $file->getStatus()); - } - - public function testAFailedSignerUpdateLeavesNoPartiallyUpdatedWorkflow(): void { - $this->withPolicy(self::policy(behavior: 'cancel')); - $file = $this->file(); - $signRequest = $this->signRequest(); - - $this->signRequestMapper - ->method('update') - ->willThrowException(new \RuntimeException('database is gone')); - $this->fileStatusService->expects($this->never())->method('update'); - $this->db->expects($this->once())->method('rollBack'); - - $this->expectException(LibresignException::class); - - try { - $this->getService()->reject($file, $signRequest); - } finally { - $this->assertSame(SignRequestStatus::ABLE_TO_SIGN, $signRequest->getStatusEnum()); - $this->assertSame(FileStatus::ABLE_TO_SIGN->value, $file->getStatus()); - } - } - - #[DataProvider('provideWorkflowCancellation')] - public function testRejectionDispatchesTheEvent(bool $cancelWorkflow): void { - $this->withPolicy(self::policy(behavior: $cancelWorkflow ? 'cancel' : 'continue')); - $file = $this->file(); - $signRequest = $this->signRequest(); - - $dispatched = null; - $this->eventDispatcher - ->expects($this->once()) - ->method('dispatchTyped') - ->willReturnCallback(function (object $event) use (&$dispatched): void { - $dispatched = $event; - }); - - $this->getService()->reject($file, $signRequest); - - $this->assertInstanceOf(SignatureRejectedEvent::class, $dispatched); - $this->assertSame($signRequest, $dispatched->getSignRequest()); - $this->assertSame($file, $dispatched->getLibreSignFile()); - $this->assertSame($cancelWorkflow, $dispatched->wasWorkflowCanceled()); - } - - /** - * @return iterable - */ - public static function provideWorkflowCancellation(): iterable { - yield 'workflow continues' => [false]; - yield 'workflow canceled' => [true]; - } - - public function testAWorkflowThatContinuesIsReportedCanceledOnceEverybodyRejected(): void { - $this->withPolicy(self::policy(behavior: 'continue')); - $file = $this->file(); - $this->signingWorkflowStatusResolver->method('resolve') - ->willReturn(FileStatus::CANCELED); - - $dispatched = null; - $this->eventDispatcher - ->expects($this->once()) - ->method('dispatchTyped') - ->willReturnCallback(function (object $event) use (&$dispatched): void { - $dispatched = $event; - }); - - $this->getService()->reject($file, $this->signRequest()); - - $this->assertSame(FileStatus::CANCELED->value, $file->getStatus()); - $this->assertInstanceOf(SignatureRejectedEvent::class, $dispatched); - $this->assertTrue($dispatched->wasWorkflowCanceled()); - } - - public function testRejectingAnEnvelopeReportsTheStatusItsDocumentsLeftIt(): void { - $this->withPolicy(self::policy(behavior: 'continue')); - $envelope = $this->envelope(); - $onDoc = $this->signRequest(id: 11); - $onDoc->setFileId(21); - $this->envelopeChildSignRequests = [$onDoc]; - // The envelope row the documents propagate their status to. - $storedEnvelope = $this->envelope(); - $this->filesById[1] = $storedEnvelope; - - $this->signingWorkflowStatusResolver->method('resolve') - ->willReturn(FileStatus::CANCELED); - $this->fileStatusService->method('update') - ->willReturnCallback(function (File $document) use ($storedEnvelope): File { - $storedEnvelope->setStatusEnum(FileStatus::CANCELED); - return $document; - }); - - $dispatched = null; - $this->eventDispatcher - ->method('dispatchTyped') - ->willReturnCallback(function (object $event) use (&$dispatched): void { - $dispatched = $event; - }); - - $this->getService()->reject($envelope, $onDoc); - - $this->assertSame(FileStatus::CANCELED->value, $envelope->getStatus()); - $this->assertTrue($dispatched->wasWorkflowCanceled()); - } - - public function testAFailingListenerDoesNotDiscardARecordedRejection(): void { - $this->withPolicy(self::policy()); - $signRequest = $this->signRequest(); - - $this->db->expects($this->once())->method('commit'); - $this->eventDispatcher - ->method('dispatchTyped') - ->willThrowException(new \RuntimeException('listener exploded')); - $this->logger->expects($this->once())->method('error'); - - $result = $this->getService()->reject($this->file(), $signRequest); - - $this->assertSame(SignRequestStatus::REJECTED, $result->getStatusEnum()); - } - - public function testRejectingAnEnvelopeClosesEverySignatureRequestOfTheSigner(): void { - // Signing an envelope closes the request of every document it contains plus - // the one on the envelope itself; a rejection has to close the same set. - $this->withPolicy(self::policy(commentMode: 'optional')); - $envelope = $this->envelope(); - $onDoc1 = $this->signRequest(id: 11); - $onDoc2 = $this->signRequest(id: 12); - $onTheEnvelope = $this->signRequest(id: 13); - - $this->envelopeChildSignRequests = [$onDoc1, $onDoc2]; - $this->envelopeSignRequest = $onTheEnvelope; - - $updated = []; - $this->signRequestMapper - ->expects($this->exactly(3)) - ->method('update') - ->willReturnCallback(function (SignRequest $signRequest) use (&$updated): SignRequest { - $updated[] = $signRequest->getId(); - return $signRequest; - }); - - $this->getService()->reject($envelope, $onDoc1, 'I do not agree with this package'); - - $this->assertSame([11, 12, 13], $updated); - foreach ([$onDoc1, $onDoc2, $onTheEnvelope] as $signRequest) { - $this->assertSame(SignRequestStatus::REJECTED, $signRequest->getStatusEnum()); - $this->assertSame(self::REJECTED_AT, $signRequest->getRejectedAt()?->format(\DateTimeInterface::ATOM)); - $this->assertSame('I do not agree with this package', $signRequest->getRejectionComment()); - } - } - - public function testADocumentTheSignerAlreadySignedKeepsItsSignature(): void { - $this->withPolicy(self::policy()); - $envelope = $this->envelope(); - $pending = $this->signRequest(id: 11); - $alreadySigned = $this->signRequest(SignRequestStatus::SIGNED->value, id: 12); - $alreadySigned->setSigned(new \DateTime('2026-09-05T10:00:00+00:00')); - - $this->envelopeChildSignRequests = [$pending, $alreadySigned]; - - $updated = []; - $this->signRequestMapper - ->method('update') - ->willReturnCallback(function (SignRequest $signRequest) use (&$updated): SignRequest { - $updated[] = $signRequest->getId(); - return $signRequest; - }); - - $this->getService()->reject($envelope, $pending); - - $this->assertSame([11], $updated); - $this->assertSame(SignRequestStatus::SIGNED, $alreadySigned->getStatusEnum()); - } - - public function testAPlainRequestNeverLooksForEnvelopeSiblings(): void { - $this->withPolicy(self::policy()); - $this->signRequestMapper->expects($this->never())->method('getByEnvelopeChildrenAndIdentifyMethod'); - $this->signRequestMapper->expects($this->never())->method('getByIdentifyMethodAndFileId'); - - $this->getService()->reject($this->file(), $this->signRequest()); - } - - public function testIsRejected(): void { - $service = $this->getService(); - - $this->assertFalse($service->isRejected($this->signRequest())); - $this->assertTrue($service->isRejected($this->signRequest(SignRequestStatus::REJECTED->value))); - } - - public function testIsWorkflowCanceled(): void { - $service = $this->getService(); - - $this->assertFalse($service->isWorkflowCanceled($this->file())); - $this->assertTrue($service->isWorkflowCanceled($this->file(FileStatus::CANCELED->value))); + public function testStatusQueriesUseTheEntitiesWithoutInfrastructure(): void { + $this->assertFalse($this->service->isRejected($this->signer())); + $this->assertTrue($this->service->isRejected($this->signer(SignRequestStatus::REJECTED->value))); + $this->assertFalse($this->service->isWorkflowCanceled($this->file())); + $this->assertTrue($this->service->isWorkflowCanceled($this->file(FileStatus::CANCELED->value))); } } diff --git a/tests/php/Unit/Service/SignatureRejection/SignatureRejectionWorkflowTest.php b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionWorkflowTest.php new file mode 100644 index 0000000000..17e0c887e3 --- /dev/null +++ b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionWorkflowTest.php @@ -0,0 +1,217 @@ + */ + private array $storedFiles = []; + + protected function setUp(): void { + $this->signRequests = $this->createMock(SignRequestMapper::class); + $this->files = $this->createMock(FileMapper::class); + $this->sequential = $this->createMock(SequentialSigningService::class); + $this->statusResolver = $this->createMock(SigningWorkflowStatusResolver::class); + $this->statuses = $this->createMock(FileStatusService::class); + $this->identification = $this->createMock(IdentifyMethodService::class); + $this->workflow = new SignatureRejectionWorkflow( + $this->signRequests, $this->files, $this->identification, + $this->sequential, $this->statusResolver, $this->statuses, + ); + $this->sequential->method('setFile')->willReturnSelf(); + $this->files->method('getById') + ->willReturnCallback(fn (int $id): File => $this->storedFiles[$id]); + } + + public function testPlainDocumentTargetsOnlyTheRequestingSigner(): void { + $signer = $this->signer(); + $this->signRequests->expects($this->never())->method('getByEnvelopeChildrenAndIdentifyMethod'); + $this->signRequests->expects($this->never())->method('getByIdentifyMethodAndFileId'); + + $this->assertSame([$signer], $this->workflow->collectSignRequestsToReject($this->file(), $signer)); + } + + public function testEnvelopeIncludesDocumentAndEnvelopeRequestsWithoutDuplicates(): void { + $original = $this->signer(id: 11); + $original->setFileId(21); + $sibling = $this->signer(id: 12); + $sibling->setFileId(22); + $envelopeSigner = $this->signer(id: 13); + $envelopeSigner->setFileId(1); + $this->signRequests->method('getByEnvelopeChildrenAndIdentifyMethod')->willReturn([$original, $sibling, $sibling]); + $this->signRequests->method('getByIdentifyMethodAndFileId')->willReturn($envelopeSigner); + + $result = $this->workflow->collectSignRequestsToReject($this->envelope(), $original); + + $this->assertSame([11, 12, 13], array_map(static fn (SignRequest $item): int => $item->getId(), $result)); + } + + public function testAlreadySignedEnvelopeSiblingPreservesItsSignature(): void { + $original = $this->signer(id: 11); + $signed = $this->signer(SignRequestStatus::SIGNED->value, 12); + $signed->setSigned(new \DateTime(self::REJECTED_AT)); + $this->signRequests->method('getByEnvelopeChildrenAndIdentifyMethod')->willReturn([$signed]); + $this->signRequests->method('getByIdentifyMethodAndFileId') + ->willThrowException(new DoesNotExistException('optional envelope-level signer missing')); + + $this->assertSame([$original], $this->workflow->collectSignRequestsToReject($this->envelope(), $original)); + $this->assertSame(SignRequestStatus::SIGNED, $signed->getStatusEnum()); + } + + public function testContinuingWorkflowActivatesNextSignerAndResolvesDocumentStatus(): void { + $document = $this->file(FileStatus::PARTIAL_SIGNED->value); + $rejected = $this->signer(); + $next = $this->signer(id: 99); + $this->sequential->method('activateNextOrder')->willReturn([$next]); + $this->signRequests->method('getByFileId')->willReturn([$rejected]); + $this->statusResolver->method('resolve')->willReturn(FileStatus::SIGNED); + + $activated = $this->workflow->continueWorkflow($document, [$rejected]); + + $this->assertSame([$next], $activated); + $this->assertSame(FileStatus::SIGNED->value, $document->getStatus()); + } + + public function testContinuingWorkflowDoesNotPersistUnchangedStatus(): void { + $document = $this->file(FileStatus::PARTIAL_SIGNED->value); + $this->sequential->method('activateNextOrder')->willReturn([]); + $this->statusResolver->method('resolve')->willReturn(FileStatus::PARTIAL_SIGNED); + $this->statuses->expects($this->never())->method('update'); + + $this->workflow->continueWorkflow($document, [$this->signer()]); + $this->assertSame(FileStatus::PARTIAL_SIGNED->value, $document->getStatus()); + } + + public function testEnvelopeResolvesChildDocumentsButNotEnvelopeAsAChild(): void { + $envelope = $this->envelope(FileStatus::PARTIAL_SIGNED->value); + $first = $this->file(FileStatus::PARTIAL_SIGNED->value); + $first->setId(21); + $second = $this->file(FileStatus::PARTIAL_SIGNED->value); + $second->setId(22); + $this->storedFiles = [1 => $envelope, 21 => $first, 22 => $second]; + $signers = []; + foreach ([21, 22, 1] as $id) { + $signer = $this->signer(id: $id); + $signer->setFileId($id); + $signers[] = $signer; + } + $resolvedIds = []; + $this->statusResolver->method('resolve')->willReturnCallback( + static function (File $file) use (&$resolvedIds): FileStatus { + $resolvedIds[] = $file->getId(); + return FileStatus::SIGNED; + }, + ); + $this->sequential->method('activateNextOrder')->willReturn([]); + + $activated = $this->workflow->continueWorkflow($envelope, $signers); + + $this->assertSame([], $activated); + $this->assertSame([21, 22], $resolvedIds); + $this->assertSame(FileStatus::SIGNED->value, $first->getStatus()); + $this->assertSame(FileStatus::SIGNED->value, $second->getStatus()); + } + + public function testCancelingAChildClosesItsEnvelopeAndPropagatesToOtherChildren(): void { + $child = $this->file(parentFileId: 1); + $envelope = $this->envelope(); + $this->storedFiles[1] = $envelope; + $this->statuses->expects($this->once())->method('propagateStatusToChildren') + ->with(1, FileStatus::CANCELED->value); + + $this->workflow->cancelWorkflow($child); + + $this->assertSame(FileStatus::CANCELED->value, $child->getStatus()); + $this->assertSame(FileStatus::CANCELED->value, $envelope->getStatus()); + } + + public function testCancelingAnEnvelopePropagatesToItsChildren(): void { + $envelope = $this->envelope(); + $this->statuses->expects($this->once())->method('propagateStatusToChildren') + ->with(1, FileStatus::CANCELED->value); + + $this->workflow->cancelWorkflow($envelope); + $this->assertSame(FileStatus::CANCELED->value, $envelope->getStatus()); + } + + public function testFailedSequentialActivationRemainsVisibleToTransactionOwner(): void { + $this->sequential->method('activateNextOrder')->willThrowException(new \RuntimeException('storage unavailable')); + $this->expectException(\RuntimeException::class); + + $this->workflow->continueWorkflow($this->file(), [$this->signer()]); + } + + public function testEnvelopeContinuesSequentialOrderOnEachRejectedDocument(): void { + $envelope = $this->envelope(); + $documents = [$envelope]; + $signers = []; + foreach ([21, 22, 1] as $id) { + $file = $id === 1 ? $envelope : $this->file(); + $file->setId($id); + $this->storedFiles[$id] = $file; + $signer = $this->signer(id: $id); + $signer->setFileId($id); + $signers[] = $signer; + } + $this->statusResolver->method('resolve')->willReturn(null); + $released = []; + $this->sequential->method('activateNextOrder')->willReturnCallback( + static function (int $fileId) use (&$released): array { + $released[] = $fileId; + return []; + }, + ); + + $this->assertSame([], $this->workflow->continueWorkflow($envelope, $signers)); + $this->assertSame([21, 22, 1], $released); + } + + public function testFinalRejectionCanSetWorkflowCanceledWithoutExplicitCancelPolicy(): void { + $file = $this->file(FileStatus::PARTIAL_SIGNED->value); + $this->sequential->method('activateNextOrder')->willReturn([]); + $this->statusResolver->method('resolve')->willReturn(FileStatus::CANCELED); + + $this->workflow->continueWorkflow($file, [$this->signer()]); + + $this->assertSame(FileStatus::CANCELED->value, $file->getStatus()); + } + + public function testAStatusUpdateFailureIsPropagatedForRollback(): void { + $file = $this->file(FileStatus::PARTIAL_SIGNED->value); + $this->sequential->method('activateNextOrder')->willReturn([]); + $this->statusResolver->method('resolve')->willReturn(FileStatus::SIGNED); + $this->statuses->method('update')->willThrowException(new \RuntimeException('status persistence failed')); + $this->expectException(\RuntimeException::class); + + $this->workflow->continueWorkflow($file, [$this->signer()]); + } +} From a481992f6a19fa48734391784b083873ab920fc7 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Wed, 11 Nov 2026 03:50:22 +0000 Subject: [PATCH 18/23] refactor: remove redundant rejection listener comment Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- lib/Service/SignatureRejection/SignatureRejectionNotifier.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/lib/Service/SignatureRejection/SignatureRejectionNotifier.php b/lib/Service/SignatureRejection/SignatureRejectionNotifier.php index f5bc2fc88a..473fc90103 100644 --- a/lib/Service/SignatureRejection/SignatureRejectionNotifier.php +++ b/lib/Service/SignatureRejection/SignatureRejectionNotifier.php @@ -39,8 +39,6 @@ private function dispatchRejectedEvent( FileEntity $libreSignFile, bool $workflowCanceled, ): void { - // The rejection is already committed at this point: a failing listener must - // not turn a recorded rejection into an error for the signer. try { $groupedIdentifyMethods = $this->identifyMethodService->getIdentifyMethodsFromSignRequestId($signRequest->getId()); foreach ($groupedIdentifyMethods as $identifyMethods) { From 0df9b43e299bbd287225900773fa001e5751c42d Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Wed, 11 Nov 2026 04:14:28 +0000 Subject: [PATCH 19/23] fix: address native webhook lifecycle review regressions Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- lib/Controller/SignFileController.php | 2 + lib/Db/FileMapper.php | 13 ++ lib/Events/SigningRequestReadyEvent.php | 10 +- lib/Service/FileStatusService.php | 12 ++ lib/Service/RequestSignatureService.php | 63 +++++-- .../SignatureRejectionNotifier.php | 24 ++- .../SignatureRejectionPersistence.php | 2 + .../Controller/SignFileControllerTest.php | 2 + tests/php/Unit/Db/FileMapperCacheTest.php | 50 +++++ .../Unit/Events/NativeWebhookEventsTest.php | 16 ++ .../Unit/Service/FileStatusServiceTest.php | 38 ++++ .../Service/RequestSignatureServiceTest.php | 171 ++++++++++++++++++ .../SignatureRejectionNotifierTest.php | 43 +++++ .../SignatureRejectionPersistenceTest.php | 14 +- .../SignatureRejectionWorkflowTest.php | 25 +++ 15 files changed, 454 insertions(+), 31 deletions(-) create mode 100644 tests/php/Unit/Db/FileMapperCacheTest.php diff --git a/lib/Controller/SignFileController.php b/lib/Controller/SignFileController.php index e38a63503d..f52b571c81 100644 --- a/lib/Controller/SignFileController.php +++ b/lib/Controller/SignFileController.php @@ -394,6 +394,8 @@ private function reject( } catch (\Throwable $th) { $this->logger->error('Unable to process signature rejection', [ 'errorType' => get_debug_type($th), + 'errorFile' => $th->getFile(), + 'errorLine' => $th->getLine(), ]); return new DataResponse( // TRANSLATORS Error shown when a signature rejection fails unexpectedly. diff --git a/lib/Db/FileMapper.php b/lib/Db/FileMapper.php index d27ff72510..c317b06f58 100644 --- a/lib/Db/FileMapper.php +++ b/lib/Db/FileMapper.php @@ -53,6 +53,19 @@ public function update(Entity $entity): File { return parent::update($entity); } + #[\Override] + public function invalidateCachedEntity(Entity $entity): void { + parent::invalidateCachedEntity($entity); + if ($entity instanceof File) { + if ($entity->getNodeId() !== null) { + $this->cacheRemove('node_id:' . $entity->getNodeId()); + } + if ($entity->getUuid() !== '') { + $this->cacheRemove('uuid:' . $entity->getUuid()); + } + } + } + #[\Override] protected function cacheEntity(Entity $entity): void { parent::cacheEntity($entity); diff --git a/lib/Events/SigningRequestReadyEvent.php b/lib/Events/SigningRequestReadyEvent.php index 5a184f4262..63d0113f64 100644 --- a/lib/Events/SigningRequestReadyEvent.php +++ b/lib/Events/SigningRequestReadyEvent.php @@ -20,6 +20,7 @@ final class SigningRequestReadyEvent extends Event implements IWebhookCompatible private function __construct( private readonly string $requestUuid, private readonly string $requestType, + private readonly string $eventId, ) { parent::__construct(); } @@ -32,14 +33,19 @@ public static function fromTransition(FileEntity $file, int $previousStatus): ?s return null; } - return new self($file->getUuid(), $file->isEnvelope() ? 'envelope' : 'document'); + $transitionId = ($file->getMetadata() ?? [])['ready_event_id'] ?? null; + $eventId = 'libresign.workflow.ready.v1:' . $file->getUuid(); + if (is_string($transitionId) && $transitionId !== '') { + $eventId .= ':' . $transitionId; + } + return new self($file->getUuid(), $file->isEnvelope() ? 'envelope' : 'document', $eventId); } #[\Override] public function getWebhookSerializable(): array { return [ 'contractVersion' => self::CONTRACT_VERSION, - 'eventId' => 'libresign.workflow.ready.v1:' . $this->requestUuid, + 'eventId' => $this->eventId, 'requestUuid' => $this->requestUuid, 'requestType' => $this->requestType, 'status' => 'ready_to_sign', diff --git a/lib/Service/FileStatusService.php b/lib/Service/FileStatusService.php index a4b37fa47b..7408295db8 100644 --- a/lib/Service/FileStatusService.php +++ b/lib/Service/FileStatusService.php @@ -28,6 +28,9 @@ public function __construct( public function updateFileStatusIfUpgrade(FileEntity $file, int $newStatus): FileEntity { if ($newStatus > $file->getStatus()) { $this->markPolicySnapshotFrozen($file, $newStatus); + if (!$file->hasParent() && $file->getStatus() === FileStatus::DRAFT->value && $newStatus === FileStatus::ABLE_TO_SIGN->value) { + $this->markReadyTransition($file); + } $file->setStatus($newStatus); $this->touchStatusChangedAt($file); $this->fileMapper->update($file); @@ -99,6 +102,9 @@ public function propagateStatusToParent(int $parentId): void { if ($parent->getStatus() !== $newStatus) { $this->markPolicySnapshotFrozen($parent, $newStatus); + if ($parent->getStatus() === FileStatus::DRAFT->value && $newStatus === FileStatus::ABLE_TO_SIGN->value) { + $this->markReadyTransition($parent); + } $parent->setStatus($newStatus); $this->touchStatusChangedAt($parent); $this->fileMapper->update($parent); @@ -206,6 +212,12 @@ private static function hasFrozenPolicySnapshot(FileEntity $file): bool { || $file->getStatus() >= FileStatus::ABLE_TO_SIGN->value; } + public function markReadyTransition(FileEntity $file): void { + $metadata = $file->getMetadata() ?? []; + $metadata['ready_event_id'] = bin2hex(random_bytes(16)); + $file->setMetadata($metadata); + } + private function touchStatusChangedAt(FileEntity $file): void { $metadata = $file->getMetadata() ?? []; $metadata['status_changed_at'] = (new DateTime())->format(DateTimeInterface::ATOM); diff --git a/lib/Service/RequestSignatureService.php b/lib/Service/RequestSignatureService.php index 3ef9da6a45..ee21bf18b5 100644 --- a/lib/Service/RequestSignatureService.php +++ b/lib/Service/RequestSignatureService.php @@ -141,22 +141,38 @@ public function saveFiles(array $data): array { } public function save(array $data): FileEntity { - $result = $this->persistFile($data); - $file = $result['file']; - $data['status'] ??= $file->getStatus(); - $this->atomic(function () use ($file, $data): void { - $this->sequentialSigningService->setFile($file); - $this->associateToSigners($data, $file); - $this->propagateSignersToChildren($file, $data); - $this->saveVisibleElements($data, $file); - }, $this->db); + $file = null; + try { + $result = $this->atomic(function () use ($data, &$file): array { + $result = $this->persistFile($data); + $file = $result['file']; + $data['status'] ??= $file->getStatus(); + $this->sequentialSigningService->setFile($file); + $this->associateToSigners($data, $file); + $this->propagateSignersToChildren($file, $data); + $this->saveVisibleElements($data, $file); + return $result; + }, $this->db); + } catch (\Throwable $e) { + if ($file !== null) { + try { + $this->fileMapper->invalidateCachedEntity($file); + $this->fileStatusService->invalidateCachedStatus($file); + } catch (\Throwable $cacheError) { + $this->logger->warning('Unable to invalidate request caches after rollback', [ + 'errorType' => get_debug_type($cacheError), + ]); + } + } + throw $e; + } $this->notifications->flushCommitted(); if ($result['becameReady']) { - $this->webhooks->requestReady($file); + $this->webhooks->requestReady($result['file']); } - return $file; + return $result['file']; } private function propagateSignersToChildren(FileEntity $envelope, array $data): void { @@ -220,11 +236,21 @@ public function saveEnvelope(array $data): array { $files[] = $fileEntity; } - if (!empty($data['signers'])) { - $this->atomic(function () use ($envelope, $data): void { - $this->sequentialSigningService->setFile($envelope); - $this->associateToSigners($data, $envelope); - $this->propagateSignersToChildren($envelope, $data); + $makeReady = ($data['status'] ?? FileStatus::DRAFT->value) === FileStatus::ABLE_TO_SIGN->value; + if (!empty($data['signers']) || $makeReady) { + $this->atomic(function () use ($envelope, $data, $makeReady): void { + if (!empty($data['signers'])) { + $this->sequentialSigningService->setFile($envelope); + $this->associateToSigners($data, $envelope); + } + if ($makeReady) { + $this->fileStatusService->updateFileStatusIfUpgrade($envelope, FileStatus::ABLE_TO_SIGN->value); + } + if (!empty($data['signers'])) { + $this->propagateSignersToChildren($envelope, $data); + } elseif ($makeReady) { + $this->fileStatusService->propagateStatusToChildren($envelope->getId(), $envelope->getStatus()); + } }, $this->db); $this->notifications->flushCommitted(); } @@ -233,7 +259,7 @@ public function saveEnvelope(array $data): array { throw $e; } - if ($envelope->getStatus() === FileStatus::ABLE_TO_SIGN->value) { + if ($makeReady && $envelope->getStatus() === FileStatus::ABLE_TO_SIGN->value) { $this->webhooks->requestReady($envelope); } return [ @@ -438,6 +464,9 @@ private function persistFile(array $data): array { $file->setStatus(FileStatus::ABLE_TO_SIGN->value); } $this->fileStatusService->markPolicySnapshotFrozen($file, $file->getStatus()); + if ($file->getStatus() === FileStatus::ABLE_TO_SIGN->value && empty($data['parentFileId'])) { + $this->fileStatusService->markReadyTransition($file); + } if (isset($data['parentFileId'])) { $file->setParentFileId($data['parentFileId']); diff --git a/lib/Service/SignatureRejection/SignatureRejectionNotifier.php b/lib/Service/SignatureRejection/SignatureRejectionNotifier.php index 473fc90103..1cc5beb3ca 100644 --- a/lib/Service/SignatureRejection/SignatureRejectionNotifier.php +++ b/lib/Service/SignatureRejection/SignatureRejectionNotifier.php @@ -41,20 +41,24 @@ private function dispatchRejectedEvent( ): void { try { $groupedIdentifyMethods = $this->identifyMethodService->getIdentifyMethodsFromSignRequestId($signRequest->getId()); - foreach ($groupedIdentifyMethods as $identifyMethods) { - foreach ($identifyMethods as $identifyMethod) { - $this->eventDispatcher->dispatchTyped(new SignatureRejectedEvent( - $signRequest, - $libreSignFile, - $identifyMethod, - $workflowCanceled, - )); - } - } } catch (\Exception $e) { $this->logger->error('Error dispatching SignatureRejectedEvent', [ 'errorType' => get_debug_type($e), ]); + return; + } + + foreach ($groupedIdentifyMethods as $identifyMethods) { + foreach ($identifyMethods as $identifyMethod) { + $event = new SignatureRejectedEvent($signRequest, $libreSignFile, $identifyMethod, $workflowCanceled); + try { + $this->eventDispatcher->dispatchTyped($event); + } catch (\Throwable $e) { + $this->logger->error('Error dispatching SignatureRejectedEvent', [ + 'errorType' => get_debug_type($e), + ]); + } + } } } } diff --git a/lib/Service/SignatureRejection/SignatureRejectionPersistence.php b/lib/Service/SignatureRejection/SignatureRejectionPersistence.php index 42812adfa0..4f5c7e110d 100644 --- a/lib/Service/SignatureRejection/SignatureRejectionPersistence.php +++ b/lib/Service/SignatureRejection/SignatureRejectionPersistence.php @@ -69,6 +69,8 @@ public function commit( $this->rollBackRejection($libreSignFile, $signRequests, $previousSignerStatuses, $previousFileStatus); $this->logger->error('Failed to register the signature rejection', [ 'errorType' => get_debug_type($e), + 'errorFile' => $e->getFile(), + 'errorLine' => $e->getLine(), 'signRequestId' => $signRequest->getId(), ]); diff --git a/tests/php/Unit/Controller/SignFileControllerTest.php b/tests/php/Unit/Controller/SignFileControllerTest.php index 2a52a51157..09880f5e36 100644 --- a/tests/php/Unit/Controller/SignFileControllerTest.php +++ b/tests/php/Unit/Controller/SignFileControllerTest.php @@ -258,6 +258,8 @@ public function testRejectPublicApiDoesNotExposeUnexpectedServerError(): void { 'Unable to process signature rejection', $this->callback(static fn (array $context): bool => ($context['errorType'] ?? null) === \TypeError::class + && ($context['errorFile'] ?? null) === __FILE__ + && is_int($context['errorLine'] ?? null) && !str_contains(json_encode($context), '/private/not-for-client') ), ); diff --git a/tests/php/Unit/Db/FileMapperCacheTest.php b/tests/php/Unit/Db/FileMapperCacheTest.php new file mode 100644 index 0000000000..f258552749 --- /dev/null +++ b/tests/php/Unit/Db/FileMapperCacheTest.php @@ -0,0 +1,50 @@ +createMock(ICache::class); + $removed = []; + $cache->method('remove')->willReturnCallback( + static function (string $key) use (&$removed): bool { + $removed[] = $key; + return true; + }, + ); + $factory = $this->createMock(ICacheFactory::class); + $factory->method('isAvailable')->willReturn(true); + $factory->method('createDistributed')->willReturn($cache); + $mapper = new FileMapper( + $this->createMock(IDBConnection::class), + $this->createMock(IL10N::class), + $factory, + ); + $file = new File(); + $file->setId(42); + $file->setUuid('rolled-back-uuid'); + $file->setNodeId(77); + + $mapper->invalidateCachedEntity($file); + + $this->assertSame([ + 'libresign_file:id:42', + 'libresign_file:node_id:77', + 'libresign_file:uuid:rolled-back-uuid', + ], $removed); + } +} diff --git a/tests/php/Unit/Events/NativeWebhookEventsTest.php b/tests/php/Unit/Events/NativeWebhookEventsTest.php index 1998f504c2..2baf3e608a 100644 --- a/tests/php/Unit/Events/NativeWebhookEventsTest.php +++ b/tests/php/Unit/Events/NativeWebhookEventsTest.php @@ -63,6 +63,22 @@ public function testReadyRequiresRealRootTransition(FileStatus $previous, FileSt ], $event->getWebhookSerializable()); } + public function testTwoReadyTransitionsOfSameRequestHaveDistinctStableEventIds(): void { + $file = self::file('same-request'); + $file->setStatus(FileStatus::ABLE_TO_SIGN->value); + $file->setMetadata(['ready_event_id' => 'transition-one']); + $first = SigningRequestReadyEvent::fromTransition($file, FileStatus::DRAFT->value); + $this->assertNotNull($first); + $this->assertSame($first->getWebhookSerializable(), SigningRequestReadyEvent::fromTransition($file, FileStatus::DRAFT->value)->getWebhookSerializable()); + + $file->setStatus(FileStatus::DRAFT->value); + $file->setStatus(FileStatus::ABLE_TO_SIGN->value); + $file->setMetadata(['ready_event_id' => 'transition-two']); + $second = SigningRequestReadyEvent::fromTransition($file, FileStatus::DRAFT->value); + $this->assertNotNull($second); + $this->assertNotSame($first->getWebhookSerializable()['eventId'], $second->getWebhookSerializable()['eventId']); + } + /** @return array */ public static function canceledTransitions(): array { return [ diff --git a/tests/php/Unit/Service/FileStatusServiceTest.php b/tests/php/Unit/Service/FileStatusServiceTest.php index c0c39159a6..451018bf48 100644 --- a/tests/php/Unit/Service/FileStatusServiceTest.php +++ b/tests/php/Unit/Service/FileStatusServiceTest.php @@ -60,6 +60,44 @@ public function testStatusPersistenceDoesNotDispatchEvents(): void { $this->assertSame(FileStatus::ABLE_TO_SIGN->value, $file->getStatus()); } + public function testRepeatedReadyTransitionsReceiveUniquePersistedIdentifiers(): void { + $file = new FileEntity(); + $file->setId(11); + $file->setUuid('repeat-ready'); + $file->setStatus(FileStatus::DRAFT->value); + $this->service->updateFileStatusIfUpgrade($file, FileStatus::ABLE_TO_SIGN->value); + $first = $file->getMetadata()['ready_event_id'] ?? null; + $this->assertMatchesRegularExpression('/^[a-f0-9]{32}$/', $first); + + $this->service->updateFileStatusIfUpgrade($file, FileStatus::ABLE_TO_SIGN->value); + $this->assertSame($first, $file->getMetadata()['ready_event_id']); + + $file->setStatus(FileStatus::DRAFT->value); + $this->service->updateFileStatusIfUpgrade($file, FileStatus::ABLE_TO_SIGN->value); + $this->assertNotSame($first, $file->getMetadata()['ready_event_id']); + } + + public function testChildUpgradeMarksTheEnvelopeReadyTransitionOnly(): void { + $envelope = new FileEntity(); + $envelope->setId(45); + $envelope->setUuid('envelope-ready'); + $envelope->setNodeType('envelope'); + $envelope->setStatus(FileStatus::DRAFT->value); + $child = new FileEntity(); + $child->setId(46); + $child->setUuid('child-ready'); + $child->setParentFileId(45); + $child->setStatus(FileStatus::DRAFT->value); + $this->fileMapper->method('getById')->with(45)->willReturn($envelope); + $this->fileMapper->method('getChildrenFiles')->with(45)->willReturn([$child]); + + $this->service->updateFileStatusIfUpgrade($child, FileStatus::ABLE_TO_SIGN->value); + + $this->assertSame(FileStatus::ABLE_TO_SIGN->value, $envelope->getStatus()); + $this->assertMatchesRegularExpression('/^[a-f0-9]{32}$/', $envelope->getMetadata()['ready_event_id']); + $this->assertArrayNotHasKey('ready_event_id', $child->getMetadata() ?? []); + } + #[DataProvider('dataFileStatusUpgrade')] public function testUpdateFileStatusIfUpgrade(int $currentStatus, int $newStatus, bool $shouldUpdate): void { $file = new FileEntity(); diff --git a/tests/php/Unit/Service/RequestSignatureServiceTest.php b/tests/php/Unit/Service/RequestSignatureServiceTest.php index be289f0b48..22cb6b879e 100644 --- a/tests/php/Unit/Service/RequestSignatureServiceTest.php +++ b/tests/php/Unit/Service/RequestSignatureServiceTest.php @@ -355,6 +355,67 @@ public function testReadyRequestEventIsPublishedOnlyAfterSignerTransactionCommit ])); } + public function testReadyStatusUpdateSharesTheSignerTransaction(): void { + $file = new \OCA\Libresign\Db\File(); + $file->setUuid('transaction-uuid'); + $file->setStatus(\OCA\Libresign\Enum\FileStatus::DRAFT->value); + $this->fileMapper->method('getByUuid')->willReturn($file); + $inTransaction = false; + $this->db->expects($this->once())->method('beginTransaction')->willReturnCallback( + static function () use (&$inTransaction): void { + $inTransaction = true; + }, + ); + $this->fileStatusService->method('updateFileStatusIfUpgrade')->willReturnCallback( + function ($file, int $newStatus) use (&$inTransaction) { + $this->assertTrue($inTransaction, 'Ready status must be part of the signer transaction'); + $file->setStatus($newStatus); + return $file; + }, + ); + $this->db->method('commit')->willReturnCallback( + static function () use (&$inTransaction): void { + $inTransaction = false; + }, + ); + + $this->getService()->save([ + 'uuid' => 'transaction-uuid', + 'status' => \OCA\Libresign\Enum\FileStatus::ABLE_TO_SIGN->value, + ]); + $this->assertFalse($inTransaction); + } + + public function testReadyRequestNewInsertIsPublishedAfterCommit(): void { + $node = $this->createMock(\OCP\Files\File::class); + $node->method('getId')->willReturn(501); + $node->method('getExtension')->willReturn(''); + $node->method('getName')->willReturn('contract.pdf'); + $this->fileService->method('getNodeFromData')->willReturn($node); + $this->fileMapper->method('insert')->willReturnArgument(0); + $this->user->method('getUID')->willReturn('tester'); + $committed = false; + $this->db->expects($this->once())->method('commit')->willReturnCallback( + static function () use (&$committed): void { + $committed = true; + }, + ); + $this->fileStatusService->expects($this->once())->method('markReadyTransition'); + $this->webhooks->expects($this->once())->method('requestReady')->with( + $this->callback(static function ($file) use (&$committed): bool { + return $committed + && $file->getStatus() === \OCA\Libresign\Enum\FileStatus::ABLE_TO_SIGN->value + && $file->getUuid() !== ''; + }), + ); + + $this->getService()->save([ + 'name' => 'contract', + 'userManager' => $this->user, + 'status' => \OCA\Libresign\Enum\FileStatus::ABLE_TO_SIGN->value, + ]); + } + public function testReadyRequestEventIsNotPublishedWhenSignerPersistenceFails(): void { $file = new \OCA\Libresign\Db\File(); $file->setUuid('ready-uuid'); @@ -379,6 +440,116 @@ public function testReadyRequestEventIsNotPublishedWhenSignerPersistenceFails(): ]); } + public function testNewEnvelopeReadyRequestPublishesAfterCommit(): void { + $service = $this->getService(['saveFile']); + $envelope = new \OCA\Libresign\Db\File(); + $envelope->setId(51); + $envelope->setUuid('envelope-ready'); + $envelope->setNodeType('envelope'); + $envelope->setStatus(\OCA\Libresign\Enum\FileStatus::DRAFT->value); + $folder = $this->createMock(Folder::class); + $folder->method('getId')->willReturn(204); + $node = $this->createMock(\OCP\Files\Node::class); + $node->method('getName')->willReturn('contract.pdf'); + $node->method('getId')->willReturn(205); + $this->user->method('getUID')->willReturn('synthetic-requester'); + $this->envelopeService->method('createEnvelope')->willReturn($envelope); + $this->envelopeService->method('getEnvelopeFolder')->willReturn($folder); + $this->envelopeService->method('addFileToEnvelope')->willReturn(new \OCA\Libresign\Db\File()); + $this->fileService->method('getNodeFromData')->willReturn($node); + $this->envelopeFileRelocator->method('ensureFileInEnvelopeFolder')->willReturn($node); + $service->method('saveFile')->willReturn(new \OCA\Libresign\Db\File()); + $this->fileStatusService->expects($this->once())->method('updateFileStatusIfUpgrade') + ->with($envelope, \OCA\Libresign\Enum\FileStatus::ABLE_TO_SIGN->value) + ->willReturnCallback(static function ($file, int $status) { + $file->setStatus($status); + return $file; + }); + $this->fileStatusService->expects($this->once())->method('propagateStatusToChildren') + ->with(51, \OCA\Libresign\Enum\FileStatus::ABLE_TO_SIGN->value); + $committed = false; + $this->db->expects($this->once())->method('commit')->willReturnCallback( + static function () use (&$committed): void { + $committed = true; + }, + ); + $this->webhooks->expects($this->once())->method('requestReady')->with( + $this->callback(static function ($file) use (&$committed, $envelope): bool { + return $committed + && $file === $envelope + && $file->getStatus() === \OCA\Libresign\Enum\FileStatus::ABLE_TO_SIGN->value; + }), + ); + + $result = $service->saveEnvelope([ + 'files' => [['name' => 'a.pdf', 'file' => ['path' => '/a.pdf']], + ['name' => 'b.pdf', 'file' => ['path' => '/b.pdf']]], + 'name' => 'Signed package', + 'userManager' => $this->user, + 'settings' => [], + 'signers' => [], + 'status' => \OCA\Libresign\Enum\FileStatus::ABLE_TO_SIGN->value, + ]); + + $this->assertSame($envelope, $result['envelope']); + $this->assertSame(\OCA\Libresign\Enum\FileStatus::ABLE_TO_SIGN->value, $envelope->getStatus()); + } + + public function testFailedSignerWriteCanBeRetriedWithoutLosingReadyEvent(): void { + $storedStatus = \OCA\Libresign\Enum\FileStatus::DRAFT->value; + $this->fileMapper->method('getByUuid')->willReturnCallback( + static function () use (&$storedStatus) { + $file = new \OCA\Libresign\Db\File(); + $file->setId(42); + $file->setUuid('retry-ready'); + $file->setStatus($storedStatus); + return $file; + }, + ); + $this->fileStatusService->method('updateFileStatusIfUpgrade')->willReturnCallback( + static function ($file, int $newStatus) use (&$storedStatus) { + $file->setStatus($newStatus); + $storedStatus = $newStatus; + return $file; + }, + ); + $this->db->expects($this->once())->method('rollBack')->willReturnCallback( + static function () use (&$storedStatus): void { + $storedStatus = \OCA\Libresign\Enum\FileStatus::DRAFT->value; + }, + ); + $this->fileMapper->expects($this->once())->method('invalidateCachedEntity'); + $this->fileStatusService->expects($this->once())->method('invalidateCachedStatus'); + $calls = 0; + $this->signerValidator->method('normalizeRequestSigners')->willReturnCallback( + static function () use (&$calls): array { + if (++$calls === 1) { + throw new \RuntimeException('synthetic signer write failed'); + } + return []; + }, + ); + $this->db->expects($this->once())->method('commit'); + $this->webhooks->expects($this->once())->method('requestReady'); + $data = [ + 'uuid' => 'retry-ready', + 'status' => \OCA\Libresign\Enum\FileStatus::ABLE_TO_SIGN->value, + 'signers' => [['identifyMethods' => []]], + ]; + + try { + $this->getService()->save($data); + $this->fail('The first attempt must fail before commit'); + } catch (\RuntimeException $e) { + $this->assertSame('synthetic signer write failed', $e->getMessage()); + $this->assertSame(\OCA\Libresign\Enum\FileStatus::DRAFT->value, $storedStatus); + } + + $this->getService()->save($data); + $this->assertSame(\OCA\Libresign\Enum\FileStatus::ABLE_TO_SIGN->value, $storedStatus); + $this->assertSame(3, $calls); + } + public function testSaveFilesUsesSaveForSingleFile(): void { $service = $this->getService(['save']); diff --git a/tests/php/Unit/Service/SignatureRejection/SignatureRejectionNotifierTest.php b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionNotifierTest.php index b46c083e70..cf4aebfd7a 100644 --- a/tests/php/Unit/Service/SignatureRejection/SignatureRejectionNotifierTest.php +++ b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionNotifierTest.php @@ -80,6 +80,49 @@ public function testListenerFailureDoesNotPreventPostCommitSignerNotification(): $this->notifier->afterCommit($this->file(), $this->signer(), new CommittedRejection(1, [$next])); } + public function testLegacyListenerTypeErrorDoesNotInterruptCommittedRejection(): void { + $this->identification->method('getIdentifyMethodsFromSignRequestId')->willReturn([ + 'account' => [$this->createMock(IIdentifyMethod::class)], + ]); + $this->events->method('dispatchTyped')->willThrowException(new \TypeError('private listener error')); + $this->logger->expects($this->once())->method('error')->with( + 'Error dispatching SignatureRejectedEvent', + ['errorType' => \TypeError::class], + ); + $next = $this->signer(id: 77); + $this->sequential->expects($this->once())->method('notifyActivatedSigners')->with([$next]); + + $this->notifier->afterCommit( + $this->file(), + $this->signer(), + new CommittedRejection(1, [$next]), + ); + } + + public function testFailureInOneLegacyMethodDoesNotBlockOtherMethods(): void { + $this->identification->method('getIdentifyMethodsFromSignRequestId')->willReturn([ + 'account' => [ + $this->createMock(IIdentifyMethod::class), + $this->createMock(IIdentifyMethod::class), + ], + ]); + $calls = 0; + $this->events->method('dispatchTyped')->willReturnCallback( + static function () use (&$calls): void { + if (++$calls === 1) { + throw new \TypeError('legacy listener error'); + } + }, + ); + $this->logger->expects($this->once())->method('error') + ->with('Error dispatching SignatureRejectedEvent', ['errorType' => \TypeError::class]); + $this->sequential->expects($this->once())->method('notifyActivatedSigners')->with([]); + + $this->notifier->afterCommit($this->file(), $this->signer(), new CommittedRejection(1, [])); + + $this->assertSame(2, $calls); + } + public function testNotificationFailureAfterCommitRemainsVisible(): void { $this->identification->method('getIdentifyMethodsFromSignRequestId')->willReturn([]); $this->sequential->method('notifyActivatedSigners') diff --git a/tests/php/Unit/Service/SignatureRejection/SignatureRejectionPersistenceTest.php b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionPersistenceTest.php index 30fa590ccf..c2e17a5d8d 100644 --- a/tests/php/Unit/Service/SignatureRejection/SignatureRejectionPersistenceTest.php +++ b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionPersistenceTest.php @@ -32,6 +32,7 @@ final class SignatureRejectionPersistenceTest extends TestCase { private FileMapper&MockObject $files; private SignatureRejectionWorkflow&MockObject $workflow; private IDBConnection&MockObject $db; + private LoggerInterface&MockObject $logger; private SignatureRejectionPersistence $persistence; protected function setUp(): void { @@ -43,10 +44,10 @@ protected function setUp(): void { $clock->method('getDateTime')->willReturn(new \DateTime(self::REJECTED_AT)); $l10n = $this->createMock(IL10N::class); $l10n->method('t')->willReturnArgument(0); - $logger = $this->createMock(LoggerInterface::class); + $this->logger = $this->createMock(LoggerInterface::class); $this->persistence = new SignatureRejectionPersistence( $this->signRequests, $this->files, $this->workflow, - $this->db, $clock, $l10n, $logger, + $this->db, $clock, $l10n, $this->logger, ); } @@ -121,6 +122,15 @@ public function testFailedWriteRollsBackAndRestoresMutatedSigner(): void { $signer = $this->signer(); $this->workflow->method('collectSignRequestsToReject')->willReturn([$signer]); $this->signRequests->method('update')->willThrowException(new \RuntimeException('database error')); + $this->logger->expects($this->once())->method('error')->with( + 'Failed to register the signature rejection', + $this->callback(static fn (array $context): bool + => ($context['errorType'] ?? null) === \RuntimeException::class + && ($context['signRequestId'] ?? null) === $signer->getId() + && is_string($context['errorFile'] ?? null) + && is_int($context['errorLine'] ?? null) + && !array_key_exists('exception', $context)), + ); $this->db->expects($this->never())->method('commit'); $this->db->expects($this->once())->method('rollBack'); $this->expectException(LibresignException::class); diff --git a/tests/php/Unit/Service/SignatureRejection/SignatureRejectionWorkflowTest.php b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionWorkflowTest.php index 17e0c887e3..f5cbbc39ba 100644 --- a/tests/php/Unit/Service/SignatureRejection/SignatureRejectionWorkflowTest.php +++ b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionWorkflowTest.php @@ -87,6 +87,31 @@ public function testAlreadySignedEnvelopeSiblingPreservesItsSignature(): void { $this->assertSame(SignRequestStatus::SIGNED, $signed->getStatusEnum()); } + public function testDuplicateEnvelopeIdentityFailsBeforeAnyRejectionIsPersisted(): void { + $signer = $this->signer(); + $this->signRequests->method('getByEnvelopeChildrenAndIdentifyMethod')->willReturn([]); + $this->signRequests->method('getByIdentifyMethodAndFileId')->willThrowException( + new \OCP\AppFramework\Db\MultipleObjectsReturnedException('ambiguous signer identity'), + ); + $this->expectException(\OCP\AppFramework\Db\MultipleObjectsReturnedException::class); + + try { + $this->workflow->collectSignRequestsToReject($this->envelope(), $signer); + } finally { + $this->assertSame(SignRequestStatus::ABLE_TO_SIGN, $signer->getStatusEnum()); + } + } + + public function testInvalidEnvelopeIdentificationCannotSilentlySkipRelatedSignatures(): void { + $signer = $this->signer(); + $this->identification->method('getIdentifiedMethod')->willThrowException( + new \OCA\Libresign\Exception\LibresignException('Invalid identification method'), + ); + $this->expectException(\OCA\Libresign\Exception\LibresignException::class); + + $this->workflow->collectSignRequestsToReject($this->envelope(), $signer); + } + public function testContinuingWorkflowActivatesNextSignerAndResolvesDocumentStatus(): void { $document = $this->file(FileStatus::PARTIAL_SIGNED->value); $rejected = $this->signer(); From b77f330c83a8c3668bd90904d74ff82fa9e9bec0 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Wed, 11 Nov 2026 04:26:39 +0000 Subject: [PATCH 20/23] fix: keep ready transition metadata out of public responses Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- lib/Events/SigningRequestReadyEvent.php | 3 ++- lib/Service/File/FileListService.php | 15 ++++++++---- .../File/ValidationMetadataNormalizer.php | 2 +- lib/Service/FileStatusService.php | 3 ++- .../Unit/Service/File/FileListServiceTest.php | 22 +++++++++++++++++ .../Unit/Service/File/MetadataLoaderTest.php | 24 +++++++++++++++++++ .../File/ValidationMetadataNormalizerTest.php | 12 ++++++++++ 7 files changed, 74 insertions(+), 7 deletions(-) diff --git a/lib/Events/SigningRequestReadyEvent.php b/lib/Events/SigningRequestReadyEvent.php index 63d0113f64..1193223d9b 100644 --- a/lib/Events/SigningRequestReadyEvent.php +++ b/lib/Events/SigningRequestReadyEvent.php @@ -10,6 +10,7 @@ use OCA\Libresign\Db\File as FileEntity; use OCA\Libresign\Enum\FileStatus; +use OCA\Libresign\Service\FileStatusService; use OCP\EventDispatcher\Event; use OCP\EventDispatcher\IWebhookCompatibleEvent; @@ -33,7 +34,7 @@ public static function fromTransition(FileEntity $file, int $previousStatus): ?s return null; } - $transitionId = ($file->getMetadata() ?? [])['ready_event_id'] ?? null; + $transitionId = ($file->getMetadata() ?? [])[FileStatusService::READY_EVENT_ID_METADATA_KEY] ?? null; $eventId = 'libresign.workflow.ready.v1:' . $file->getUuid(); if (is_string($transitionId) && $transitionId !== '') { $eventId .= ':' . $transitionId; diff --git a/lib/Service/File/FileListService.php b/lib/Service/File/FileListService.php index b0e3e9827c..2394a3c7a0 100644 --- a/lib/Service/File/FileListService.php +++ b/lib/Service/File/FileListService.php @@ -262,7 +262,7 @@ private function formatSingleFileData( 'uuid' => $fileEntity->getUuid(), 'name' => $fileEntity->getName(), 'status' => $fileEntity->getStatus(), - 'metadata' => $fileEntity->getMetadata() ?? [], + 'metadata' => self::publicMetadata($fileEntity), 'docmdpLevel' => $fileEntity->getDocmdpLevel(), 'createdAt' => $fileEntity->getCreatedAt(), 'userId' => $fileEntity->getUserId(), @@ -353,7 +353,7 @@ private function formatSingleFileSummary( IUser $user, ?File $envelope = null, ): array { - $metadata = $fileEntity->getMetadata() ?? []; + $metadata = self::publicMetadata($fileEntity); $nodeType = $fileEntity->getNodeType(); $filesCount = $nodeType === 'envelope' ? max(0, (int)($metadata['filesCount'] ?? 0)) @@ -831,7 +831,7 @@ private function isCurrentUserSigner(array $identifyMethodsOfSigner, IUser $user * @psalm-suppress MoreSpecificReturnType */ public function formatFileWithChildren(File $mainEntity, array $childFiles, ?IUser $user = null): array { - $metadata = $mainEntity->getMetadata() ?? []; + $metadata = self::publicMetadata($mainEntity); $signRequestEntities = $this->signRequestMapper->getByFileId($mainEntity->getId()); $identifyMethods = $this->signRequestMapper->getIdentifyMethodsFromSigners($signRequestEntities); @@ -1094,7 +1094,7 @@ private function formatChildFilesResponse( return array_values(array_map(function (File $file) use ($signersByFileId, $identifyMethods, $user, $meSignRequestId) { $signers = $signersByFileId[$file->getId()] ?? []; - $metadata = $file->getMetadata() ?? []; + $metadata = self::publicMetadata($file); $size = $this->getFileSize($file); $rejectionViewer = $this->rejectionViewer($file, $signers, $identifyMethods, $user, $meSignRequestId); $hiddenRejection = $this->signatureRejectionVisibilityService->hasHiddenRejection($file, $signers, $rejectionViewer); @@ -1148,6 +1148,13 @@ private function formatChildFilesResponse( }, $files)); } + /** @return array */ + private static function publicMetadata(File $file): array { + $metadata = $file->getMetadata() ?? []; + unset($metadata[FileStatusService::READY_EVENT_ID_METADATA_KEY]); + return $metadata; + } + private function getFileSize(File $file): int { $nodeId = $file->getSignedNodeId() ?: $file->getNodeId(); if ($nodeId === null || $file->getUserId() === '') { diff --git a/lib/Service/File/ValidationMetadataNormalizer.php b/lib/Service/File/ValidationMetadataNormalizer.php index 46cadc3725..e482906057 100644 --- a/lib/Service/File/ValidationMetadataNormalizer.php +++ b/lib/Service/File/ValidationMetadataNormalizer.php @@ -28,7 +28,7 @@ final class ValidationMetadataNormalizer { public static function normalize(array $metadata, string $fileName, int $totalPages): array { $normalized = $metadata; // Internal lifecycle marker, not part of the validation metadata. - unset($normalized[FileStatusService::POLICY_SNAPSHOT_FROZEN_AT]); + unset($normalized[FileStatusService::POLICY_SNAPSHOT_FROZEN_AT], $normalized[FileStatusService::READY_EVENT_ID_METADATA_KEY]); $normalized['p'] = self::normalizePageCount($totalPages); $normalized['extension'] = self::normalizeExtension($normalized, $fileName); diff --git a/lib/Service/FileStatusService.php b/lib/Service/FileStatusService.php index 7408295db8..a8802abfb3 100644 --- a/lib/Service/FileStatusService.php +++ b/lib/Service/FileStatusService.php @@ -18,6 +18,7 @@ class FileStatusService { public const POLICY_SNAPSHOT_FROZEN_AT = 'policy_snapshot_frozen_at'; + public const READY_EVENT_ID_METADATA_KEY = 'ready_event_id'; public function __construct( private FileMapper $fileMapper, @@ -214,7 +215,7 @@ private static function hasFrozenPolicySnapshot(FileEntity $file): bool { public function markReadyTransition(FileEntity $file): void { $metadata = $file->getMetadata() ?? []; - $metadata['ready_event_id'] = bin2hex(random_bytes(16)); + $metadata[self::READY_EVENT_ID_METADATA_KEY] = bin2hex(random_bytes(16)); $file->setMetadata($metadata); } diff --git a/tests/php/Unit/Service/File/FileListServiceTest.php b/tests/php/Unit/Service/File/FileListServiceTest.php index 2e6bbc934c..6c7b608f7e 100644 --- a/tests/php/Unit/Service/File/FileListServiceTest.php +++ b/tests/php/Unit/Service/File/FileListServiceTest.php @@ -83,6 +83,28 @@ private function getService(): FileListService { ); } + public function testPublicFileMetadataExcludesInternalReadyTransitionId(): void { + $file = self::createFileEntity(1, 'file', 'contract.pdf', [ + 'ready_event_id' => 'private-transition-identifier', + 'filesCount' => 1, + 'purpose' => 'signature', + ]); + $this->signRequestMapper->method('getByMultipleFileId')->willReturn([]); + $this->signRequestMapper->method('getByFileId')->willReturn([]); + $this->signRequestMapper->method('getIdentifyMethodsFromSigners')->willReturn([]); + $this->signRequestMapper->method('getVisibleElementsFromSigners')->willReturn([]); + + $service = $this->getService(); + $summary = $service->formatSingleFile($this->user, $file); + $details = $service->formatFileWithChildren($file, [], $this->user); + + foreach ([$summary, $details] as $response) { + $this->assertArrayNotHasKey('ready_event_id', $response['metadata']); + $this->assertSame('signature', $response['metadata']['purpose']); + } + $this->assertSame('private-transition-identifier', $file->getMetadata()['ready_event_id']); + } + #[DataProvider('provideNodeTypeScenarios')] public function testFormatSingleFileStructureByNodeType( string $nodeType, diff --git a/tests/php/Unit/Service/File/MetadataLoaderTest.php b/tests/php/Unit/Service/File/MetadataLoaderTest.php index cfcb669bbe..2c88491146 100644 --- a/tests/php/Unit/Service/File/MetadataLoaderTest.php +++ b/tests/php/Unit/Service/File/MetadataLoaderTest.php @@ -81,6 +81,30 @@ public function testLoadMetadataWithFileSize(): void { $this->assertEquals('application/pdf', $fileData->mime); } + public function testValidationMetadataHidesInternalReadyIdWithoutRemovingStoredValue(): void { + $file = new File(); + $file->setId(1); + $file->setName('agreement.pdf'); + $file->setUserId('synthetic-user'); + $file->setSignedNodeId(123); + $file->setMetadata([ + 'p' => 1, + 'ready_event_id' => 'internal-transition', + 'status_changed_at' => '2026-11-11T00:00:00+00:00', + ]); + $node = $this->createMock(\OCP\Files\File::class); + $node->method('getSize')->willReturn(1024); + $node->method('getMimeType')->willReturn('application/pdf'); + $this->folderService->method('getReadableNodeById')->with('synthetic-user', 123)->willReturn($node); + + $response = new stdClass(); + $this->getService()->loadMetadata($file, $response); + + $this->assertArrayNotHasKey('ready_event_id', $response->metadata); + $this->assertSame('2026-11-11T00:00:00+00:00', $response->metadata['status_changed_at']); + $this->assertSame('internal-transition', $file->getMetadata()['ready_event_id']); + } + public function testLoadMetadataWithPages(): void { $file = new File(); $file->setId(1); diff --git a/tests/php/Unit/Service/File/ValidationMetadataNormalizerTest.php b/tests/php/Unit/Service/File/ValidationMetadataNormalizerTest.php index 7210e98dba..6a5dbdfe2f 100644 --- a/tests/php/Unit/Service/File/ValidationMetadataNormalizerTest.php +++ b/tests/php/Unit/Service/File/ValidationMetadataNormalizerTest.php @@ -107,6 +107,18 @@ public static function provideNormalizationScenarios(): array { ], 'missingKeys' => ['d'], ], + 'excludes the internal ready transition ID from public validation metadata' => [ + 'metadata' => [ + 'ready_event_id' => 'private-transition-identifier', + 'status_changed_at' => '2026-11-11T00:00:00+00:00', + ], + 'fileName' => 'contract.pdf', + 'totalPages' => 1, + 'expectedSubset' => [ + 'status_changed_at' => '2026-11-11T00:00:00+00:00', + ], + 'missingKeys' => ['ready_event_id'], + ], 'drops the policy snapshot freeze marker' => [ 'metadata' => [ 'status_changed_at' => '2026-01-01T00:00:00+00:00', From 449b65bf355827ac4ff33d05c3cfbc08c3d55830 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:08:21 +0000 Subject: [PATCH 21/23] fix: clean up failed request storage and improve rejection diagnostics Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- lib/Service/RequestSignatureService.php | 26 +++++ .../SignatureRejectionNotifier.php | 4 + .../Service/RequestSignatureServiceTest.php | 109 ++++++++++++++++++ .../SignatureRejectionNotifierTest.php | 41 ++++++- 4 files changed, 175 insertions(+), 5 deletions(-) diff --git a/lib/Service/RequestSignatureService.php b/lib/Service/RequestSignatureService.php index ee21bf18b5..0ac7b5a87c 100644 --- a/lib/Service/RequestSignatureService.php +++ b/lib/Service/RequestSignatureService.php @@ -142,6 +142,20 @@ public function saveFiles(array $data): array { public function save(array $data): FileEntity { $file = null; + $createdNode = null; + + // Creating a storage node cannot be rolled back by the database transaction. + // Resolve new content first, but leave already supplied node references alone. + if (empty($data['uuid']) + && !isset($data['file']['fileNode']) + && empty($data['file']['nodeId']) + && !isset($data['file']['path']) + && !isset($data['file']['fileId'])) { + $createdNode = $this->fileService->getNodeFromData($data); + $data['file'] = ['fileNode' => $createdNode]; + unset($data['uploadedFile']); + } + try { $result = $this->atomic(function () use ($data, &$file): array { $result = $this->persistFile($data); @@ -154,6 +168,18 @@ public function save(array $data): FileEntity { return $result; }, $this->db); } catch (\Throwable $e) { + if ($createdNode !== null) { + try { + $createdNode->delete(); + } catch (\Throwable $deleteError) { + $this->logger->error('Unable to remove newly created request node after rollback', [ + 'nodeId' => $createdNode->getId(), + 'errorType' => get_debug_type($deleteError), + 'errorFile' => $deleteError->getFile(), + 'errorLine' => $deleteError->getLine(), + ]); + } + } if ($file !== null) { try { $this->fileMapper->invalidateCachedEntity($file); diff --git a/lib/Service/SignatureRejection/SignatureRejectionNotifier.php b/lib/Service/SignatureRejection/SignatureRejectionNotifier.php index 1cc5beb3ca..062a036349 100644 --- a/lib/Service/SignatureRejection/SignatureRejectionNotifier.php +++ b/lib/Service/SignatureRejection/SignatureRejectionNotifier.php @@ -44,6 +44,8 @@ private function dispatchRejectedEvent( } catch (\Exception $e) { $this->logger->error('Error dispatching SignatureRejectedEvent', [ 'errorType' => get_debug_type($e), + 'errorFile' => $e->getFile(), + 'errorLine' => $e->getLine(), ]); return; } @@ -56,6 +58,8 @@ private function dispatchRejectedEvent( } catch (\Throwable $e) { $this->logger->error('Error dispatching SignatureRejectedEvent', [ 'errorType' => get_debug_type($e), + 'errorFile' => $e->getFile(), + 'errorLine' => $e->getLine(), ]); } } diff --git a/tests/php/Unit/Service/RequestSignatureServiceTest.php b/tests/php/Unit/Service/RequestSignatureServiceTest.php index 22cb6b879e..83b9eb5d13 100644 --- a/tests/php/Unit/Service/RequestSignatureServiceTest.php +++ b/tests/php/Unit/Service/RequestSignatureServiceTest.php @@ -327,6 +327,115 @@ public function testANewRequestCreatedReadyToSignStartsWithItsPolicySnapshotFroz $this->assertSame(['freeze:' . \OCA\Libresign\Enum\FileStatus::ABLE_TO_SIGN->value, 'insert'], $calls); } + + public function testNewStorageNodeIsCreatedBeforeTransactionAndDeletedAfterSignerRollback(): void { + $node = $this->createMock(\OCP\Files\File::class); + $node->method('getId')->willReturn(621); + $node->method('getExtension')->willReturn(''); + $node->method('getName')->willReturn('new-contract.pdf'); + + $inTransaction = false; + $this->db->expects($this->once())->method('beginTransaction')->willReturnCallback( + static function () use (&$inTransaction): void { + $inTransaction = true; + }, + ); + $this->fileService->expects($this->once())->method('getNodeFromData') + ->with($this->callback(function (array $data) use (&$inTransaction): bool { + $this->assertFalse($inTransaction, 'Storage creation must happen outside the database transaction'); + return ($data['file']['url'] ?? null) === 'https://example.invalid/contract.pdf'; + })) + ->willReturn($node); + $this->fileMapper->expects($this->once())->method('insert')->willReturnArgument(0); + $this->filePolicyApplier->expects($this->once())->method('applyAll') + ->with($this->anything(), $this->callback( + static fn (array $data): bool => ($data['file']['fileNode'] ?? null) === $node + && !isset($data['file']['url']) + )); + $this->signerValidator->method('normalizeRequestSigners') + ->willThrowException(new \RuntimeException('synthetic signer failure')); + $this->db->expects($this->once())->method('rollBack')->willReturnCallback( + static function () use (&$inTransaction): void { + $inTransaction = false; + }, + ); + $node->expects($this->once())->method('delete'); + $this->webhooks->expects($this->never())->method('requestReady'); + + try { + $this->getService()->save([ + 'name' => 'new-contract', + 'userManager' => $this->user, + 'status' => \OCA\Libresign\Enum\FileStatus::ABLE_TO_SIGN->value, + 'file' => ['url' => 'https://example.invalid/contract.pdf'], + 'signers' => [['identifyMethods' => []]], + ]); + $this->fail('Signer persistence failure must abort the request'); + } catch (\RuntimeException $e) { + $this->assertSame('synthetic signer failure', $e->getMessage()); + } + $this->assertFalse($inTransaction); + } + + public function testExistingStorageNodeIsNotDeletedAfterSignerRollback(): void { + $node = $this->createMock(\OCP\Files\File::class); + $node->method('getId')->willReturn(622); + $node->method('getExtension')->willReturn(''); + $node->method('getName')->willReturn('existing-contract.pdf'); + $this->fileService->expects($this->once())->method('getNodeFromData')->willReturn($node); + $this->fileMapper->expects($this->once())->method('insert')->willReturnArgument(0); + $this->signerValidator->method('normalizeRequestSigners') + ->willThrowException(new \RuntimeException('synthetic signer failure')); + $this->db->expects($this->once())->method('rollBack'); + $node->expects($this->never())->method('delete'); + + $this->expectException(\RuntimeException::class); + $this->getService()->save([ + 'name' => 'existing-contract', + 'userManager' => $this->user, + 'file' => ['path' => '/documents/existing-contract.pdf'], + 'signers' => [['identifyMethods' => []]], + ]); + } + + public function testNewStorageNodeRemainsAvailableAfterCommit(): void { + $node = $this->createMock(\OCP\Files\File::class); + $node->method('getId')->willReturn(623); + $node->method('getExtension')->willReturn(''); + $node->method('getName')->willReturn('new-contract.pdf'); + $this->fileService->expects($this->once())->method('getNodeFromData')->willReturn($node); + $this->fileMapper->expects($this->once())->method('insert')->willReturnArgument(0); + $this->db->expects($this->once())->method('commit'); + $node->expects($this->never())->method('delete'); + + $result = $this->getService()->save([ + 'name' => 'new-contract', + 'userManager' => $this->user, + 'file' => ['url' => 'https://example.invalid/contract.pdf'], + 'status' => \OCA\Libresign\Enum\FileStatus::DRAFT->value, + ]); + + $this->assertSame(623, $result->getNodeId()); + } + + public function testCreatedNodeIsRemovedIfFilePersistenceFailsBeforeEntityAssignment(): void { + $node = $this->createMock(\OCP\Files\File::class); + $node->method('getId')->willReturn(624); + $node->method('getExtension')->willReturn(''); + $node->method('getName')->willReturn('new-contract.pdf'); + $this->fileService->method('getNodeFromData')->willReturn($node); + $this->filePolicyApplier->method('applyAll')->willThrowException(new \RuntimeException('policy persistence failed')); + $this->db->expects($this->once())->method('rollBack'); + $node->expects($this->once())->method('delete'); + + $this->expectException(\RuntimeException::class); + $this->getService()->save([ + 'name' => 'new-contract', + 'userManager' => $this->user, + 'file' => ['url' => 'https://example.invalid/contract.pdf'], + ]); + } + public function testReadyRequestEventIsPublishedOnlyAfterSignerTransactionCommits(): void { $file = new \OCA\Libresign\Db\File(); $file->setUuid('ready-uuid'); diff --git a/tests/php/Unit/Service/SignatureRejection/SignatureRejectionNotifierTest.php b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionNotifierTest.php index cf4aebfd7a..30dfcd6828 100644 --- a/tests/php/Unit/Service/SignatureRejection/SignatureRejectionNotifierTest.php +++ b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionNotifierTest.php @@ -71,9 +71,14 @@ public function testListenerFailureDoesNotPreventPostCommitSignerNotification(): $this->identification->method('getIdentifyMethodsFromSignRequestId')->willReturn([ 'account' => [$this->createMock(IIdentifyMethod::class)], ]); - $this->events->method('dispatchTyped')->willThrowException(new \RuntimeException('listener failed')); + $failure = new \RuntimeException('listener failed'); + $this->events->method('dispatchTyped')->willThrowException($failure); $this->logger->expects($this->once())->method('error') - ->with('Error dispatching SignatureRejectedEvent', ['errorType' => \RuntimeException::class]); + ->with('Error dispatching SignatureRejectedEvent', [ + 'errorType' => \RuntimeException::class, + 'errorFile' => $failure->getFile(), + 'errorLine' => $failure->getLine(), + ]); $next = $this->signer(id: 77); $this->sequential->expects($this->once())->method('notifyActivatedSigners')->with([$next]); @@ -84,10 +89,15 @@ public function testLegacyListenerTypeErrorDoesNotInterruptCommittedRejection(): $this->identification->method('getIdentifyMethodsFromSignRequestId')->willReturn([ 'account' => [$this->createMock(IIdentifyMethod::class)], ]); - $this->events->method('dispatchTyped')->willThrowException(new \TypeError('private listener error')); + $failure = new \TypeError('private listener error'); + $this->events->method('dispatchTyped')->willThrowException($failure); $this->logger->expects($this->once())->method('error')->with( 'Error dispatching SignatureRejectedEvent', - ['errorType' => \TypeError::class], + [ + 'errorType' => \TypeError::class, + 'errorFile' => $failure->getFile(), + 'errorLine' => $failure->getLine(), + ], ); $next = $this->signer(id: 77); $this->sequential->expects($this->once())->method('notifyActivatedSigners')->with([$next]); @@ -115,7 +125,10 @@ static function () use (&$calls): void { }, ); $this->logger->expects($this->once())->method('error') - ->with('Error dispatching SignatureRejectedEvent', ['errorType' => \TypeError::class]); + ->with('Error dispatching SignatureRejectedEvent', $this->callback( + static fn (array $context): bool => $context['errorType'] === \TypeError::class + && $context['errorFile'] !== '' && $context['errorLine'] > 0 + )); $this->sequential->expects($this->once())->method('notifyActivatedSigners')->with([]); $this->notifier->afterCommit($this->file(), $this->signer(), new CommittedRejection(1, [])); @@ -123,6 +136,24 @@ static function () use (&$calls): void { $this->assertSame(2, $calls); } + + public function testIdentificationLookupFailureLogsSourceWithoutExceptionMessage(): void { + $failure = new \RuntimeException('private identification details'); + $this->identification->method('getIdentifyMethodsFromSignRequestId')->willThrowException($failure); + $this->logger->expects($this->once())->method('error')->with( + 'Error dispatching SignatureRejectedEvent', + [ + 'errorType' => \RuntimeException::class, + 'errorFile' => $failure->getFile(), + 'errorLine' => $failure->getLine(), + ], + ); + $this->events->expects($this->never())->method('dispatchTyped'); + $this->sequential->expects($this->once())->method('notifyActivatedSigners')->with([]); + + $this->notifier->afterCommit($this->file(), $this->signer(), new CommittedRejection(1, [])); + } + public function testNotificationFailureAfterCommitRemainsVisible(): void { $this->identification->method('getIdentifyMethodsFromSignRequestId')->willReturn([]); $this->sequential->method('notifyActivatedSigners') From e58986df11f3e3554091596f3cc18725193b3f7c Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:33:43 +0000 Subject: [PATCH 22/23] test: align new request mocks with file lookup contract Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- lib/Service/RequestSignatureService.php | 8 ++++---- .../Service/RequestSignatureServiceTest.php | 17 ++++++++++++++++- .../SignatureRejectionNotifierTest.php | 1 - 3 files changed, 20 insertions(+), 6 deletions(-) diff --git a/lib/Service/RequestSignatureService.php b/lib/Service/RequestSignatureService.php index 0ac7b5a87c..1379a77638 100644 --- a/lib/Service/RequestSignatureService.php +++ b/lib/Service/RequestSignatureService.php @@ -157,8 +157,8 @@ public function save(array $data): FileEntity { } try { - $result = $this->atomic(function () use ($data, &$file): array { - $result = $this->persistFile($data); + $result = $this->atomic(function () use ($data, &$file, $createdNode): array { + $result = $this->persistFile($data, $createdNode); $file = $result['file']; $data['status'] ??= $file->getStatus(); $this->sequentialSigningService->setFile($file); @@ -428,7 +428,7 @@ public function saveFile(array $data): FileEntity { } /** @return array{file: FileEntity, becameReady: bool} */ - private function persistFile(array $data): array { + private function persistFile(array $data, ?Node $createdNode = null): array { if (!empty($data['uuid'])) { $file = $this->fileMapper->getByUuid($data['uuid']); $this->filePolicyApplier->syncCoreFlowPolicies($file, $data); @@ -459,7 +459,7 @@ private function persistFile(array $data): array { } } - $node = $this->fileService->getNodeFromData($data); + $node = $createdNode ?? $this->fileService->getNodeFromData($data); $file = new FileEntity(); $file->setNodeId($node->getId()); diff --git a/tests/php/Unit/Service/RequestSignatureServiceTest.php b/tests/php/Unit/Service/RequestSignatureServiceTest.php index 83b9eb5d13..06969d38d6 100644 --- a/tests/php/Unit/Service/RequestSignatureServiceTest.php +++ b/tests/php/Unit/Service/RequestSignatureServiceTest.php @@ -327,12 +327,15 @@ public function testANewRequestCreatedReadyToSignStartsWithItsPolicySnapshotFroz $this->assertSame(['freeze:' . \OCA\Libresign\Enum\FileStatus::ABLE_TO_SIGN->value, 'insert'], $calls); } - public function testNewStorageNodeIsCreatedBeforeTransactionAndDeletedAfterSignerRollback(): void { $node = $this->createMock(\OCP\Files\File::class); $node->method('getId')->willReturn(621); $node->method('getExtension')->willReturn(''); $node->method('getName')->willReturn('new-contract.pdf'); + $this->fileMapper->expects($this->once())->method('getByNodeId') + ->with(621) + ->willThrowException(new \OCP\AppFramework\Db\DoesNotExistException('new node is not yet registered')); + $inTransaction = false; $this->db->expects($this->once())->method('beginTransaction')->willReturnCallback( @@ -403,6 +406,10 @@ public function testNewStorageNodeRemainsAvailableAfterCommit(): void { $node->method('getId')->willReturn(623); $node->method('getExtension')->willReturn(''); $node->method('getName')->willReturn('new-contract.pdf'); + $this->fileMapper->expects($this->once())->method('getByNodeId') + ->with(623) + ->willThrowException(new \OCP\AppFramework\Db\DoesNotExistException('new node is not yet registered')); + $this->fileService->expects($this->once())->method('getNodeFromData')->willReturn($node); $this->fileMapper->expects($this->once())->method('insert')->willReturnArgument(0); $this->db->expects($this->once())->method('commit'); @@ -423,6 +430,10 @@ public function testCreatedNodeIsRemovedIfFilePersistenceFailsBeforeEntityAssign $node->method('getId')->willReturn(624); $node->method('getExtension')->willReturn(''); $node->method('getName')->willReturn('new-contract.pdf'); + $this->fileMapper->expects($this->once())->method('getByNodeId') + ->with(624) + ->willThrowException(new \OCP\AppFramework\Db\DoesNotExistException('new node is not yet registered')); + $this->fileService->method('getNodeFromData')->willReturn($node); $this->filePolicyApplier->method('applyAll')->willThrowException(new \RuntimeException('policy persistence failed')); $this->db->expects($this->once())->method('rollBack'); @@ -500,6 +511,10 @@ public function testReadyRequestNewInsertIsPublishedAfterCommit(): void { $node->method('getId')->willReturn(501); $node->method('getExtension')->willReturn(''); $node->method('getName')->willReturn('contract.pdf'); + $this->fileMapper->expects($this->once())->method('getByNodeId') + ->with(501) + ->willThrowException(new \OCP\AppFramework\Db\DoesNotExistException('new node is not yet registered')); + $this->fileService->method('getNodeFromData')->willReturn($node); $this->fileMapper->method('insert')->willReturnArgument(0); $this->user->method('getUID')->willReturn('tester'); diff --git a/tests/php/Unit/Service/SignatureRejection/SignatureRejectionNotifierTest.php b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionNotifierTest.php index 30dfcd6828..aeb556a564 100644 --- a/tests/php/Unit/Service/SignatureRejection/SignatureRejectionNotifierTest.php +++ b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionNotifierTest.php @@ -136,7 +136,6 @@ static function () use (&$calls): void { $this->assertSame(2, $calls); } - public function testIdentificationLookupFailureLogsSourceWithoutExceptionMessage(): void { $failure = new \RuntimeException('private identification details'); $this->identification->method('getIdentifyMethodsFromSignRequestId')->willThrowException($failure); From 7bb6149d23a1b5440dd8c40c96778c4a03ea3969 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:35:28 +0000 Subject: [PATCH 23/23] style: normalize PHPUnit test spacing Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- tests/php/Unit/Service/RequestSignatureServiceTest.php | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/php/Unit/Service/RequestSignatureServiceTest.php b/tests/php/Unit/Service/RequestSignatureServiceTest.php index 06969d38d6..6bb87ea801 100644 --- a/tests/php/Unit/Service/RequestSignatureServiceTest.php +++ b/tests/php/Unit/Service/RequestSignatureServiceTest.php @@ -336,7 +336,6 @@ public function testNewStorageNodeIsCreatedBeforeTransactionAndDeletedAfterSigne ->with(621) ->willThrowException(new \OCP\AppFramework\Db\DoesNotExistException('new node is not yet registered')); - $inTransaction = false; $this->db->expects($this->once())->method('beginTransaction')->willReturnCallback( static function () use (&$inTransaction): void {