diff --git a/lib/Controller/SignFileController.php b/lib/Controller/SignFileController.php index 0ee2d0b4b3..f52b571c81 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) { + $this->logger->error('Unable to process signature rejection', [ + 'errorType' => get_debug_type($th), + 'errorFile' => $th->getFile(), + 'errorLine' => $th->getLine(), + ]); 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/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/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/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..1193223d9b --- /dev/null +++ b/lib/Events/SigningRequestReadyEvent.php @@ -0,0 +1,55 @@ +hasParent() + || $previousStatus !== FileStatus::DRAFT->value + || $file->getStatus() !== FileStatus::ABLE_TO_SIGN->value + || $file->getUuid() === '') { + return 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; + } + return new self($file->getUuid(), $file->isEnvelope() ? 'envelope' : 'document', $eventId); + } + + #[\Override] + public function getWebhookSerializable(): array { + return [ + 'contractVersion' => self::CONTRACT_VERSION, + 'eventId' => $this->eventId, + 'requestUuid' => $this->requestUuid, + 'requestType' => $this->requestType, + 'status' => 'ready_to_sign', + ]; + } +} 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 b95bca2457..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, @@ -26,14 +27,15 @@ public function __construct( } public function updateFileStatusIfUpgrade(FileEntity $file, int $newStatus): FileEntity { - $currentStatus = $file->getStatus(); - if ($newStatus > $currentStatus) { + 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); $this->statusCacheService->setStatus($file->getUuid(), $newStatus); - if ($file->hasParent()) { $this->propagateStatusToParent($file->getParentFileId()); } @@ -101,6 +103,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); @@ -208,6 +213,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[self::READY_EVENT_ID_METADATA_KEY] = 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/Notification/NotificationSubmissionService.php b/lib/Service/Notification/NotificationSubmissionService.php index d9702450c0..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,6 +30,7 @@ public function __construct( private NotificationFailureClassifier $failureClassifier, private NotificationHistoryService $history, private LoggerInterface $logger, + private NativeWebhookEventPublisher $webhooks, ) { } @@ -90,7 +92,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->webhooks->notificationOutcome($delivery->getId()); } return true; } + } diff --git a/lib/Service/RequestSignatureService.php b/lib/Service/RequestSignatureService.php index 35009a3fe4..1379a77638 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, ) { } @@ -139,19 +141,64 @@ public function saveFiles(array $data): array { } public function save(array $data): FileEntity { - $file = $this->saveFile($data); - if (!isset($data['status'])) { - $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; + $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, $createdNode): array { + $result = $this->persistFile($data, $createdNode); + $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 ($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); + $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($result['file']); + } - return $file; + return $result['file']; } private function propagateSignersToChildren(FileEntity $envelope, array $data): void { @@ -215,23 +262,36 @@ 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(); } - - return [ - 'envelope' => $envelope, - 'files' => $files, - ]; } catch (\Throwable $e) { $this->rollbackEnvelopeCreation($envelope, $files, $createdNodes); throw $e; } + + if ($makeReady && $envelope->getStatus() === FileStatus::ABLE_TO_SIGN->value) { + $this->webhooks->requestReady($envelope); + } + return [ + 'envelope' => $envelope, + 'files' => $files, + ]; } private function processFileData(array $fileData, ?IUser $userManager, array $settings): Node { @@ -364,6 +424,11 @@ private function createFileForEnvelope( * } $data */ public function saveFile(array $data): FileEntity { + return $this->persistFile($data)['file']; + } + + /** @return array{file: FileEntity, becameReady: bool} */ + private function persistFile(array $data, ?Node $createdNode = null): array { if (!empty($data['uuid'])) { $file = $this->fileMapper->getByUuid($data['uuid']); $this->filePolicyApplier->syncCoreFlowPolicies($file, $data); @@ -371,7 +436,7 @@ public function saveFile(array $data): FileEntity { $file->setName($data['name']); $this->fileService->update($file); } - return $this->fileStatusService->updateFileStatusIfUpgrade($file, $data['status'] ?? 0); + return $this->upgradeExistingFileStatus($file, $data['status'] ?? 0); } $nodeId = null; if (isset($data['file']['fileNode']) && $data['file']['fileNode'] instanceof Node) { @@ -390,11 +455,11 @@ public function saveFile(array $data): FileEntity { } if ($file !== null) { $this->filePolicyApplier->syncAllPolicies($file, $data); - return $this->fileStatusService->updateFileStatusIfUpgrade($file, $data['status'] ?? 0); + return $this->upgradeExistingFileStatus($file, $data['status'] ?? 0); } } - $node = $this->fileService->getNodeFromData($data); + $node = $createdNode ?? $this->fileService->getNodeFromData($data); $file = new FileEntity(); $file->setNodeId($node->getId()); @@ -425,6 +490,9 @@ public function saveFile(array $data): FileEntity { $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']); @@ -433,7 +501,21 @@ public function saveFile(array $data): FileEntity { $this->filePolicyApplier->applyAll($file, $data); $this->fileMapper->insert($file); - return $file; + return [ + 'file' => $file, + 'becameReady' => !$file->hasParent() && $file->getStatus() === FileStatus::ABLE_TO_SIGN->value, + ]; + } + + /** @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 { diff --git a/lib/Service/SignFileService.php b/lib/Service/SignFileService.php index a230d1a5df..ad7852b129 100644 --- a/lib/Service/SignFileService.php +++ b/lib/Service/SignFileService.php @@ -31,7 +31,6 @@ use OCA\Libresign\Enum\IdentifyMethodRequirement; use OCA\Libresign\Enum\SignRequestStatus; use OCA\Libresign\Events\SignedEventFactory; -use OCA\Libresign\Events\SigningRequestCompletedEvent; use OCA\Libresign\Exception\FooterStampUnavailableException; use OCA\Libresign\Exception\LibresignException; use OCA\Libresign\Handler\DocMdpHandler; @@ -56,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; @@ -143,6 +143,7 @@ public function __construct( private TemporarySignatureImageService $temporarySignatureImageService, private NotificationDeliveryMapper $notificationDeliveries, private SigningWorkflowStatusResolver $signingWorkflowStatusResolver, + private NativeWebhookEventPublisher $webhooks, ) { } @@ -980,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 { @@ -1010,14 +1002,18 @@ protected function dispatchSignedEvent(): void { } } - $event = $this->signedEventFactory->make( - $this->signRequest, - $this->libreSignFile, - $this->getEngine()->getInputFile(), - $this->signWithoutPassword, - $certificateSerialNumber, - ); - $this->eventDispatcher->dispatchTyped($event); + try { + $event = $this->signedEventFactory->make( + $this->signRequest, + $this->libreSignFile, + $this->getEngine()->getInputFile(), + $this->signWithoutPassword, + $certificateSerialNumber, + ); + $this->eventDispatcher->dispatchTyped($event); + } finally { + $this->webhooks->signerSigned($this->libreSignFile, $this->signRequest); + } } protected function identifyEngine(File $file): ISignEngineHandler { 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 { + try { + $groupedIdentifyMethods = $this->identifyMethodService->getIdentifyMethodsFromSignRequestId($signRequest->getId()); + } catch (\Exception $e) { + $this->logger->error('Error dispatching SignatureRejectedEvent', [ + 'errorType' => get_debug_type($e), + 'errorFile' => $e->getFile(), + 'errorLine' => $e->getLine(), + ]); + 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), + 'errorFile' => $e->getFile(), + 'errorLine' => $e->getLine(), + ]); + } + } + } + } +} diff --git a/lib/Service/SignatureRejection/SignatureRejectionPersistence.php b/lib/Service/SignatureRejection/SignatureRejectionPersistence.php new file mode 100644 index 0000000000..4f5c7e110d --- /dev/null +++ b/lib/Service/SignatureRejection/SignatureRejectionPersistence.php @@ -0,0 +1,115 @@ +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), + 'errorFile' => $e->getFile(), + 'errorLine' => $e->getLine(), + '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 b5de4b2282..34e7b9907d 100644 --- a/lib/Service/SignatureRejection/SignatureRejectionService.php +++ b/lib/Service/SignatureRejection/SignatureRejectionService.php @@ -9,80 +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 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 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; - - $activatedSigners = $this->persistRejection($libreSignFile, $signRequest, $normalizedComment, $commentIsPrivate, $config->cancelsWorkflow()); - // 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->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; } @@ -94,290 +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 (\Throwable $e) { - $this->db->rollBack(); - $this->restoreState($libreSignFile, $signRequests, $previousSignerStatuses, $previousFileStatus); - $this->logger->error('Failed to register the signature rejection: ' . $e->getMessage(), [ - 'exception' => $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.')); - } - - 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 (\Throwable) { - // The envelope itself carries no signature request for this signer. - } - - // 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 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 (\Throwable $e) { - $this->logger->error('Error dispatching SignatureRejectedEvent: ' . $e->getMessage(), ['exception' => $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/lib/Service/Webhook/NativeWebhookEventPublisher.php b/lib/Service/Webhook/NativeWebhookEventPublisher.php new file mode 100644 index 0000000000..f46ded3cea --- /dev/null +++ b/lib/Service/Webhook/NativeWebhookEventPublisher.php @@ -0,0 +1,136 @@ +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 (DoesNotExistException $e) { + $this->reportFailure($e, 'prepare', 'signer.rejected', $context); + return; + } + + $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 (DoesNotExistException $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 { + $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/Integration/Service/NotificationDeliveryServiceTest.php b/tests/php/Integration/Service/NotificationDeliveryServiceTest.php index 439efad08b..926af12a62 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(bin2hex(random_bytes(16))); + $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/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/Controller/SignFileControllerTest.php b/tests/php/Unit/Controller/SignFileControllerTest.php index 23472bcd77..09880f5e36 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,44 @@ 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 + && ($context['errorFile'] ?? null) === __FILE__ + && is_int($context['errorLine'] ?? null) + && !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') 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 new file mode 100644 index 0000000000..2baf3e608a --- /dev/null +++ b/tests/php/Unit/Events/NativeWebhookEventsTest.php @@ -0,0 +1,193 @@ +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()); + } + + 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 [ + '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/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', diff --git a/tests/php/Unit/Service/FileStatusServiceTest.php b/tests/php/Unit/Service/FileStatusServiceTest.php index 6bbe403d11..451018bf48 100644 --- a/tests/php/Unit/Service/FileStatusServiceTest.php +++ b/tests/php/Unit/Service/FileStatusServiceTest.php @@ -49,6 +49,55 @@ public function testCommittedEnqueueDoesNotOverwriteNewerSigningProgress(): void $this->service->onQueuedJobCommitted($file); } + public function testStatusPersistenceDoesNotDispatchEvents(): 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); + + $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/Notification/NotificationSubmissionServiceTest.php b/tests/php/Unit/Service/Notification/NotificationSubmissionServiceTest.php index 32c82fc91d..724ba62735 100644 --- a/tests/php/Unit/Service/Notification/NotificationSubmissionServiceTest.php +++ b/tests/php/Unit/Service/Notification/NotificationSubmissionServiceTest.php @@ -24,6 +24,7 @@ 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; @@ -34,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, + NativeWebhookEventPublisher $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); @@ -65,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)); + $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); } @@ -103,4 +123,77 @@ 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 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(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.'); + }); + + $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(NativeWebhookEventPublisher::class); + $publisher->expects($this->never())->method('notificationOutcome'); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('ledger write failed'); + + $this->service($deliveries, $attempts, $publisher, $db)->submit( + $delivery, + $this->message(), + $this->createMock(NotificationChannel::class), + ); + } + + 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(NativeWebhookEventPublisher::class); + $publisher->expects($this->never())->method('notificationOutcome'); + $this->assertFalse($this->service( + $deliveries, + $this->createMock(NotificationAttemptMapper::class), + $publisher, + )->submit($delivery, $this->message(), $channel)); + } + } diff --git a/tests/php/Unit/Service/NotificationDeliveryServiceTest.php b/tests/php/Unit/Service/NotificationDeliveryServiceTest.php index fbd8fae78d..134418473a 100644 --- a/tests/php/Unit/Service/NotificationDeliveryServiceTest.php +++ b/tests/php/Unit/Service/NotificationDeliveryServiceTest.php @@ -79,6 +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\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 7af9e9f6de..6bb87ea801 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; @@ -85,6 +86,9 @@ 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; + private NativeWebhookEventPublisher&MockObject $webhooks; public function setUp(): void { parent::setUp(); @@ -123,6 +127,9 @@ 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); + $this->webhooks = $this->createMock(NativeWebhookEventPublisher::class); } private function getService(array $methods = []): RequestSignatureService|MockObject { @@ -158,8 +165,9 @@ 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, + $this->webhooks, ]) ->onlyMethods($methods) ->getMock(); @@ -195,8 +203,9 @@ 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, + $this->webhooks, ); } @@ -318,6 +327,352 @@ 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( + 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->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'); + $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->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'); + $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'); + $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->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; + })); + + $this->assertSame($file, $this->getService()->save([ + 'uuid' => 'ready-uuid', + 'status' => \OCA\Libresign\Enum\FileStatus::ABLE_TO_SIGN->value, + ])); + } + + 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->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'); + $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'); + $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->webhooks->expects($this->never())->method('requestReady'); + $this->expectException(\RuntimeException::class); + + $this->getService()->save([ + 'uuid' => 'ready-uuid', + 'status' => \OCA\Libresign\Enum\FileStatus::ABLE_TO_SIGN->value, + 'signers' => [['identifyMethods' => []]], + ]); + } + + 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']); @@ -880,6 +1235,7 @@ public function testDeleteIdentifyMethodIfNotExitsKeepsMatchingIdentifyMethods() $this->signerRemovalService, $this->createMock(\OCP\IDBConnection::class), $this->createMock(\OCA\Libresign\Service\NotificationDeliveryService::class), + $this->webhooks, ]) ->onlyMethods(['unassociateToUser']) ->getMock(); @@ -958,6 +1314,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 9da9d45bc3..ffd2cf76de 100644 --- a/tests/php/Unit/Service/SignFileServiceTest.php +++ b/tests/php/Unit/Service/SignFileServiceTest.php @@ -30,7 +30,6 @@ use OCA\Libresign\Enum\SignRequestStatus; use OCA\Libresign\Events\SignedEvent; use OCA\Libresign\Events\SignedEventFactory; -use OCA\Libresign\Events\SigningRequestCompletedEvent; use OCA\Libresign\Exception\LibresignException; use OCA\Libresign\Handler\DocMdpHandler; use OCA\Libresign\Handler\FooterHandler; @@ -68,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; @@ -108,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; @@ -163,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); @@ -542,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(); @@ -591,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, ); } @@ -825,57 +829,61 @@ 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'); + $this->webhooks->expects($this->once())->method('requestCompleted') + ->with($file, FileStatus::PARTIAL_SIGNED->value); + $service->signSingleFile($file, new SignRequest()); + } - $events = []; - $this->eventDispatcher->method('dispatchTyped') - ->willReturnCallback(static function ($event) use (&$events): void { - $events[] = $event; - }); + 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'); - $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, - )); + $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)); + + $this->webhooks->expects($this->once())->method('signerSigned')->with($file, $signer); + $this->eventDispatcher->method('dispatchTyped')->willReturnCallback( + static function ($event): void { + if ($event instanceof SignedEvent) { + throw new \RuntimeException('private callback details'); + } + }, + ); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('private callback details'); + $service->signSingleFile($file, $signer); } public function testUpdateEnvelopeStatusAddsStatusChangedAt(): void { diff --git a/tests/php/Unit/Service/SignatureRejection/SignatureRejectionNotifierTest.php b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionNotifierTest.php new file mode 100644 index 0000000000..aeb556a564 --- /dev/null +++ b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionNotifierTest.php @@ -0,0 +1,217 @@ +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)], + ]); + $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, + 'errorFile' => $failure->getFile(), + 'errorLine' => $failure->getLine(), + ]); + $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 testLegacyListenerTypeErrorDoesNotInterruptCommittedRejection(): void { + $this->identification->method('getIdentifyMethodsFromSignRequestId')->willReturn([ + 'account' => [$this->createMock(IIdentifyMethod::class)], + ]); + $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, + 'errorFile' => $failure->getFile(), + 'errorLine' => $failure->getLine(), + ], + ); + $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', $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, [])); + + $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') + ->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..c2e17a5d8d --- /dev/null +++ b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionPersistenceTest.php @@ -0,0 +1,253 @@ +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); + $this->logger = $this->createMock(LoggerInterface::class); + $this->persistence = new SignatureRejectionPersistence( + $this->signRequests, $this->files, $this->workflow, + $this->db, $clock, $l10n, $this->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->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); + + 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 6d34ac914a..d7cfa1e3af 100644 --- a/tests/php/Unit/Service/SignatureRejection/SignatureRejectionServiceTest.php +++ b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionServiceTest.php @@ -8,877 +8,89 @@ namespace OCA\Libresign\Tests\Unit\Service\SignatureRejection; -use OCA\Libresign\Db\File; -use OCA\Libresign\Db\FileMapper; -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\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 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; - /** @var list */ - private array $envelopeChildSignRequests = []; - private ?SignRequest $envelopeSignRequest = null; - /** @var array */ - private array $filesById = []; + 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->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(); - - // 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 (isset($this->filesById[$id])) { - return $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, - ); - } - - 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()); + $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); } - #[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.']; - } - - 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()); - + 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('You already rejected this signature request.'); - $this->getService()->reject($this->file(), $this->signRequest(SignRequestStatus::REJECTED->value)); + $this->service->reject($this->file(), $this->signer()); } - public function testCommentIsRefusedWhenThePolicyDoesNotAcceptComments(): void { - $this->withPolicy(self::policy(commentMode: 'disabled')); - - $this->expectException(LibresignException::class); - $this->expectExceptionMessage('Rejection comments are not allowed for this document.'); + 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); - $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); - } - - /** - * @return iterable - */ - public static function provideMissingRequiredComments(): iterable { - yield 'null' => [null]; - yield 'empty string' => ['']; - yield 'only whitespace' => [" \n\t "]; - } - - 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()); - } - - 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'); + $this->notifier->method('afterCommit')->willThrowException(new \RuntimeException('external notification failed')); + $this->expectException(\RuntimeException::class); 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); + $this->service->reject($this->file(), $signer); } 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()); + $this->assertSame(SignRequestStatus::REJECTED, $signer->getStatusEnum()); } } - 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..f5cbbc39ba --- /dev/null +++ b/tests/php/Unit/Service/SignatureRejection/SignatureRejectionWorkflowTest.php @@ -0,0 +1,242 @@ + */ + 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 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(); + $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()]); + } +} diff --git a/tests/php/Unit/Service/Webhook/NativeWebhookEventPublisherTest.php b/tests/php/Unit/Service/Webhook/NativeWebhookEventPublisherTest.php new file mode 100644 index 0000000000..2b8b7d9098 --- /dev/null +++ b/tests/php/Unit/Service/Webhook/NativeWebhookEventPublisherTest.php @@ -0,0 +1,290 @@ +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 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 = []; + $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 testMissingPersistedDeliveryIsLoggedAsAnErrorWithoutPrivateMessage(): void { + $this->deliveries->method('findById')->willThrowException( + 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) === DoesNotExistException::class + && is_string($context['errorFile'] ?? null) + && is_int($context['errorLine'] ?? null) + && !str_contains(json_encode($context), 'PRIVATE_RECIPIENT'), + )); + $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( + 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()); + } +}