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
1 change: 1 addition & 0 deletions appinfo/info.xml
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ https://libresign.coop
<command>OCA\Libresign\Command\Crl\Stats</command>
<command>OCA\Libresign\Command\Crl\Cleanup</command>
<command>OCA\Libresign\Command\Crl\Revoke</command>
<command>OCA\Libresign\Command\IdDocs\Recover</command>
<command>OCA\Libresign\Command\SignatureElements\Cleanup</command>
<command>OCA\Libresign\Command\Developer\Reset</command>
<command>OCA\Libresign\Command\Developer\SignSetup</command>
Expand Down
73 changes: 73 additions & 0 deletions lib/Command/IdDocs/Recover.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?php

declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2026 LibreCode coop and contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\Libresign\Command\IdDocs;

use OCA\Libresign\Service\IdDocsRecoveryService;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

/** Administrator-initiated repair of identification documents orphaned in appdata. */
class Recover extends Command {
public function __construct(
private IdDocsRecoveryService $recoveryService,
) {
parent::__construct();
}

#[\Override]
protected function configure(): void {
$this->setName('libresign:id-docs:recover')
->setDescription('Find identification documents of external signers stored in the unauthenticated appdata folder and copy them to the owner storage')
->setHelp(
"Runs as a dry-run by default and only reports what would change.\n"
. "With --execute, each affected document is copied into a new folder of the owner,\n"
. "its content is compared with the original, and only then is the file record\n"
. 'updated to the copy. The original stays in appdata and must be removed manually.'
)
->addOption('execute', null, InputOption::VALUE_NONE, 'Copy the affected documents and update their file records');
}

#[\Override]
protected function execute(InputInterface $input, OutputInterface $output): int {
$execute = (bool)$input->getOption('execute');
$results = $this->recoveryService->run($execute);

if ($results !== []) {
$table = new Table($output);
$table->setHeaders(['ID doc', 'File', 'Node', 'Status', 'Reason', 'New node']);
foreach ($results as $result) {
$table->addRow([
$result['idDocId'],
$result['fileId'],
$result['nodeId'] ?? '',
$result['status'],
$result['reason'],
$result['newNodeId'] ?? $result['leftoverNodeId'] ?? '',
]);
}
$table->render();
}

$totals = array_count_values(array_column($results, 'status'));
ksort($totals);
$summary = [];
foreach ($totals as $status => $total) {
$summary[] = $status . ': ' . $total;
}
$output->writeln('Checked ' . count($results) . ' identification documents' . ($summary === [] ? '.' : ' (' . implode(', ', $summary) . ').'));
if (!$execute && isset($totals[IdDocsRecoveryService::STATUS_AFFECTED])) {
$output->writeln('Dry-run: nothing was changed. Run again with --execute to recover the affected documents.');
}

return isset($totals[IdDocsRecoveryService::STATUS_FAILED]) ? self::FAILURE : self::SUCCESS;
}
}
19 changes: 19 additions & 0 deletions lib/Db/FileMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,25 @@ public function getByNodeId(int $nodeId): File {
return $file;
}

/**
* Count the records that reference a node, bypassing the entity cache.
*/
public function countByNodeId(int $nodeId): int {
$qb = $this->db->getQueryBuilder();
$qb->select($qb->func()->count('*', 'total'))
->from($this->getTableName())
->where(
$qb->expr()->orX(
$qb->expr()->eq('node_id', $qb->createNamedParameter($nodeId, IQueryBuilder::PARAM_INT)),
$qb->expr()->eq('signed_node_id', $qb->createNamedParameter($nodeId, IQueryBuilder::PARAM_INT))
)
);
$result = $qb->executeQuery();
$total = (int)$result->fetchOne();
$result->closeCursor();
return $total;
}

public function nodeIdExists(int $nodeId): bool {
$qb = $this->db->getQueryBuilder();

Expand Down
44 changes: 44 additions & 0 deletions lib/Db/IdDocsMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,50 @@ public function getBySignRequestIdAndNodeId(int $signRequestId, int $nodeId): Id
return $this->findEntity($qb);
}

