diff --git a/appinfo/info.xml b/appinfo/info.xml index 9dc66f3f99..da381dbbf9 100644 --- a/appinfo/info.xml +++ b/appinfo/info.xml @@ -76,6 +76,9 @@ https://libresign.coop OCA\Libresign\Command\Crl\Stats OCA\Libresign\Command\Crl\Cleanup OCA\Libresign\Command\Crl\Revoke + OCA\Libresign\Command\OrganizationSeal\Add + OCA\Libresign\Command\OrganizationSeal\Delete + OCA\Libresign\Command\OrganizationSeal\ListCommand OCA\Libresign\Command\SignatureElements\Cleanup OCA\Libresign\Command\Developer\Reset OCA\Libresign\Command\Developer\SignSetup diff --git a/lib/Command/OrganizationSeal/Add.php b/lib/Command/OrganizationSeal/Add.php new file mode 100644 index 0000000000..ce8b69471e --- /dev/null +++ b/lib/Command/OrganizationSeal/Add.php @@ -0,0 +1,82 @@ +setName('libresign:organization-seal:add') + ->setDescription('Add an organization seal certificate (PKCS#12) applied after the last signature when a request asks for it') + ->addArgument('label', InputArgument::REQUIRED, 'Label shown to requesters') + ->addArgument('pfx', InputArgument::REQUIRED, 'Path to the PKCS#12 (.p12/.pfx) file') + ->addOption('password-from-env', null, InputOption::VALUE_NONE, 'Read the certificate password from the ' . self::PASSWORD_ENV . ' environment variable instead of asking for it'); + } + + #[\Override] + protected function execute(InputInterface $input, OutputInterface $output): int { + $path = (string)$input->getArgument('pfx'); + $pfx = is_file($path) && is_readable($path) ? file_get_contents($path) : false; + if ($pfx === false) { + $output->writeln('Cannot read the certificate file.'); + return self::FAILURE; + } + + $password = $this->getPassword($input, $output); + if ($password === null) { + $output->writeln('No certificate password given.'); + return self::FAILURE; + } + + try { + $seal = $this->sealStore->add((string)$input->getArgument('label'), $pfx, $password); + } catch (LibresignException $e) { + $output->writeln('' . $e->getMessage() . ''); + return self::FAILURE; + } + + $output->writeln(sprintf('Organization seal added with id %s (%s, valid until %s).', $seal['id'], $seal['subject'], $seal['validTo'])); + return self::SUCCESS; + } + + private function getPassword(InputInterface $input, OutputInterface $output): ?string { + if ($input->getOption('password-from-env')) { + $password = getenv(self::PASSWORD_ENV); + return is_string($password) ? $password : null; + } + + if (!$input->isInteractive()) { + return null; + } + + $question = (new Question('Certificate password: ')) + ->setHidden(true) + ->setHiddenFallback(false); + $password = (new QuestionHelper())->ask($input, $output, $question); + return is_string($password) ? $password : ''; + } +} diff --git a/lib/Command/OrganizationSeal/Delete.php b/lib/Command/OrganizationSeal/Delete.php new file mode 100644 index 0000000000..2e9a65b24a --- /dev/null +++ b/lib/Command/OrganizationSeal/Delete.php @@ -0,0 +1,42 @@ +setName('libresign:organization-seal:delete') + ->setDescription('Delete an organization seal certificate') + ->addArgument('id', InputArgument::REQUIRED, 'Id of the seal, see libresign:organization-seal:list'); + } + + #[\Override] + protected function execute(InputInterface $input, OutputInterface $output): int { + if (!$this->sealStore->delete((string)$input->getArgument('id'))) { + $output->writeln('Unknown organization seal.'); + return self::FAILURE; + } + + $output->writeln('Organization seal deleted.'); + return self::SUCCESS; + } +} diff --git a/lib/Command/OrganizationSeal/ListCommand.php b/lib/Command/OrganizationSeal/ListCommand.php new file mode 100644 index 0000000000..09f031464a --- /dev/null +++ b/lib/Command/OrganizationSeal/ListCommand.php @@ -0,0 +1,36 @@ +setName('libresign:organization-seal:list') + ->setDescription('List the organization seal certificates'); + } + + #[\Override] + protected function execute(InputInterface $input, OutputInterface $output): int { + $this->writeTableInOutputFormat($input, $output, $this->sealStore->list()); + return self::SUCCESS; + } +} 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/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/lib/ResponseDefinitions.php b/lib/ResponseDefinitions.php index 81fe277cdf..16abb1c2f0 100644 --- a/lib/ResponseDefinitions.php +++ b/lib/ResponseDefinitions.php @@ -551,6 +551,11 @@ * effectiveValue: string, * sourceScope: string, * } + * @psalm-type LibresignOrganizationSealResult = array{ + * status: 'sealed'|'failed', + * error?: string, + * at: string, + * } * @psalm-type LibresignPolicySnapshotLegalInformationEntry = array{ * effectiveValue: string, * sourceScope: string, @@ -628,6 +633,7 @@ * rejection_comment_mode?: LibresignPolicySnapshotSignatureRejectionCommentModeEntry, * rejection_visibility?: LibresignPolicySnapshotSignatureRejectionVisibilityEntry, * rejection_comment_visibility?: LibresignPolicySnapshotSignatureRejectionVisibilityEntry, + * organization_seals?: LibresignPolicySnapshotEntry, * } * @psalm-type LibresignValidateMetadata = array{ * extension: string, @@ -637,6 +643,7 @@ * policy_snapshot?: LibresignValidatePolicySnapshot, * pdfVersion?: string, * status_changed_at?: string, + * organization_seals?: array, * } * @psalm-type LibresignFileRuntimeMetadata = LibresignValidateMetadata|array * @psalm-type LibresignValidationPageResolution = array{ diff --git a/lib/Service/OrganizationSeal/OrganizationSealService.php b/lib/Service/OrganizationSeal/OrganizationSealService.php new file mode 100644 index 0000000000..eea9e967dd --- /dev/null +++ b/lib/Service/OrganizationSeal/OrganizationSealService.php @@ -0,0 +1,154 @@ +}> */ + private FrozenFilePolicySnapshotResolver $snapshotResolver; + + public function __construct( + FileMapper $fileMapper, + private OrganizationSealStore $sealStore, + private Pkcs12Handler $pkcs12Handler, + private DocMdpHandler $docMdpHandler, + private ITimeFactory $timeFactory, + private LoggerInterface $logger, + ) { + $this->snapshotResolver = new FrozenFilePolicySnapshotResolver( + $fileMapper, + OrganizationSealsPolicy::KEY, + static fn (mixed $value): array => ['seals' => OrganizationSealsPolicyValue::decode($value)], + ); + } + + /** + * The seal ids stored on the request when it was sent, in order. + * + * @return list + */ + public function getRequestedSeals(FileEntity $file): array { + return $this->snapshotResolver->findSnapshot($file)['seals'] ?? []; + } + + /** + * Seal the signed file with every seal chosen for the request. + * + * Never throws: the signatures are already in the file, so a seal that + * cannot be applied is recorded in the file metadata and the file stays + * as it is. The result of every seal is stored under + * metadata.organization_seals. + * + * @return bool whether the content of the signed file changed + */ + public function apply(FileEntity $libreSignFile, File $signedFile): bool { + $results = []; + $changed = false; + foreach ($this->getRequestedSeals($libreSignFile) as $id) { + $error = $this->applySeal($id, $signedFile, $libreSignFile); + $results[$id] = $error === null + ? ['status' => self::STATUS_SEALED] + : ['status' => self::STATUS_FAILED, 'error' => $error]; + $results[$id]['at'] = $this->timeFactory->getDateTime('now', new \DateTimeZone('UTC'))->format(\DateTimeInterface::ATOM); + $changed = $changed || $error === null; + } + + if ($results !== []) { + $metadata = $libreSignFile->getMetadata() ?? []; + $metadata[self::RESULT_METADATA_KEY] = $results; + $libreSignFile->setMetadata($metadata); + } + + return $changed; + } + + /** + * @return string|null the error code, null when the seal was applied + */ + private function applySeal(string $id, File $signedFile, FileEntity $libreSignFile): ?string { + $credentials = $this->sealStore->getCredentials($id); + if ($credentials === null) { + $this->logger->warning('Organization seal {id} is not configured, file {uuid} was not sealed with it', [ + 'id' => $id, + 'uuid' => $libreSignFile->getUuid(), + ]); + return self::ERROR_NOT_FOUND; + } + + try { + if (!$this->allowsAdditionalSignatures($signedFile)) { + $this->logger->warning('File {uuid} is certified with no changes allowed, organization seal {id} was not applied', [ + 'id' => $id, + 'uuid' => $libreSignFile->getUuid(), + ]); + return self::ERROR_DOCMDP; + } + + $engine = $this->getEngine(); + $engine->setInputFile($signedFile); + $engine->setCertificate($credentials['pfx']); + $engine->setPassword($credentials['password']); + $engine->setVisibleElements([]); + $engine->setSignatureParams(['SignerCommonName' => $credentials['subject']]); + $engine->sign(); + } catch (\Throwable $e) { + $this->logger->error('Failed to apply organization seal {id} to file {uuid}', [ + 'id' => $id, + 'uuid' => $libreSignFile->getUuid(), + 'exception' => $e, + ]); + return self::ERROR_SIGN; + } + + return null; + } + + /** + * A copy of the signing engine, so the state of the engine used by the + * current signer is not changed by the seal. + */ + protected function getEngine(): Pkcs12Handler { + return clone $this->pkcs12Handler; + } + + private function allowsAdditionalSignatures(File $signedFile): bool { + $resource = $signedFile->fopen('rb'); + if ($resource === false) { + throw new \RuntimeException('Unable to open the signed file for reading.'); + } + try { + return $this->docMdpHandler->allowsAdditionalSignatures($resource); + } finally { + fclose($resource); + } + } +} diff --git a/lib/Service/OrganizationSeal/OrganizationSealStore.php b/lib/Service/OrganizationSeal/OrganizationSealStore.php new file mode 100644 index 0000000000..4ccacf1e41 --- /dev/null +++ b/lib/Service/OrganizationSeal/OrganizationSealStore.php @@ -0,0 +1,196 @@ + + */ + public function list(): array { + $decoded = json_decode($this->appConfig->getValueString(Application::APP_ID, self::INDEX_APP_CONFIG_KEY, '[]', lazy: true), true); + if (!is_array($decoded)) { + return []; + } + + $seals = []; + foreach ($decoded as $seal) { + if (!is_array($seal) || !isset($seal['id'], $seal['label']) || !is_string($seal['id']) || !is_string($seal['label'])) { + continue; + } + $seals[] = [ + 'id' => $seal['id'], + 'label' => $seal['label'], + 'subject' => is_string($seal['subject'] ?? null) ? $seal['subject'] : '', + 'validTo' => is_string($seal['validTo'] ?? null) ? $seal['validTo'] : '', + ]; + } + return $seals; + } + + /** + * @return array{id: string, label: string, subject: string, validTo: string}|null + */ + public function get(string $id): ?array { + foreach ($this->list() as $seal) { + if ($seal['id'] === $id) { + return $seal; + } + } + return null; + } + + public function exists(string $id): bool { + return $this->get($id) !== null; + } + + /** + * @return array{id: string, label: string, subject: string, validTo: string} + * @throws LibresignException when the label or the certificate is not usable + */ + public function add(string $label, string $pfx, string $password): array { + $label = trim($label); + if ($label === '' || mb_strlen($label) > self::MAX_LABEL_LENGTH) { + throw new LibresignException(sprintf('The label must have between 1 and %d characters.', self::MAX_LABEL_LENGTH)); + } + foreach ($this->list() as $seal) { + if ($seal['label'] === $label) { + throw new LibresignException('A seal with this label already exists.'); + } + } + + $certificate = $this->readCertificate($pfx, $password); + + $seal = [ + 'id' => $this->secureRandom->generate(16, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS), + 'label' => $label, + 'subject' => $certificate['subject'], + 'validTo' => $certificate['validTo'], + ]; + + $this->appConfig->setValueString( + Application::APP_ID, + self::CREDENTIAL_APP_CONFIG_KEY_PREFIX . $seal['id'], + json_encode(['pfx' => base64_encode($pfx), 'password' => $password], JSON_THROW_ON_ERROR), + lazy: true, + sensitive: true, + ); + $this->saveIndex([...$this->list(), $seal]); + + return $seal; + } + + public function delete(string $id): bool { + $seals = $this->list(); + $remaining = array_values(array_filter($seals, static fn (array $seal): bool => $seal['id'] !== $id)); + if (count($remaining) === count($seals)) { + return false; + } + + $this->saveIndex($remaining); + $this->appConfig->deleteKey(Application::APP_ID, self::CREDENTIAL_APP_CONFIG_KEY_PREFIX . $id); + return true; + } + + /** + * @return array{pfx: string, password: string, subject: string}|null null when the seal is unknown + */ + public function getCredentials(string $id): ?array { + $seal = $this->get($id); + if ($seal === null) { + return null; + } + + $decoded = json_decode($this->appConfig->getValueString(Application::APP_ID, self::CREDENTIAL_APP_CONFIG_KEY_PREFIX . $id, '', lazy: true), true); + if (!is_array($decoded) || !is_string($decoded['pfx'] ?? null) || !is_string($decoded['password'] ?? null)) { + return null; + } + + $pfx = base64_decode($decoded['pfx'], true); + if ($pfx === false) { + return null; + } + + return ['pfx' => $pfx, 'password' => $decoded['password'], 'subject' => $seal['subject']]; + } + + /** + * @return array{subject: string, validTo: string} + * @throws LibresignException + */ + private function readCertificate(string $pfx, string $password): array { + if ($pfx === '' || strlen($pfx) > self::MAX_PFX_SIZE) { + throw new LibresignException('The certificate file is empty or too large.'); + } + + $certificates = []; + if (!openssl_pkcs12_read($pfx, $certificates, $password)) { + throw new LibresignException('The certificate file cannot be read with this password.'); + } + if (empty($certificates['cert']) || empty($certificates['pkey'])) { + throw new LibresignException('The certificate file must contain a certificate and its private key.'); + } + if (!openssl_x509_check_private_key($certificates['cert'], $certificates['pkey'])) { + throw new LibresignException('The private key does not match the certificate.'); + } + + $parsed = openssl_x509_parse($certificates['cert']); + if (!is_array($parsed) || !isset($parsed['validTo_time_t'])) { + throw new LibresignException('The certificate cannot be parsed.'); + } + if ((int)$parsed['validTo_time_t'] <= time()) { + throw new LibresignException('The certificate has expired.'); + } + + $commonName = $parsed['subject']['CN'] ?? ''; + if (is_array($commonName)) { + $commonName = (string)reset($commonName); + } + + return [ + 'subject' => (string)$commonName, + 'validTo' => (new \DateTimeImmutable('@' . (int)$parsed['validTo_time_t']))->format(\DateTimeInterface::ATOM), + ]; + } + + /** + * @param list $seals + */ + private function saveIndex(array $seals): void { + $this->appConfig->setValueString( + Application::APP_ID, + self::INDEX_APP_CONFIG_KEY, + json_encode($seals, JSON_THROW_ON_ERROR), + lazy: true, + ); + } +} diff --git a/lib/Service/Policy/Provider/OrganizationSeals/FilePolicy/OrganizationSealsFilePolicyApplier.php b/lib/Service/Policy/Provider/OrganizationSeals/FilePolicy/OrganizationSealsFilePolicyApplier.php new file mode 100644 index 0000000000..d5de1dec1d --- /dev/null +++ b/lib/Service/Policy/Provider/OrganizationSeals/FilePolicy/OrganizationSealsFilePolicyApplier.php @@ -0,0 +1,113 @@ +getOverrides($data); + $this->assertSealsExist($requestOverrides); + $activeContext = $this->extractActiveContext($data); + $resolvedPolicy = $activeContext === null + ? $this->policyService->resolveForUser(OrganizationSealsPolicy::KEY, $user, $requestOverrides) + : $this->policyService->resolveForUser(OrganizationSealsPolicy::KEY, $user, $requestOverrides, $activeContext); + $this->assertOverrideAllowed($requestOverrides, $resolvedPolicy); + $this->storePolicySnapshot($file, $resolvedPolicy); + } + + #[\Override] + public function sync(FileEntity $file, array $data): void { + $requestOverrides = $this->getOverrides($data); + if ($this->isPolicySnapshotFrozen($file, OrganizationSealsPolicy::KEY)) { + // A client may send the stored value along an unrelated update, which changes nothing. + if ($requestOverrides !== [] && $requestOverrides[OrganizationSealsPolicy::KEY] !== $this->getStoredValue($file)) { + throw new LibresignException( + // TRANSLATORS Error shown when someone tries to change the organization seals of a signature request after the signing flow already started. + $this->l10n?->t('The organization seals cannot be changed after the signing flow has started.') + ?? 'The organization seals cannot be changed after the signing flow has started.', + Http::STATUS_UNPROCESSABLE_ENTITY, + ); + } + return; + } + + $this->assertSealsExist($requestOverrides); + $activeContext = $this->extractActiveContext($data); + $resolvedPolicy = $activeContext === null + ? $this->policyService->resolveForUserId(OrganizationSealsPolicy::KEY, $file->getUserId(), $requestOverrides) + : $this->policyService->resolveForUserId(OrganizationSealsPolicy::KEY, $file->getUserId(), $requestOverrides, $activeContext); + $this->assertOverrideAllowed($requestOverrides, $resolvedPolicy); + $metadataBeforeUpdate = $file->getMetadata() ?? []; + $this->storePolicySnapshot($file, $resolvedPolicy); + + if (($file->getMetadata() ?? []) !== $metadataBeforeUpdate) { + $this->fileService->update($file); + } + } + + #[\Override] + public function supportsCoreFlowSync(): bool { + return true; + } + + public function setSealStore(OrganizationSealStore $sealStore): void { + $this->sealStore = $sealStore; + } + + /** @return array */ + private function getOverrides(array $data): array { + return $this->extractSinglePolicyOverride( + $data, + OrganizationSealsPolicy::KEY, + static fn (mixed $value): string => OrganizationSealsPolicyValue::encode($value), + ); + } + + /** @param array $requestOverrides */ + private function assertSealsExist(array $requestOverrides): void { + if ($requestOverrides === []) { + return; + } + + $sealStore = $this->sealStore ??= Server::get(OrganizationSealStore::class); + foreach (OrganizationSealsPolicyValue::decode($requestOverrides[OrganizationSealsPolicy::KEY]) as $id) { + if (!$sealStore->exists($id)) { + throw new LibresignException( + // TRANSLATORS Error shown when a signature request asks for an organization seal that the administrator has not configured. + $this->l10n?->t('Unknown organization seal.') ?? 'Unknown organization seal.', + Http::STATUS_UNPROCESSABLE_ENTITY, + ); + } + } + } + + private function getStoredValue(FileEntity $file): string { + $metadata = $file->getMetadata() ?? []; + return OrganizationSealsPolicyValue::encode($metadata['policy_snapshot'][OrganizationSealsPolicy::KEY]['effectiveValue'] ?? []); + } + + /** @param array $requestOverrides */ + private function assertOverrideAllowed(array $requestOverrides, ResolvedPolicy $resolvedPolicy): void { + $this->assertRequestOverrideAllowed($requestOverrides, $resolvedPolicy, 'Organization seals override is blocked by %s.'); + } +} diff --git a/lib/Service/Policy/Provider/OrganizationSeals/OrganizationSealsPolicy.php b/lib/Service/Policy/Provider/OrganizationSeals/OrganizationSealsPolicy.php new file mode 100644 index 0000000000..9ad61e61dc --- /dev/null +++ b/lib/Service/Policy/Provider/OrganizationSeals/OrganizationSealsPolicy.php @@ -0,0 +1,72 @@ + new PolicySpec( + key: self::KEY, + defaultSystemValue: OrganizationSealsPolicyValue::encode([]), + allowedValues: static fn (): array => [], + supportsRequestOverride: true, + requestLifecycle: PolicySpec::LIFECYCLE_REQUEST_SNAPSHOT, + normalizer: static fn (mixed $rawValue): string => OrganizationSealsPolicyValue::encode($rawValue), + validator: static function (mixed $value): void { + if (!is_string($value)) { + throw new \InvalidArgumentException('Invalid value for ' . self::KEY); + } + if (count(OrganizationSealsPolicyValue::decode($value)) > OrganizationSealsPolicyValue::MAX_SEALS) { + throw new \InvalidArgumentException('Too many seals for ' . self::KEY); + } + }, + persistenceValidator: function (mixed $value): void { + foreach (OrganizationSealsPolicyValue::decode($value) as $id) { + if (!$this->sealStore->exists($id)) { + throw new \InvalidArgumentException('Unknown seal in ' . self::KEY); + } + } + }, + appConfigKey: self::SYSTEM_APP_CONFIG_KEY, + supportsUserPreference: false, + backendOnly: true, + ), + default => throw new \InvalidArgumentException('Unknown policy key: ' . PolicyKeyNormalizer::normalize($policyKey)), + }; + } +} diff --git a/lib/Service/Policy/Provider/OrganizationSeals/OrganizationSealsPolicyValue.php b/lib/Service/Policy/Provider/OrganizationSeals/OrganizationSealsPolicyValue.php new file mode 100644 index 0000000000..16190972e5 --- /dev/null +++ b/lib/Service/Policy/Provider/OrganizationSeals/OrganizationSealsPolicyValue.php @@ -0,0 +1,50 @@ + */ + public static function decode(mixed $rawValue): array { + if (is_string($rawValue)) { + $trimmed = trim($rawValue); + if ($trimmed === '') { + return []; + } + $rawValue = json_decode($trimmed, true); + } + + if (!is_array($rawValue)) { + return []; + } + + $ids = []; + foreach ($rawValue as $id) { + if (!is_string($id)) { + continue; + } + $id = trim($id); + if ($id === '' || in_array($id, $ids, true)) { + continue; + } + $ids[] = $id; + } + + return $ids; + } + + public static function encode(mixed $rawValue): string { + return json_encode(self::decode($rawValue), JSON_THROW_ON_ERROR); + } +} diff --git a/lib/Service/Policy/Provider/PolicyProviders.php b/lib/Service/Policy/Provider/PolicyProviders.php index 4319d04f57..21e796eb52 100644 --- a/lib/Service/Policy/Provider/PolicyProviders.php +++ b/lib/Service/Policy/Provider/PolicyProviders.php @@ -24,6 +24,7 @@ use OCA\Libresign\Service\Policy\Provider\MailSenderStrategy\MailSenderStrategyPolicy; use OCA\Libresign\Service\Policy\Provider\NotificationDelivery\NotificationDeliveryModePolicy; use OCA\Libresign\Service\Policy\Provider\ObserverProfile\ObserverProfilePolicy; +use OCA\Libresign\Service\Policy\Provider\OrganizationSeals\OrganizationSealsPolicy; use OCA\Libresign\Service\Policy\Provider\Reminder\ReminderPolicy; use OCA\Libresign\Service\Policy\Provider\RequestSignGroups\RequestSignGroupsPolicy; use OCA\Libresign\Service\Policy\Provider\Signature\SignatureFlowPolicy; @@ -70,6 +71,7 @@ final class PolicyProviders { IdentificationDocumentsPolicy::KEY => IdentificationDocumentsPolicy::class, IdentifyMethodsPolicy::KEY => IdentifyMethodsPolicy::class, ObserverProfilePolicy::KEY => ObserverProfilePolicy::class, + OrganizationSealsPolicy::KEY => OrganizationSealsPolicy::class, SignatureTextPolicy::KEY => SignatureTextPolicy::class, SignerGeolocationPolicy::KEY => SignerGeolocationPolicy::class, SignerIpGeolocationPolicy::KEY => SignerIpGeolocationPolicy::class, diff --git a/lib/Service/SignFileService.php b/lib/Service/SignFileService.php index 05f653c6c4..17db89cfe4 100644 --- a/lib/Service/SignFileService.php +++ b/lib/Service/SignFileService.php @@ -45,6 +45,7 @@ use OCA\Libresign\Service\File\SigningWorkflowStatusResolver; use OCA\Libresign\Service\IdentifyMethod\IIdentifyMethod; use OCA\Libresign\Service\IdentifyMethod\SignatureMethod\IToken; +use OCA\Libresign\Service\OrganizationSeal\OrganizationSealService; use OCA\Libresign\Service\Policy\PolicyService; use OCA\Libresign\Service\Policy\Provider\CollectMetadata\CollectMetadataPolicy; use OCA\Libresign\Service\Policy\Provider\Footer\FooterPolicy; @@ -141,6 +142,7 @@ public function __construct( private NotificationDeliveryMapper $notificationDeliveries, private SigningWorkflowStatusResolver $signingWorkflowStatusResolver, private NativeWebhookEventPublisher $webhooks, + private OrganizationSealService $organizationSealService, ) { } @@ -514,6 +516,7 @@ public function signSingleFile(FileEntity $libreSignFile, SignRequestEntity $sig $hash = $this->computeHash($signedFile); $this->updateSignRequest($hash); + $hash = $this->applyOrganizationSealsIfCompleted($signedFile, $hash); $this->updateLibreSignFile($libreSignFile, $signedFile->getId(), $hash); $this->dispatchSignedEvent(); @@ -679,6 +682,7 @@ private function signSequentially(array $signRequests): ?DateTimeInterface { $envelopeLastSignedDate = $this->getEngine()->getLastSignedDate(); $this->updateSignRequest($hash); + $hash = $this->applyOrganizationSealsIfCompleted($signedFile, $hash); $this->updateLibreSignFile($this->libreSignFile, $signedFile->getId(), $hash); $this->dispatchSignedEvent(); @@ -907,6 +911,28 @@ protected function updateSignRequest(string $hash): void { ); } + /** + * Once the last signer has signed, apply the organization seals chosen + * for the request to the signed file. + * + * @return string the hash of the signed file to store + */ + protected function applyOrganizationSealsIfCompleted(File $signedFile, string $hash): string { + if ($this->organizationSealService->getRequestedSeals($this->libreSignFile) === []) { + return $hash; + } + + if ($this->evaluateStatusFromSigners($this->libreSignFile) !== FileStatus::SIGNED->value) { + return $hash; + } + + if (!$this->organizationSealService->apply($this->libreSignFile, $signedFile)) { + return $hash; + } + + return $this->computeHash($signedFile); + } + private function storeCertificateInfoInMetadata(array $certificateInfo): void { $metadata = $this->signRequest->getMetadata() ?? []; diff --git a/openapi-full.json b/openapi-full.json index c7c79e3450..96f2bd8e77 100644 --- a/openapi-full.json +++ b/openapi-full.json @@ -2218,6 +2218,28 @@ } } }, + "OrganizationSealResult": { + "type": "object", + "required": [ + "status", + "at" + ], + "properties": { + "status": { + "type": "string", + "enum": [ + "sealed", + "failed" + ] + }, + "error": { + "type": "string" + }, + "at": { + "type": "string" + } + } + }, "Pagination": { "type": "object", "required": [ @@ -3819,6 +3841,12 @@ }, "status_changed_at": { "type": "string" + }, + "organization_seals": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/OrganizationSealResult" + } } } }, @@ -3866,6 +3894,9 @@ }, "rejection_comment_visibility": { "$ref": "#/components/schemas/PolicySnapshotSignatureRejectionVisibilityEntry" + }, + "organization_seals": { + "$ref": "#/components/schemas/PolicySnapshotEntry" } } }, diff --git a/openapi.json b/openapi.json index 6b4e635e67..641f3e125f 100644 --- a/openapi.json +++ b/openapi.json @@ -1803,6 +1803,28 @@ } } }, + "OrganizationSealResult": { + "type": "object", + "required": [ + "status", + "at" + ], + "properties": { + "status": { + "type": "string", + "enum": [ + "sealed", + "failed" + ] + }, + "error": { + "type": "string" + }, + "at": { + "type": "string" + } + } + }, "Pagination": { "type": "object", "required": [ @@ -3277,6 +3299,12 @@ }, "status_changed_at": { "type": "string" + }, + "organization_seals": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/OrganizationSealResult" + } } } }, @@ -3324,6 +3352,9 @@ }, "rejection_comment_visibility": { "$ref": "#/components/schemas/PolicySnapshotSignatureRejectionVisibilityEntry" + }, + "organization_seals": { + "$ref": "#/components/schemas/PolicySnapshotEntry" } } }, diff --git a/src/types/openapi/openapi-full.ts b/src/types/openapi/openapi-full.ts index a37db13462..c412e8fc8b 100644 --- a/src/types/openapi/openapi-full.ts +++ b/src/types/openapi/openapi-full.ts @@ -1952,6 +1952,12 @@ export type components = { totalitems?: string; itemsperpage?: string; }; + OrganizationSealResult: { + /** @enum {string} */ + status: "sealed" | "failed"; + error?: string; + at: string; + }; Pagination: { /** Format: int64 */ total: number; @@ -2398,6 +2404,9 @@ export type components = { policy_snapshot?: components["schemas"]["ValidatePolicySnapshot"]; pdfVersion?: string; status_changed_at?: string; + organization_seals?: { + [key: string]: components["schemas"]["OrganizationSealResult"]; + }; }; ValidatePolicySnapshot: { docmdp?: components["schemas"]["PolicySnapshotNumericEntry"]; @@ -2414,6 +2423,7 @@ export type components = { rejection_comment_mode?: components["schemas"]["PolicySnapshotSignatureRejectionCommentModeEntry"]; rejection_visibility?: components["schemas"]["PolicySnapshotSignatureRejectionVisibilityEntry"]; rejection_comment_visibility?: components["schemas"]["PolicySnapshotSignatureRejectionVisibilityEntry"]; + organization_seals?: components["schemas"]["PolicySnapshotEntry"]; }; ValidatedChildFile: { /** Format: int64 */ diff --git a/src/types/openapi/openapi.ts b/src/types/openapi/openapi.ts index 9fd7aa8f47..d63aebb46c 100644 --- a/src/types/openapi/openapi.ts +++ b/src/types/openapi/openapi.ts @@ -1512,6 +1512,12 @@ export type components = { totalitems?: string; itemsperpage?: string; }; + OrganizationSealResult: { + /** @enum {string} */ + status: "sealed" | "failed"; + error?: string; + at: string; + }; Pagination: { /** Format: int64 */ total: number; @@ -1930,6 +1936,9 @@ export type components = { policy_snapshot?: components["schemas"]["ValidatePolicySnapshot"]; pdfVersion?: string; status_changed_at?: string; + organization_seals?: { + [key: string]: components["schemas"]["OrganizationSealResult"]; + }; }; ValidatePolicySnapshot: { docmdp?: components["schemas"]["PolicySnapshotNumericEntry"]; @@ -1946,6 +1955,7 @@ export type components = { rejection_comment_mode?: components["schemas"]["PolicySnapshotSignatureRejectionCommentModeEntry"]; rejection_visibility?: components["schemas"]["PolicySnapshotSignatureRejectionVisibilityEntry"]; rejection_comment_visibility?: components["schemas"]["PolicySnapshotSignatureRejectionVisibilityEntry"]; + organization_seals?: components["schemas"]["PolicySnapshotEntry"]; }; ValidatedChildFile: { /** Format: int64 */ 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, 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/Command/OrganizationSeal/AddTest.php b/tests/php/Unit/Command/OrganizationSeal/AddTest.php new file mode 100644 index 0000000000..90e41cc644 --- /dev/null +++ b/tests/php/Unit/Command/OrganizationSeal/AddTest.php @@ -0,0 +1,92 @@ +sealStore = $this->createMock(OrganizationSealStore::class); + $this->pfxPath = (string)tempnam(sys_get_temp_dir(), 'libresign-seal-'); + file_put_contents($this->pfxPath, 'pfx content'); + } + + public function tearDown(): void { + @unlink($this->pfxPath); + putenv(Add::PASSWORD_ENV); + parent::tearDown(); + } + + public function testAddsTheSealWithThePasswordFromTheEnvironment(): void { + putenv(Add::PASSWORD_ENV . '=env secret'); + $this->sealStore->expects($this->once()) + ->method('add') + ->with('Main seal', 'pfx content', 'env secret') + ->willReturn(['id' => 'abc', 'label' => 'Main seal', 'subject' => 'Example Seal', 'validTo' => '2030-01-01T00:00:00+00:00']); + + $tester = new CommandTester(new Add($this->sealStore)); + $status = $tester->execute(['label' => 'Main seal', 'pfx' => $this->pfxPath, '--password-from-env' => true]); + + $this->assertSame(Command::SUCCESS, $status); + $this->assertStringContainsString('abc', $tester->getDisplay()); + $this->assertStringNotContainsString('env secret', $tester->getDisplay()); + } + + public function testAsksForThePasswordWhenInteractive(): void { + $this->sealStore->expects($this->once()) + ->method('add') + ->with('Main seal', 'pfx content', 'typed secret') + ->willReturn(['id' => 'abc', 'label' => 'Main seal', 'subject' => '', 'validTo' => '']); + + $tester = new CommandTester(new Add($this->sealStore)); + $tester->setInputs(['typed secret']); + $status = $tester->execute(['label' => 'Main seal', 'pfx' => $this->pfxPath]); + + $this->assertSame(Command::SUCCESS, $status); + } + + public function testFailsWithoutPasswordWhenNotInteractive(): void { + $this->sealStore->expects($this->never())->method('add'); + + $tester = new CommandTester(new Add($this->sealStore)); + $status = $tester->execute(['label' => 'Main seal', 'pfx' => $this->pfxPath], ['interactive' => false]); + + $this->assertSame(Command::FAILURE, $status); + } + + public function testFailsWhenTheFileCannotBeRead(): void { + $this->sealStore->expects($this->never())->method('add'); + + $tester = new CommandTester(new Add($this->sealStore)); + $status = $tester->execute(['label' => 'Main seal', 'pfx' => $this->pfxPath . '-missing', '--password-from-env' => true]); + + $this->assertSame(Command::FAILURE, $status); + } + + public function testReportsAnUnusableCertificate(): void { + putenv(Add::PASSWORD_ENV . '=wrong'); + $this->sealStore->method('add')->willThrowException(new LibresignException('The certificate file cannot be read with this password.')); + + $tester = new CommandTester(new Add($this->sealStore)); + $status = $tester->execute(['label' => 'Main seal', 'pfx' => $this->pfxPath, '--password-from-env' => true]); + + $this->assertSame(Command::FAILURE, $status); + $this->assertStringContainsString('cannot be read with this password', $tester->getDisplay()); + } +} 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, ], ]; } diff --git a/tests/php/Unit/Service/OrganizationSeal/OrganizationSealServiceTest.php b/tests/php/Unit/Service/OrganizationSeal/OrganizationSealServiceTest.php new file mode 100644 index 0000000000..00270d6aed --- /dev/null +++ b/tests/php/Unit/Service/OrganizationSeal/OrganizationSealServiceTest.php @@ -0,0 +1,194 @@ + */ + private array $engines = []; + /** @var list */ + private array $signedAs = []; + + public function setUp(): void { + parent::setUp(); + $this->fileMapper = $this->createMock(FileMapper::class); + $this->sealStore = $this->createMock(OrganizationSealStore::class); + $this->docMdpHandler = $this->createMock(DocMdpHandler::class); + $this->timeFactory = $this->createMock(ITimeFactory::class); + $this->timeFactory->method('getDateTime')->willReturn(new \DateTime('2026-01-01T00:00:00Z')); + $this->logger = $this->createMock(LoggerInterface::class); + } + + private function getService(): OrganizationSealService&MockObject { + $service = $this->getMockBuilder(OrganizationSealService::class) + ->setConstructorArgs([ + $this->fileMapper, + $this->sealStore, + $this->createMock(Pkcs12Handler::class), + $this->docMdpHandler, + $this->timeFactory, + $this->logger, + ]) + ->onlyMethods(['getEngine']) + ->getMock(); + $service->method('getEngine')->willReturnCallback(function (): Pkcs12Handler { + $engine = $this->createMock(Pkcs12Handler::class); + $engine->expects($this->once())->method('sign'); + $engine->method('setSignatureParams')->willReturnCallback(function (array $params) use ($engine): Pkcs12Handler { + $this->signedAs[] = $params['SignerCommonName']; + return $engine; + }); + $this->engines[] = $engine; + return $engine; + }); + return $service; + } + + private function requestWithSeals(array $seals): FileEntity { + $file = new FileEntity(); + $file->setUuid('file-uuid'); + $file->setMetadata([ + 'policy_snapshot' => [ + OrganizationSealsPolicy::KEY => [ + 'effectiveValue' => json_encode($seals), + 'sourceScope' => 'request', + ], + ], + ]); + return $file; + } + + private function signedFile(): File&MockObject { + $signedFile = $this->createMock(File::class); + $signedFile->method('fopen')->willReturnCallback(static fn () => fopen('php://memory', 'r+')); + return $signedFile; + } + + private function credentials(string $subject): array { + return ['pfx' => 'pfx-of-' . $subject, 'password' => 'password-of-' . $subject, 'subject' => $subject]; + } + + public function testRequestWithoutSealsIsLeftUnchanged(): void { + $file = new FileEntity(); + $file->setMetadata(['extension' => 'pdf']); + $this->sealStore->expects($this->never())->method('getCredentials'); + + $service = $this->getService(); + $this->assertSame([], $service->getRequestedSeals($file)); + $this->assertFalse($service->apply($file, $this->signedFile())); + $this->assertSame(['extension' => 'pdf'], $file->getMetadata()); + $this->assertSame([], $this->engines); + } + + public function testEverySealIsAppliedInOrder(): void { + $file = $this->requestWithSeals(['first', 'second']); + $signedFile = $this->signedFile(); + $this->sealStore->method('getCredentials')->willReturnCallback(fn (string $id): array => $this->credentials($id . ' seal')); + $this->docMdpHandler->method('allowsAdditionalSignatures')->willReturn(true); + + $this->assertTrue($this->getService()->apply($file, $signedFile)); + + $this->assertSame(['first seal', 'second seal'], $this->signedAs); + $this->assertSame([ + 'first' => ['status' => 'sealed', 'at' => '2026-01-01T00:00:00+00:00'], + 'second' => ['status' => 'sealed', 'at' => '2026-01-01T00:00:00+00:00'], + ], $file->getMetadata()[OrganizationSealService::RESULT_METADATA_KEY]); + } + + public function testTheSealEngineGetsTheSealCredentialsWithoutVisibleElements(): void { + $file = $this->requestWithSeals(['first']); + $signedFile = $this->signedFile(); + $this->sealStore->method('getCredentials')->willReturn($this->credentials('Example Seal')); + $this->docMdpHandler->method('allowsAdditionalSignatures')->willReturn(true); + + $engine = $this->createMock(Pkcs12Handler::class); + $engine->expects($this->once())->method('setInputFile')->with($this->identicalTo($signedFile))->willReturnSelf(); + $engine->expects($this->once())->method('setCertificate')->with('pfx-of-Example Seal')->willReturnSelf(); + $engine->expects($this->once())->method('setPassword')->with('password-of-Example Seal')->willReturnSelf(); + $engine->expects($this->once())->method('setVisibleElements')->with([])->willReturnSelf(); + $engine->expects($this->once())->method('setSignatureParams')->with(['SignerCommonName' => 'Example Seal'])->willReturnSelf(); + $engine->expects($this->once())->method('sign')->willReturn($signedFile); + + $service = $this->getMockBuilder(OrganizationSealService::class) + ->setConstructorArgs([$this->fileMapper, $this->sealStore, $engine, $this->docMdpHandler, $this->timeFactory, $this->logger]) + ->onlyMethods(['getEngine']) + ->getMock(); + $service->method('getEngine')->willReturn($engine); + + $this->assertTrue($service->apply($file, $signedFile)); + } + + public function testFailuresAreRecordedAndTheOtherSealsStillApplied(): void { + $file = $this->requestWithSeals(['missing', 'broken', 'good']); + $this->sealStore->method('getCredentials')->willReturnCallback(fn (string $id): ?array => $id === 'missing' ? null : $this->credentials($id)); + $this->docMdpHandler->method('allowsAdditionalSignatures')->willReturn(true); + $this->logger->expects($this->once())->method('warning'); + $this->logger->expects($this->once())->method('error'); + + $service = $this->getMockBuilder(OrganizationSealService::class) + ->setConstructorArgs([$this->fileMapper, $this->sealStore, $this->createMock(Pkcs12Handler::class), $this->docMdpHandler, $this->timeFactory, $this->logger]) + ->onlyMethods(['getEngine']) + ->getMock(); + $broken = $this->createMock(Pkcs12Handler::class); + $broken->method('sign')->willThrowException(new \RuntimeException('engine failure')); + $good = $this->createMock(Pkcs12Handler::class); + $good->expects($this->once())->method('sign'); + $service->method('getEngine')->willReturnOnConsecutiveCalls($broken, $good); + + $this->assertTrue($service->apply($file, $this->signedFile())); + + $results = $file->getMetadata()[OrganizationSealService::RESULT_METADATA_KEY]; + $this->assertSame(['status' => 'failed', 'error' => OrganizationSealService::ERROR_NOT_FOUND], array_diff_key($results['missing'], ['at' => true])); + $this->assertSame(['status' => 'failed', 'error' => OrganizationSealService::ERROR_SIGN], array_diff_key($results['broken'], ['at' => true])); + $this->assertSame('sealed', $results['good']['status']); + } + + public function testNothingIsSignedWhenTheDocumentForbidsChanges(): void { + $file = $this->requestWithSeals(['first']); + $this->sealStore->method('getCredentials')->willReturn($this->credentials('Example Seal')); + $this->docMdpHandler->method('allowsAdditionalSignatures')->willReturn(false); + + $service = $this->getService(); + $this->assertFalse($service->apply($file, $this->signedFile())); + + $this->assertSame([], $this->engines); + $this->assertSame( + OrganizationSealService::ERROR_DOCMDP, + $file->getMetadata()[OrganizationSealService::RESULT_METADATA_KEY]['first']['error'], + ); + } + + public function testDocumentOfAnEnvelopeUsesTheSealsOfTheEnvelope(): void { + $envelope = $this->requestWithSeals(['first']); + $envelope->setId(10); + $envelope->setNodeType('envelope'); + $this->fileMapper->method('getById')->with(10)->willReturn($envelope); + $child = new FileEntity(); + $child->setParentFileId(10); + + $this->assertSame(['first'], $this->getService()->getRequestedSeals($child)); + } +} diff --git a/tests/php/Unit/Service/OrganizationSeal/OrganizationSealStoreTest.php b/tests/php/Unit/Service/OrganizationSeal/OrganizationSealStoreTest.php new file mode 100644 index 0000000000..f429cf1e1e --- /dev/null +++ b/tests/php/Unit/Service/OrganizationSeal/OrganizationSealStoreTest.php @@ -0,0 +1,139 @@ +appConfig = $this->getMockAppConfigWithReset(); + } + + private function getStore(?IAppConfig $appConfig = null): OrganizationSealStore { + $secureRandom = $this->createMock(ISecureRandom::class); + $secureRandom->method('generate')->willReturnCallback(fn (): string => 'seal' . ++$this->idCounter); + return new OrganizationSealStore($appConfig ?? $this->appConfig, $secureRandom); + } + + public function testAddListsTheSealWithoutItsCredentials(): void { + $credential = self::generatePkcs12('Example Seal', 'secret'); + $store = $this->getStore(); + + $seal = $store->add(' Main seal ', $credential['pfx'], 'secret'); + + $this->assertSame('seal1', $seal['id']); + $this->assertSame('Main seal', $seal['label']); + $this->assertSame('Example Seal', $seal['subject']); + $this->assertNotSame('', $seal['validTo']); + $this->assertSame([$seal], $store->list()); + $index = $this->appConfig->getValueString(Application::APP_ID, OrganizationSealStore::INDEX_APP_CONFIG_KEY); + $this->assertStringNotContainsString('secret', $index); + $this->assertStringNotContainsString(base64_encode($credential['pfx']), $index); + } + + public function testGetCredentialsReturnsTheStoredCertificate(): void { + $credential = self::generatePkcs12('Example Seal', 'secret'); + $store = $this->getStore(); + $seal = $store->add('Main seal', $credential['pfx'], 'secret'); + + $this->assertSame( + ['pfx' => $credential['pfx'], 'password' => 'secret', 'subject' => 'Example Seal'], + $store->getCredentials($seal['id']), + ); + $this->assertNull($store->getCredentials('unknown')); + } + + public function testCredentialsAreStoredAsSensitiveLazyValue(): void { + $credential = self::generatePkcs12('Example Seal', 'secret'); + $writes = []; + $appConfig = $this->createMock(IAppConfig::class); + $appConfig->method('getValueString')->willReturn('[]'); + $appConfig->method('setValueString')->willReturnCallback( + function (string $app, string $key, string $value, bool $lazy = false, bool $sensitive = false) use (&$writes): bool { + $writes[$key] = ['lazy' => $lazy, 'sensitive' => $sensitive]; + return true; + } + ); + + $this->getStore($appConfig)->add('Main seal', $credential['pfx'], 'secret'); + + $this->assertSame(['lazy' => true, 'sensitive' => true], $writes[OrganizationSealStore::CREDENTIAL_APP_CONFIG_KEY_PREFIX . 'seal1']); + $this->assertSame(['lazy' => true, 'sensitive' => false], $writes[OrganizationSealStore::INDEX_APP_CONFIG_KEY]); + } + + public function testDeleteRemovesTheSealAndItsCredentials(): void { + $store = $this->getStore(); + $first = $store->add('First', self::generatePkcs12('First Seal', 'one')['pfx'], 'one'); + $second = $store->add('Second', self::generatePkcs12('Second Seal', 'two')['pfx'], 'two'); + + $this->assertTrue($store->delete($first['id'])); + $this->assertFalse($store->delete($first['id'])); + + $this->assertSame([$second], $store->list()); + $this->assertFalse($this->appConfig->hasKey(Application::APP_ID, OrganizationSealStore::CREDENTIAL_APP_CONFIG_KEY_PREFIX . $first['id'])); + $this->assertTrue($store->exists($second['id'])); + } + + public function testAddRejectsADuplicateLabel(): void { + $store = $this->getStore(); + $store->add('Main seal', self::generatePkcs12('Example Seal', 'secret')['pfx'], 'secret'); + + $this->expectException(LibresignException::class); + $store->add('Main seal', self::generatePkcs12('Other Seal', 'secret')['pfx'], 'secret'); + } + + #[DataProvider('providerUnusableCertificate')] + public function testAddRejectsAnUnusableCertificate(string $label, string $pfx, string $password): void { + $store = $this->getStore(); + + try { + $store->add($label, $pfx, $password); + $this->fail('The seal must be refused'); + } catch (LibresignException) { + } + + $this->assertSame([], $store->list()); + } + + public static function providerUnusableCertificate(): array { + $valid = self::generatePkcs12('Example Seal', 'secret'); + $expired = self::generatePkcs12('Expired Seal', 'secret', -1); + return [ + 'empty label' => [' ', $valid['pfx'], 'secret'], + 'label too long' => [str_repeat('a', OrganizationSealStore::MAX_LABEL_LENGTH + 1), $valid['pfx'], 'secret'], + 'wrong password' => ['Main seal', $valid['pfx'], 'wrong'], + 'not a PKCS#12 file' => ['Main seal', 'not a certificate', 'secret'], + 'empty file' => ['Main seal', '', 'secret'], + 'expired certificate' => ['Main seal', $expired['pfx'], 'secret'], + ]; + } + + /** + * A throwaway self-signed credential. + * + * @return array{pfx: string} + */ + public static function generatePkcs12(string $commonName, string $password, int $days = 1): array { + $key = openssl_pkey_new(['private_key_type' => OPENSSL_KEYTYPE_EC, 'curve_name' => 'prime256v1']); + $csr = openssl_csr_new(['commonName' => $commonName], $key, ['digest_alg' => 'sha256']); + $certificate = openssl_csr_sign($csr, null, $key, $days, ['digest_alg' => 'sha256'], random_int(1, 0x7fffffff)); + openssl_pkcs12_export($certificate, $pfx, $key, $password); + return ['pfx' => $pfx]; + } +} diff --git a/tests/php/Unit/Service/Policy/FilePolicyApplierTest.php b/tests/php/Unit/Service/Policy/FilePolicyApplierTest.php index 177357d4f1..616ebfe7c9 100644 --- a/tests/php/Unit/Service/Policy/FilePolicyApplierTest.php +++ b/tests/php/Unit/Service/Policy/FilePolicyApplierTest.php @@ -23,6 +23,7 @@ use OCA\Libresign\Service\Policy\Provider\IdentifyMethods\IdentifyMethodsPolicy; use OCA\Libresign\Service\Policy\Provider\LegalInformation\LegalInformationPolicy; use OCA\Libresign\Service\Policy\Provider\ObserverProfile\ObserverProfilePolicy; +use OCA\Libresign\Service\Policy\Provider\OrganizationSeals\OrganizationSealsPolicy; use OCA\Libresign\Service\Policy\Provider\Signature\SignatureFlowPolicy; use OCA\Libresign\Service\Policy\Provider\SignatureRejection\FilePolicy\SignatureRejectionFilePolicyApplier; use OCA\Libresign\Service\Policy\Provider\SignatureRejection\SignatureRejectionPolicy; @@ -85,7 +86,7 @@ public function testApplyAllAppliesAllRegisteredFilePolicies(): void { ]; $this->policyService - ->expects($this->exactly(14)) + ->expects($this->exactly(15)) ->method('resolveForUser') ->willReturnCallback(function (string $policyKey) use ($identificationDocumentsValue, $identifyMethodsPolicyValue): ResolvedPolicy { return match ($policyKey) { @@ -138,6 +139,11 @@ public function testApplyAllAppliesAllRegisteredFilePolicies(): void { ], 'system', ), + OrganizationSealsPolicy::KEY => $this->createResolvedPolicy( + OrganizationSealsPolicy::KEY, + '[]', + 'system', + ), SignatureRejectionPolicy::KEY_ENABLED, SignatureRejectionPolicy::KEY_BEHAVIOR, SignatureRejectionPolicy::KEY_COMMENT_MODE, @@ -185,6 +191,10 @@ public function testApplyAllAppliesAllRegisteredFilePolicies(): void { 'effectiveValue' => true, 'sourceScope' => 'system', ], $metadata['policy_snapshot'][ObserverProfilePolicy::KEY] ?? null); + $this->assertSame([ + 'effectiveValue' => '[]', + 'sourceScope' => 'system', + ], $metadata['policy_snapshot'][OrganizationSealsPolicy::KEY] ?? null); // Every rejection setting is frozen on its own, one snapshot entry per key. foreach (SignatureRejectionPolicyConfig::defaults()->toKeyedValues() as $policyKey => $effectiveValue) { $this->assertSame([ @@ -201,7 +211,7 @@ public function testSyncCoreFlowPoliciesPersistsFooterSnapshot(): void { $file->setDocmdpLevelEnum(DocMdpLevel::NOT_CERTIFIED); $this->policyService - ->expects($this->exactly(11)) + ->expects($this->exactly(12)) ->method('resolveForUserId') ->willReturnCallback(function (string $policyKey): ResolvedPolicy { return match ($policyKey) { @@ -239,6 +249,11 @@ public function testSyncCoreFlowPoliciesPersistsFooterSnapshot(): void { ], 'system', ), + OrganizationSealsPolicy::KEY => $this->createResolvedPolicy( + OrganizationSealsPolicy::KEY, + '[]', + 'system', + ), SignatureRejectionPolicy::KEY_ENABLED, SignatureRejectionPolicy::KEY_BEHAVIOR, SignatureRejectionPolicy::KEY_COMMENT_MODE, @@ -253,7 +268,7 @@ public function testSyncCoreFlowPoliciesPersistsFooterSnapshot(): void { }); $this->fileService - ->expects($this->exactly(7)) + ->expects($this->exactly(8)) ->method('update') ->with($this->identicalTo($file)); @@ -307,7 +322,7 @@ public function testSyncAllPoliciesSyncsAllRegisteredProviders(): void { ]); $this->policyService - ->expects($this->exactly(13)) + ->expects($this->exactly(14)) ->method('resolveForUserId') ->willReturnCallback(function (string $policyKey): ResolvedPolicy { return match ($policyKey) { @@ -365,6 +380,11 @@ public function testSyncAllPoliciesSyncsAllRegisteredProviders(): void { ], 'system', ), + OrganizationSealsPolicy::KEY => $this->createResolvedPolicy( + OrganizationSealsPolicy::KEY, + '[]', + 'system', + ), SignatureRejectionPolicy::KEY_ENABLED, SignatureRejectionPolicy::KEY_BEHAVIOR, SignatureRejectionPolicy::KEY_COMMENT_MODE, @@ -379,7 +399,7 @@ public function testSyncAllPoliciesSyncsAllRegisteredProviders(): void { }); $this->fileService - ->expects($this->exactly(4)) + ->expects($this->exactly(5)) ->method('update'); $this->getApplier()->syncAllPolicies($file, []); diff --git a/tests/php/Unit/Service/Policy/Provider/OrganizationSeals/FilePolicy/OrganizationSealsFilePolicyApplierTest.php b/tests/php/Unit/Service/Policy/Provider/OrganizationSeals/FilePolicy/OrganizationSealsFilePolicyApplierTest.php new file mode 100644 index 0000000000..2a8032e5b5 --- /dev/null +++ b/tests/php/Unit/Service/Policy/Provider/OrganizationSeals/FilePolicy/OrganizationSealsFilePolicyApplierTest.php @@ -0,0 +1,146 @@ +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); + $this->sealStore = $this->createMock(OrganizationSealStore::class); + $this->sealStore->method('exists')->willReturnCallback(static fn (string $id): bool => in_array($id, ['first', 'second'], true)); + } + + private function getApplier(): OrganizationSealsFilePolicyApplier { + $applier = new OrganizationSealsFilePolicyApplier( + $this->policyService, + $this->fileService, + $this->l10n, + $this->createMock(FileMapper::class), + ); + $applier->setSealStore($this->sealStore); + return $applier; + } + + private function resolvedPolicy(string $value, string $sourceScope, bool $canOverride = true): ResolvedPolicy { + return (new ResolvedPolicy()) + ->setPolicyKey(OrganizationSealsPolicy::KEY) + ->setEffectiveValue($value) + ->setSourceScope($sourceScope) + ->setCanUseAsRequestOverride($canOverride); + } + + public function testApplyStoresTheRequestedSeals(): void { + $file = new FileEntity(); + $this->policyService->expects($this->once()) + ->method('resolveForUser') + ->with(OrganizationSealsPolicy::KEY, null, [OrganizationSealsPolicy::KEY => '["second","first"]']) + ->willReturn($this->resolvedPolicy('["second","first"]', 'request')); + + $this->getApplier()->apply($file, ['policyOverrides' => [OrganizationSealsPolicy::KEY => ['second', 'first']]]); + + $this->assertSame([ + 'effectiveValue' => '["second","first"]', + 'sourceScope' => 'request', + ], $file->getMetadata()['policy_snapshot'][OrganizationSealsPolicy::KEY]); + } + + public function testApplyWithoutChoiceStoresTheDefault(): void { + $file = new FileEntity(); + $this->policyService->method('resolveForUser')->willReturn($this->resolvedPolicy('[]', 'system', false)); + + $this->getApplier()->apply($file, []); + + $this->assertSame('[]', $file->getMetadata()['policy_snapshot'][OrganizationSealsPolicy::KEY]['effectiveValue']); + } + + public function testApplyRejectsAnUnknownSeal(): void { + $this->policyService->expects($this->never())->method('resolveForUser'); + + $this->expectException(LibresignException::class); + $this->expectExceptionMessage('Unknown organization seal.'); + $this->getApplier()->apply(new FileEntity(), ['policyOverrides' => [OrganizationSealsPolicy::KEY => ['first', 'unknown']]]); + } + + public function testApplyRejectsAChoiceTheAdministratorDidNotAllow(): void { + $this->policyService->method('resolveForUser')->willReturn($this->resolvedPolicy('[]', 'system', false)); + + $this->expectException(LibresignException::class); + $this->getApplier()->apply(new FileEntity(), ['policyOverrides' => [OrganizationSealsPolicy::KEY => ['first']]]); + } + + public function testSyncCannotChangeTheSealsOfASentRequest(): void { + $file = $this->sentRequestWithSeals('["first"]'); + $this->policyService->expects($this->never())->method('resolveForUserId'); + + $this->expectException(LibresignException::class); + $this->getApplier()->sync($file, ['policyOverrides' => [OrganizationSealsPolicy::KEY => ['second']]]); + } + + public function testSyncAcceptsTheStoredSealsOfASentRequest(): void { + $file = $this->sentRequestWithSeals('["first"]'); + $this->policyService->expects($this->never())->method('resolveForUserId'); + $this->fileService->expects($this->never())->method('update'); + + $this->getApplier()->sync($file, ['policyOverrides' => [OrganizationSealsPolicy::KEY => ['first']]]); + $this->getApplier()->sync($file, []); + + $this->assertSame('["first"]', $file->getMetadata()['policy_snapshot'][OrganizationSealsPolicy::KEY]['effectiveValue']); + } + + public function testSyncUpdatesADraft(): void { + $file = new FileEntity(); + $file->setUserId('john'); + $file->setStatus(FileStatus::DRAFT->value); + $this->policyService->method('resolveForUserId')->willReturn($this->resolvedPolicy('["second"]', 'request')); + $this->fileService->expects($this->once())->method('update')->with($this->identicalTo($file)); + + $this->getApplier()->sync($file, ['policyOverrides' => [OrganizationSealsPolicy::KEY => ['second']]]); + + $this->assertSame('["second"]', $file->getMetadata()['policy_snapshot'][OrganizationSealsPolicy::KEY]['effectiveValue']); + } + + private function sentRequestWithSeals(string $seals): FileEntity { + $file = new FileEntity(); + $file->setUserId('john'); + $file->setStatus(FileStatus::ABLE_TO_SIGN->value); + $file->setMetadata([ + 'policy_snapshot' => [ + OrganizationSealsPolicy::KEY => [ + 'effectiveValue' => $seals, + 'sourceScope' => 'request', + ], + ], + ]); + return $file; + } +} diff --git a/tests/php/Unit/Service/Policy/Provider/OrganizationSeals/OrganizationSealsPolicyTest.php b/tests/php/Unit/Service/Policy/Provider/OrganizationSeals/OrganizationSealsPolicyTest.php new file mode 100644 index 0000000000..b208929d92 --- /dev/null +++ b/tests/php/Unit/Service/Policy/Provider/OrganizationSeals/OrganizationSealsPolicyTest.php @@ -0,0 +1,74 @@ +createMock(OrganizationSealStore::class); + $sealStore->method('exists')->willReturnCallback(static fn (string $id): bool => in_array($id, $knownSeals, true)); + return (new OrganizationSealsPolicy($sealStore))->get(OrganizationSealsPolicy::KEY); + } + + public function testDefinitionMetadata(): void { + $definition = $this->getDefinition(); + + $this->assertSame(OrganizationSealsPolicy::KEY, $definition->key()); + $this->assertSame('[]', $definition->defaultSystemValue()); + $this->assertTrue($definition->supportsRequestOverride()); + $this->assertSame(PolicySpec::LIFECYCLE_REQUEST_SNAPSHOT, $definition->requestLifecycle()); + $this->assertFalse($definition->supportsUserPreference()); + $this->assertTrue($definition->isBackendOnly()); + $this->assertSame(OrganizationSealsPolicy::SYSTEM_APP_CONFIG_KEY, $definition->getAppConfigKey()); + $this->assertNotSame(OrganizationSealStore::INDEX_APP_CONFIG_KEY, $definition->getAppConfigKey()); + } + + #[DataProvider('providerNormalize')] + public function testNormalizeValue(mixed $rawValue, string $expected): void { + $this->assertSame($expected, $this->getDefinition()->normalizeValue($rawValue)); + } + + public static function providerNormalize(): array { + return [ + 'list keeps the order' => [['second', 'first'], '["second","first"]'], + 'json string' => ['["first"]', '["first"]'], + 'duplicates and blanks are dropped' => [['first', ' ', 'first', 7, ' second '], '["first","second"]'], + 'empty string means no seal' => ['', '[]'], + 'unexpected type means no seal' => [true, '[]'], + ]; + } + + public function testValidateRejectsTooManySeals(): void { + $this->expectException(\InvalidArgumentException::class); + $ids = array_map(static fn (int $i): string => 'seal' . $i, range(0, OrganizationSealsPolicyValue::MAX_SEALS)); + $this->getDefinition()->validateValue(OrganizationSealsPolicyValue::encode($ids), new PolicyContext()); + } + + public function testValidateDoesNotRequireTheSealToExist(): void { + $this->getDefinition()->validateValue('["removed"]', new PolicyContext()); + $this->addToAssertionCount(1); + } + + public function testSavingRejectsAnUnknownSeal(): void { + $this->expectException(\InvalidArgumentException::class); + $this->getDefinition(['first'])->validateValueForPersistence('["first","unknown"]', new PolicyContext()); + } + + public function testSavingAcceptsConfiguredSeals(): void { + $this->getDefinition(['first', 'second'])->validateValueForPersistence('["second","first"]', new PolicyContext()); + $this->addToAssertionCount(1); + } +} diff --git a/tests/php/Unit/Service/SignFileServiceTest.php b/tests/php/Unit/Service/SignFileServiceTest.php index a4c0fe68c1..73b1d3cb26 100644 --- a/tests/php/Unit/Service/SignFileServiceTest.php +++ b/tests/php/Unit/Service/SignFileServiceTest.php @@ -50,6 +50,7 @@ use OCA\Libresign\Service\IdentifyMethod\SignatureMethod\EmailToken; use OCA\Libresign\Service\IdentifyMethod\SignatureMethod\ISignatureMethod; use OCA\Libresign\Service\IdentifyMethodService; +use OCA\Libresign\Service\OrganizationSeal\OrganizationSealService; use OCA\Libresign\Service\PdfSignatureDetectionService; use OCA\Libresign\Service\PfxProvider; use OCA\Libresign\Service\Policy\Model\ResolvedPolicy; @@ -136,6 +137,7 @@ final class SignFileServiceTest extends \OCA\Libresign\Tests\Unit\TestCase { private SubjectAlternativeNameService&MockObject $subjectAlternativeNameService; private SignRequestService&MockObject $signRequestService; private PolicyService&MockObject $policyService; + private OrganizationSealService&MockObject $organizationSealService; private SignatureRejectionPolicyService&MockObject $signatureRejectionPolicyService; /** @var array */ private array $policyValues = []; @@ -199,6 +201,7 @@ public function setUp(): void { ); $this->signRequestService = $this->createMock(SignRequestService::class); $this->policyService = $this->createMock(PolicyService::class); + $this->organizationSealService = $this->createMock(OrganizationSealService::class); $this->signatureRejectionPolicyService = $this->createMock(SignatureRejectionPolicyService::class); $this->signatureRejectionPolicyService ->method('getBehavior') @@ -595,6 +598,7 @@ private function getService(array $methods = []): SignFileService|MockObject { $this->notificationDeliveries, new SigningWorkflowStatusResolver($this->idDocsMapper, $this->signatureRejectionPolicyService), $this->webhooks, + $this->organizationSealService, ]) ->onlyMethods($methods) ->getMock(); @@ -644,6 +648,7 @@ private function getService(array $methods = []): SignFileService|MockObject { $this->notificationDeliveries, new SigningWorkflowStatusResolver($this->idDocsMapper, $this->signatureRejectionPolicyService), $this->webhooks, + $this->organizationSealService, ); } @@ -868,6 +873,87 @@ public function testDispatchEventWhenSign(): void { ->sign(); } + #[DataProvider('providerOrganizationSealsAfterLastSignature')] + public function testOrganizationSealsAfterLastSignature(array $requestedSeals, ?string $otherSignerSigned, bool $sealed, string $expectedHash): void { + $service = $this->getService(['computeHash']); + $service->method('computeHash')->willReturn('sealed-hash'); + + $file = new File(); + $file->setId(5); + $signer = new SignRequest(); + $signer->setFileId(5); + $signer->setSigned(new \DateTime()); + $otherSigner = new SignRequest(); + $otherSigner->setFileId(5); + if ($otherSignerSigned !== null) { + $otherSigner->setSigned(new \DateTime($otherSignerSigned)); + } + $this->signRequestMapper->method('getByFileId')->with(5)->willReturn([$signer, $otherSigner]); + $signedFile = $this->createMock(\OCP\Files\File::class); + + $this->organizationSealService->method('getRequestedSeals')->with($file)->willReturn($requestedSeals); + $this->organizationSealService->expects($sealed ? $this->once() : $this->never()) + ->method('apply') + ->with($file, $signedFile) + ->willReturn(true); + + $service->setLibreSignFile($file)->setSignRequest($signer); + $hash = self::invokePrivate($service, 'applyOrganizationSealsIfCompleted', [$signedFile, 'signer-hash']); + + $this->assertSame($expectedHash, $hash); + } + + public static function providerOrganizationSealsAfterLastSignature(): array { + return [ + 'no seal requested' => [[], '2026-01-01', false, 'signer-hash'], + 'another signer has not signed yet' => [['first'], null, false, 'signer-hash'], + 'last signature seals and stores the new hash' => [['first'], '2026-01-01', true, 'sealed-hash'], + ]; + } + + public function testSignedHashIsKeptWhenNoSealWasApplied(): void { + $service = $this->getService(['computeHash']); + $service->expects($this->never())->method('computeHash'); + + $file = new File(); + $file->setId(5); + $signer = new SignRequest(); + $signer->setFileId(5); + $signer->setSigned(new \DateTime()); + $this->signRequestMapper->method('getByFileId')->willReturn([$signer]); + $this->organizationSealService->method('getRequestedSeals')->willReturn(['first']); + $this->organizationSealService->expects($this->once())->method('apply')->willReturn(false); + + $service->setLibreSignFile($file)->setSignRequest($signer); + $hash = self::invokePrivate($service, 'applyOrganizationSealsIfCompleted', [$this->createMock(\OCP\Files\File::class), 'signer-hash']); + + $this->assertSame('signer-hash', $hash); + } + + public function testSigningStoresTheHashOfTheSealedFile(): void { + $service = $this->getService([ + 'getEngine', 'computeHash', 'validateDocMdpAllowsSignatures', + 'updateSignRequest', 'updateLibreSignFile', 'dispatchSignedEvent', 'applyOrganizationSealsIfCompleted', + ]); + $file = new File(); + $file->setId(33); + $file->setStatus(FileStatus::PARTIAL_SIGNED->value); + $signedFile = $this->createMock(\OCP\Files\File::class); + $signedFile->method('getId')->willReturn(999); + $engine = $this->createMock(Pkcs12Handler::class); + $engine->method('sign')->willReturn($signedFile); + $service->method('getEngine')->willReturn($engine); + $service->method('computeHash')->willReturn('signer-hash'); + $service->expects($this->once())->method('updateSignRequest')->with('signer-hash'); + $service->expects($this->once()) + ->method('applyOrganizationSealsIfCompleted') + ->with($signedFile, 'signer-hash') + ->willReturn('sealed-hash'); + $service->expects($this->once())->method('updateLibreSignFile')->with($file, 999, 'sealed-hash'); + + $service->signSingleFile($file, new SignRequest()); + } + public function testSigningDelegatesCompletionAfterPersistence(): void { $service = $this->getService([ 'getEngine', 'computeHash', 'validateDocMdpAllowsSignatures',