diff --git a/ProcessMaker/Exception/UnsupportedImportAssetException.php b/ProcessMaker/Exception/UnsupportedImportAssetException.php new file mode 100644 index 0000000000..2ecfc7e96d --- /dev/null +++ b/ProcessMaker/Exception/UnsupportedImportAssetException.php @@ -0,0 +1,14 @@ + $this->getMessage(), 'message' => $this->getMessage()], 422); + } +} diff --git a/ProcessMaker/ImportExport/Manifest.php b/ProcessMaker/ImportExport/Manifest.php index ac5372b777..9f19622d19 100644 --- a/ProcessMaker/ImportExport/Manifest.php +++ b/ProcessMaker/ImportExport/Manifest.php @@ -83,6 +83,7 @@ public function toArray($skipHidden = false) public static function fromArray(array $array, Options $options, $logger, $root) { + (new UnsupportedAssetValidator())->validate($array); self::$logger = $logger; self::buildParentModeMap($array, $options); diff --git a/ProcessMaker/ImportExport/UnsupportedAssetValidator.php b/ProcessMaker/ImportExport/UnsupportedAssetValidator.php new file mode 100644 index 0000000000..fe61cfe60e --- /dev/null +++ b/ProcessMaker/ImportExport/UnsupportedAssetValidator.php @@ -0,0 +1,65 @@ +rules = array_map(function (array $rule) { + return [ + 'name' => $rule['name'], + 'classes' => array_map(self::normalizeClass(...), $rule['classes'] ?? []), + 'namespace_prefixes' => array_map( + fn (string $prefix) => self::normalizeClass($prefix) . '\\', + $rule['namespace_prefixes'] ?? [] + ), + ]; + }, config('import-export.unsupported_assets', [])); + } + + public function validate(array $assets): void + { + foreach ($assets as $asset) { + $this->validateReference($asset); + foreach ($asset['dependents'] ?? [] as $dependent) { + $this->validateReference($dependent); + } + } + } + + private function validateReference(array $reference): void + { + foreach (['model', 'exporter', 'modelClass', 'exporterClass'] as $key) { + if (!isset($reference[$key])) { + continue; + } + $class = self::normalizeClass($reference[$key]); + foreach ($this->rules as $rule) { + $matches = in_array($class, $rule['classes'], true); + foreach ($rule['namespace_prefixes'] as $prefix) { + if (str_starts_with($class, $prefix)) { + $matches = true; + break; + } + } + if ($matches) { + throw new UnsupportedImportAssetException( + __('This process package contains :resource resources, which are not supported for import. Remove the :resource resources and references from the source process, export it again, and retry the import.', [ + 'resource' => __($rule['name']), + ]) + ); + } + } + } + } + + private static function normalizeClass(string $class): string + { + return strtolower(trim($class, '\\')); + } +} diff --git a/ProcessMaker/Jobs/ImportV2.php b/ProcessMaker/Jobs/ImportV2.php index 8937976082..52df91fae8 100644 --- a/ProcessMaker/Jobs/ImportV2.php +++ b/ProcessMaker/Jobs/ImportV2.php @@ -10,6 +10,7 @@ use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Storage; use ProcessMaker\Exception\ImportPasswordException; +use ProcessMaker\Exception\UnsupportedImportAssetException; use ProcessMaker\ImportExport\Importer; use ProcessMaker\ImportExport\Logger; use ProcessMaker\ImportExport\Options; @@ -84,7 +85,13 @@ private function runImport($logger) } $options = new Options($options); - $importer = new Importer($payload, $options, $logger); + try { + $importer = new Importer($payload, $options, $logger); + } catch (UnsupportedImportAssetException $e) { + $logger->error($e->getMessage()); + + return; + } if ($this->isPreview) { $manifest = $importer->previewImport(); Storage::put(self::MANIFEST_PATH, json_encode($manifest)); diff --git a/config/import-export.php b/config/import-export.php new file mode 100644 index 0000000000..4ad12c627e --- /dev/null +++ b/config/import-export.php @@ -0,0 +1,15 @@ + [ + [ + 'name' => 'Vocabulary', + 'classes' => [], + 'namespace_prefixes' => [ + 'ProcessMaker\\Package\\PackageVocabularies', + ], + ], + ], +]; diff --git a/tests/unit/ImportUnsupportedVocabularyTest.php b/tests/unit/ImportUnsupportedVocabularyTest.php new file mode 100644 index 0000000000..ac9991b90e --- /dev/null +++ b/tests/unit/ImportUnsupportedVocabularyTest.php @@ -0,0 +1,175 @@ + [['model' => $model]], + 'exporter without an installed package' => [['exporter' => $exporter]], + 'dependent model without a standalone asset' => [['dependents' => [['modelClass' => $model]]]], + 'dependent exporter without a standalone asset' => [['dependents' => [['exporterClass' => $exporter]]]], + 'case insensitive class with leading separator' => [['model' => '\\' . strtoupper($model)]], + ]; + } + + #[DataProvider('vocabularyReferences')] + public function testRejectsVocabularyBeforeResolvingAnyModels(array $asset): void + { + // This first asset must never be resolved: validation rejects the whole package first. + $payload = ['root' => 'process', 'export' => [ + 'process' => ['model' => 'MissingProcessModel', 'exporter' => 'MissingProcessExporter'], + 'vocabulary' => $asset, + ]]; + + $this->expectException(UnsupportedImportAssetException::class); + $this->expectExceptionMessage('Vocabulary resources, which are not supported for import'); + + new Importer($payload, new Options([])); + } + + public static function additionalReferences(): array + { + return [ + 'exact class' => [['model' => '\\Example\\RetiredAsset']], + 'case insensitive exact class' => [['exporter' => 'EXAMPLE\\RETIREDASSET']], + 'namespace with trailing separator' => [['model' => 'Example\\Legacy\\Models\\Asset']], + 'dependent namespace' => [['dependents' => [['exporterClass' => 'example\\legacy\\AssetExporter']]]], + ]; + } + + #[DataProvider('additionalReferences')] + public function testNewRulesRejectResourcesWithoutInstallingClasses(array $asset): void + { + $rules = config('import-export.unsupported_assets'); + $rules[] = [ + 'name' => 'Legacy Example', + 'classes' => ['Example\\RetiredAsset'], + 'namespace_prefixes' => ['\\Example\\Legacy\\'], + ]; + config(['import-export.unsupported_assets' => $rules]); + + $this->expectException(UnsupportedImportAssetException::class); + $this->expectExceptionMessage('Legacy Example resources, which are not supported for import'); + + (new UnsupportedAssetValidator())->validate([$asset]); + } + + public function testSimilarClassNamesAndAllowedResourcesAreNotRejected(): void + { + config(['import-export.unsupported_assets' => [[ + 'name' => 'Legacy Example', + 'classes' => ['Example\\RetiredAsset'], + 'namespace_prefixes' => ['Example\\Legacy'], + ]]]); + $assets = [ + ['model' => 'Example\\RetiredAssetReplacement'], + ['exporter' => 'Example\\LegacyReplacement\\Exporter'], + ['model' => 'Example\\Current\\Asset'], + ['dependents' => [['modelClass' => 'Example\\RetiredAsset\\Child']]], + ]; + + (new UnsupportedAssetValidator())->validate($assets); + $this->assertFalse(class_exists('Example\\RetiredAssetReplacement')); + } + + public function testResourcesAreAllowedWhenNoRulesAreConfigured(): void + { + config(['import-export.unsupported_assets' => []]); + + (new UnsupportedAssetValidator())->validate([ + ['model' => 'ProcessMaker\\Package\\PackageVocabularies\\Models\\Vocabulary'], + ]); + $this->assertSame([], config('import-export.unsupported_assets')); + } + + public function testValidationResponseContainsOnlyActionableMessages(): void + { + config(['app.debug' => true]); + $request = Request::create('/api/1.0/import/preview', 'POST'); + $request->headers->set('Accept', 'application/json'); + $response = app(ExceptionHandler::class)->render( + $request, + new UnsupportedImportAssetException('Vocabulary resources cannot be imported.') + ); + + $this->assertSame(422, $response->getStatusCode()); + $this->assertSame([ + 'error' => 'Vocabulary resources cannot be imported.', + 'message' => 'Vocabulary resources cannot be imported.', + ], $response->getData(true)); + } + + public static function importModes(): array + { + return ['preview' => [true], 'import' => [false]]; + } + + #[DataProvider('importModes')] + public function testQueuedValidationReportsACleanErrorAndReleasesTheLock(bool $preview): void + { + config(['cache.default' => 'array']); + Storage::fake(); + Event::fake([ImportLog::class]); + $payload = json_encode(['root' => 'vocabulary', 'export' => [ + 'vocabulary' => ['model' => 'ProcessMaker\\Package\\PackageVocabularies\\Models\\Vocabulary'], + ]]); + Storage::put(ImportV2::FILE_PATH, $payload); + Storage::put(ImportV2::OPTIONS_PATH, '{}'); + + (new ImportV2(1, null, md5($payload), $preview))->handle(); + + Event::assertDispatched(ImportLog::class, function ($event) { + return $event->type === 'error' + && str_starts_with($event->message, 'This process package contains Vocabulary resources,') + && !str_contains($event->message, 'Exception') + && !str_contains($event->message, '#0'); + }); + Event::assertNotDispatched(ImportLog::class, fn ($event) => $event->message === 'preview' || $event->message === 'Done'); + $this->assertFalse(Storage::exists(ImportV2::MANIFEST_PATH)); + $lock = Cache::lock(ImportV2::CACHE_LOCK_KEY, ImportV2::RELEASE_LOCK_AFTER); + $this->assertTrue($lock->get()); + $lock->release(); + } + + public function testUnexpectedFailureKeepsTheLockUntilTheFailureCallback(): void + { + config(['cache.default' => 'array']); + Storage::fake(); + Event::fake([ImportLog::class]); + Storage::put(ImportV2::FILE_PATH, '{}'); + $job = new ImportV2(1, null, 'incorrect-hash', true); + + try { + $job->handle(); + $this->fail('An invalid hash must fail the import.'); + } catch (\Exception $exception) { + $this->assertSame('File hash does not match. Is another user importing?', $exception->getMessage()); + } + + $nextLock = Cache::lock(ImportV2::CACHE_LOCK_KEY, ImportV2::RELEASE_LOCK_AFTER); + $this->assertFalse($nextLock->get()); + $job->failed($exception); + $this->assertTrue($nextLock->get()); + $nextLock->release(); + } +}