/**
* Identification documents uploaded by signers without an account, with
* the references needed to locate their node and its expected owner.
*
* @return list<array{id_doc_id: int, file_id: int, sign_request_id: ?int, file_exists: bool, node_id: ?int, signed_node_id: ?int, owner: ?string, signed_document_id: ?int, signed_document_owner: ?string, signed_document_exists: bool}>
*/
public function getExternalSignerDocuments(): array {
$qb = $this->db->getQueryBuilder();
$qb->select('id.id', 'id.file_id', 'id.sign_request_id')
->selectAlias('f.id', 'file_row_id')
->selectAlias('f.node_id', 'node_id')
->selectAlias('f.signed_node_id', 'signed_node_id')
->selectAlias('f.user_id', 'owner')
->selectAlias('sr.id', 'sign_request_row_id')
->selectAlias('sr.file_id', 'signed_document_id')
->selectAlias('sf.id', 'signed_document_row_id')
->selectAlias('sf.user_id', 'signed_document_owner')
->from($this->getTableName(), 'id')
->leftJoin('id', 'libresign_file', 'f', 'f.id = id.file_id')
->leftJoin('id', 'libresign_sign_request', 'sr', 'sr.id = id.sign_request_id')
->leftJoin('sr', 'libresign_file', 'sf', 'sf.id = sr.file_id')
->where($qb->expr()->isNull('id.user_id'))
->orderBy('id.id');

$rows = [];
$result = $qb->executeQuery();
while ($row = $result->fetch()) {
$rows[] = [
'id_doc_id' => (int)$row['id'],
'file_id' => (int)$row['file_id'],
'sign_request_id' => $row['sign_request_row_id'] === null ? null : (int)$row['sign_request_row_id'],
'file_exists' => $row['file_row_id'] !== null,
'node_id' => $row['node_id'] === null ? null : (int)$row['node_id'],
'signed_node_id' => $row['signed_node_id'] === null ? null : (int)$row['signed_node_id'],
'owner' => $row['owner'] === null || $row['owner'] === '' ? null : (string)$row['owner'],
'signed_document_id' => $row['signed_document_id'] === null ? null : (int)$row['signed_document_id'],
'signed_document_owner' => $row['signed_document_owner'] === null || $row['signed_document_owner'] === '' ? null : (string)$row['signed_document_owner'],
'signed_document_exists' => $row['signed_document_row_id'] !== null,
];
}
$result->closeCursor();
return $rows;
}

