Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions lib/Handler/SignEngine/JSignPdf/JSignPdfHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -194,11 +194,12 @@ private function replacePdfVersion(string $content, string $newVersion): string
}

private function getCertificationLevel(): ?string {
if (!$this->docMdpConfigService->isEnabled()) {
return null;
$level = $this->getDocMdpLevel();
if ($level === null && $this->docMdpConfigService->isEnabled()) {
$level = $this->docMdpConfigService->getLevel();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The request-specific DocMDP level may expose stale certification parameters when a JSignPdfHandler instance is reused.

getJSignParam() caches its parameter object, and addJSignParameters() merges new options without clearing previously supplied ones.

When a first document uses a certifying level and a second document uses NOT_CERTIFIED, the second signing operation does not explicitly remove the previous -cl option.

Please add a regression test using the same handler instance for two consecutive signing operations:

  1. Sign a document with certification level 1.
  2. Sign another document with NOT_CERTIFIED.
  3. Verify that the second operation does not pass -cl and that its resulting PDF contains no DocMDP certification.
  4. Use a fresh handler signing with NOT_CERTIFIED as a control.

Please also cover the visible-signature path, which clones the cached parameters.

If the test confirms parameter reuse, reset or rebuild the per-document parameters and retain the regression test.

}

return $this->docMdpConfigService->getLevel()->name;
return $level !== null && $level->isCertifying() ? $level->name : null;
}

#[\Override]
Expand All @@ -214,6 +215,9 @@ public function sign(): File {
public function getSignedContent(): string {
$normalizedPdf = $this->normalizePdfVersion($this->getInputFile()->getContent());
$hashAlgorithm = $this->hashAlgorithmResolver->forSignature($this->extractPdfVersion($normalizedPdf));
// Options only accumulate on the params, so a reused handler would carry
// the certification level of the previous document into this one.
$this->jSignParam = null;
$param = $this->getJSignParam();
$param->setCertificate($this->getCertificate())
->setPdf($normalizedPdf)
Expand Down
11 changes: 7 additions & 4 deletions lib/Handler/SignEngine/PhpNativeHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -249,15 +249,18 @@ private function getTsaSettings(): array {
}

private function resolveCertificationLevel(bool $noVisibleElements): ?CertificationLevel {
if (!$this->docMdpConfigService->isEnabled()) {
$level = $this->getDocMdpLevel();
if ($level === null && $this->docMdpConfigService->isEnabled()) {
$level = $this->docMdpConfigService->getLevel();
}
if ($level === null || !$level->isCertifying()) {
return null;
}

// DocMDP values mirror CertificationLevel: 1=NoChanges, 2=FormFilling, 3=FormFillAndAnnotations
$level = $this->docMdpConfigService->getLevel()->value;
// Only certify on invisible signatures or on the first visible element
if ($noVisibleElements || !$this->hasExistingSignatures($this->getInputFile()->getContent())) {
return CertificationLevel::fromInt($level);
// DocMDP values mirror CertificationLevel: 1=NoChanges, 2=FormFilling, 3=FormFillAndAnnotations
return CertificationLevel::fromInt($level->value);
}

return null;
Expand Down
1 change: 1 addition & 0 deletions lib/Handler/SignEngine/Pkcs12Handler.php
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,7 @@ public function sign(): File {
->setPassword($this->getPassword())
->setSignatureParams($this->getSignatureParams())
->setVisibleElements($this->getVisibleElements())
->setDocMdpLevel($this->getDocMdpLevel())
->getSignedContent();
$this->getInputFile()->putContent($signedContent);
return $this->getInputFile();
Expand Down
15 changes: 15 additions & 0 deletions lib/Handler/SignEngine/SignEngineHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

use InvalidArgumentException;
use OCA\Libresign\DataObjects\VisibleElementAssoc;
use OCA\Libresign\Enum\DocMdpLevel;
use OCA\Libresign\Exception\EmptyCertificateException;
use OCA\Libresign\Exception\LibresignException;
use OCA\Libresign\Exception\PasswordToSignNotDefinedException;
Expand All @@ -31,6 +32,7 @@ abstract class SignEngineHandler implements IPkcs12SignEngineHandler {
/** @var VisibleElementAssoc[] */
private array $visibleElements = [];
private array $signatureParams = [];
private ?DocMdpLevel $docMdpLevel = null;

public function __construct(
private IL10N $l10n,
Expand Down Expand Up @@ -119,6 +121,19 @@ public function setSignatureParams(array $params): self {
return $this;
}

/**
* The certification level to sign with, used as is. Without one, the
* current level applies.
*/
public function setDocMdpLevel(?DocMdpLevel $docMdpLevel): self {
$this->docMdpLevel = $docMdpLevel;
return $this;
}

public function getDocMdpLevel(): ?DocMdpLevel {
return $this->docMdpLevel;
}

public function setLeafExpiryOverrideInDays(?int $days): self {
$this->getCertificateEngine()->setLeafExpiryOverrideInDays($days);
return $this;
Expand Down
30 changes: 22 additions & 8 deletions lib/Service/DocMdp/Validator.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@

use OCA\Libresign\Db\File;
use OCA\Libresign\Db\FileMapper;
use OCA\Libresign\Enum\DocMdpLevel;
use OCA\Libresign\Enum\ParticipantRole;
use OCA\Libresign\Exception\LibresignException;
use OCA\Libresign\Service\File\Pdf\PdfValidator;
use OCA\Libresign\Service\Policy\Provider\DocMdp\FilePolicy\DocMdpFilePolicyApplier;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\Files\IRootFolder;
use OCP\IL10N;
Expand All @@ -25,6 +27,7 @@ public function __construct(
private ConfigService $configService,
private PdfValidator $pdfValidator,
private IRootFolder $root,
private DocMdpFilePolicyApplier $docMdpFilePolicyApplier,
) {
}

Expand Down Expand Up @@ -96,22 +99,33 @@ private function countSigningParticipants(array $signers): int {
return $count;
}

/**
* Signers are checked before the request is saved, so this is the level the
* request will certify with once saved, not the one it stores now. An
* envelope is not certified itself: each of its documents is, with its own
* level, so one that allows no changes is enough to refuse more signers.
*/
private function getDocMdpLevel(array $data, ?File &$file): int {
$docMdpLevel = null;

if (!empty($data['uuid'])) {
try {
$file = $this->fileMapper->getByUuid($data['uuid']);
$docMdpLevel = $file->getDocmdpLevel();
} catch (DoesNotExistException) {
// File doesn't exist, use global configured level
// File doesn't exist, resolve the level of a new request
}
}

if ($docMdpLevel === null || $docMdpLevel === 0) {
return $this->configService->getLevel()->value;
$documents = $file?->isEnvelope() ? $this->fileMapper->getChildrenFiles($file->getId()) : [];
if ($documents === []) {
$documents = [$file];
}

return $docMdpLevel;
$levels = array_map(
fn (?File $document): int => ($this->docMdpFilePolicyApplier->resolveLevel($document, $data)
?? $this->configService->getLevel())->value,
$documents,
);

return in_array(DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED->value, $levels, true)
? DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED->value
: $levels[0];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,32 +10,32 @@

use OCA\Libresign\Db\File as FileEntity;
use OCA\Libresign\Enum\DocMdpLevel;
use OCA\Libresign\Exception\LibresignException;
use OCA\Libresign\Service\Policy\AbstractFilePolicyApplier;
use OCA\Libresign\Service\Policy\Model\ResolvedPolicy;
use OCA\Libresign\Service\Policy\Provider\DocMdp\DocMdpPolicy;
use OCP\AppFramework\Http;
use OCP\IUser;

class DocMdpFilePolicyApplier extends AbstractFilePolicyApplier {

#[\Override]
public function apply(FileEntity $file, array $data): void {
$user = ($data['userManager'] ?? null) instanceof IUser ? $data['userManager'] : null;
$requestOverrides = $this->getOverrides($data);
$activeContext = $this->extractActiveContext($data);
$resolvedPolicy = $activeContext === null
? $this->policyService->resolveForUser(DocMdpPolicy::KEY, $user, $requestOverrides)
: $this->policyService->resolveForUser(DocMdpPolicy::KEY, $user, $requestOverrides, $activeContext);
$file->setDocmdpLevelEnum(DocMdpLevel::tryFrom((int)$resolvedPolicy->getEffectiveValue()) ?? DocMdpLevel::NOT_CERTIFIED);
$resolvedPolicy = $this->resolveForRequester($data);
$file->setDocmdpLevelEnum($this->toLevel($resolvedPolicy));
$this->storePolicySnapshot($file, $resolvedPolicy);
}

#[\Override]
public function sync(FileEntity $file, array $data): void {
$requestOverrides = $this->getOverrides($data);
$activeContext = $this->extractActiveContext($data);
$resolvedPolicy = $activeContext === null
? $this->policyService->resolveForUserId(DocMdpPolicy::KEY, $file->getUserId(), $requestOverrides)
: $this->policyService->resolveForUserId(DocMdpPolicy::KEY, $file->getUserId(), $requestOverrides, $activeContext);
$newLevel = DocMdpLevel::tryFrom((int)$resolvedPolicy->getEffectiveValue()) ?? DocMdpLevel::NOT_CERTIFIED;
if ($this->isPolicySnapshotFrozen($file, DocMdpPolicy::KEY)) {
$this->assertFrozenLevelIsKept($file, $requestOverrides);
return;
}

$resolvedPolicy = $this->resolveForFileOwner($file, $data);
$newLevel = $this->toLevel($resolvedPolicy);
$metadataBeforeUpdate = $file->getMetadata() ?? [];
$this->storePolicySnapshot($file, $resolvedPolicy);
$metadataChanged = ($file->getMetadata() ?? []) !== $metadataBeforeUpdate;
Expand All @@ -51,8 +51,71 @@ public function supportsCoreFlowSync(): bool {
return true;
}

/**
* The level a request certifies with once saved with $data, so its signers
* can be checked before it is: the stored one when frozen, otherwise the
* one apply() or sync() resolves. Null when a frozen request stores none, in
* which case the current level applies.
*/
public function resolveLevel(?FileEntity $file, array $data): ?DocMdpLevel {
if ($file === null) {
return $this->toLevel($this->resolveForRequester($data));
}

if (!$this->isPolicySnapshotFrozen($file, DocMdpPolicy::KEY)) {
return $this->toLevel($this->resolveForFileOwner($file, $data));
}

$policySnapshot = ($file->getMetadata() ?? [])['policy_snapshot'] ?? null;
return is_array($policySnapshot) && array_key_exists(DocMdpPolicy::KEY, $policySnapshot)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

resolveLevel() reads the envelope's own DocMDP snapshot, but EnvelopeService::createEnvelope() only stores the observer-profile policy on the envelope. The effective DocMDP level is stored on each child document.

Consequently, signer validation may fall back to the current system level even though the children will be signed using their frozen levels.

Please add a parameterized API regression test in tests/php/Api/Controller/RequestSignatureControllerTest.php using #[DataProvider('provideFrozenEnvelopeDocMdpCases')].

Suggested named datasets, expressed as (initial system level, request override, subsequent system level, expected status):

  • frozen override L1, current L3: (2, 1, 3, 422)
  • frozen L2, current L1: (2, null, 1, 200)
  • frozen L0, current L1: (0, null, 1, 200)

Use a shared fixture helper to create a two-document envelope with one signing participant, then PATCH the envelope UUID with two signing participants after changing the system level.

Assert the effective DocMDP level and sourceScope persisted on each child, the HTTP response, the final signer counts on the envelope and children, and that both child snapshots remain unchanged. In the rejected case, verify that no additional signers were persisted and that the failure is specifically caused by DocMDP validation.

The initial single-signer request also serves as a control proving that the override was authorized.

If the regression reproduces, align envelope signer validation with the effective frozen policy of its documents. Avoid introducing a separate policy-resolution implementation solely for envelopes.

? $file->getDocmdpLevelEnum()
: null;
}

private function resolveForRequester(array $data): ResolvedPolicy {
$user = ($data['userManager'] ?? null) instanceof IUser ? $data['userManager'] : null;
$requestOverrides = $this->getOverrides($data);
$activeContext = $this->extractActiveContext($data);
return $activeContext === null
? $this->policyService->resolveForUser(DocMdpPolicy::KEY, $user, $requestOverrides)
: $this->policyService->resolveForUser(DocMdpPolicy::KEY, $user, $requestOverrides, $activeContext);
}

private function resolveForFileOwner(FileEntity $file, array $data): ResolvedPolicy {
$requestOverrides = $this->getOverrides($data);
$activeContext = $this->extractActiveContext($data);
return $activeContext === null
? $this->policyService->resolveForUserId(DocMdpPolicy::KEY, $file->getUserId(), $requestOverrides)
: $this->policyService->resolveForUserId(DocMdpPolicy::KEY, $file->getUserId(), $requestOverrides, $activeContext);
}

private function toLevel(ResolvedPolicy $resolvedPolicy): DocMdpLevel {
return DocMdpLevel::tryFrom((int)$resolvedPolicy->getEffectiveValue()) ?? DocMdpLevel::NOT_CERTIFIED;
}

/** @return array<string, int> */
private function getOverrides(array $data): array {
return $this->extractSinglePolicyOverride($data, DocMdpPolicy::KEY);
}

/**
* A frozen request keeps the certification level it was sent with. A client
* may still send that same level along an unrelated update, which changes
* nothing.
*
* @param array<string, mixed> $requestOverrides
*/
private function assertFrozenLevelIsKept(FileEntity $file, array $requestOverrides): void {
$submittedLevel = $requestOverrides[DocMdpPolicy::KEY] ?? null;
if ($submittedLevel === null || (is_numeric($submittedLevel) && (int)$submittedLevel === $file->getDocmdpLevel())) {
return;
}

throw new LibresignException(
// TRANSLATORS Error shown when someone tries to change the PDF certification (DocMDP level) of a document after the signing flow already started.
$this->l10n?->t('The PDF certification cannot be changed after the signing flow has started.')
?? 'The PDF certification cannot be changed after the signing flow has started.',
Http::STATUS_UNPROCESSABLE_ENTITY,
);
}
}
52 changes: 33 additions & 19 deletions lib/Service/RequestSignatureService.php
Original file line number Diff line number Diff line change
Expand Up @@ -437,25 +437,10 @@ private function persistFile(array $data, ?Node $createdNode = null): array {
}
return $this->upgradeExistingFileStatus($file, $data['status'] ?? 0);
}
$nodeId = null;
if (isset($data['file']['fileNode']) && $data['file']['fileNode'] instanceof Node) {
$nodeId = $data['file']['fileNode']->getId();
} elseif (!empty($data['file']['nodeId'])) {
$nodeId = $data['file']['nodeId'];
}
if (!is_null($nodeId)) {
try {
$file = $this->fileMapper->getByNodeId($nodeId);
} catch (DoesNotExistException) {
$file = null;
} catch (MultipleObjectsReturnedException) {
// TRANSLATORS Error shown when a document cannot be updated because LibreSign has more than one record for it.
throw new LibresignException($this->l10n->t('This document is registered more than once, so it cannot be updated. Please contact your administrator.'), 422);
}
if ($file !== null) {
$this->filePolicyApplier->syncAllPolicies($file, $data);
return $this->upgradeExistingFileStatus($file, $data['status'] ?? 0);
}
$file = $this->getFileOfNode($data);
if ($file !== null) {
$this->filePolicyApplier->syncAllPolicies($file, $data);
return $this->upgradeExistingFileStatus($file, $data['status'] ?? 0);
}

$node = $createdNode ?? $this->fileService->getNodeFromData($data);
Expand Down Expand Up @@ -514,6 +499,30 @@ private function upgradeExistingFileStatus(FileEntity $file, int $newStatus): ar
];
}

/**
* The file LibreSign already registered for the node a request points at,
* which the request then updates instead of creating another one.
*/
private function getFileOfNode(array $data): ?FileEntity {
$nodeId = null;
if (isset($data['file']['fileNode']) && $data['file']['fileNode'] instanceof Node) {
$nodeId = $data['file']['fileNode']->getId();
} elseif (!empty($data['file']['nodeId'])) {
$nodeId = $data['file']['nodeId'];
}
if (is_null($nodeId)) {
return null;
}
try {
return $this->fileMapper->getByNodeId($nodeId);
} catch (DoesNotExistException) {
return null;
} catch (MultipleObjectsReturnedException) {
// TRANSLATORS Error shown when a document cannot be updated because LibreSign has more than one record for it.
throw new LibresignException($this->l10n->t('This document is registered more than once, so it cannot be updated. Please contact your administrator.'), 422);
}
}

private function getFileMetadata(\OCP\Files\Node $node): array {
$metadata = [];
if ($extension = strtolower($node->getExtension())) {
Expand Down Expand Up @@ -703,6 +712,11 @@ public function validateSigners(array $data): void {
throw new \Exception($this->l10n->t('Signers list needs to be an array'));
}

// persistFile() reuses the file already registered for the node, so the
// signers are checked against that request, as on an update by uuid.
if (empty($data['uuid'])) {
$data['uuid'] = $this->getFileOfNode($data)?->getUuid();
}
$this->signerValidator->validateIdentifySigners($data);
$normalizedSigners = $this->signerValidator->normalizeRequestSigners($data['signers']);

Expand Down
20 changes: 19 additions & 1 deletion lib/Service/SignFileService.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
use OCA\Libresign\Db\SignRequest as SignRequestEntity;
use OCA\Libresign\Db\SignRequestMapper;
use OCA\Libresign\Db\UserElementMapper;
use OCA\Libresign\Enum\DocMdpLevel;
use OCA\Libresign\Enum\FileStatus;
use OCA\Libresign\Enum\IdentifyMethodRequirement;
use OCA\Libresign\Enum\SignRequestStatus;
Expand All @@ -47,6 +48,7 @@
use OCA\Libresign\Service\IdentifyMethod\SignatureMethod\IToken;
use OCA\Libresign\Service\Policy\PolicyService;
use OCA\Libresign\Service\Policy\Provider\CollectMetadata\CollectMetadataPolicy;
use OCA\Libresign\Service\Policy\Provider\DocMdp\DocMdpPolicy;
use OCA\Libresign\Service\Policy\Provider\Footer\FooterPolicy;
use OCA\Libresign\Service\Policy\Provider\Footer\FooterPolicyValue;
use OCA\Libresign\Service\SignRequest\SignRequestService;
Expand Down Expand Up @@ -1246,7 +1248,8 @@ private function configureEngine(): void {
$this->restoreMissingVisibleElementImages();
$this->engine
->setVisibleElements($this->getVisibleElements())
->setSignatureParams($this->getSignatureParams());
->setSignatureParams($this->getSignatureParams())
->setDocMdpLevel($this->getDocMdpLevel());
}
}

Expand Down Expand Up @@ -1492,6 +1495,21 @@ private function getFooterPolicyValue(): string {
return $this->footerPolicyValue;
}

/**
* Once frozen, the request certifies with the level it stores, whatever the
* current level. Without a stored level, the current one applies.
*/
private function getDocMdpLevel(): ?DocMdpLevel {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The signing engine now uses the frozen request's DocMDP level, but signer validation still relies on the current system configuration in some cases.

DocMdp\Validator::getDocMdpLevel() ignores request/group overrides when creating a request and treats a stored level of 0 as missing.

This can allow two signers on a request whose effective certification is level 1, or reject signers on a frozen level-0 request after the administrator changes the global configuration.

Please align signer validation with the backend-resolved effective policy.

Add regression tests covering:

  • System level 2 with an authorized request override to level 1: two signing participants must be rejected.
  • A frozen level-0 request followed by a global change to level 1: adding valid signers must remain allowed.
  • A valid level-2 request with two signing participants: it must continue to be accepted.

The tests should assert the observable API behavior and persisted policy, rather than only checking calls to the validator.

$policySnapshot = ($this->libreSignFile->getMetadata() ?? [])['policy_snapshot'] ?? null;
if (!is_array($policySnapshot) || !array_key_exists(DocMdpPolicy::KEY, $policySnapshot)) {
return null;
}

return FileStatusService::isPolicySnapshotFrozen($this->libreSignFile, $this->fileMapper->findEnvelope($this->libreSignFile))
? $this->libreSignFile->getDocmdpLevelEnum()
: null;
}

protected function getSignedFile(): ?File {
$nodeId = $this->libreSignFile->getSignedNodeId();
if (!$nodeId) {
Expand Down
Loading
Loading