From 858eca8b2ee37443bac37e71f07dd694b88d973a Mon Sep 17 00:00:00 2001 From: no84by <50858621+no84by@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:53:43 +0000 Subject: [PATCH 1/2] fix: native engine must not certify an already signed document A certification (DocMDP) signature has to be the first signature of a document. With DocMDP enabled, the native engine certified every invisible signature, also on a document that was already signed or already certified, which invalidates the earlier signatures' DocMDP semantics. Certify only when the document has no signature yet, for invisible and visible signatures alike. Signed-off-by: no84by <50858621+no84by@users.noreply.github.com> --- lib/Handler/SignEngine/PhpNativeHandler.php | 16 ++-- .../PhpNativeSigningRegressionTest.php | 76 +++++++++++++++++-- .../SignEngine/PhpNativeHandlerTest.php | 25 +++--- 3 files changed, 90 insertions(+), 27 deletions(-) diff --git a/lib/Handler/SignEngine/PhpNativeHandler.php b/lib/Handler/SignEngine/PhpNativeHandler.php index 2a5a639446..aebd8bda3a 100644 --- a/lib/Handler/SignEngine/PhpNativeHandler.php +++ b/lib/Handler/SignEngine/PhpNativeHandler.php @@ -69,7 +69,7 @@ public function getSignedContent(): string { $visibleElements = $this->getVisibleElements(); $metadata = $this->buildMetadata(); $timestamp = $this->buildTimestampOptions(); - $certificationLevel = $this->resolveCertificationLevel(empty($visibleElements)); + $certificationLevel = $this->resolveCertificationLevel(); if (empty($visibleElements)) { return $service->sign(SignPdfRequestDto::fromRequired( @@ -248,19 +248,19 @@ private function getTsaSettings(): array { return $settings; } - private function resolveCertificationLevel(bool $noVisibleElements): ?CertificationLevel { + private function resolveCertificationLevel(): ?CertificationLevel { if (!$this->docMdpConfigService->isEnabled()) { 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); + // A certification signature must be the first signature of the + // document; with visible elements only the first element certifies. + if ($this->hasExistingSignatures($this->getInputFile()->getContent())) { + return null; } - return null; + // DocMDP values mirror CertificationLevel: 1=NoChanges, 2=FormFilling, 3=FormFillAndAnnotations + return CertificationLevel::fromInt($this->docMdpConfigService->getLevel()->value); } private function hasExistingSignatures(string $pdfContent): bool { diff --git a/tests/php/Integration/Handler/SignEngine/PhpNativeSigningRegressionTest.php b/tests/php/Integration/Handler/SignEngine/PhpNativeSigningRegressionTest.php index 322ca799b0..48eb5f8a66 100644 --- a/tests/php/Integration/Handler/SignEngine/PhpNativeSigningRegressionTest.php +++ b/tests/php/Integration/Handler/SignEngine/PhpNativeSigningRegressionTest.php @@ -14,10 +14,12 @@ use OCA\Libresign\Db\FileMapper; use OCA\Libresign\Db\SignRequest; use OCA\Libresign\Db\SignRequestMapper; +use OCA\Libresign\Enum\DocMdpLevel; use OCA\Libresign\Enum\FileStatus; use OCA\Libresign\Handler\CertificateEngine\CertificateEngineFactory; use OCA\Libresign\Handler\CertificateEngine\IEngineHandler; use OCA\Libresign\Handler\SignEngine\PhpNativeHandler; +use OCA\Libresign\Service\DocMdp\ConfigService as DocMdpConfigService; use OCA\Libresign\Service\Signature\PdfSignatureValidationService; use OCA\Libresign\Service\SigningAttemptGuard; use OCA\Libresign\Service\SignRequest\Error\SignRequestErrorReporter; @@ -47,6 +49,7 @@ final class PhpNativeSigningRegressionTest extends TestCase { private IL10N $l10n; private LoggerInterface $logger; private PhpNativeHandler $handler; + private CertificateEngineFactory $certificateEngineFactory; /** @var resource[] */ private array $cleanupResources = []; /** @var string[] */ @@ -79,17 +82,21 @@ public function setUp(): void { $certificateEngine->method('isSetupOk')->willReturn(true); $certificateEngine->method('validateRootCertificate')->willReturnCallback(static function (): void { }); - $certificateEngineFactory = $this->createMock(CertificateEngineFactory::class); - $certificateEngineFactory->method('getEngine')->willReturn($certificateEngine); + $this->certificateEngineFactory = $this->createMock(CertificateEngineFactory::class); + $this->certificateEngineFactory->method('getEngine')->willReturn($certificateEngine); - $this->handler = new PhpNativeHandler( + $this->handler = $this->createHandler(\OCP\Server::get(DocMdpConfigService::class)); + } + + private function createHandler(DocMdpConfigService $docMdpConfigService): PhpNativeHandler { + return new PhpNativeHandler( $this->appConfig, - \OCP\Server::get(\OCA\Libresign\Service\DocMdp\ConfigService::class), + $docMdpConfigService, \OCP\Server::get(\OCA\Libresign\Service\SignatureTextService::class), \OCP\Server::get(\OCA\Libresign\Service\SignatureStampPreview\SignatureStampAppearanceBuilder::class), \OCP\Server::get(\OCA\Libresign\Service\SignatureBackgroundService::class), \OCP\Server::get(\OCA\Libresign\Service\Policy\PolicyService::class), - $certificateEngineFactory, + $this->certificateEngineFactory, ); } @@ -174,6 +181,65 @@ public function testSecondNativeSignaturePreservesFirstSignature(): void { } } + /** + * A certification signature must be the first signature of a document. + * With DocMDP enabled, an invisible signature on a document that is + * already signed is an approval signature and both stay valid. + */ + public function testInvisibleSignatureDoesNotCertifyASignedDocument(): void { + $identity = $this->generatePkcs12('rsa'); + + $this->handler + ->setInputFile($this->fileNode($this->simplePdf())) + ->setCertificate($identity['pfx']) + ->setPassword($identity['password']); + $signedOnce = $this->handler->getSignedContent(); + $this->assertSame(0, $this->countDocMdpTransforms($signedOnce)); + + $signedTwice = $this->createHandler($this->docMdpEnabled()) + ->setInputFile($this->fileNode($signedOnce)) + ->setCertificate($identity['pfx']) + ->setPassword($identity['password']) + ->getSignedContent(); + + $this->assertSame(0, $this->countDocMdpTransforms($signedTwice)); + $this->assertCryptographicallyValid($signedTwice, 2); + } + + /** + * The first signature certifies, a later signature keeps that one + * certification and both signatures stay valid. + */ + public function testLaterSignatureKeepsTheCertificationOfTheFirstSignature(): void { + $identity = $this->generatePkcs12('rsa'); + $handler = $this->createHandler($this->docMdpEnabled()); + + $handler + ->setInputFile($this->fileNode($this->simplePdf())) + ->setCertificate($identity['pfx']) + ->setPassword($identity['password']); + $certified = $handler->getSignedContent(); + $this->assertSame(1, $this->countDocMdpTransforms($certified)); + + $signedTwice = $handler + ->setInputFile($this->fileNode($certified)) + ->getSignedContent(); + + $this->assertSame(1, $this->countDocMdpTransforms($signedTwice)); + $this->assertCryptographicallyValid($signedTwice, 2); + } + + private function docMdpEnabled(): DocMdpConfigService { + $docMdpConfigService = $this->createMock(DocMdpConfigService::class); + $docMdpConfigService->method('isEnabled')->willReturn(true); + $docMdpConfigService->method('getLevel')->willReturn(DocMdpLevel::CERTIFIED_FORM_FILLING); + return $docMdpConfigService; + } + + private function countDocMdpTransforms(string $pdf): int { + return (int)preg_match_all('/\/TransformMethod\s*\/DocMDP/', $pdf); + } + /** * An EC PKCS#12 credential exercises the ECDSA CMS path end to end: * LibreSign signs, and the real validation layer parses and verifies diff --git a/tests/php/Unit/Handler/SignEngine/PhpNativeHandlerTest.php b/tests/php/Unit/Handler/SignEngine/PhpNativeHandlerTest.php index 7849e08c7b..5ca2efd0b1 100644 --- a/tests/php/Unit/Handler/SignEngine/PhpNativeHandlerTest.php +++ b/tests/php/Unit/Handler/SignEngine/PhpNativeHandlerTest.php @@ -273,7 +273,6 @@ public static function providerTimestampHashAlgorithm(): array { #[DataProvider('providerResolveCertificationLevel')] public function testResolveCertificationLevel( bool $docMdpEnabled, - bool $noVisibleElements, string $pdfContent, bool $expectNull, ): void { @@ -285,13 +284,11 @@ public function testResolveCertificationLevel( $handler = $this->getHandler(); - if (!$noVisibleElements) { - $inputFile = $this->createMock(File::class); - $inputFile->method('getContent')->willReturn($pdfContent); - $handler->setInputFile($inputFile); - } + $inputFile = $this->createMock(File::class); + $inputFile->method('getContent')->willReturn($pdfContent); + $handler->setInputFile($inputFile); - $result = $this->callPrivateMethod($handler, 'resolveCertificationLevel', $noVisibleElements); + $result = $this->callPrivateMethod($handler, 'resolveCertificationLevel'); if ($expectNull) { $this->assertNull($result); @@ -303,16 +300,16 @@ public function testResolveCertificationLevel( public static function providerResolveCertificationLevel(): array { return [ 'DocMDP disabled always returns null' => [ - false, true, '', true, + false, '%PDF-1.4 startxref 0 %%EOF', true, ], - 'DocMDP enabled with no visible elements certifies' => [ - true, true, '', false, + 'DocMDP enabled, clean PDF certifies the first signature' => [ + true, '%PDF-1.4 startxref 0 %%EOF', false, ], - 'DocMDP enabled, visible elements, clean PDF certifies first signature' => [ - true, false, '%PDF-1.4 startxref 0 %%EOF', false, + 'DocMDP enabled, PDF already signed skips certification' => [ + true, '/ByteRange [0 0 0 0]', true, ], - 'DocMDP enabled, visible elements, PDF already signed skips certification' => [ - true, false, '/ByteRange [0 0 0 0]', true, + 'DocMDP enabled, PDF already certified skips certification' => [ + true, '/Perms << /DocMDP 5 0 R >>', true, ], ]; } From 38b0b7daaa350076dc9ea091df998c3506fb17d9 Mon Sep 17 00:00:00 2001 From: no84by <50858621+no84by@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:53:43 +0000 Subject: [PATCH 2/2] fix(jsignpdf): do not reuse the certification level of an earlier signature The JSignPdf parameters are kept on the handler between signatures and new parameters are merged into them. After a certifying signature, the next signature made by the same handler (for example on a document that is already signed) still carried "-cl" and certified again. When DocMDP is enabled, a signature that does not certify now sends "-cl NOT_CERTIFIED", which replaces any earlier level. Signed-off-by: no84by <50858621+no84by@users.noreply.github.com> --- .../SignEngine/JSignPdf/JSignPdfHandler.php | 9 +++- .../JSignPdf/JSignPdfHandlerTest.php | 49 ++++++++++++++++++- 2 files changed, 55 insertions(+), 3 deletions(-) diff --git a/lib/Handler/SignEngine/JSignPdf/JSignPdfHandler.php b/lib/Handler/SignEngine/JSignPdf/JSignPdfHandler.php index 5255ef4045..e4f87b1eb4 100644 --- a/lib/Handler/SignEngine/JSignPdf/JSignPdfHandler.php +++ b/lib/Handler/SignEngine/JSignPdf/JSignPdfHandler.php @@ -11,6 +11,7 @@ use Imagick; use ImagickPixel; use OCA\Libresign\AppInfo\Application; +use OCA\Libresign\Enum\DocMdpLevel; use OCA\Libresign\Exception\LibresignException; use OCA\Libresign\Handler\CertificateEngine\CertificateEngineFactory; use OCA\Libresign\Handler\SignEngine\Pkcs12Handler; @@ -221,8 +222,12 @@ public function getSignedContent(): string { $parameters = []; $certificationLevel = $this->getCertificationLevel(); - if ($certificationLevel !== null && !$this->getVisibleElements() && !$this->hasExistingSignatures($normalizedPdf)) { - $parameters['-cl'] = $certificationLevel; + if ($certificationLevel !== null) { + // The parameters are kept on this handler between signatures, so a + // signature that does not certify clears the level of an earlier one. + $parameters['-cl'] = !$this->getVisibleElements() && !$this->hasExistingSignatures($normalizedPdf) + ? $certificationLevel + : DocMdpLevel::NOT_CERTIFIED->name; } $parameters += $this->getTsaParameters(); $param->addJSignParameters($parameters); diff --git a/tests/php/Integration/Handler/SignEngine/JSignPdf/JSignPdfHandlerTest.php b/tests/php/Integration/Handler/SignEngine/JSignPdf/JSignPdfHandlerTest.php index c341d9726c..3eb6edbf70 100644 --- a/tests/php/Integration/Handler/SignEngine/JSignPdf/JSignPdfHandlerTest.php +++ b/tests/php/Integration/Handler/SignEngine/JSignPdf/JSignPdfHandlerTest.php @@ -1232,6 +1232,53 @@ public function testCertificationLevelWithoutVisibleElements(bool $docMdpEnabled $this->assertSame(self::expectedJSignParameters($expectedParameters), $paramsAsOptions); } + /** + * The handler keeps its parameters between signatures. A signature that + * does not certify must not reuse the level of an earlier one. + */ + public function testCertificationLevelIsNotReusedByTheNextSignature(): void { + if (self::$certificateEngineFactory === null || empty(self::$certificateContent)) { + $this->markTestSkipped('Certificate initialization failed'); + } + $this->resolvedPolicyValues[TsaPolicy::KEY] = TsaPolicyValue::encode(['url' => '']); + $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->persistHashAlgorithmPolicy('SHA256'); + + $unsignedFile = $this->createMock(\OC\Files\Node\File::class); + $unsignedFile->method('getContent')->willReturn('%PDF-1.6'); + $signedFile = $this->createMock(\OC\Files\Node\File::class); + $signedFile->method('getContent')->willReturn("%PDF-1.6\n/ByteRange [0 0 0 0]"); + + $paramsSeen = []; + $mock = $this->createMock(JSignPDF::class); + $mock->method('setParam') + ->willReturnCallback(function (JSignParam $param) use (&$paramsSeen): void { + $paramsSeen[] = $param->getJSignParameters(); + }); + $mock->method('sign')->willReturn('content'); + + $docMdpConfigService = $this->createMock(DocMdpConfigService::class); + $docMdpConfigService->method('isEnabled')->willReturn(true); + $docMdpConfigService->method('getLevel')->willReturn(DocMdpLevel::CERTIFIED_FORM_FILLING_AND_ANNOTATIONS); + + $jSignPdfHandler = $this->getInstance(); + $this->setDocMdpConfigService($jSignPdfHandler, $docMdpConfigService); + $jSignPdfHandler->setVisibleElements([]); + $jSignPdfHandler->setJSignPdf($mock); + $jSignPdfHandler->setCertificate(self::$certificateContent); + $jSignPdfHandler->setPassword('password'); + $jSignPdfHandler->setInputFile($unsignedFile); + $jSignPdfHandler->getSignedContent(); + $jSignPdfHandler->setInputFile($signedFile); + $jSignPdfHandler->getSignedContent(); + + $this->assertCount(2, $paramsSeen); + $this->assertStringContainsString("'-cl' '" . DocMdpLevel::CERTIFIED_FORM_FILLING_AND_ANNOTATIONS->name . "'", $paramsSeen[0]); + $this->assertStringNotContainsString(DocMdpLevel::CERTIFIED_FORM_FILLING_AND_ANNOTATIONS->name, $paramsSeen[1]); + } + public static function providerCertificationLevelWithoutVisibleElements(): array { $element = self::getElement([ 'page' => 1, @@ -1254,7 +1301,7 @@ public static function providerCertificationLevelWithoutVisibleElements(): array [], "%PDF-1.6\n/ByteRange [0 0 0 0]", $tsa, - ['--tsa-server-url' => 'https://tsa.example.test/tsr', '--tsa-hash-algorithm' => 'SHA-256', '--hash-algorithm' => 'SHA256'], + ['-cl' => DocMdpLevel::NOT_CERTIFIED->name, '--tsa-server-url' => 'https://tsa.example.test/tsr', '--tsa-hash-algorithm' => 'SHA-256', '--hash-algorithm' => 'SHA256'], ], 'no certification when DocMDP is disabled, even with a visible element on a signed PDF' => [ false,