From d1cb2127f3978a00960c1e6b54025a6acb83be16 Mon Sep 17 00:00:00 2001 From: Paulo Raoni Date: Thu, 5 Nov 2026 00:36:14 -0300 Subject: [PATCH 1/6] fix: certify a frozen request with the level it stores Later changes to the PDF certification policy no longer apply to it. Signed-off-by: Paulo Raoni --- .../SignEngine/JSignPdf/JSignPdfHandler.php | 7 +- lib/Handler/SignEngine/PhpNativeHandler.php | 11 ++-- lib/Handler/SignEngine/Pkcs12Handler.php | 1 + lib/Handler/SignEngine/SignEngineHandler.php | 15 +++++ lib/Service/SignFileService.php | 20 +++++- .../JSignPdf/JSignPdfHandlerTest.php | 21 ++++++ .../SignEngine/PhpNativeHandlerTest.php | 20 ++++++ .../Handler/SignEngine/Pkcs12HandlerTest.php | 31 +++++++++ .../php/Unit/Service/SignFileServiceTest.php | 64 +++++++++++++++++++ 9 files changed, 182 insertions(+), 8 deletions(-) diff --git a/lib/Handler/SignEngine/JSignPdf/JSignPdfHandler.php b/lib/Handler/SignEngine/JSignPdf/JSignPdfHandler.php index 5255ef4045..9642ba0f60 100644 --- a/lib/Handler/SignEngine/JSignPdf/JSignPdfHandler.php +++ b/lib/Handler/SignEngine/JSignPdf/JSignPdfHandler.php @@ -194,11 +194,12 @@ private function replacePdfVersion(string $content, string $newVersion): string } private function getCertificationLevel(): ?string { - if (!$this->docMdpConfigService->isEnabled()) { - return null; + $level = $this->getDocMdpLevel(); + if ($level === null && $this->docMdpConfigService->isEnabled()) { + $level = $this->docMdpConfigService->getLevel(); } - return $this->docMdpConfigService->getLevel()->name; + return $level !== null && $level->isCertifying() ? $level->name : null; } #[\Override] diff --git a/lib/Handler/SignEngine/PhpNativeHandler.php b/lib/Handler/SignEngine/PhpNativeHandler.php index 2a5a639446..567f4a2565 100644 --- a/lib/Handler/SignEngine/PhpNativeHandler.php +++ b/lib/Handler/SignEngine/PhpNativeHandler.php @@ -249,15 +249,18 @@ private function getTsaSettings(): array { } private function resolveCertificationLevel(bool $noVisibleElements): ?CertificationLevel { - if (!$this->docMdpConfigService->isEnabled()) { + $level = $this->getDocMdpLevel(); + if ($level === null && $this->docMdpConfigService->isEnabled()) { + $level = $this->docMdpConfigService->getLevel(); + } + if ($level === null || !$level->isCertifying()) { return null; } - // DocMDP values mirror CertificationLevel: 1=NoChanges, 2=FormFilling, 3=FormFillAndAnnotations - $level = $this->docMdpConfigService->getLevel()->value; // Only certify on invisible signatures or on the first visible element if ($noVisibleElements || !$this->hasExistingSignatures($this->getInputFile()->getContent())) { - return CertificationLevel::fromInt($level); + // DocMDP values mirror CertificationLevel: 1=NoChanges, 2=FormFilling, 3=FormFillAndAnnotations + return CertificationLevel::fromInt($level->value); } return null; diff --git a/lib/Handler/SignEngine/Pkcs12Handler.php b/lib/Handler/SignEngine/Pkcs12Handler.php index 65ffdac2ce..57892f13bf 100644 --- a/lib/Handler/SignEngine/Pkcs12Handler.php +++ b/lib/Handler/SignEngine/Pkcs12Handler.php @@ -409,6 +409,7 @@ public function sign(): File { ->setPassword($this->getPassword()) ->setSignatureParams($this->getSignatureParams()) ->setVisibleElements($this->getVisibleElements()) + ->setDocMdpLevel($this->getDocMdpLevel()) ->getSignedContent(); $this->getInputFile()->putContent($signedContent); return $this->getInputFile(); diff --git a/lib/Handler/SignEngine/SignEngineHandler.php b/lib/Handler/SignEngine/SignEngineHandler.php index af1b05e8ec..4453a1f5a3 100644 --- a/lib/Handler/SignEngine/SignEngineHandler.php +++ b/lib/Handler/SignEngine/SignEngineHandler.php @@ -10,6 +10,7 @@ use InvalidArgumentException; use OCA\Libresign\DataObjects\VisibleElementAssoc; +use OCA\Libresign\Enum\DocMdpLevel; use OCA\Libresign\Exception\EmptyCertificateException; use OCA\Libresign\Exception\LibresignException; use OCA\Libresign\Exception\PasswordToSignNotDefinedException; @@ -31,6 +32,7 @@ abstract class SignEngineHandler implements IPkcs12SignEngineHandler { /** @var VisibleElementAssoc[] */ private array $visibleElements = []; private array $signatureParams = []; + private ?DocMdpLevel $docMdpLevel = null; public function __construct( private IL10N $l10n, @@ -119,6 +121,19 @@ public function setSignatureParams(array $params): self { return $this; } + /** + * The certification level to sign with, used as is. Without one, the + * current level applies. + */ + public function setDocMdpLevel(?DocMdpLevel $docMdpLevel): self { + $this->docMdpLevel = $docMdpLevel; + return $this; + } + + public function getDocMdpLevel(): ?DocMdpLevel { + return $this->docMdpLevel; + } + public function setLeafExpiryOverrideInDays(?int $days): self { $this->getCertificateEngine()->setLeafExpiryOverrideInDays($days); return $this; diff --git a/lib/Service/SignFileService.php b/lib/Service/SignFileService.php index 05f653c6c4..420dca20c5 100644 --- a/lib/Service/SignFileService.php +++ b/lib/Service/SignFileService.php @@ -26,6 +26,7 @@ use OCA\Libresign\Db\SignRequest as SignRequestEntity; use OCA\Libresign\Db\SignRequestMapper; use OCA\Libresign\Db\UserElementMapper; +use OCA\Libresign\Enum\DocMdpLevel; use OCA\Libresign\Enum\FileStatus; use OCA\Libresign\Enum\IdentifyMethodRequirement; use OCA\Libresign\Enum\SignRequestStatus; @@ -47,6 +48,7 @@ use OCA\Libresign\Service\IdentifyMethod\SignatureMethod\IToken; use OCA\Libresign\Service\Policy\PolicyService; use OCA\Libresign\Service\Policy\Provider\CollectMetadata\CollectMetadataPolicy; +use OCA\Libresign\Service\Policy\Provider\DocMdp\DocMdpPolicy; use OCA\Libresign\Service\Policy\Provider\Footer\FooterPolicy; use OCA\Libresign\Service\Policy\Provider\Footer\FooterPolicyValue; use OCA\Libresign\Service\SignRequest\SignRequestService; @@ -1246,7 +1248,8 @@ private function configureEngine(): void { $this->restoreMissingVisibleElementImages(); $this->engine ->setVisibleElements($this->getVisibleElements()) - ->setSignatureParams($this->getSignatureParams()); + ->setSignatureParams($this->getSignatureParams()) + ->setDocMdpLevel($this->getDocMdpLevel()); } } @@ -1492,6 +1495,21 @@ private function getFooterPolicyValue(): string { return $this->footerPolicyValue; } + /** + * Once frozen, the request certifies with the level it stores, whatever the + * current level. Without a stored level, the current one applies. + */ + private function getDocMdpLevel(): ?DocMdpLevel { + $policySnapshot = ($this->libreSignFile->getMetadata() ?? [])['policy_snapshot'] ?? null; + if (!is_array($policySnapshot) || !array_key_exists(DocMdpPolicy::KEY, $policySnapshot)) { + return null; + } + + return FileStatusService::isPolicySnapshotFrozen($this->libreSignFile, $this->fileMapper->findEnvelope($this->libreSignFile)) + ? $this->libreSignFile->getDocmdpLevelEnum() + : null; + } + protected function getSignedFile(): ?File { $nodeId = $this->libreSignFile->getSignedNodeId(); if (!$nodeId) { diff --git a/tests/php/Integration/Handler/SignEngine/JSignPdf/JSignPdfHandlerTest.php b/tests/php/Integration/Handler/SignEngine/JSignPdf/JSignPdfHandlerTest.php index c341d9726c..a3b8d5c912 100644 --- a/tests/php/Integration/Handler/SignEngine/JSignPdf/JSignPdfHandlerTest.php +++ b/tests/php/Integration/Handler/SignEngine/JSignPdf/JSignPdfHandlerTest.php @@ -1189,6 +1189,27 @@ public static function providerTsaParameters(): array { ]; } + #[DataProvider('providerTheGivenLevelWinsOverTheCurrentLevel')] + public function testTheGivenLevelWinsOverTheCurrentLevel(?DocMdpLevel $givenLevel, DocMdpLevel $currentLevel, ?string $expected): void { + $docMdpConfigService = $this->createMock(DocMdpConfigService::class); + $docMdpConfigService->method('isEnabled')->willReturn($currentLevel->isCertifying()); + $docMdpConfigService->method('getLevel')->willReturn($currentLevel); + $jSignPdfHandler = $this->getInstance(); + $this->setDocMdpConfigService($jSignPdfHandler, $docMdpConfigService); + $jSignPdfHandler->setDocMdpLevel($givenLevel); + + $this->assertSame($expected, self::invokePrivate($jSignPdfHandler, 'getCertificationLevel')); + } + + public static function providerTheGivenLevelWinsOverTheCurrentLevel(): array { + return [ + 'another certifying level' => [DocMdpLevel::CERTIFIED_FORM_FILLING_AND_ANNOTATIONS, DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED, DocMdpLevel::CERTIFIED_FORM_FILLING_AND_ANNOTATIONS->name], + 'not certified while the current level certifies' => [DocMdpLevel::NOT_CERTIFIED, DocMdpLevel::CERTIFIED_FORM_FILLING, null], + 'certified while the current level does not' => [DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED, DocMdpLevel::NOT_CERTIFIED, DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED->name], + 'no level given falls back to the current level' => [null, DocMdpLevel::CERTIFIED_FORM_FILLING, DocMdpLevel::CERTIFIED_FORM_FILLING->name], + ]; + } + #[DataProvider('providerCertificationLevelWithoutVisibleElements')] public function testCertificationLevelWithoutVisibleElements(bool $docMdpEnabled, array $visibleElements, string $pdfContent, array $tsaSettings, array $expectedParameters): void { if (self::$certificateEngineFactory === null || empty(self::$certificateContent)) { diff --git a/tests/php/Unit/Handler/SignEngine/PhpNativeHandlerTest.php b/tests/php/Unit/Handler/SignEngine/PhpNativeHandlerTest.php index 7849e08c7b..0fa4c93b5d 100644 --- a/tests/php/Unit/Handler/SignEngine/PhpNativeHandlerTest.php +++ b/tests/php/Unit/Handler/SignEngine/PhpNativeHandlerTest.php @@ -317,6 +317,26 @@ public static function providerResolveCertificationLevel(): array { ]; } + #[DataProvider('providerTheGivenLevelWinsOverTheCurrentLevel')] + public function testTheGivenLevelWinsOverTheCurrentLevel(?DocMdpLevel $givenLevel, DocMdpLevel $currentLevel, ?CertificationLevel $expected): void { + $this->docMdpConfigService->method('isEnabled')->willReturn($currentLevel->isCertifying()); + $this->docMdpConfigService->method('getLevel')->willReturn($currentLevel); + + $handler = $this->getHandler(); + $handler->setDocMdpLevel($givenLevel); + + $this->assertSame($expected, $this->callPrivateMethod($handler, 'resolveCertificationLevel', true)); + } + + public static function providerTheGivenLevelWinsOverTheCurrentLevel(): array { + return [ + 'another certifying level' => [DocMdpLevel::CERTIFIED_FORM_FILLING_AND_ANNOTATIONS, DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED, CertificationLevel::FormFillSignaturesAndAnnotations], + 'not certified while the current level certifies' => [DocMdpLevel::NOT_CERTIFIED, DocMdpLevel::CERTIFIED_FORM_FILLING, null], + 'certified while the current level does not' => [DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED, DocMdpLevel::NOT_CERTIFIED, CertificationLevel::NoChangesAllowed], + 'no level given falls back to the current level' => [null, DocMdpLevel::CERTIFIED_FORM_FILLING, CertificationLevel::FormFillAndSignatures], + ]; + } + public function testBuildAppearanceForElementSetsSignatureImageInGraphicAndDescriptionMode(): void { $imagePath = realpath(__DIR__ . '/../../../../../img/app-dark.png'); $this->assertNotFalse($imagePath, 'Test image must exist'); diff --git a/tests/php/Unit/Handler/SignEngine/Pkcs12HandlerTest.php b/tests/php/Unit/Handler/SignEngine/Pkcs12HandlerTest.php index a8e9d17201..eca7cc6067 100644 --- a/tests/php/Unit/Handler/SignEngine/Pkcs12HandlerTest.php +++ b/tests/php/Unit/Handler/SignEngine/Pkcs12HandlerTest.php @@ -8,9 +8,11 @@ namespace OCA\Libresign\Tests\Unit\Handler\SignEngine; +use OCA\Libresign\Enum\DocMdpLevel; use OCA\Libresign\Handler\CertificateEngine\CertificateEngineFactory; use OCA\Libresign\Handler\DocMdpHandler; use OCA\Libresign\Handler\FooterHandler; +use OCA\Libresign\Handler\SignEngine\PhpNativeHandler; use OCA\Libresign\Handler\SignEngine\Pkcs12Handler; use OCA\Libresign\Service\CaIdentifierService; use OCA\Libresign\Service\Crl\CrlService; @@ -103,4 +105,33 @@ public function testGetPfxOfCurrentSignerDoesNotReuseCertificateFromDifferentUse $this->assertSame('alice-pfx', $handler->getPfxOfCurrentSigner('alice')); $this->assertSame('bob-pfx', $handler->getPfxOfCurrentSigner('bob')); } + + public function testSignPassesTheGivenLevelToTheEngine(): void { + $appConfig = $this->createMock(IAppConfig::class); + $appConfig->method('getValueString')->willReturn('PhpNative'); + $handler = new Pkcs12Handler( + $this->folderService, + $appConfig, + $this->createMock(CertificateEngineFactory::class), + $this->createMock(IL10N::class), + $this->createMock(FooterHandler::class), + $this->createMock(LoggerInterface::class), + $this->createMock(CaIdentifierService::class), + $this->createMock(DocMdpHandler::class), + $this->createMock(CrlService::class), + $this->createMock(PdfSignatureValidationService::class), + ); + $engine = $this->getMockBuilder(PhpNativeHandler::class) + ->disableOriginalConstructor() + ->onlyMethods(['getSignedContent']) + ->getMock(); + $engine->method('getSignedContent')->willReturn('signed'); + (new \ReflectionProperty(Pkcs12Handler::class, 'phpNativeHandler'))->setValue($handler, $engine); + + $handler->setInputFile($this->createMock(File::class)); + $handler->setDocMdpLevel(DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED); + $handler->sign(); + + $this->assertSame(DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED, $engine->getDocMdpLevel()); + } } diff --git a/tests/php/Unit/Service/SignFileServiceTest.php b/tests/php/Unit/Service/SignFileServiceTest.php index a4c0fe68c1..8b8dddf9ba 100644 --- a/tests/php/Unit/Service/SignFileServiceTest.php +++ b/tests/php/Unit/Service/SignFileServiceTest.php @@ -31,6 +31,7 @@ use OCA\Libresign\Events\SignedEvent; use OCA\Libresign\Events\SignedEventFactory; use OCA\Libresign\Exception\LibresignException; +use OCA\Libresign\Handler\CertificateEngine\CertificateEngineFactory; use OCA\Libresign\Handler\DocMdpHandler; use OCA\Libresign\Handler\FooterHandler; use OCA\Libresign\Handler\PdfTk\Pdf; @@ -39,7 +40,9 @@ use OCA\Libresign\Handler\SignEngine\SignEngineFactory; use OCA\Libresign\Handler\SignEngine\SignEngineHandler; use OCA\Libresign\Helper\JavaHelper; +use OCA\Libresign\Service\CaIdentifierService; use OCA\Libresign\Service\CertificateValidityPolicy; +use OCA\Libresign\Service\Crl\CrlService; use OCA\Libresign\Service\Envelope\EnvelopeStatusDeterminer; use OCA\Libresign\Service\File\SigningWorkflowStatusResolver; use OCA\Libresign\Service\FileStatusService; @@ -55,9 +58,11 @@ use OCA\Libresign\Service\Policy\Model\ResolvedPolicy; use OCA\Libresign\Service\Policy\PolicyService; use OCA\Libresign\Service\Policy\Provider\CollectMetadata\CollectMetadataPolicy; +use OCA\Libresign\Service\Policy\Provider\DocMdp\DocMdpPolicy; use OCA\Libresign\Service\Policy\Provider\Footer\FooterPolicy; use OCA\Libresign\Service\Policy\Provider\Footer\FooterPolicyValue; use OCA\Libresign\Service\SessionService; +use OCA\Libresign\Service\Signature\PdfSignatureValidationService; use OCA\Libresign\Service\SignatureRejection\SignatureRejectionPolicyService; use OCA\Libresign\Service\SignerElementsService; use OCA\Libresign\Service\SignFileService; @@ -1506,6 +1511,65 @@ private function createRequestWithStoredFooter(int $status, array $metadata, ?st return $libreSignFile; } + /** @param array $metadata */ + #[DataProvider('provideDocMdpLevelsGivenToTheEngine')] + public function testTheEngineCertifiesWithTheLevelTheFrozenRequestStores(int $status, array $metadata, ?File $envelope, ?DocMdpLevel $expected): void { + $libreSignFile = new File(); + $libreSignFile->setUuid('uuid'); + $libreSignFile->setStatus($status); + $libreSignFile->setMetadata($metadata); + $libreSignFile->setDocmdpLevelEnum(DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED); + if ($envelope !== null) { + $libreSignFile->setParentFileId(5); + $this->fileMapper->method('findEnvelope')->with($libreSignFile)->willReturn($envelope); + } + + $pfx = $this->createMock(\OCP\Files\File::class); + $pfx->method('getContent')->willReturn('pfx'); + $folder = $this->createMock(\OCP\Files\Folder::class); + $folder->method('get')->willReturn($pfx); + $folderService = $this->createMock(FolderService::class); + $folderService->method('getFolder')->willReturn($folder); + $engine = new Pkcs12Handler( + $folderService, + $this->appConfig, + $this->createMock(CertificateEngineFactory::class), + $this->l10n, + $this->footerHandler, + $this->createMock(LoggerInterface::class), + $this->createMock(CaIdentifierService::class), + $this->createMock(DocMdpHandler::class), + $this->createMock(CrlService::class), + $this->createMock(PdfSignatureValidationService::class), + ); + + $service = $this->getService(['getFileToSign', 'readCertificate']); + $service->method('getFileToSign')->willReturn($this->createMock(\OCP\Files\File::class)); + $service->method('readCertificate')->willReturn(['issuer' => ['CN' => 'LibreCode'], 'subject' => ['CN' => 'Jane Doe']]); + $service->setLibreSignFile($libreSignFile); + $service->setSignRequest($this->createSignRequestMock(['getId' => 171, 'getMetadata' => []])); + (new \ReflectionProperty(SignFileService::class, 'engine'))->setValue($service, $engine); + + self::invokePrivate($service, 'configureEngine'); + + $this->assertSame($expected, $engine->getDocMdpLevel()); + } + + /** @return iterable, 2: ?File, 3: ?DocMdpLevel}> */ + public static function provideDocMdpLevelsGivenToTheEngine(): iterable { + $frozen = ['policy_snapshot_frozen_at' => '2026-01-01T00:00:00+00:00']; + $stored = ['policy_snapshot' => [DocMdpPolicy::KEY => ['effectiveValue' => DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED->value, 'sourceScope' => 'system']]]; + $frozenEnvelope = new File(); + $frozenEnvelope->setMetadata($frozen); + + yield 'sent' => [FileStatus::ABLE_TO_SIGN->value, $frozen + $stored, null, DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED]; + yield 'returned to draft' => [FileStatus::DRAFT->value, $frozen + $stored, null, DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED]; + yield 'sent before the freeze was recorded' => [FileStatus::ABLE_TO_SIGN->value, $stored, null, DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED]; + yield 'document of a sent envelope' => [FileStatus::DRAFT->value, $stored, $frozenEnvelope, DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED]; + yield 'sent before the level was stored' => [FileStatus::ABLE_TO_SIGN->value, $frozen, null, null]; + yield 'draft never sent' => [FileStatus::DRAFT->value, $stored, null, null]; + } + /** @return array */ private function getSignatureParamsFor(File $libreSignFile): array { $service = $this->getService(['readCertificate']); From ee62fb4b7040ed2def8cf4221b955f82d7db9898 Mon Sep 17 00:00:00 2001 From: Paulo Raoni Date: Thu, 5 Nov 2026 00:36:17 -0300 Subject: [PATCH 2/6] fix: freeze the PDF certification once the request is sent Signed-off-by: Paulo Raoni --- .../FilePolicy/DocMdpFilePolicyApplier.php | 28 ++++ .../RequestSignatureControllerTest.php | 142 ++++++++++++++++++ .../DocMdpFilePolicyApplierTest.php | 92 ++++++++++++ 3 files changed, 262 insertions(+) diff --git a/lib/Service/Policy/Provider/DocMdp/FilePolicy/DocMdpFilePolicyApplier.php b/lib/Service/Policy/Provider/DocMdp/FilePolicy/DocMdpFilePolicyApplier.php index 9a4e420a13..a9674dee64 100644 --- a/lib/Service/Policy/Provider/DocMdp/FilePolicy/DocMdpFilePolicyApplier.php +++ b/lib/Service/Policy/Provider/DocMdp/FilePolicy/DocMdpFilePolicyApplier.php @@ -10,8 +10,10 @@ use OCA\Libresign\Db\File as FileEntity; use OCA\Libresign\Enum\DocMdpLevel; +use OCA\Libresign\Exception\LibresignException; use OCA\Libresign\Service\Policy\AbstractFilePolicyApplier; use OCA\Libresign\Service\Policy\Provider\DocMdp\DocMdpPolicy; +use OCP\AppFramework\Http; use OCP\IUser; class DocMdpFilePolicyApplier extends AbstractFilePolicyApplier { @@ -31,6 +33,11 @@ public function apply(FileEntity $file, array $data): void { #[\Override] public function sync(FileEntity $file, array $data): void { $requestOverrides = $this->getOverrides($data); + if ($this->isPolicySnapshotFrozen($file, DocMdpPolicy::KEY)) { + $this->assertFrozenLevelIsKept($file, $requestOverrides); + return; + } + $activeContext = $this->extractActiveContext($data); $resolvedPolicy = $activeContext === null ? $this->policyService->resolveForUserId(DocMdpPolicy::KEY, $file->getUserId(), $requestOverrides) @@ -55,4 +62,25 @@ public function supportsCoreFlowSync(): bool { private function getOverrides(array $data): array { return $this->extractSinglePolicyOverride($data, DocMdpPolicy::KEY); } + + /** + * A frozen request keeps the certification level it was sent with. A client + * may still send that same level along an unrelated update, which changes + * nothing. + * + * @param array $requestOverrides + */ + private function assertFrozenLevelIsKept(FileEntity $file, array $requestOverrides): void { + $submittedLevel = $requestOverrides[DocMdpPolicy::KEY] ?? null; + if ($submittedLevel === null || (is_numeric($submittedLevel) && (int)$submittedLevel === $file->getDocmdpLevel())) { + return; + } + + throw new LibresignException( + // TRANSLATORS Error shown when someone tries to change the PDF certification (DocMDP level) of a document after the signing flow already started. + $this->l10n?->t('The PDF certification cannot be changed after the signing flow has started.') + ?? 'The PDF certification cannot be changed after the signing flow has started.', + Http::STATUS_UNPROCESSABLE_ENTITY, + ); + } } diff --git a/tests/php/Api/Controller/RequestSignatureControllerTest.php b/tests/php/Api/Controller/RequestSignatureControllerTest.php index 341d5edcbf..da47e1c18e 100644 --- a/tests/php/Api/Controller/RequestSignatureControllerTest.php +++ b/tests/php/Api/Controller/RequestSignatureControllerTest.php @@ -11,6 +11,7 @@ use OCA\Libresign\AppInfo\Application; use OCA\Libresign\Db\FileMapper; use OCA\Libresign\Db\SignRequestMapper; +use OCA\Libresign\Enum\DocMdpLevel; use OCA\Libresign\Enum\FileStatus; use OCA\Libresign\Service\Policy\Provider\Footer\FooterPolicyValue; use OCA\Libresign\Service\RequestSignatureService; @@ -357,4 +358,145 @@ public function testUuidPatchRejectsChangedFrozenFooterWithoutMutatingSnapshot() $this->assertSame('The footer cannot be changed after the signing flow has started.', $body['ocs']['data']['message']); $this->assertSame($before['policy_snapshot'], $fileMapper->getById($file->getId())->getMetadata()['policy_snapshot']); } + + /** + * @runInSeparateProcess + */ + public function testUuidPatchKeepsTheFrozenDocMdpAfterTheAdminChangesIt(): void { + $user = $this->createAccount('allowrequestsign', 'password', 'testGroup'); + $appConfig = $this->getMockAppConfig(); + $appConfig->setValueString(Application::APP_ID, 'groups_request_sign', '{"allowGroups":["admin","testGroup"],"denyGroups":[]}'); + $appConfig->setValueBool(Application::APP_ID, 'notifyUnsignedUser', false); + $appConfig->setValueInt(Application::APP_ID, 'docmdp_level', DocMdpLevel::CERTIFIED_FORM_FILLING->value); + $signers = [[ + 'identifyMethods' => [[ + 'method' => 'email', + 'requirement' => 'optional', + 'value' => 'external-signer@test.coop', + ]], + ]]; + $file = $this->requestSignFile([ + 'file' => ['base64' => base64_encode(file_get_contents(__DIR__ . '/../../fixtures/pdfs/small_valid.pdf'))], + 'name' => 'sent', + 'signers' => $signers, + 'userManager' => $user, + ]); + $fileMapper = \OCP\Server::get(FileMapper::class); + $before = $fileMapper->getById($file->getId()); + $this->assertSame(DocMdpLevel::CERTIFIED_FORM_FILLING->value, $before->getMetadata()['policy_snapshot']['docmdp']['effectiveValue']); + + $appConfig->setValueInt(Application::APP_ID, 'docmdp_level', DocMdpLevel::CERTIFIED_FORM_FILLING_AND_ANNOTATIONS->value); + $this->request + ->withMethod('PATCH') + ->withPath('/api/v1/request-signature') + ->withRequestHeader([ + 'Authorization' => 'Basic ' . base64_encode('allowrequestsign:password'), + 'Content-Type' => 'application/json', + ]) + ->withRequestBody([ + 'uuid' => $file->getUuid(), + 'name' => 'renamed', + 'signers' => $signers, + ]) + ->expectStatus(200); + + $this->assertRequest(); + $after = $fileMapper->getById($file->getId()); + $this->assertSame(DocMdpLevel::CERTIFIED_FORM_FILLING, $after->getDocmdpLevelEnum()); + $this->assertSame($before->getMetadata()['policy_snapshot']['docmdp'], $after->getMetadata()['policy_snapshot']['docmdp']); + } + + /** + * @runInSeparateProcess + */ + public function testUuidPatchRejectsAnotherDocMdpOnceTheRequestWasSent(): void { + $user = $this->createAccount('allowrequestsign', 'password', 'testGroup'); + $appConfig = $this->getMockAppConfig(); + $appConfig->setValueString(Application::APP_ID, 'groups_request_sign', '{"allowGroups":["admin","testGroup"],"denyGroups":[]}'); + $appConfig->setValueBool(Application::APP_ID, 'notifyUnsignedUser', false); + $appConfig->setValueInt(Application::APP_ID, 'docmdp_level', DocMdpLevel::CERTIFIED_FORM_FILLING->value); + $appConfig->setValueString(Application::APP_ID, 'docmdp_level.allow_child_override', '1'); + $signers = [[ + 'identifyMethods' => [[ + 'method' => 'email', + 'requirement' => 'optional', + 'value' => 'external-signer@test.coop', + ]], + ]]; + $file = $this->requestSignFile([ + 'file' => ['base64' => base64_encode(file_get_contents(__DIR__ . '/../../fixtures/pdfs/small_valid.pdf'))], + 'name' => 'sent', + 'signers' => $signers, + 'userManager' => $user, + ]); + $fileMapper = \OCP\Server::get(FileMapper::class); + $before = $fileMapper->getById($file->getId())->getMetadata(); + + $this->request + ->withMethod('PATCH') + ->withPath('/api/v1/request-signature') + ->withRequestHeader([ + 'Authorization' => 'Basic ' . base64_encode('allowrequestsign:password'), + 'Content-Type' => 'application/json', + ]) + ->withRequestBody([ + 'uuid' => $file->getUuid(), + 'signers' => $signers, + 'policy' => ['overrides' => ['docmdp' => DocMdpLevel::CERTIFIED_FORM_FILLING_AND_ANNOTATIONS->value]], + ]) + ->expectStatus(422); + + $response = $this->assertRequest(); + $body = json_decode($response->getBody()->getContents(), true); + $this->assertSame('The PDF certification cannot be changed after the signing flow has started.', $body['ocs']['data']['message']); + $this->assertSame($before['policy_snapshot'], $fileMapper->getById($file->getId())->getMetadata()['policy_snapshot']); + } + + /** + * @runInSeparateProcess + */ + public function testUuidPatchRefreshesDraftDocMdpBeforeFreezing(): void { + $user = $this->createAccount('allowrequestsign', 'password', 'testGroup'); + $appConfig = $this->getMockAppConfig(); + $appConfig->setValueString(Application::APP_ID, 'groups_request_sign', '{"allowGroups":["admin","testGroup"],"denyGroups":[]}'); + $appConfig->setValueBool(Application::APP_ID, 'notifyUnsignedUser', false); + $appConfig->setValueInt(Application::APP_ID, 'docmdp_level', DocMdpLevel::CERTIFIED_FORM_FILLING->value); + + $file = $this->requestSignFile([ + 'file' => ['base64' => base64_encode(file_get_contents(__DIR__ . '/../../fixtures/pdfs/small_valid.pdf'))], + 'name' => 'draft', + 'status' => FileStatus::DRAFT->value, + 'signers' => [], + 'userManager' => $user, + ]); + $fileMapper = \OCP\Server::get(FileMapper::class); + $this->assertSame(DocMdpLevel::CERTIFIED_FORM_FILLING, $fileMapper->getById($file->getId())->getDocmdpLevelEnum()); + + $appConfig->setValueInt(Application::APP_ID, 'docmdp_level', DocMdpLevel::CERTIFIED_FORM_FILLING_AND_ANNOTATIONS->value); + $this->request + ->withMethod('PATCH') + ->withPath('/api/v1/request-signature') + ->withRequestHeader([ + 'Authorization' => 'Basic ' . base64_encode('allowrequestsign:password'), + 'Content-Type' => 'application/json', + ]) + ->withRequestBody([ + 'uuid' => $file->getUuid(), + 'status' => FileStatus::ABLE_TO_SIGN->value, + 'signers' => [[ + 'identifyMethods' => [[ + 'method' => 'email', + 'requirement' => 'optional', + 'value' => 'external-signer@test.coop', + ]], + ]], + ]) + ->expectStatus(200); + + $this->assertRequest(); + $sent = $fileMapper->getById($file->getId()); + $this->assertSame(DocMdpLevel::CERTIFIED_FORM_FILLING_AND_ANNOTATIONS, $sent->getDocmdpLevelEnum()); + $this->assertSame(DocMdpLevel::CERTIFIED_FORM_FILLING_AND_ANNOTATIONS->value, $sent->getMetadata()['policy_snapshot']['docmdp']['effectiveValue']); + $this->assertArrayHasKey('policy_snapshot_frozen_at', $sent->getMetadata()); + } } diff --git a/tests/php/Unit/Service/Policy/Provider/DocMdp/FilePolicy/DocMdpFilePolicyApplierTest.php b/tests/php/Unit/Service/Policy/Provider/DocMdp/FilePolicy/DocMdpFilePolicyApplierTest.php index 56ad5b336c..96851b2e2e 100644 --- a/tests/php/Unit/Service/Policy/Provider/DocMdp/FilePolicy/DocMdpFilePolicyApplierTest.php +++ b/tests/php/Unit/Service/Policy/Provider/DocMdp/FilePolicy/DocMdpFilePolicyApplierTest.php @@ -8,28 +8,41 @@ namespace OCA\Libresign\Tests\Unit\Service\Policy\Provider\DocMdp\FilePolicy; +use OCA\Libresign\Db\File; use OCA\Libresign\Enum\DocMdpLevel; +use OCA\Libresign\Enum\FileStatus; +use OCA\Libresign\Exception\LibresignException; use OCA\Libresign\Service\FileService; +use OCA\Libresign\Service\Policy\Model\PolicySpec; use OCA\Libresign\Service\Policy\Model\ResolvedPolicy; use OCA\Libresign\Service\Policy\PolicyService; use OCA\Libresign\Service\Policy\Provider\DocMdp\DocMdpPolicy; use OCA\Libresign\Service\Policy\Provider\DocMdp\FilePolicy\DocMdpFilePolicyApplier; +use OCP\IL10N; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\MockObject\MockObject; final class DocMdpFilePolicyApplierTest extends \OCA\Libresign\Tests\Unit\TestCase { + private const FROZEN = ['policy_snapshot_frozen_at' => '2026-01-01T00:00:00+00:00']; + private PolicyService&MockObject $policyService; private FileService&MockObject $fileService; + private IL10N&MockObject $l10n; public function setUp(): void { parent::setUp(); $this->policyService = $this->createMock(PolicyService::class); + $this->policyService->method('getRequestLifecycle')->willReturn(PolicySpec::LIFECYCLE_REQUEST_SNAPSHOT); $this->fileService = $this->createMock(FileService::class); + $this->l10n = $this->createMock(IL10N::class); + $this->l10n->method('t')->willReturnArgument(0); } private function getApplier(): DocMdpFilePolicyApplier { return new DocMdpFilePolicyApplier( $this->policyService, $this->fileService, + $this->l10n, ); } @@ -109,6 +122,85 @@ public function testSyncDoesNotPersistWhenNothingChangedAndSnapshotExists(): voi $this->getApplier()->sync($file, []); } + /** + * @param array $metadata + * @param array $policyOverrides + */ + #[DataProvider('provideFrozenUpdates')] + public function testAFrozenRequestKeepsItsStoredLevel(int $status, array $metadata, array $policyOverrides): void { + $file = $this->createStoredRequest($status, $metadata); + $storedMetadata = $file->getMetadata(); + + $this->policyService->expects($this->never())->method('resolveForUserId'); + $this->fileService->expects($this->never())->method('update'); + + $this->getApplier()->sync($file, ['policyOverrides' => $policyOverrides]); + + $this->assertSame(DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED, $file->getDocmdpLevelEnum()); + $this->assertSame($storedMetadata, $file->getMetadata()); + } + + /** @return iterable, 2: array}> */ + public static function provideFrozenUpdates(): iterable { + yield 'nothing submitted' => [FileStatus::ABLE_TO_SIGN->value, self::FROZEN, []]; + yield 'stored level sent again' => [FileStatus::ABLE_TO_SIGN->value, self::FROZEN, [DocMdpPolicy::KEY => DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED->value]]; + yield 'stored level sent again as a string' => [FileStatus::ABLE_TO_SIGN->value, self::FROZEN, [DocMdpPolicy::KEY => '1']]; + yield 'null submitted' => [FileStatus::ABLE_TO_SIGN->value, self::FROZEN, [DocMdpPolicy::KEY => null]]; + yield 'returned to draft' => [FileStatus::DRAFT->value, self::FROZEN, []]; + yield 'sent before the freeze was recorded' => [FileStatus::ABLE_TO_SIGN->value, [], []]; + } + + /** @param array $metadata */ + #[DataProvider('provideFrozenChangeAttempts')] + public function testChangingTheLevelOfAFrozenRequestIsRefused(int $status, array $metadata, mixed $submittedLevel): void { + $file = $this->createStoredRequest($status, $metadata); + + $this->policyService->expects($this->never())->method('resolveForUserId'); + $this->fileService->expects($this->never())->method('update'); + $this->expectException(LibresignException::class); + $this->expectExceptionCode(422); + $this->expectExceptionMessage('The PDF certification cannot be changed after the signing flow has started.'); + + $this->getApplier()->sync($file, ['policyOverrides' => [DocMdpPolicy::KEY => $submittedLevel]]); + } + + /** @return iterable, 2: mixed}> */ + public static function provideFrozenChangeAttempts(): iterable { + yield 'another level' => [FileStatus::ABLE_TO_SIGN->value, self::FROZEN, DocMdpLevel::CERTIFIED_FORM_FILLING->value]; + yield 'not certified' => [FileStatus::ABLE_TO_SIGN->value, self::FROZEN, DocMdpLevel::NOT_CERTIFIED->value]; + yield 'after returning to draft' => [FileStatus::DRAFT->value, self::FROZEN, DocMdpLevel::CERTIFIED_FORM_FILLING->value]; + yield 'not a level' => [FileStatus::ABLE_TO_SIGN->value, self::FROZEN, 'one']; + } + + public function testADraftStillResolvesTheSubmittedLevel(): void { + $file = $this->createStoredRequest(FileStatus::DRAFT->value, []); + + $this->policyService + ->expects($this->once()) + ->method('resolveForUserId') + ->with(DocMdpPolicy::KEY, 'john', [DocMdpPolicy::KEY => 2]) + ->willReturn($this->createResolvedPolicy(2, sourceScope: 'request')); + $this->fileService->expects($this->once())->method('update'); + + $this->getApplier()->sync($file, ['policyOverrides' => [DocMdpPolicy::KEY => 2]]); + + $this->assertSame(DocMdpLevel::CERTIFIED_FORM_FILLING, $file->getDocmdpLevelEnum()); + } + + /** @param array $metadata */ + private function createStoredRequest(int $status, array $metadata): File { + $file = new File(); + $file->setUserId('john'); + $file->setStatus($status); + $file->setDocmdpLevelEnum(DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED); + $file->setMetadata($metadata + [ + 'policy_snapshot' => [ + DocMdpPolicy::KEY => ['effectiveValue' => DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED->value, 'sourceScope' => 'system'], + ], + ]); + return $file; + } + private function createResolvedPolicy(int $effectiveValue, string $sourceScope = 'system'): ResolvedPolicy { return (new ResolvedPolicy()) ->setPolicyKey(DocMdpPolicy::KEY) From 4fdbaabdecd552fae90e81e0f0f1fcb62bcca5b2 Mon Sep 17 00:00:00 2001 From: Paulo Raoni Date: Tue, 10 Nov 2026 19:05:58 -0300 Subject: [PATCH 3/6] fix: check signers against the certification the request will use Overrides, the frozen level and an uncertified level are no longer replaced by the current level. Signed-off-by: Paulo Raoni --- lib/Service/DocMdp/Validator.php | 18 ++- .../FilePolicy/DocMdpFilePolicyApplier.php | 59 +++++-- .../RequestSignatureControllerTest.php | 151 ++++++++++++++++++ .../php/Unit/Service/DocMdp/ValidatorTest.php | 52 +++++- .../DocMdpFilePolicyApplierTest.php | 54 +++++++ 5 files changed, 309 insertions(+), 25 deletions(-) diff --git a/lib/Service/DocMdp/Validator.php b/lib/Service/DocMdp/Validator.php index 7b7bc255a6..b66c440aea 100644 --- a/lib/Service/DocMdp/Validator.php +++ b/lib/Service/DocMdp/Validator.php @@ -14,6 +14,7 @@ use OCA\Libresign\Enum\ParticipantRole; use OCA\Libresign\Exception\LibresignException; use OCA\Libresign\Service\File\Pdf\PdfValidator; +use OCA\Libresign\Service\Policy\Provider\DocMdp\FilePolicy\DocMdpFilePolicyApplier; use OCP\AppFramework\Db\DoesNotExistException; use OCP\Files\IRootFolder; use OCP\IL10N; @@ -25,6 +26,7 @@ public function __construct( private ConfigService $configService, private PdfValidator $pdfValidator, private IRootFolder $root, + private DocMdpFilePolicyApplier $docMdpFilePolicyApplier, ) { } @@ -96,22 +98,22 @@ private function countSigningParticipants(array $signers): int { return $count; } + /** + * Signers are checked before the request is saved, so this is the level the + * request will certify with once saved, not the one it stores now. + */ private function getDocMdpLevel(array $data, ?File &$file): int { - $docMdpLevel = null; - if (!empty($data['uuid'])) { try { $file = $this->fileMapper->getByUuid($data['uuid']); - $docMdpLevel = $file->getDocmdpLevel(); } catch (DoesNotExistException) { - // File doesn't exist, use global configured level + // File doesn't exist, resolve the level of a new request } } - if ($docMdpLevel === null || $docMdpLevel === 0) { - return $this->configService->getLevel()->value; - } + $level = $this->docMdpFilePolicyApplier->resolveLevel($file, $data) + ?? $this->configService->getLevel(); - return $docMdpLevel; + return $level->value; } } diff --git a/lib/Service/Policy/Provider/DocMdp/FilePolicy/DocMdpFilePolicyApplier.php b/lib/Service/Policy/Provider/DocMdp/FilePolicy/DocMdpFilePolicyApplier.php index a9674dee64..519be42022 100644 --- a/lib/Service/Policy/Provider/DocMdp/FilePolicy/DocMdpFilePolicyApplier.php +++ b/lib/Service/Policy/Provider/DocMdp/FilePolicy/DocMdpFilePolicyApplier.php @@ -12,6 +12,7 @@ use OCA\Libresign\Enum\DocMdpLevel; use OCA\Libresign\Exception\LibresignException; use OCA\Libresign\Service\Policy\AbstractFilePolicyApplier; +use OCA\Libresign\Service\Policy\Model\ResolvedPolicy; use OCA\Libresign\Service\Policy\Provider\DocMdp\DocMdpPolicy; use OCP\AppFramework\Http; use OCP\IUser; @@ -20,13 +21,8 @@ class DocMdpFilePolicyApplier extends AbstractFilePolicyApplier { #[\Override] public function apply(FileEntity $file, array $data): void { - $user = ($data['userManager'] ?? null) instanceof IUser ? $data['userManager'] : null; - $requestOverrides = $this->getOverrides($data); - $activeContext = $this->extractActiveContext($data); - $resolvedPolicy = $activeContext === null - ? $this->policyService->resolveForUser(DocMdpPolicy::KEY, $user, $requestOverrides) - : $this->policyService->resolveForUser(DocMdpPolicy::KEY, $user, $requestOverrides, $activeContext); - $file->setDocmdpLevelEnum(DocMdpLevel::tryFrom((int)$resolvedPolicy->getEffectiveValue()) ?? DocMdpLevel::NOT_CERTIFIED); + $resolvedPolicy = $this->resolveForRequester($data); + $file->setDocmdpLevelEnum($this->toLevel($resolvedPolicy)); $this->storePolicySnapshot($file, $resolvedPolicy); } @@ -38,11 +34,8 @@ public function sync(FileEntity $file, array $data): void { return; } - $activeContext = $this->extractActiveContext($data); - $resolvedPolicy = $activeContext === null - ? $this->policyService->resolveForUserId(DocMdpPolicy::KEY, $file->getUserId(), $requestOverrides) - : $this->policyService->resolveForUserId(DocMdpPolicy::KEY, $file->getUserId(), $requestOverrides, $activeContext); - $newLevel = DocMdpLevel::tryFrom((int)$resolvedPolicy->getEffectiveValue()) ?? DocMdpLevel::NOT_CERTIFIED; + $resolvedPolicy = $this->resolveForFileOwner($file, $data); + $newLevel = $this->toLevel($resolvedPolicy); $metadataBeforeUpdate = $file->getMetadata() ?? []; $this->storePolicySnapshot($file, $resolvedPolicy); $metadataChanged = ($file->getMetadata() ?? []) !== $metadataBeforeUpdate; @@ -58,6 +51,48 @@ public function supportsCoreFlowSync(): bool { return true; } + /** + * The level a request certifies with once saved with $data, so its signers + * can be checked before it is: the stored one when frozen, otherwise the + * one apply() or sync() resolves. Null when a frozen request stores none, in + * which case the current level applies. + */ + public function resolveLevel(?FileEntity $file, array $data): ?DocMdpLevel { + if ($file === null) { + return $this->toLevel($this->resolveForRequester($data)); + } + + if (!$this->isPolicySnapshotFrozen($file, DocMdpPolicy::KEY)) { + return $this->toLevel($this->resolveForFileOwner($file, $data)); + } + + $policySnapshot = ($file->getMetadata() ?? [])['policy_snapshot'] ?? null; + return is_array($policySnapshot) && array_key_exists(DocMdpPolicy::KEY, $policySnapshot) + ? $file->getDocmdpLevelEnum() + : null; + } + + private function resolveForRequester(array $data): ResolvedPolicy { + $user = ($data['userManager'] ?? null) instanceof IUser ? $data['userManager'] : null; + $requestOverrides = $this->getOverrides($data); + $activeContext = $this->extractActiveContext($data); + return $activeContext === null + ? $this->policyService->resolveForUser(DocMdpPolicy::KEY, $user, $requestOverrides) + : $this->policyService->resolveForUser(DocMdpPolicy::KEY, $user, $requestOverrides, $activeContext); + } + + private function resolveForFileOwner(FileEntity $file, array $data): ResolvedPolicy { + $requestOverrides = $this->getOverrides($data); + $activeContext = $this->extractActiveContext($data); + return $activeContext === null + ? $this->policyService->resolveForUserId(DocMdpPolicy::KEY, $file->getUserId(), $requestOverrides) + : $this->policyService->resolveForUserId(DocMdpPolicy::KEY, $file->getUserId(), $requestOverrides, $activeContext); + } + + private function toLevel(ResolvedPolicy $resolvedPolicy): DocMdpLevel { + return DocMdpLevel::tryFrom((int)$resolvedPolicy->getEffectiveValue()) ?? DocMdpLevel::NOT_CERTIFIED; + } + /** @return array */ private function getOverrides(array $data): array { return $this->extractSinglePolicyOverride($data, DocMdpPolicy::KEY); diff --git a/tests/php/Api/Controller/RequestSignatureControllerTest.php b/tests/php/Api/Controller/RequestSignatureControllerTest.php index da47e1c18e..c1dafb74a4 100644 --- a/tests/php/Api/Controller/RequestSignatureControllerTest.php +++ b/tests/php/Api/Controller/RequestSignatureControllerTest.php @@ -16,6 +16,7 @@ use OCA\Libresign\Service\Policy\Provider\Footer\FooterPolicyValue; use OCA\Libresign\Service\RequestSignatureService; use OCA\Libresign\Tests\Api\ApiTestCase; +use OCP\IDBConnection; /** * @group DB @@ -499,4 +500,154 @@ public function testUuidPatchRefreshesDraftDocMdpBeforeFreezing(): void { $this->assertSame(DocMdpLevel::CERTIFIED_FORM_FILLING_AND_ANNOTATIONS->value, $sent->getMetadata()['policy_snapshot']['docmdp']['effectiveValue']); $this->assertArrayHasKey('policy_snapshot_frozen_at', $sent->getMetadata()); } + + /** + * @runInSeparateProcess + */ + public function testPostRejectsTwoSignersWhenTheRequestOverridesDocMdpToNoChanges(): void { + $this->createAccount('allowrequestsign', 'password', 'testGroup'); + $appConfig = $this->getMockAppConfig(); + $appConfig->setValueString(Application::APP_ID, 'groups_request_sign', '{"allowGroups":["admin","testGroup"],"denyGroups":[]}'); + $appConfig->setValueBool(Application::APP_ID, 'notifyUnsignedUser', false); + $appConfig->setValueInt(Application::APP_ID, 'docmdp_level', DocMdpLevel::CERTIFIED_FORM_FILLING->value); + $appConfig->setValueString(Application::APP_ID, 'docmdp_level.allow_child_override', '1'); + $policy = ['overrides' => ['docmdp' => DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED->value]]; + + $body = $this->postDocMdpRequest(['one@test.coop', 'two@test.coop'], 422, $policy); + $this->assertSame('This document has been certified with no changes allowed. You cannot add more signers to this document.', $body['ocs']['data']['message']); + $this->assertSame(0, $this->countFilesOf('allowrequestsign')); + } + + /** + * The override the previous test relies on is authorized: with a single + * signer it is stored as the request's level. + * + * @runInSeparateProcess + */ + public function testPostStoresTheDocMdpOverrideWithASingleSigner(): void { + $this->createAccount('allowrequestsign', 'password', 'testGroup'); + $appConfig = $this->getMockAppConfig(); + $appConfig->setValueString(Application::APP_ID, 'groups_request_sign', '{"allowGroups":["admin","testGroup"],"denyGroups":[]}'); + $appConfig->setValueBool(Application::APP_ID, 'notifyUnsignedUser', false); + $appConfig->setValueInt(Application::APP_ID, 'docmdp_level', DocMdpLevel::CERTIFIED_FORM_FILLING->value); + $appConfig->setValueString(Application::APP_ID, 'docmdp_level.allow_child_override', '1'); + + $body = $this->postDocMdpRequest(['one@test.coop'], 200, ['overrides' => ['docmdp' => DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED->value]]); + $file = \OCP\Server::get(FileMapper::class)->getByUuid($body['ocs']['data']['uuid']); + $this->assertSame(DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED, $file->getDocmdpLevelEnum()); + $this->assertSame( + ['effectiveValue' => DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED->value, 'sourceScope' => 'request'], + $file->getMetadata()['policy_snapshot']['docmdp'], + ); + } + + /** + * @runInSeparateProcess + */ + public function testPostAcceptsTwoSignersWhenDocMdpAllowsFormFilling(): void { + $this->createAccount('allowrequestsign', 'password', 'testGroup'); + $appConfig = $this->getMockAppConfig(); + $appConfig->setValueString(Application::APP_ID, 'groups_request_sign', '{"allowGroups":["admin","testGroup"],"denyGroups":[]}'); + $appConfig->setValueBool(Application::APP_ID, 'notifyUnsignedUser', false); + $appConfig->setValueInt(Application::APP_ID, 'docmdp_level', DocMdpLevel::CERTIFIED_FORM_FILLING->value); + + $body = $this->postDocMdpRequest(['one@test.coop', 'two@test.coop'], 200); + $file = \OCP\Server::get(FileMapper::class)->getByUuid($body['ocs']['data']['uuid']); + $this->assertSame(DocMdpLevel::CERTIFIED_FORM_FILLING, $file->getDocmdpLevelEnum()); + $this->assertSame(DocMdpLevel::CERTIFIED_FORM_FILLING->value, $file->getMetadata()['policy_snapshot']['docmdp']['effectiveValue']); + $this->assertCount(2, $this->getSignersFromFileId($file->getId())); + } + + /** + * @runInSeparateProcess + */ + public function testUuidPatchAddsSignersToAFrozenUncertifiedRequestAfterTheAdminCertifies(): void { + $user = $this->createAccount('allowrequestsign', 'password', 'testGroup'); + $appConfig = $this->getMockAppConfig(); + $appConfig->setValueString(Application::APP_ID, 'groups_request_sign', '{"allowGroups":["admin","testGroup"],"denyGroups":[]}'); + $appConfig->setValueBool(Application::APP_ID, 'notifyUnsignedUser', false); + $appConfig->setValueInt(Application::APP_ID, 'docmdp_level', DocMdpLevel::NOT_CERTIFIED->value); + $file = $this->requestSignFile([ + 'file' => ['base64' => base64_encode(file_get_contents(__DIR__ . '/../../fixtures/pdfs/small_valid.pdf'))], + 'name' => 'sent', + 'signers' => $this->buildEmailSigners(['one@test.coop']), + 'userManager' => $user, + ]); + $fileMapper = \OCP\Server::get(FileMapper::class); + $before = $fileMapper->getById($file->getId()); + $this->assertSame(DocMdpLevel::NOT_CERTIFIED->value, $before->getMetadata()['policy_snapshot']['docmdp']['effectiveValue']); + + $appConfig->setValueInt(Application::APP_ID, 'docmdp_level', DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED->value); + $this->request + ->withMethod('PATCH') + ->withPath('/api/v1/request-signature') + ->withRequestHeader([ + 'Authorization' => 'Basic ' . base64_encode('allowrequestsign:password'), + 'Content-Type' => 'application/json', + ]) + ->withRequestBody([ + 'uuid' => $file->getUuid(), + 'signers' => $this->buildEmailSigners(['one@test.coop', 'two@test.coop']), + ]) + ->expectStatus(200); + + $this->assertRequest(); + $after = $fileMapper->getById($file->getId()); + $this->assertSame(DocMdpLevel::NOT_CERTIFIED, $after->getDocmdpLevelEnum()); + $this->assertSame($before->getMetadata()['policy_snapshot']['docmdp'], $after->getMetadata()['policy_snapshot']['docmdp']); + $this->assertCount(2, $this->getSignersFromFileId($file->getId())); + } + + /** + * @param list $emails + * @param array|null $policy + * @return array + */ + private function postDocMdpRequest(array $emails, int $expectedStatus, ?array $policy = null): array { + $body = [ + 'name' => 'docmdp', + 'file' => ['base64' => base64_encode(file_get_contents(__DIR__ . '/../../fixtures/pdfs/small_valid.pdf'))], + 'signers' => $this->buildEmailSigners($emails), + ]; + if ($policy !== null) { + $body['policy'] = $policy; + } + $this->request + ->withMethod('POST') + ->withPath('/api/v1/request-signature') + ->withRequestHeader([ + 'Authorization' => 'Basic ' . base64_encode('allowrequestsign:password'), + 'Content-Type' => 'application/json', + ]) + ->withRequestBody($body) + ->expectStatus($expectedStatus); + + $response = $this->assertRequest(); + return json_decode($response->getBody()->getContents(), true); + } + + /** + * @param list $emails + * @return list> + */ + private function buildEmailSigners(array $emails): array { + return array_map(static fn (string $email): array => [ + 'identifyMethods' => [[ + 'method' => 'email', + 'requirement' => 'optional', + 'value' => $email, + ]], + ], $emails); + } + + private function countFilesOf(string $userId): int { + $qb = \OCP\Server::get(IDBConnection::class)->getQueryBuilder(); + $qb->select($qb->func()->count('*', 'total')) + ->from('libresign_file') + ->where($qb->expr()->eq('user_id', $qb->createNamedParameter($userId))); + $result = $qb->executeQuery(); + $total = (int)$result->fetchOne(); + $result->closeCursor(); + return $total; + } } diff --git a/tests/php/Unit/Service/DocMdp/ValidatorTest.php b/tests/php/Unit/Service/DocMdp/ValidatorTest.php index 4a7eb685c2..c1ff4ced2b 100644 --- a/tests/php/Unit/Service/DocMdp/ValidatorTest.php +++ b/tests/php/Unit/Service/DocMdp/ValidatorTest.php @@ -15,6 +15,7 @@ use OCA\Libresign\Service\DocMdp\ConfigService; use OCA\Libresign\Service\DocMdp\Validator; use OCA\Libresign\Service\File\Pdf\PdfValidator; +use OCA\Libresign\Service\Policy\Provider\DocMdp\FilePolicy\DocMdpFilePolicyApplier; use OCP\Files\IRootFolder; use OCP\IL10N; use PHPUnit\Framework\Attributes\DataProvider; @@ -27,6 +28,7 @@ final class ValidatorTest extends TestCase { private ConfigService&MockObject $configService; private PdfValidator&MockObject $pdfValidator; private IRootFolder&MockObject $root; + private DocMdpFilePolicyApplier&MockObject $docMdpFilePolicyApplier; protected function setUp(): void { $this->l10n = $this->createMock(IL10N::class); @@ -37,6 +39,7 @@ protected function setUp(): void { $this->configService = $this->createMock(ConfigService::class); $this->pdfValidator = $this->createMock(PdfValidator::class); $this->root = $this->createMock(IRootFolder::class); + $this->docMdpFilePolicyApplier = $this->createMock(DocMdpFilePolicyApplier::class); } private function createValidator(): Validator { @@ -46,6 +49,7 @@ private function createValidator(): Validator { $this->configService, $this->pdfValidator, $this->root, + $this->docMdpFilePolicyApplier, ); } @@ -64,6 +68,10 @@ public function testValidateSignersCountFromFile( ->method('getByUuid') ->with('uuid-1') ->willReturn($file); + $this->docMdpFilePolicyApplier + ->method('resolveLevel') + ->with($this->identicalTo($file)) + ->willReturn($docMdpLevel); $validator = $this->createValidator(); @@ -153,26 +161,58 @@ public function testValidateSignersCountSkipsWhenNoSigners(): void { $this->addToAssertionCount(1); } - public function testValidateSignersCountUsesConfigWhenUuidMissing(): void { + public function testValidateSignersCountUsesTheLevelResolvedForANewRequest(): void { + $data = [ + 'policyOverrides' => ['docmdp' => DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED->value], + 'signers' => [ + ['identifyMethods' => [['method' => 'email', 'value' => 'one@example.com']]], + ['identifyMethods' => [['method' => 'email', 'value' => 'two@example.com']]], + ], + ]; $this->fileMapper ->expects($this->never()) ->method('getByUuid'); + $this->docMdpFilePolicyApplier + ->expects($this->once()) + ->method('resolveLevel') + ->with(null, $data) + ->willReturn(DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED); $this->configService ->method('getLevel') - ->willReturn(DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED); + ->willReturn(DocMdpLevel::CERTIFIED_FORM_FILLING); $validator = $this->createValidator(); $this->expectException(LibresignException::class); - $validator->validateSignersCount([ + $validator->validateSignersCount($data); + } + + public function testValidateSignersCountKeepsAStoredUncertifiedLevel(): void { + $file = new File(); + $file->setDocmdpLevel(0); + + $this->fileMapper + ->method('getByUuid') + ->with('uuid-1') + ->willReturn($file); + $this->docMdpFilePolicyApplier + ->method('resolveLevel') + ->willReturn(DocMdpLevel::NOT_CERTIFIED); + $this->configService + ->method('getLevel') + ->willReturn(DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED); + + $this->createValidator()->validateSignersCount([ + 'uuid' => 'uuid-1', 'signers' => [ ['identifyMethods' => [['method' => 'email', 'value' => 'one@example.com']]], ['identifyMethods' => [['method' => 'email', 'value' => 'two@example.com']]], ], ]); + $this->addToAssertionCount(1); } - public function testValidateSignersCountFallsBackToConfigWhenDocMdpLevelZero(): void { + public function testValidateSignersCountUsesTheCurrentLevelWhenNoneIsStored(): void { $file = new File(); $file->setDocmdpLevel(0); $file->setSignedHash('hash'); @@ -181,6 +221,9 @@ public function testValidateSignersCountFallsBackToConfigWhenDocMdpLevelZero(): ->method('getByUuid') ->with('uuid-1') ->willReturn($file); + $this->docMdpFilePolicyApplier + ->method('resolveLevel') + ->willReturn(null); $this->configService ->method('getLevel') ->willReturn(DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED); @@ -192,7 +235,6 @@ public function testValidateSignersCountFallsBackToConfigWhenDocMdpLevelZero(): 'uuid' => 'uuid-1', 'signers' => [ ['identifyMethods' => [['method' => 'email', 'value' => 'one@example.com']]], - ['identifyMethods' => [['method' => 'email', 'value' => 'two@example.com']]], ], ]); } diff --git a/tests/php/Unit/Service/Policy/Provider/DocMdp/FilePolicy/DocMdpFilePolicyApplierTest.php b/tests/php/Unit/Service/Policy/Provider/DocMdp/FilePolicy/DocMdpFilePolicyApplierTest.php index 96851b2e2e..7beb94f528 100644 --- a/tests/php/Unit/Service/Policy/Provider/DocMdp/FilePolicy/DocMdpFilePolicyApplierTest.php +++ b/tests/php/Unit/Service/Policy/Provider/DocMdp/FilePolicy/DocMdpFilePolicyApplierTest.php @@ -187,6 +187,60 @@ public function testADraftStillResolvesTheSubmittedLevel(): void { $this->assertSame(DocMdpLevel::CERTIFIED_FORM_FILLING, $file->getDocmdpLevelEnum()); } + public function testResolveLevelOfANewRequestUsesTheSubmittedOverride(): void { + $this->policyService + ->expects($this->once()) + ->method('resolveForUser') + ->with(DocMdpPolicy::KEY, null, [DocMdpPolicy::KEY => 1], ['type' => 'group', 'id' => 'sales']) + ->willReturn($this->createResolvedPolicy(1, sourceScope: 'request')); + + $level = $this->getApplier()->resolveLevel(null, [ + 'policyOverrides' => [DocMdpPolicy::KEY => 1], + 'policyActiveContext' => ['type' => 'group', 'id' => 'sales'], + ]); + + $this->assertSame(DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED, $level); + } + + public function testResolveLevelOfADraftUsesTheLevelSyncWouldStore(): void { + $file = $this->createStoredRequest(FileStatus::DRAFT->value, []); + + $this->policyService + ->expects($this->once()) + ->method('resolveForUserId') + ->with(DocMdpPolicy::KEY, 'john', [DocMdpPolicy::KEY => 2]) + ->willReturn($this->createResolvedPolicy(2, sourceScope: 'request')); + + $level = $this->getApplier()->resolveLevel($file, ['policyOverrides' => [DocMdpPolicy::KEY => 2]]); + + $this->assertSame(DocMdpLevel::CERTIFIED_FORM_FILLING, $level); + } + + public function testResolveLevelOfAFrozenRequestIsTheStoredOneEvenWhenUncertified(): void { + $file = $this->createStoredRequest(FileStatus::ABLE_TO_SIGN->value, self::FROZEN + [ + 'policy_snapshot' => [ + DocMdpPolicy::KEY => ['effectiveValue' => DocMdpLevel::NOT_CERTIFIED->value, 'sourceScope' => 'system'], + ], + ]); + $file->setDocmdpLevelEnum(DocMdpLevel::NOT_CERTIFIED); + + $this->policyService->expects($this->never())->method('resolveForUserId'); + $this->policyService->expects($this->never())->method('resolveForUser'); + + $this->assertSame(DocMdpLevel::NOT_CERTIFIED, $this->getApplier()->resolveLevel($file, [])); + } + + public function testResolveLevelOfAFrozenRequestWithoutAStoredLevelLeavesItToTheCurrentOne(): void { + $file = new File(); + $file->setUserId('john'); + $file->setStatus(FileStatus::ABLE_TO_SIGN->value); + $file->setDocmdpLevelEnum(DocMdpLevel::NOT_CERTIFIED); + + $this->policyService->expects($this->never())->method('resolveForUserId'); + + $this->assertNull($this->getApplier()->resolveLevel($file, [])); + } + /** @param array $metadata */ private function createStoredRequest(int $status, array $metadata): File { $file = new File(); From c573796cf3d79d3835a89f3c668319a079d7cada Mon Sep 17 00:00:00 2001 From: Paulo Raoni Date: Tue, 10 Nov 2026 19:06:09 -0300 Subject: [PATCH 4/6] fix: do not carry the certification of a previous document into JSignPdf Signed-off-by: Paulo Raoni --- .../SignEngine/JSignPdf/JSignPdfHandler.php | 3 + .../JSignPdf/JSignPdfHandlerTest.php | 66 +++++++++++++++++++ 2 files changed, 69 insertions(+) diff --git a/lib/Handler/SignEngine/JSignPdf/JSignPdfHandler.php b/lib/Handler/SignEngine/JSignPdf/JSignPdfHandler.php index 9642ba0f60..54fddb616f 100644 --- a/lib/Handler/SignEngine/JSignPdf/JSignPdfHandler.php +++ b/lib/Handler/SignEngine/JSignPdf/JSignPdfHandler.php @@ -215,6 +215,9 @@ public function sign(): File { public function getSignedContent(): string { $normalizedPdf = $this->normalizePdfVersion($this->getInputFile()->getContent()); $hashAlgorithm = $this->hashAlgorithmResolver->forSignature($this->extractPdfVersion($normalizedPdf)); + // Options only accumulate on the params, so a reused handler would carry + // the certification level of the previous document into this one. + $this->jSignParam = null; $param = $this->getJSignParam(); $param->setCertificate($this->getCertificate()) ->setPdf($normalizedPdf) diff --git a/tests/php/Integration/Handler/SignEngine/JSignPdf/JSignPdfHandlerTest.php b/tests/php/Integration/Handler/SignEngine/JSignPdf/JSignPdfHandlerTest.php index a3b8d5c912..22c4be1a0e 100644 --- a/tests/php/Integration/Handler/SignEngine/JSignPdf/JSignPdfHandlerTest.php +++ b/tests/php/Integration/Handler/SignEngine/JSignPdf/JSignPdfHandlerTest.php @@ -796,6 +796,72 @@ public function testDocMdpSkippedWhenSignatureExists(): void { $this->assertStringNotContainsString("'-cl' '" . DocMdpLevel::CERTIFIED_FORM_FILLING_AND_ANNOTATIONS->name . "'", $paramsSeen[0]); } + #[DataProvider('providerAReusedHandlerDoesNotCertifyAnUncertifiedDocument')] + public function testAReusedHandlerDoesNotCertifyAnUncertifiedDocument(bool $firstVisible, bool $secondVisible): void { + if (self::$certificateEngineFactory === null || empty(self::$certificateContent)) { + $this->markTestSkipped('Certificate initialization failed'); + } + $this->appConfig->setValueString('libresign', 'java_path', __FILE__); + $this->appConfig->setValueString('libresign', 'jsignpdf_temp_path', sys_get_temp_dir()); + $this->appConfig->setValueString('libresign', 'jsignpdf_path', __DIR__); + $this->persistSignatureStampPolicy('', SignerElementsService::RENDER_MODE_DESCRIPTION_ONLY, 10, SignatureTextPolicyValue::DEFAULT_SIGNATURE_FONT_SIZE, 100, 100, 'deleted'); + $this->persistHashAlgorithmPolicy('SHA256'); + $this->signatureBackgroundService->method('getSignatureBackgroundType')->willReturn('deleted'); + + $reusedHandler = $this->getInstance(); + $certified = $this->signDocument($reusedHandler, DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED, $firstVisible); + $uncertified = $this->signDocument($reusedHandler, DocMdpLevel::NOT_CERTIFIED, $secondVisible); + $control = $this->signDocument($this->getInstance(), DocMdpLevel::NOT_CERTIFIED, $secondVisible); + + $this->assertStringContainsString("'-cl' '" . DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED->name . "'", $certified[0]); + $this->assertStringNotContainsString("'-cl'", $control[0]); + $this->assertStringNotContainsString("'-cl'", $uncertified[0]); + } + + public static function providerAReusedHandlerDoesNotCertifyAnUncertifiedDocument(): array { + return [ + 'invisible after invisible' => [false, false], + 'visible after invisible' => [false, true], + 'invisible after visible' => [true, false], + 'visible after visible' => [true, true], + ]; + } + + /** @return list The JSignPdf options of each signing call */ + private function signDocument(JSignPdfHandler $handler, DocMdpLevel $level, bool $visible): array { + $inputFile = $this->createMock(\OC\Files\Node\File::class); + $inputFile->method('getContent')->willReturn('%PDF-1.6'); + + $paramsSeen = []; + $jSignPdf = $this->createMock(JSignPDF::class); + $jSignPdf->method('setParam') + ->willReturnCallback(function (JSignParam $param) use (&$paramsSeen): void { + $paramsSeen[] = $param->getJSignParameters(); + }); + $jSignPdf->method('sign')->willReturn('content'); + + $docMdpConfigService = $this->createMock(DocMdpConfigService::class); + $docMdpConfigService->method('isEnabled')->willReturn(false); + $this->setDocMdpConfigService($handler, $docMdpConfigService); + $handler->setVisibleElements($visible ? [self::getElement([ + 'page' => 1, + 'llx' => 10, + 'lly' => 10, + 'urx' => 110, + 'ury' => 60, + ], realpath(__DIR__ . '/../../../../../../img/app-dark.png'))] : []); + $handler->setJSignPdf($jSignPdf); + $handler->setInputFile($inputFile); + $handler->setSignatureParams(['SignerCommonName' => 'Test User']); + $handler->setCertificate(self::$certificateContent); + $handler->setPassword('password'); + $handler->setDocMdpLevel($level); + $handler->getSignedContent(); + + $this->assertCount(1, $paramsSeen); + return $paramsSeen; + } + #[DataProvider('providerSignatureDimensions')] public function testMergeBackgroundWithSignatureFitsOversizedSignatureInsideStampBox(int $signatureWidth, int $signatureHeight): void { if (!extension_loaded('imagick')) { From 57130478402760ce88c96067d2dd3e6b5c6afc79 Mon Sep 17 00:00:00 2001 From: Paulo Raoni Date: Sat, 14 Nov 2026 21:50:17 -0300 Subject: [PATCH 5/6] test: check signers against frozen envelopes and reused files Signed-off-by: Paulo Raoni --- .../RequestSignatureControllerTest.php | 192 ++++++++++++++++++ 1 file changed, 192 insertions(+) diff --git a/tests/php/Api/Controller/RequestSignatureControllerTest.php b/tests/php/Api/Controller/RequestSignatureControllerTest.php index c1dafb74a4..8dd6b10506 100644 --- a/tests/php/Api/Controller/RequestSignatureControllerTest.php +++ b/tests/php/Api/Controller/RequestSignatureControllerTest.php @@ -9,14 +9,19 @@ namespace OCA\Libresign\Tests\Api\Controller; use OCA\Libresign\AppInfo\Application; +use OCA\Libresign\Db\File; use OCA\Libresign\Db\FileMapper; use OCA\Libresign\Db\SignRequestMapper; use OCA\Libresign\Enum\DocMdpLevel; use OCA\Libresign\Enum\FileStatus; use OCA\Libresign\Service\Policy\Provider\Footer\FooterPolicyValue; use OCA\Libresign\Service\RequestSignatureService; +use OCA\Libresign\Service\RequestSignatureWorkflowService; use OCA\Libresign\Tests\Api\ApiTestCase; use OCP\IDBConnection; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\PreserveGlobalState; +use PHPUnit\Framework\Attributes\RunInSeparateProcess; /** * @group DB @@ -598,6 +603,193 @@ public function testUuidPatchAddsSignersToAFrozenUncertifiedRequestAfterTheAdmin $this->assertCount(2, $this->getSignersFromFileId($file->getId())); } + /** @return array */ + public static function provideFrozenEnvelopeDocMdpCases(): array { + return [ + 'frozen override L1, current L3' => [2, 1, 3, 422], + 'frozen override L2, current L1' => [1, 2, 1, 200], + 'frozen L2, current L1' => [2, null, 1, 200], + 'frozen L0, current L1' => [0, null, 1, 200], + ]; + } + + #[RunInSeparateProcess] + #[PreserveGlobalState(false)] + #[DataProvider('provideFrozenEnvelopeDocMdpCases')] + public function testUuidPatchChecksEnvelopeSignersAgainstTheFrozenDocMdpOfItsDocuments( + int $initialLevel, + ?int $requestOverride, + int $currentLevel, + int $expectedStatus, + ): void { + [$envelope, $childrenBefore] = $this->createFrozenDocMdpEnvelope($initialLevel, $requestOverride); + + $this->getMockAppConfig()->setValueInt(Application::APP_ID, 'docmdp_level', $currentLevel); + $this->request + ->withMethod('PATCH') + ->withPath('/api/v1/request-signature') + ->withRequestHeader([ + 'Authorization' => 'Basic ' . base64_encode('allowrequestsign:password'), + 'Content-Type' => 'application/json', + ]) + ->withRequestBody([ + 'uuid' => $envelope->getUuid(), + 'signers' => $this->buildEmailSigners(['one@test.coop', 'two@test.coop']), + ]) + ->expectStatus($expectedStatus); + + $response = $this->assertRequest(); + $body = json_decode($response->getBody()->getContents(), true); + if ($expectedStatus === 422) { + $this->assertSame('This document has been certified with no changes allowed. You cannot add more signers to this document.', $body['ocs']['data']['message']); + } + $expectedSigners = $expectedStatus === 200 ? 2 : 1; + $fileMapper = \OCP\Server::get(FileMapper::class); + $this->assertCount($expectedSigners, $this->getSignersFromFileId($envelope->getId())); + foreach ($childrenBefore as $before) { + $after = $fileMapper->getById($before->getId()); + $this->assertSame($before->getDocmdpLevelEnum(), $after->getDocmdpLevelEnum()); + $this->assertSame($before->getMetadata()['policy_snapshot']['docmdp'], $after->getMetadata()['policy_snapshot']['docmdp']); + $this->assertCount($expectedSigners, $this->getSignersFromFileId($after->getId())); + } + } + + /** @return array */ + public static function provideFrozenNodeIdDocMdpCases(): array { + return [ + 'frozen L1, current L2' => [1, 2, 422], + 'frozen L0, current L1' => [0, 1, 200], + 'frozen L2, current L1' => [2, 1, 200], + ]; + } + + #[RunInSeparateProcess] + #[PreserveGlobalState(false)] + #[DataProvider('provideFrozenNodeIdDocMdpCases')] + public function testPostByNodeIdChecksSignersAgainstTheFrozenDocMdpOfTheReusedFile( + int $frozenLevel, + int $currentLevel, + int $expectedStatus, + ): void { + $before = $this->createFrozenDocMdpDraft($frozenLevel); + $filesBefore = $this->countFilesOf('allowrequestsign'); + + $this->getMockAppConfig()->setValueInt(Application::APP_ID, 'docmdp_level', $currentLevel); + $this->request + ->withMethod('POST') + ->withPath('/api/v1/request-signature') + ->withRequestHeader([ + 'Authorization' => 'Basic ' . base64_encode('allowrequestsign:password'), + 'Content-Type' => 'application/json', + ]) + ->withRequestBody([ + 'name' => 'reused', + 'file' => ['nodeId' => $before->getNodeId()], + 'signers' => $this->buildEmailSigners(['one@test.coop', 'two@test.coop']), + ]) + ->expectStatus($expectedStatus); + + $response = $this->assertRequest(); + $body = json_decode($response->getBody()->getContents(), true); + if ($expectedStatus === 422) { + $this->assertSame('This document has been certified with no changes allowed. You cannot add more signers to this document.', $body['ocs']['data']['message']); + } else { + $this->assertSame($before->getUuid(), $body['ocs']['data']['uuid']); + } + $fileMapper = \OCP\Server::get(FileMapper::class); + $after = $fileMapper->getByNodeId($before->getNodeId()); + $this->assertSame($before->getId(), $after->getId()); + $this->assertSame($filesBefore, $this->countFilesOf('allowrequestsign')); + $this->assertSame(DocMdpLevel::from($frozenLevel), $after->getDocmdpLevelEnum()); + $this->assertSame($before->getMetadata()['policy_snapshot']['docmdp'], $after->getMetadata()['policy_snapshot']['docmdp']); + $this->assertCount($expectedStatus === 200 ? 2 : 0, $this->getSignersFromFileId($after->getId())); + } + + /** + * Creates a two-document envelope for one signer and sends it, through the + * workflow behind the POST and PATCH endpoints. Creating it is the control + * proving the override, when any, was authorized. + * + * @return array{File, list} + */ + private function createFrozenDocMdpEnvelope(int $initialLevel, ?int $requestOverride): array { + $user = $this->createAccount('allowrequestsign', 'password', 'testGroup'); + $appConfig = $this->getMockAppConfig(); + $appConfig->setValueString(Application::APP_ID, 'groups_request_sign', '{"allowGroups":["admin","testGroup"],"denyGroups":[]}'); + $appConfig->setValueBool(Application::APP_ID, 'notifyUnsignedUser', false); + $appConfig->setValueInt(Application::APP_ID, 'docmdp_level', $initialLevel); + $policy = null; + if ($requestOverride !== null) { + $appConfig->setValueString(Application::APP_ID, 'docmdp_level.allow_child_override', '1'); + $policy = ['overrides' => ['docmdp' => $requestOverride]]; + } + $workflow = \OCP\Server::get(RequestSignatureWorkflowService::class); + $created = $workflow->createRequest( + $user, + [], + [ + ['name' => 'first.pdf', 'base64' => base64_encode(file_get_contents(__DIR__ . '/../../fixtures/pdfs/small_valid.pdf'))], + ['name' => 'second.pdf', 'base64' => base64_encode(file_get_contents(__DIR__ . '/../../fixtures/pdfs/small_valid.pdf'))], + ], + 'envelope', + [], + $this->buildEmailSigners(['one@test.coop']), + FileStatus::DRAFT->value, + policy: $policy, + ); + $uuid = $created['file']->getUuid(); + // A new envelope stays a draft until it is sent, which freezes its documents. + $workflow->updateExistingRequest($user, $this->buildEmailSigners(['one@test.coop']), $uuid, null, [], FileStatus::ABLE_TO_SIGN->value); + + $fileMapper = \OCP\Server::get(FileMapper::class); + $envelope = $fileMapper->getByUuid($uuid); + $this->assertTrue($envelope->isEnvelope()); + $this->assertSame(FileStatus::ABLE_TO_SIGN->value, $envelope->getStatus()); + $this->assertCount(1, $this->getSignersFromFileId($envelope->getId())); + $children = $fileMapper->getChildrenFiles($envelope->getId()); + $this->assertCount(2, $children); + $expected = [ + 'effectiveValue' => $requestOverride ?? $initialLevel, + 'sourceScope' => $requestOverride === null ? 'global' : 'request', + ]; + foreach ($children as $child) { + $this->assertSame(DocMdpLevel::from($requestOverride ?? $initialLevel), $child->getDocmdpLevelEnum()); + $this->assertSame($expected, $child->getMetadata()['policy_snapshot']['docmdp']); + $this->assertArrayHasKey('policy_snapshot_frozen_at', $child->getMetadata()); + $this->assertCount(1, $this->getSignersFromFileId($child->getId())); + } + return [$envelope, $children]; + } + + /** + * A request sent with one signer and then emptied returns to draft, but + * stays frozen, so it can be sent again by node id. + */ + private function createFrozenDocMdpDraft(int $frozenLevel): File { + $user = $this->createAccount('allowrequestsign', 'password', 'testGroup'); + $appConfig = $this->getMockAppConfig(); + $appConfig->setValueString(Application::APP_ID, 'groups_request_sign', '{"allowGroups":["admin","testGroup"],"denyGroups":[]}'); + $appConfig->setValueBool(Application::APP_ID, 'notifyUnsignedUser', false); + $appConfig->setValueInt(Application::APP_ID, 'docmdp_level', $frozenLevel); + $file = $this->requestSignFile([ + 'file' => ['base64' => base64_encode(file_get_contents(__DIR__ . '/../../fixtures/pdfs/small_valid.pdf'))], + 'name' => 'sent', + 'signers' => $this->buildEmailSigners(['one@test.coop']), + 'userManager' => $user, + ]); + foreach (\OCP\Server::get(SignRequestMapper::class)->getByFileId($file->getId()) as $signRequest) { + \OCP\Server::get(RequestSignatureService::class)->unassociateToUser($file->getId(), $signRequest->getId()); + } + + $draft = \OCP\Server::get(FileMapper::class)->getById($file->getId()); + $this->assertSame(FileStatus::DRAFT->value, $draft->getStatus()); + $this->assertArrayHasKey('policy_snapshot_frozen_at', $draft->getMetadata()); + $this->assertSame(DocMdpLevel::from($frozenLevel), $draft->getDocmdpLevelEnum()); + $this->assertSame($frozenLevel, $draft->getMetadata()['policy_snapshot']['docmdp']['effectiveValue']); + $this->assertSame([], $this->getSignersFromFileId($draft->getId())); + return $draft; + } + /** * @param list $emails * @param array|null $policy From 34678ff9cf18a6277e7afb38ba2ad4e6a19b5b2e Mon Sep 17 00:00:00 2001 From: Paulo Raoni Date: Sat, 14 Nov 2026 21:50:21 -0300 Subject: [PATCH 6/6] fix: check signers against the docmdp of envelope and reused documents An envelope's documents and a file reused by node id keep their frozen level, so signers are checked against it. Signed-off-by: Paulo Raoni --- lib/Service/DocMdp/Validator.php | 22 ++++++++--- lib/Service/RequestSignatureService.php | 52 ++++++++++++++++--------- 2 files changed, 50 insertions(+), 24 deletions(-) diff --git a/lib/Service/DocMdp/Validator.php b/lib/Service/DocMdp/Validator.php index b66c440aea..54ac495994 100644 --- a/lib/Service/DocMdp/Validator.php +++ b/lib/Service/DocMdp/Validator.php @@ -11,6 +11,7 @@ use OCA\Libresign\Db\File; use OCA\Libresign\Db\FileMapper; +use OCA\Libresign\Enum\DocMdpLevel; use OCA\Libresign\Enum\ParticipantRole; use OCA\Libresign\Exception\LibresignException; use OCA\Libresign\Service\File\Pdf\PdfValidator; @@ -100,7 +101,9 @@ private function countSigningParticipants(array $signers): int { /** * Signers are checked before the request is saved, so this is the level the - * request will certify with once saved, not the one it stores now. + * request will certify with once saved, not the one it stores now. An + * envelope is not certified itself: each of its documents is, with its own + * level, so one that allows no changes is enough to refuse more signers. */ private function getDocMdpLevel(array $data, ?File &$file): int { if (!empty($data['uuid'])) { @@ -111,9 +114,18 @@ private function getDocMdpLevel(array $data, ?File &$file): int { } } - $level = $this->docMdpFilePolicyApplier->resolveLevel($file, $data) - ?? $this->configService->getLevel(); - - return $level->value; + $documents = $file?->isEnvelope() ? $this->fileMapper->getChildrenFiles($file->getId()) : []; + if ($documents === []) { + $documents = [$file]; + } + $levels = array_map( + fn (?File $document): int => ($this->docMdpFilePolicyApplier->resolveLevel($document, $data) + ?? $this->configService->getLevel())->value, + $documents, + ); + + return in_array(DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED->value, $levels, true) + ? DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED->value + : $levels[0]; } } diff --git a/lib/Service/RequestSignatureService.php b/lib/Service/RequestSignatureService.php index 484bf57c52..81952acdb9 100644 --- a/lib/Service/RequestSignatureService.php +++ b/lib/Service/RequestSignatureService.php @@ -437,25 +437,10 @@ private function persistFile(array $data, ?Node $createdNode = null): array { } return $this->upgradeExistingFileStatus($file, $data['status'] ?? 0); } - $nodeId = null; - if (isset($data['file']['fileNode']) && $data['file']['fileNode'] instanceof Node) { - $nodeId = $data['file']['fileNode']->getId(); - } elseif (!empty($data['file']['nodeId'])) { - $nodeId = $data['file']['nodeId']; - } - if (!is_null($nodeId)) { - try { - $file = $this->fileMapper->getByNodeId($nodeId); - } catch (DoesNotExistException) { - $file = null; - } catch (MultipleObjectsReturnedException) { - // TRANSLATORS Error shown when a document cannot be updated because LibreSign has more than one record for it. - throw new LibresignException($this->l10n->t('This document is registered more than once, so it cannot be updated. Please contact your administrator.'), 422); - } - if ($file !== null) { - $this->filePolicyApplier->syncAllPolicies($file, $data); - return $this->upgradeExistingFileStatus($file, $data['status'] ?? 0); - } + $file = $this->getFileOfNode($data); + if ($file !== null) { + $this->filePolicyApplier->syncAllPolicies($file, $data); + return $this->upgradeExistingFileStatus($file, $data['status'] ?? 0); } $node = $createdNode ?? $this->fileService->getNodeFromData($data); @@ -514,6 +499,30 @@ private function upgradeExistingFileStatus(FileEntity $file, int $newStatus): ar ]; } + /** + * The file LibreSign already registered for the node a request points at, + * which the request then updates instead of creating another one. + */ + private function getFileOfNode(array $data): ?FileEntity { + $nodeId = null; + if (isset($data['file']['fileNode']) && $data['file']['fileNode'] instanceof Node) { + $nodeId = $data['file']['fileNode']->getId(); + } elseif (!empty($data['file']['nodeId'])) { + $nodeId = $data['file']['nodeId']; + } + if (is_null($nodeId)) { + return null; + } + try { + return $this->fileMapper->getByNodeId($nodeId); + } catch (DoesNotExistException) { + return null; + } catch (MultipleObjectsReturnedException) { + // TRANSLATORS Error shown when a document cannot be updated because LibreSign has more than one record for it. + throw new LibresignException($this->l10n->t('This document is registered more than once, so it cannot be updated. Please contact your administrator.'), 422); + } + } + private function getFileMetadata(\OCP\Files\Node $node): array { $metadata = []; if ($extension = strtolower($node->getExtension())) { @@ -703,6 +712,11 @@ public function validateSigners(array $data): void { throw new \Exception($this->l10n->t('Signers list needs to be an array')); } + // persistFile() reuses the file already registered for the node, so the + // signers are checked against that request, as on an update by uuid. + if (empty($data['uuid'])) { + $data['uuid'] = $this->getFileOfNode($data)?->getUuid(); + } $this->signerValidator->validateIdentifySigners($data); $normalizedSigners = $this->signerValidator->normalizeRequestSigners($data['signers']);