diff --git a/lib/AppInfo/Application.php b/lib/AppInfo/Application.php index 7f756eba53..a39c0636fb 100644 --- a/lib/AppInfo/Application.php +++ b/lib/AppInfo/Application.php @@ -22,7 +22,6 @@ use OCA\Libresign\Listener\MailNotifyListener; use OCA\Libresign\Listener\NotificationListener; use OCA\Libresign\Listener\RevokeClickToSignCertificateListener; -use OCA\Libresign\Listener\SignedCallbackListener; use OCA\Libresign\Listener\TwofactorGatewayListener; use OCA\Libresign\Listener\UserDeletedListener; use OCA\Libresign\Middleware\GlobalInjectionMiddleware; @@ -67,7 +66,6 @@ public function register(IRegistrationContext $context): void { $context->registerEventListener(LoadSidebar::class, TemplateLoader::class); $context->registerEventListener(BeforeNodeDeletedEvent::class, BeforeNodeDeletedListener::class); $context->registerEventListener(CacheEntryRemovedEvent::class, BeforeNodeDeletedListener::class); - $context->registerEventListener(SignedEvent::class, SignedCallbackListener::class); // Files newFile listener $context->registerEventListener('OCA\\Files\\Event\\LoadAdditionalScriptsEvent', LoadAdditionalListener::class); diff --git a/lib/Controller/RequestSignatureController.php b/lib/Controller/RequestSignatureController.php index 6e538af3c0..4d27495eca 100644 --- a/lib/Controller/RequestSignatureController.php +++ b/lib/Controller/RequestSignatureController.php @@ -65,7 +65,6 @@ public function __construct( * @param LibresignFolderSettings $settings Settings to define how and where the file should be stored * @param LibresignNewFile $file File object. Supports nodeId (a non-negative integer or its canonical decimal string, as Nextcloud node ids can exceed a JavaScript number), url, base64 or path. * @param list $files Multiple files to create an envelope (optional, use either file or files). Each file supports nodeId, url, base64 or path. - * @param string|null $callback URL that will receive a POST after the document is signed * @param integer|null $status Numeric code of status * 0 - no signers * 1 - signed * 2 - pending * @param LibresignRequestPolicy|null $policy Structured policy payload with request-level overrides and active context. * @return DataResponse|DataResponse @@ -84,7 +83,6 @@ public function requestSignature( array $settings = [], array $file = [], array $files = [], - ?string $callback = null, ?int $status = 1, ?array $policy = null, ): DataResponse { @@ -98,7 +96,6 @@ public function requestSignature( $settings, $signers, $status, - $callback, $policy, ); @@ -176,7 +173,6 @@ public function updateSignatureRequest( $settings, $signers, $status, - null, $policy, $visibleElements ); diff --git a/lib/Db/File.php b/lib/Db/File.php index 1f56a3a21c..c7d51f3e11 100644 --- a/lib/Db/File.php +++ b/lib/Db/File.php @@ -31,8 +31,6 @@ * @method \DateTime getCreatedAt() * @method void setName(string $name) * @method non-falsy-string getName() - * @method void setCallback(string $callback) - * @method ?string getCallback() * @method void setStatus(int $status) * @method int getStatus() * @method void setMetadata(array $metadata) @@ -57,7 +55,6 @@ class File extends Entity { protected ?string $userId = null; protected ?int $signedNodeId = null; protected ?string $signedHash = null; - protected ?string $callback = null; protected ?array $metadata = null; protected int $modificationStatus = 0; protected int $signatureFlow = SignatureFlow::NUMERIC_NONE; @@ -79,7 +76,6 @@ public function __construct() { $this->addType('uuid', Types::STRING); $this->addType('createdAt', Types::DATETIME); $this->addType('name', Types::STRING); - $this->addType('callback', Types::STRING); $this->addType('status', Types::INTEGER); $this->addType('metadata', Types::JSON); $this->addType('modificationStatus', Types::SMALLINT); diff --git a/lib/Db/IdDocsMapper.php b/lib/Db/IdDocsMapper.php index a2a23cafa0..21c6dc45ff 100644 --- a/lib/Db/IdDocsMapper.php +++ b/lib/Db/IdDocsMapper.php @@ -162,7 +162,6 @@ private function getQueryBuilder(array $filter = [], bool $count = false): IQuer 'f.id', 'f.uuid', 'f.name', - 'f.callback', 'f.status', 'f.node_id', 'f.user_id', @@ -217,7 +216,6 @@ private function getQueryBuilder(array $filter = [], bool $count = false): IQuer 'f.id', 'f.uuid', 'f.name', - 'f.callback', 'f.status', 'f.node_id', 'f.user_id', @@ -314,7 +312,6 @@ private function formatListRow(array $row, string $url): array { 'signedNodeId' => (int)$row['node_id'], 'url' => $url . $row['uuid'], ], - 'callback' => $row['callback'], 'uuid' => $row['uuid'], 'signers' => [], ], diff --git a/lib/Listener/SignedCallbackListener.php b/lib/Listener/SignedCallbackListener.php deleted file mode 100644 index d3f54339d2..0000000000 --- a/lib/Listener/SignedCallbackListener.php +++ /dev/null @@ -1,35 +0,0 @@ - */ -class SignedCallbackListener implements IEventListener { - public function __construct( - private SignFileService $signFileService, - ) { - } - - #[\Override] - public function handle(Event $event): void { - /** @var SignedEvent */ - if (!($event instanceof SignedEvent)) { - return; - } - - $updatedFields = $event->getLibreSignFile()->getUpdatedFields(); - if (isset($updatedFields['signed']) && $updatedFields['signed'] === true) { - $this->signFileService->notifyCallback($event->getSignedFile()); - } - } -} diff --git a/lib/Migration/Version19005Date20261109110000.php b/lib/Migration/Version19005Date20261109110000.php new file mode 100644 index 0000000000..8c30f4e971 --- /dev/null +++ b/lib/Migration/Version19005Date20261109110000.php @@ -0,0 +1,156 @@ +appData = $appDataFactory->get(Application::APP_ID); + } + + /** @param Closure(): ISchemaWrapper $schemaClosure */ + #[\Override] + public function preSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void { + $schema = $schemaClosure(); + if ($schema->hasTable('libresign_file') && $schema->getTable('libresign_file')->hasColumn('callback')) { + $this->backupFileCallbacks($output); + } + + $this->backupLegacyWebhookUrl($output); + } + + private function backupFileCallbacks(IOutput $output): void { + $query = $this->connection->getQueryBuilder(); + $query->select('id', 'callback') + ->from('libresign_file') + ->where($query->expr()->nonEmptyString('callback')) + ->orderBy('id'); + + $result = $query->executeQuery(); + try { + $row = $result->fetchAssociative(); + if ($row === false) { + return; + } + + // Build the CSV before creating AppData, so CSV write failures cannot + // persist a partial backup and leave the migration free to drop data. + $handle = fopen('php://temp', 'w+'); + if ($handle === false) { + throw new \RuntimeException('Could not open LibreSign callback backup buffer'); + } + + try { + if (fputcsv($handle, ['id', 'callback'], ',', '"', '') === false) { + throw new \RuntimeException('Could not write LibreSign callback backup header'); + } + + do { + if (fputcsv($handle, [$row['id'], $row['callback']], ',', '"', '') === false) { + throw new \RuntimeException('Could not write LibreSign callback backup row'); + } + } while (($row = $result->fetchAssociative()) !== false); + + $bytes = ftell($handle); + if ($bytes === false || !rewind($handle)) { + throw new \RuntimeException('Could not prepare LibreSign callback backup for storage'); + } + + $csv = stream_get_contents($handle); + if ($csv === false || strlen($csv) !== $bytes) { + throw new \RuntimeException('Could not read LibreSign callback backup buffer'); + } + + // Nextcloud closes resources passed to newFile(); pass a string instead + // so this method retains ownership of the buffer until finally. + $folder = $this->appData->getFolder('/'); + $file = $folder->newFile(self::FILE_BACKUP, $csv); + if ($file->getSize() != $bytes) { + throw new \RuntimeException('Could not verify LibreSign callback backup size'); + } + $output->info( + 'Legacy callback destinations saved to appdata_/libresign/' + . self::FILE_BACKUP . ' (may contain credentials; restrict access).', + ); + } finally { + fclose($handle); + } + } finally { + $result->closeCursor(); + } + } + + private function backupLegacyWebhookUrl(IOutput $output): void { + if (!in_array('webhook_sign_url', $this->appConfig->getKeys(Application::APP_ID), true)) { + return; + } + + $url = $this->appConfig->getValueString(Application::APP_ID, 'webhook_sign_url'); + if ($url === '') { + return; + } + + $content = json_encode(['webhook_sign_url' => $url], JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); + $folder = $this->appData->getFolder('/'); + $file = $folder->newFile(self::CONFIG_BACKUP, $content); + if ($file->getSize() != strlen($content)) { + throw new \RuntimeException('Could not verify LibreSign webhook URL backup size'); + } + $output->info( + 'Legacy webhook URL saved to appdata_/libresign/' + . self::CONFIG_BACKUP . ' (may contain credentials; restrict access).', + ); + } + + /** @param Closure(): ISchemaWrapper $schemaClosure */ + #[\Override] + public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper { + $schema = $schemaClosure(); + if (!$schema->hasTable('libresign_file')) { + return null; + } + + $table = $schema->getTable('libresign_file'); + if (!$table->hasColumn('callback')) { + return null; + } + + $table->dropColumn('callback'); + return $schema; + } + + /** @param Closure(): ISchemaWrapper $schemaClosure */ + #[\Override] + public function postSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void { + if (in_array('webhook_sign_url', $this->appConfig->getKeys(Application::APP_ID), true)) { + $this->appConfig->deleteKey(Application::APP_ID, 'webhook_sign_url'); + } + } +} diff --git a/lib/ResponseDefinitions.php b/lib/ResponseDefinitions.php index 462e7847b1..81fe277cdf 100644 --- a/lib/ResponseDefinitions.php +++ b/lib/ResponseDefinitions.php @@ -827,7 +827,6 @@ * signedNodeId: non-negative-int, * url: string, * }, - * callback: ?string, * uuid: string, * signers: list, * }, diff --git a/lib/Service/RequestSignatureService.php b/lib/Service/RequestSignatureService.php index 1379a77638..484bf57c52 100644 --- a/lib/Service/RequestSignatureService.php +++ b/lib/Service/RequestSignatureService.php @@ -412,7 +412,6 @@ private function createFileForEnvelope( * userManager?: IUser, * signRequest?: SignRequestEntity, * name?: string, - * callback?: string, * uuid?: ?string, * status?: int, * parentFileId?: int, @@ -481,9 +480,6 @@ private function persistFile(array $data, ?Node $createdNode = null): array { } $file->setName($this->removeExtensionFromName($name, $metadata)); $file->setMetadata($metadata); - if (!empty($data['callback'])) { - $file->setCallback($data['callback']); - } if (isset($data['status'])) { $file->setStatus($data['status']); } else { diff --git a/lib/Service/RequestSignatureWorkflowService.php b/lib/Service/RequestSignatureWorkflowService.php index cf65e87e82..c39d70c33b 100644 --- a/lib/Service/RequestSignatureWorkflowService.php +++ b/lib/Service/RequestSignatureWorkflowService.php @@ -59,7 +59,6 @@ public function createRequest( array $settings, array $signers, ?int $status, - ?string $callback, ?array $policy = null, ?array $visibleElements = null, ): array { @@ -75,7 +74,6 @@ public function createRequest( 'file' => $file, 'name' => $name, 'signers' => $signers, - 'callback' => $callback, 'userManager' => $user, 'policyOverrides' => $resolvedPolicy['policyOverrides'], 'policyActiveContext' => $resolvedPolicy['policyActiveContext'], diff --git a/lib/Service/SignFileService.php b/lib/Service/SignFileService.php index ad7852b129..05f653c6c4 100644 --- a/lib/Service/SignFileService.php +++ b/lib/Service/SignFileService.php @@ -13,7 +13,6 @@ use Exception; use InvalidArgumentException; use OC\AppFramework\Http as AppFrameworkHttp; -use OCA\Libresign\AppInfo\Application; use OCA\Libresign\BackgroundJob\SignSingleFileJob; use OCA\Libresign\DataObjects\VisibleElementAssoc; use OCA\Libresign\Db\File as FileEntity; @@ -63,7 +62,6 @@ use OCP\EventDispatcher\IEventDispatcher; use OCP\Files\File; use OCP\Files\NotPermittedException; -use OCP\Http\Client\IClientService; use OCP\IAppConfig; use OCP\IDateTimeZone; use OCP\IL10N; @@ -105,7 +103,6 @@ public function __construct( private IdDocsMapper $idDocsMapper, private FooterHandler $footerHandler, protected FolderService $folderService, - private IClientService $client, protected LoggerInterface $logger, private IAppConfig $appConfig, protected IdentityDocumentValidator $identityDocumentValidator, @@ -179,34 +176,6 @@ public function canDeleteRequestSignature(array $data): void { }); } - public function notifyCallback(File $file): void { - $uri = $this->libreSignFile->getCallback(); - if (!$uri) { - $uri = $this->appConfig->getValueString(Application::APP_ID, 'webhook_sign_url'); - if (!$uri) { - return; - } - } - $options = [ - 'multipart' => [ - [ - 'name' => 'uuid', - 'contents' => $this->libreSignFile->getUuid(), - ], - [ - 'name' => 'status', - 'contents' => $this->libreSignFile->getStatus(), - ], - [ - 'name' => 'file', - 'contents' => $file->fopen('r'), - 'filename' => $file->getName() - ] - ] - ]; - $this->client->newClient()->post($uri, $options); - } - /** * @return static */ diff --git a/openapi-full.json b/openapi-full.json index a1af7f85f0..c7c79e3450 100644 --- a/openapi-full.json +++ b/openapi-full.json @@ -1238,7 +1238,6 @@ "statusText", "created_at", "file", - "callback", "uuid", "signers" ], @@ -1291,10 +1290,6 @@ } } }, - "callback": { - "type": "string", - "nullable": true - }, "uuid": { "type": "string" }, @@ -12281,12 +12276,6 @@ "$ref": "#/components/schemas/NewFile" } }, - "callback": { - "type": "string", - "nullable": true, - "default": null, - "description": "URL that will receive a POST after the document is signed" - }, "status": { "type": "integer", "format": "int64", diff --git a/openapi.json b/openapi.json index f52dbe1baa..6b4e635e67 100644 --- a/openapi.json +++ b/openapi.json @@ -911,7 +911,6 @@ "statusText", "created_at", "file", - "callback", "uuid", "signers" ], @@ -964,10 +963,6 @@ } } }, - "callback": { - "type": "string", - "nullable": true - }, "uuid": { "type": "string" }, @@ -11544,12 +11539,6 @@ "$ref": "#/components/schemas/NewFile" } }, - "callback": { - "type": "string", - "nullable": true, - "default": null, - "description": "URL that will receive a POST after the document is signed" - }, "status": { "type": "integer", "format": "int64", diff --git a/src/tests/views/Documents/IdDocsValidation.spec.ts b/src/tests/views/Documents/IdDocsValidation.spec.ts index 0f1ac27396..639e6386cc 100644 --- a/src/tests/views/Documents/IdDocsValidation.spec.ts +++ b/src/tests/views/Documents/IdDocsValidation.spec.ts @@ -135,7 +135,6 @@ describe('IdDocsValidation.vue', () => { signedNodeId: 10, url: '/files/alice-passport.pdf', }, - callback: null, signers: [{ description: null, displayName: 'Approver', @@ -177,7 +176,6 @@ describe('IdDocsValidation.vue', () => { signedNodeId: 11, url: '/files/bob-license.pdf', }, - callback: null, signers: [], }, } diff --git a/src/types/openapi/openapi-full.ts b/src/types/openapi/openapi-full.ts index c2cde313ad..a37db13462 100644 --- a/src/types/openapi/openapi-full.ts +++ b/src/types/openapi/openapi-full.ts @@ -1701,7 +1701,6 @@ export type components = { signedNodeId: number; url: string; }; - callback: string | null; uuid: string; signers: components["schemas"]["SignerDetail"][]; }; @@ -5987,11 +5986,6 @@ export interface operations { * @default [] */ files?: components["schemas"]["NewFile"][]; - /** - * @description URL that will receive a POST after the document is signed - * @default null - */ - callback?: string | null; /** * Format: int64 * @description Numeric code of status * 0 - no signers * 1 - signed * 2 - pending diff --git a/src/types/openapi/openapi.ts b/src/types/openapi/openapi.ts index 095259b876..9fd7aa8f47 100644 --- a/src/types/openapi/openapi.ts +++ b/src/types/openapi/openapi.ts @@ -1287,7 +1287,6 @@ export type components = { signedNodeId: number; url: string; }; - callback: string | null; uuid: string; signers: components["schemas"]["SignerDetail"][]; }; @@ -5425,11 +5424,6 @@ export interface operations { * @default [] */ files?: components["schemas"]["NewFile"][]; - /** - * @description URL that will receive a POST after the document is signed - * @default null - */ - callback?: string | null; /** * Format: int64 * @description Numeric code of status * 0 - no signers * 1 - signed * 2 - pending diff --git a/tests/php/Unit/Controller/RequestSignatureControllerTest.php b/tests/php/Unit/Controller/RequestSignatureControllerTest.php index 73e8d5280c..237a05183a 100644 --- a/tests/php/Unit/Controller/RequestSignatureControllerTest.php +++ b/tests/php/Unit/Controller/RequestSignatureControllerTest.php @@ -130,7 +130,6 @@ public function testRequestStatusPropagation(?int $status, bool $expectStatusKey settings: [], file: ['nodeId' => 12], files: [], - callback: null, status: $status, ); diff --git a/tests/php/Unit/Migration/Version19005Date20261109110000Test.php b/tests/php/Unit/Migration/Version19005Date20261109110000Test.php new file mode 100644 index 0000000000..0830aecec8 --- /dev/null +++ b/tests/php/Unit/Migration/Version19005Date20261109110000Test.php @@ -0,0 +1,263 @@ +createMock(ITable::class); + $table->expects($this->exactly(2))->method('hasColumn')->with('callback') + ->willReturnOnConsecutiveCalls(true, false); + $table->expects($this->once())->method('dropColumn')->with('callback'); + $schema = $this->createMock(ISchemaWrapper::class); + $schema->method('hasTable')->with('libresign_file')->willReturn(true); + $schema->method('getTable')->with('libresign_file')->willReturn($table); + $output = $this->createMock(IOutput::class); + $migration = $this->migration($this->createMock(IAppConfig::class)); + + $this->assertSame($schema, $migration->changeSchema($output, static fn (): ISchemaWrapper => $schema, [])); + $this->assertNull($migration->changeSchema($output, static fn (): ISchemaWrapper => $schema, [])); + } + + public function testSkipsMissingFileTable(): void { + $schema = $this->createMock(ISchemaWrapper::class); + $schema->method('hasTable')->with('libresign_file')->willReturn(false); + + $this->assertNull($this->migration($this->createMock(IAppConfig::class))->changeSchema( + $this->createMock(IOutput::class), + static fn (): ISchemaWrapper => $schema, + [], + )); + } + + public function testBacksUpOnlyConfiguredCallbacksBeforeDroppingColumn(): void { + $rows = [ + ['id' => '12', 'callback' => 'https://example.test/a?a=1,b=2'], + ['id' => '47', 'callback' => 'https://example.test/รง?x="quoted"'], + ]; + $csvContent = ''; + $file = $this->createMock(ISimpleFile::class); + $file->expects($this->never())->method('write'); + $file->method('getSize')->willReturnCallback(static function () use (&$csvContent): int { + return strlen($csvContent); + }); + $folder = $this->createMock(ISimpleFolder::class); + $folder->expects($this->once()) + ->method('newFile') + ->with( + 'backup-table-libresign_file_callback_Version19005Date20261109110000.csv', + $this->callback(static function ($content) use (&$csvContent): bool { + if (!is_string($content)) { + return false; + } + $csvContent = $content; + return true; + }), + )->willReturn($file); + $appData = $this->createMock(IAppData::class); + $appData->method('getFolder')->with('/')->willReturn($folder); + $factory = $this->createMock(IAppDataFactory::class); + $factory->method('get')->with(Application::APP_ID)->willReturn($appData); + $output = $this->createMock(IOutput::class); + $output->expects($this->once())->method('info') + ->with($this->stringContains('backup-table-libresign_file_callback_')); + $migration = $this->migration($this->createMock(IAppConfig::class), $factory, $this->connectionForRows($rows)); + $this->runPreSchema($migration, true, $output); + + $fp = fopen('php://temp', 'w+'); + $this->assertIsResource($fp); + try { + fwrite($fp, $csvContent); + rewind($fp); + $this->assertSame(['id', 'callback'], fgetcsv($fp, 0, ',', '"', '')); + $this->assertSame(array_values($rows[0]), fgetcsv($fp, 0, ',', '"', '')); + $this->assertSame(array_values($rows[1]), fgetcsv($fp, 0, ',', '"', '')); + $this->assertFalse(fgetcsv($fp, 0, ',', '"', '')); + } finally { + fclose($fp); + } + } + + public function testCallbackBackupFailureStopsMigrationWithoutRemovingData(): void { + $folder = $this->createMock(ISimpleFolder::class); + $folder->expects($this->once())->method('newFile') + ->willThrowException(new \RuntimeException('Backup file already exists')); + $appData = $this->createMock(IAppData::class); + $appData->method('getFolder')->willReturn($folder); + $factory = $this->createMock(IAppDataFactory::class); + $factory->method('get')->willReturn($appData); + $config = $this->createMock(IAppConfig::class); + $config->expects($this->never())->method('deleteKey'); + $migration = $this->migration($config, $factory, $this->connectionForRows([ + ['id' => '4', 'callback' => 'https://example.test/callback'], + ])); + + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('Backup file already exists'); + $this->runPreSchema($migration, true); + } + + public function testTruncatedCallbackBackupAbortsMigration(): void { + $file = $this->createMock(ISimpleFile::class); + $file->method('getSize')->willReturn(1); + $folder = $this->createMock(ISimpleFolder::class); + $folder->expects($this->once())->method('newFile')->willReturn($file); + $appData = $this->createMock(IAppData::class); + $appData->method('getFolder')->willReturn($folder); + $factory = $this->createMock(IAppDataFactory::class); + $factory->method('get')->willReturn($appData); + $config = $this->createMock(IAppConfig::class); + $config->expects($this->never())->method('deleteKey'); + $output = $this->createMock(IOutput::class); + $output->expects($this->never())->method('info'); + $migration = $this->migration($config, $factory, $this->connectionForRows([ + ['id' => '4', 'callback' => 'https://example.test/callback'], + ])); + + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('Could not verify LibreSign callback backup size'); + $this->runPreSchema($migration, true, $output); + } + + public function testNoBackupFileWhenAllCallbacksAreEmpty(): void { + $appData = $this->createMock(IAppData::class); + $appData->expects($this->never())->method('getFolder'); + $factory = $this->createMock(IAppDataFactory::class); + $factory->method('get')->willReturn($appData); + $migration = $this->migration($this->createMock(IAppConfig::class), $factory, $this->connectionForRows([])); + $output = $this->createMock(IOutput::class); + $output->expects($this->never())->method('info'); + $this->runPreSchema($migration, true, $output); + } + + public function testBacksUpGlobalCallbackEvenWhenColumnIsAbsent(): void { + $config = $this->createMock(IAppConfig::class); + $config->method('getKeys')->willReturn(['webhook_sign_url']); + $config->method('getValueString')->with(Application::APP_ID, 'webhook_sign_url') + ->willReturn('https://example.test/callback?secret=abc'); + $expectedJson = "{\n \"webhook_sign_url\": \"https://example.test/callback?secret=abc\"\n}"; + $file = $this->createMock(ISimpleFile::class); + $file->method('getSize')->willReturn(strlen($expectedJson)); + $folder = $this->createMock(ISimpleFolder::class); + $folder->expects($this->once())->method('newFile') + ->with('backup-config-webhook_sign_url_Version19005Date20261109110000.json', $expectedJson) + ->willReturn($file); + $appData = $this->createMock(IAppData::class); + $appData->method('getFolder')->with('/')->willReturn($folder); + $factory = $this->createMock(IAppDataFactory::class); + $factory->method('get')->willReturn($appData); + $output = $this->createMock(IOutput::class); + $output->expects($this->once())->method('info')->with($this->callback(static function (string $message): bool { + return str_contains($message, 'backup-config-webhook_sign_url_') && !str_contains($message, 'secret=abc'); + })); + + $this->runPreSchema($this->migration($config, $factory), false, $output); + } + + public function testDoesNotDeleteConfigWhenBackupFails(): void { + $config = $this->createMock(IAppConfig::class); + $config->method('getKeys')->willReturn(['webhook_sign_url']); + $config->method('getValueString')->willReturn('https://example.test/callback'); + $config->expects($this->never())->method('deleteKey'); + $folder = $this->createMock(ISimpleFolder::class); + $folder->method('newFile')->willThrowException(new \RuntimeException('AppData unavailable')); + $appData = $this->createMock(IAppData::class); + $appData->method('getFolder')->willReturn($folder); + $factory = $this->createMock(IAppDataFactory::class); + $factory->method('get')->willReturn($appData); + + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('AppData unavailable'); + $this->runPreSchema($this->migration($config, $factory), false); + } + + public function testTruncatedConfigBackupDoesNotDeleteLegacyValue(): void { + $config = $this->createMock(IAppConfig::class); + $config->method('getKeys')->willReturn(['webhook_sign_url']); + $config->method('getValueString')->willReturn('https://example.test/callback'); + $config->expects($this->never())->method('deleteKey'); + $file = $this->createMock(ISimpleFile::class); + $file->method('getSize')->willReturn(1); + $folder = $this->createMock(ISimpleFolder::class); + $folder->method('newFile')->willReturn($file); + $appData = $this->createMock(IAppData::class); + $appData->method('getFolder')->willReturn($folder); + $factory = $this->createMock(IAppDataFactory::class); + $factory->method('get')->willReturn($appData); + + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('Could not verify LibreSign webhook URL backup size'); + $this->runPreSchema($this->migration($config, $factory), false); + } + + public function testRemovesOnlyConfiguredLegacyWebhookUrl(): void { + $config = $this->createMock(IAppConfig::class); + $config->method('getKeys')->with(Application::APP_ID)->willReturn(['webhook_sign_url', 'signature_engine']); + $config->expects($this->once())->method('deleteKey')->with(Application::APP_ID, 'webhook_sign_url'); + $this->migration($config)->postSchemaChange($this->createMock(IOutput::class), static fn (): ISchemaWrapper => throw new \LogicException('Schema unused'), []); + } + + public function testLeavesConfigUntouchedWhenLegacyKeyIsMissing(): void { + $config = $this->createMock(IAppConfig::class); + $config->method('getKeys')->with(Application::APP_ID)->willReturn(['signature_engine']); + $config->expects($this->never())->method('deleteKey'); + $this->migration($config)->postSchemaChange($this->createMock(IOutput::class), static fn (): ISchemaWrapper => throw new \LogicException('Schema unused'), []); + } + + private function runPreSchema(Version19005Date20261109110000 $migration, bool $columnExists, ?IOutput $output = null): void { + $table = $this->createMock(ITable::class); + $table->method('hasColumn')->with('callback')->willReturn($columnExists); + $schema = $this->createMock(ISchemaWrapper::class); + $schema->method('hasTable')->with('libresign_file')->willReturn(true); + $schema->method('getTable')->willReturn($table); + $migration->preSchemaChange($output ?? $this->createMock(IOutput::class), static fn (): ISchemaWrapper => $schema, []); + } + + private function connectionForRows(array $rows): IDBConnection { + $result = $this->createMock(IResult::class); + $result->method('fetchAssociative')->willReturnOnConsecutiveCalls(...[...$rows, false]); + $result->expects($this->once())->method('closeCursor'); + $expr = $this->createMock(IExpressionBuilder::class); + $expr->expects($this->once())->method('nonEmptyString')->with('callback') + ->willReturn('portable non-empty callback predicate'); + $query = $this->createMock(IQueryBuilder::class); + $query->expects($this->once())->method('select')->with('id', 'callback')->willReturnSelf(); + $query->expects($this->once())->method('where')->with('portable non-empty callback predicate')->willReturnSelf(); + $query->expects($this->never())->method('andWhere'); + foreach (['from', 'orderBy'] as $method) { + $query->method($method)->willReturnSelf(); + } + $query->method('expr')->willReturn($expr); + $query->method('executeQuery')->willReturn($result); + $connection = $this->createMock(IDBConnection::class); + $connection->method('getQueryBuilder')->willReturn($query); + return $connection; + } + + private function migration(IAppConfig $config, ?IAppDataFactory $factory = null, ?IDBConnection $connection = null): Version19005Date20261109110000 { + $factory ??= $this->createMock(IAppDataFactory::class); + $connection ??= $this->createMock(IDBConnection::class); + return new Version19005Date20261109110000($config, $connection, $factory); + } +} diff --git a/tests/php/Unit/Service/RequestSignatureWorkflowServiceTest.php b/tests/php/Unit/Service/RequestSignatureWorkflowServiceTest.php index 03aadebd32..3e5330472c 100644 --- a/tests/php/Unit/Service/RequestSignatureWorkflowServiceTest.php +++ b/tests/php/Unit/Service/RequestSignatureWorkflowServiceTest.php @@ -85,7 +85,6 @@ public function testCreateRequestThrowsWhenFileAndFilesAreMissing(): void { [], [], 1, - null, ); } @@ -114,7 +113,6 @@ public function testCreateRequestMapsPolicyAndFallsBackToFileSettings(): void { [], [['identifyMethods' => [['method' => 'email', 'value' => 'user@example.test']]]], 1, - null, [ 'overrides' => ['signature_flow' => 'parallel'], 'activeContext' => ['type' => 'group', 'id' => 'board'], @@ -157,7 +155,6 @@ public function testCreateRequestUsesEnvelopeSaveFilesAndReturnsProvidedChildren [['identifyMethods' => [['method' => 'email', 'value' => 'user@example.test']]]], 0, null, - null, [['fileId' => 31]], ); @@ -190,7 +187,6 @@ public function testCreateRequestNormalizesTheStringNodeIdOnceAtTheBoundary(): v [], [['identifyMethods' => [['method' => 'email', 'value' => 'user@example.test']]]], 1, - null, ); $this->assertSame($fileEntity, $result['file']); @@ -216,7 +212,6 @@ public function testCreateRequestKeepsAnIntegerNodeIdAsItIs(): void { [], [['identifyMethods' => [['method' => 'email', 'value' => 'user@example.test']]]], 1, - null, ); } @@ -248,7 +243,6 @@ public function testCreateRequestNormalizesTheNodeIdOfEachEnvelopeFile(): void { [], [['identifyMethods' => [['method' => 'email', 'value' => 'user@example.test']]]], 0, - null, ); } @@ -267,7 +261,6 @@ public function testCreateRequestRejectsAnInvalidNodeIdBeforeAnyService(): void [], [['identifyMethods' => [['method' => 'email', 'value' => 'user@example.test']]]], 1, - null, ); } diff --git a/tests/php/Unit/Service/SignFileServiceTest.php b/tests/php/Unit/Service/SignFileServiceTest.php index ffd2cf76de..25e7d950e5 100644 --- a/tests/php/Unit/Service/SignFileServiceTest.php +++ b/tests/php/Unit/Service/SignFileServiceTest.php @@ -74,7 +74,6 @@ use OCP\EventDispatcher\IEventDispatcher; use OCP\Files\NotFoundException; use OCP\Files\NotPermittedException; -use OCP\Http\Client\IClientService; use OCP\IAppConfig; use OCP\IDateTimeZone; use OCP\IL10N; @@ -95,7 +94,6 @@ final class SignFileServiceTest extends \OCA\Libresign\Tests\Unit\TestCase { private SignRequestMapper&MockObject $signRequestMapper; private \OCA\Libresign\Db\NotificationDeliveryMapper&MockObject $notificationDeliveries; private IdDocsMapper&MockObject $idDocsMapper; - private IClientService&MockObject $clientService; private FolderService&MockObject $folderService; private LoggerInterface&MockObject $logger; private IAppConfig $appConfig; @@ -150,7 +148,6 @@ public function setUp(): void { $this->notificationDeliveries = $this->createMock(\OCA\Libresign\Db\NotificationDeliveryMapper::class); $this->idDocsMapper = $this->createMock(IdDocsMapper::class); $this->footerHandler = $this->createMock(FooterHandler::class); - $this->clientService = $this->createMock(IClientService::class); $this->folderService = $this->createMock(FolderService::class); $this->logger = $this->createMock(LoggerInterface::class); $this->appConfig = $this->getMockAppConfigWithReset(); @@ -506,7 +503,6 @@ private function getService(array $methods = []): SignFileService|MockObject { $this->idDocsMapper, $this->footerHandler, $this->folderService, - $this->clientService, $this->logger, $this->appConfig, $this->identityDocumentValidator, @@ -556,7 +552,6 @@ private function getService(array $methods = []): SignFileService|MockObject { $this->idDocsMapper, $this->footerHandler, $this->folderService, - $this->clientService, $this->logger, $this->appConfig, $this->identityDocumentValidator, @@ -640,16 +635,6 @@ public function testCanDeleteRequestSignatureWhenNoSignatureWasRequested():void ]); } - public function testNotifyCallback():void { - $libreSignFile = new \OCA\Libresign\Db\File(); - $libreSignFile->setCallback('https://test.coop'); - $service = $this->getService(); - $service->setLibreSignFile($libreSignFile); - $file = $this->createMock(\OCP\Files\File::class); - $actual = $service->notifyCallback($file); - $this->assertNull($actual); - } - public function testSignWithFileNotFound():void { $this->expectExceptionMessage('File not found');