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
14 changes: 14 additions & 0 deletions ProcessMaker/Exception/UnsupportedImportAssetException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

namespace ProcessMaker\Exception;

use Illuminate\Http\JsonResponse;
use RuntimeException;

class UnsupportedImportAssetException extends RuntimeException
{
public function render(): JsonResponse
{
return new JsonResponse(['error' => $this->getMessage(), 'message' => $this->getMessage()], 422);
}
}
1 change: 1 addition & 0 deletions ProcessMaker/ImportExport/Manifest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
65 changes: 65 additions & 0 deletions ProcessMaker/ImportExport/UnsupportedAssetValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?php

namespace ProcessMaker\ImportExport;

use ProcessMaker\Exception\UnsupportedImportAssetException;

class UnsupportedAssetValidator
{
private array $rules;

public function __construct()
{
$this->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, '\\'));
}
}
9 changes: 8 additions & 1 deletion ProcessMaker/Jobs/ImportV2.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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));
Expand Down
15 changes: 15 additions & 0 deletions config/import-export.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

return [
// Only list resources that can no longer be imported, not all deprecated features.
// Classes need not be installed: these rules inspect names in exported packages.
'unsupported_assets' => [
[
'name' => 'Vocabulary',
'classes' => [],
'namespace_prefixes' => [
'ProcessMaker\\Package\\PackageVocabularies',
],
],
],
];
175 changes: 175 additions & 0 deletions tests/unit/ImportUnsupportedVocabularyTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
<?php

namespace Tests\Unit;

use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Foundation\Testing\TestCase;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Storage;
use PHPUnit\Framework\Attributes\DataProvider;
use ProcessMaker\Events\ImportLog;
use ProcessMaker\Exception\UnsupportedImportAssetException;
use ProcessMaker\ImportExport\Importer;
use ProcessMaker\ImportExport\Options;
use ProcessMaker\ImportExport\UnsupportedAssetValidator;
use ProcessMaker\Jobs\ImportV2;

class ImportUnsupportedVocabularyTest extends TestCase
{
public static function vocabularyReferences(): array
{
$model = 'ProcessMaker\\Package\\PackageVocabularies\\Models\\Vocabulary';
$exporter = 'ProcessMaker\\Package\\PackageVocabularies\\ImportExport\\VocabularyExporter';

return [
'model without an installed package' => [['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();
}
}
Loading