public function getByFileId(int $fileId): IdDocs {
$qb = $this->db->getQueryBuilder();
$qb->select('*')
Expand Down
23 changes: 23 additions & 0 deletions lib/Service/FolderService.php
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,17 @@ public function getUnauthenticatedFolder(): Folder {
return $service->getFolder();
}

/**
* Look up a node in the unauthenticated container without creating it.
*
* @throws NotFoundException
*/
public function getUnauthenticatedFileByNodeId(int $nodeId): File {
$service = clone $this;
$service->setUserId(null);
return $service->getFileByNodeId($nodeId);
}

/**
* @throws NotFoundException
*/
Expand Down Expand Up @@ -224,6 +235,18 @@ public function getFolderForFile(array $data, $identifier): Folder {
return $userFolder->newFolder($folderName);
}

/**
* Resolve the folder for a new file of the given user, independently of
* the user currently bound to this service.
*
* @throws LibresignException
*/
public function getFolderForUserFile(IUser $user, array $data): Folder {
$service = clone $this;
$service->setUserId($user->getUID());
return $service->getFolderForFile($data, $user);
}

/**
* @param array{settings: array, name: string} $data
* @param IUser $owner
Expand Down
201 changes: 201 additions & 0 deletions lib/Service/IdDocsRecoveryService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
<?php

declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2026 LibreCode coop and contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\Libresign\Service;

use OCA\Libresign\Db\FileMapper;
use OCA\Libresign\Db\IdDocsMapper;
use OCP\AppFramework\Db\TTransactional;
use OCP\Files\File;
use OCP\Files\Folder;
use OCP\Files\NotFoundException;
use OCP\IDBConnection;
use OCP\IUser;
use OCP\IUserManager;
use Psr\Log\LoggerInterface;

/**
* Recovers identification documents that external signers uploaded before
* the storage fix of #8368: the node was written to the unauthenticated
* appdata folder while the file record points to the signed document owner.
*
* @psalm-type RecoveryResult = array{idDocId: int, fileId: int, nodeId: ?int, status: string, reason: string, newNodeId?: int, leftoverNodeId?: int}
*/
class IdDocsRecoveryService {
use TTransactional;

public const STATUS_AFFECTED = 'affected';
public const STATUS_ALREADY_CORRECT = 'already_correct';
public const STATUS_AMBIGUOUS = 'ambiguous';
public const STATUS_UNRECOVERABLE = 'unrecoverable';
public const STATUS_RECOVERED = 'recovered';
public const STATUS_FAILED = 'failed';

public function __construct(
private IdDocsMapper $idDocsMapper,
private FileMapper $fileMapper,
private FolderService $folderService,
private IUserManager $userManager,
private IDBConnection $db,
private LoggerInterface $logger,
) {
}

/**
* Classify every external-signer identification document and, when
* $execute is true, copy each affected one into its owner's storage.
*
* @return list<RecoveryResult>
*/
public function run(bool $execute): array {
$results = [];
foreach ($this->idDocsMapper->getExternalSignerDocuments() as $row) {
[$result, $owner, $source] = $this->classify($row);
if ($execute && $result['status'] === self::STATUS_AFFECTED && $owner instanceof IUser && $source instanceof File) {
$result = $this->recover($result, $owner, $source);
}
$results[] = $result;
}
return $results;
}

/**
* @param array{id_doc_id: int, file_id: int, sign_request_id: ?int, file_exists: bool, node_id: ?int, signed_node_id: ?int, owner: ?string, signed_document_id: ?int, signed_document_owner: ?string, signed_document_exists: bool} $row
* @return array{0: RecoveryResult, 1: ?IUser, 2: ?File}
*/
private function classify(array $row): array {
$result = [
'idDocId' => $row['id_doc_id'],
'fileId' => $row['file_id'],
'nodeId' => $row['node_id'],
];
$skip = static fn (string $status, string $reason): array => [$result + ['status' => $status, 'reason' => $reason], null, null];

if (!$row['file_exists'] || $row['node_id'] === null) {
return $skip(self::STATUS_UNRECOVERABLE, 'file record missing');
}
if ($row['signed_node_id'] !== null) {
return $skip(self::STATUS_AMBIGUOUS, 'document has a signed copy');
}
if ($row['owner'] === null) {
return $skip(self::STATUS_UNRECOVERABLE, 'owner missing');
}
$owner = $this->userManager->get($row['owner']);
if (!$owner instanceof IUser) {
return $skip(self::STATUS_UNRECOVERABLE, 'owner account missing');
}
if ($row['sign_request_id'] === null) {
return $skip(self::STATUS_UNRECOVERABLE, 'sign request missing');
}
if (!$row['signed_document_exists']) {
return $skip(self::STATUS_UNRECOVERABLE, 'signed document missing');
}
if ($row['signed_document_owner'] !== $row['owner']) {
return $skip(self::STATUS_AMBIGUOUS, 'owner differs from signed document owner');
}
if ($this->folderService->getReadableNodeById($owner->getUID(), $row['node_id']) instanceof File) {
return $skip(self::STATUS_ALREADY_CORRECT, 'readable in owner storage');
}
if ($this->fileMapper->countByNodeId($row['node_id']) !== 1) {
return $skip(self::STATUS_AMBIGUOUS, 'node referenced by several file records');
}
try {
$source = $this->folderService->getUnauthenticatedFileByNodeId($row['node_id']);
} catch (NotFoundException) {
return $skip(self::STATUS_UNRECOVERABLE, 'source file missing');
}
return [$result + ['status' => self::STATUS_AFFECTED, 'reason' => 'stored in unauthenticated appdata'], $owner, $source];
}

/**
* Copy the source into a new folder of the owner, verify it and only then
* point the file record to the copy. The original is never removed.
*
* @param RecoveryResult $result
* @return RecoveryResult
*/
private function recover(array $result, IUser $owner, File $source): array {
$folder = null;
try {
$folder = $this->folderService->getFolderForUserFile($owner, ['name' => 'recovered-id-doc-' . $result['fileId']]);
// FolderService falls back to app data when the owner's files cannot
// be written, which would only create another orphan.
$ownerRoot = $this->folderService->getUserFolder($owner->getUID())->getPath();
if (!str_starts_with($folder->getPath(), $ownerRoot . '/')) {
return $this->fail($result, 'owner storage not available', $folder);
}
$stream = $source->fopen('r');
if ($stream === false) {
return $this->fail($result, 'source file not readable', $folder);
}
try {
$copy = $folder->newFile($source->getName(), $stream);
} finally {
if (is_resource($stream)) {
fclose($stream);
}
}
if ($copy->hash('sha256') !== $source->hash('sha256')) {
return $this->fail($result, 'content verification failed', $folder);
}
$newNodeId = $copy->getId();
if (!$this->folderService->getReadableNodeById($owner->getUID(), $newNodeId) instanceof File) {
return $this->fail($result, 'copy not readable in owner storage', $folder);
}
$oldNodeId = (int)$result['nodeId'];
$updated = $this->atomic(function () use ($result, $oldNodeId, $newNodeId): bool {
$file = $this->fileMapper->getByIdForUpdate($result['fileId']);
if ($file->getNodeId() !== $oldNodeId || $file->getSignedNodeId() !== null) {
return false;
}
$file->setNodeId($newNodeId);
$this->fileMapper->update($file);
return true;
}, $this->db);
if (!$updated) {
return $this->fail($result, 'file record changed during recovery', $folder);
}
return array_merge($result, [
'status' => self::STATUS_RECOVERED,
'reason' => 'copied to owner storage, original kept',
'newNodeId' => $newNodeId,
]);
} catch (\Throwable $e) {
$this->logger->error('Failed to recover identification document', [
'idDocId' => $result['idDocId'],
'fileId' => $result['fileId'],
'exception' => $e,
]);
return $this->fail($result, 'unexpected error, see the server log', $folder);
}
}

/**
* Report a failure and remove the folder created for the copy, so a retry
* starts from the same state.
*
* @param RecoveryResult $result
* @return RecoveryResult
*/
private function fail(array $result, string $reason, ?Folder $folder): array {
$result = array_merge($result, ['status' => self::STATUS_FAILED, 'reason' => $reason]);
if ($folder === null) {
return $result;
}
try {
$folder->delete();
} catch (\Throwable $e) {
$this->logger->warning('Could not remove the copy of an identification document after a failed recovery', [
'idDocId' => $result['idDocId'],
'exception' => $e,
]);
$result['leftoverNodeId'] = $folder->getId();
}
return $result;
}
}
Loading
Loading