From f27a9dbab6ff512827982eeb31b76761e6b66ffa Mon Sep 17 00:00:00 2001 From: Miguel Angel Date: Tue, 10 Nov 2026 11:00:19 -0400 Subject: [PATCH 01/10] feat: add JsonDataPath class for safe mysql json path construction --- ProcessMaker/Support/JsonDataPath.php | 69 +++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 ProcessMaker/Support/JsonDataPath.php diff --git a/ProcessMaker/Support/JsonDataPath.php b/ProcessMaker/Support/JsonDataPath.php new file mode 100644 index 0000000000..e4631a43dd --- /dev/null +++ b/ProcessMaker/Support/JsonDataPath.php @@ -0,0 +1,69 @@ + $segments + * + * @throws InvalidArgumentException when there are no segments or any segment is invalid + */ + public static function fromSegments(array $segments, string $pattern = self::VARIABLE_SEGMENT): string + { + if (count($segments) === 0) { + throw new InvalidArgumentException('The JSON path must contain at least one segment.'); + } + + foreach ($segments as $segment) { + // Compare with \z semantics: reject a trailing newline that "$" would accept. + if (!is_string($segment) || $segment === '' || str_contains($segment, "\n") || !preg_match($pattern, $segment)) { + throw new InvalidArgumentException('Invalid JSON path segment.'); + } + } + + return '$."' . implode('"."', $segments) . '"'; + } + + /** + * @throws InvalidArgumentException when the dotted path is invalid + */ + public static function fromDotNotation(string $path, string $pattern = self::VARIABLE_SEGMENT): string + { + return self::fromSegments(explode('.', $path), $pattern); + } + + public static function isValid(?string $path, string $pattern = self::VARIABLE_SEGMENT): bool + { + if ($path === null || $path === '') { + return false; + } + + try { + self::fromDotNotation($path, $pattern); + } catch (InvalidArgumentException) { + return false; + } + + return true; + } +} From 15dcd1f956b117169ee818e8d4b76d52e4f349ab Mon Sep 17 00:00:00 2001 From: Miguel Angel Date: Tue, 10 Nov 2026 11:00:34 -0400 Subject: [PATCH 02/10] test: add unit tests for JsonDataPath class validation and quoting --- .../ProcessMaker/Support/JsonDataPathTest.php | 95 +++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 tests/unit/ProcessMaker/Support/JsonDataPathTest.php diff --git a/tests/unit/ProcessMaker/Support/JsonDataPathTest.php b/tests/unit/ProcessMaker/Support/JsonDataPathTest.php new file mode 100644 index 0000000000..b6aca236ba --- /dev/null +++ b/tests/unit/ProcessMaker/Support/JsonDataPathTest.php @@ -0,0 +1,95 @@ + ["amount'"], + 'double quote' => ['amount"'], + 'parenthesis' => ['amount)'], + 'backslash' => ['amount\\'], + 'space' => ['my amount'], + 'hyphen' => ['my-amount'], + 'leading digit' => ['1amount'], + 'empty segment' => ['a..b'], + 'trailing dot' => ['a.'], + 'empty string' => [''], + 'trailing newline' => ["amount\n"], + 'sql payload' => ["amount')) AS x, (SELECT 1) AS y, SUM(CAST(JSON_EXTRACT(data, '\$.amount"], + ]; + } + + #[DataProvider('validVariables')] + public function testValidVariablesAreAccepted(string $name): void + { + $this->assertTrue(JsonDataPath::isValid($name)); + $this->assertStringStartsWith('$."', JsonDataPath::fromDotNotation($name)); + } + + #[DataProvider('invalidVariables')] + public function testInvalidVariablesAreRejected(string $name): void + { + $this->assertFalse(JsonDataPath::isValid($name)); + + $this->expectException(InvalidArgumentException::class); + JsonDataPath::fromDotNotation($name); + } + + public function testNullIsInvalid(): void + { + $this->assertFalse(JsonDataPath::isValid(null)); + } + + public function testPathSegmentsAreQuoted(): void + { + $this->assertSame('$."amount"', JsonDataPath::fromDotNotation('amount')); + $this->assertSame('$."grant"."total"', JsonDataPath::fromDotNotation('grant.total')); + } + + public function testEmptySegmentListIsRejected(): void + { + $this->expectException(InvalidArgumentException::class); + JsonDataPath::fromSegments([]); + } + + public function testFilterPatternAcceptsUnicodeSpacesAndHyphens(): void + { + $path = JsonDataPath::fromSegments(['montaña', 'año 2024', 'a-b'], JsonDataPath::FILTER_SEGMENT); + + $this->assertSame('$."montaña"."año 2024"."a-b"', $path); + } + + public function testFilterPatternStillRejectsMetacharacters(): void + { + foreach (["a'b", 'a"b', 'a(b', 'a)b', 'a\\b'] as $segment) { + $this->assertFalse( + JsonDataPath::isValid($segment, JsonDataPath::FILTER_SEGMENT), + "Segment {$segment} should be rejected" + ); + } + } + + public function testVariablePatternRejectsUnicode(): void + { + $this->assertFalse(JsonDataPath::isValid('montaña')); + } +} From a6b6c5f9f19abdb2e9149f1138a1161f9343446a Mon Sep 17 00:00:00 2001 From: Miguel Angel Date: Tue, 10 Nov 2026 11:02:13 -0400 Subject: [PATCH 03/10] refactor: enhance filter field validation in BaseFilter using JsonDataPath --- ProcessMaker/Filters/BaseFilter.php | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/ProcessMaker/Filters/BaseFilter.php b/ProcessMaker/Filters/BaseFilter.php index 828e24df23..06615c8f41 100644 --- a/ProcessMaker/Filters/BaseFilter.php +++ b/ProcessMaker/Filters/BaseFilter.php @@ -6,8 +6,10 @@ use Illuminate\Database\Eloquent\Builder; use Illuminate\Support\Arr; use Illuminate\Support\Facades\DB; +use InvalidArgumentException; use ProcessMaker\Models\ProcessRequestToken; use ProcessMaker\Models\User; +use ProcessMaker\Support\JsonDataPath; use ProcessMaker\Traits\InteractsWithRawFilter; abstract class BaseFilter @@ -211,16 +213,14 @@ private function jsonSelectorPath(): string array_shift($parts); - foreach ($parts as $part) { - // Allow any Unicode letter (\p{L}) or number (\p{N}) plus underscore, hyphen and - // space, so field names in any language are accepted. The /u flag enables UTF-8 - // matching. SQL/JSON-path metacharacters such as ' " ( ) are intentionally rejected. - if (!preg_match('/^[\p{L}\p{N}_\- ]+$/u', $part)) { - abort(422, 'Invalid filter field.'); - } + try { + // Allows any Unicode letter or number plus underscore, hyphen and space, so field + // names in any language are accepted. SQL/JSON-path metacharacters such as ' " ( ) + // are intentionally rejected. + return JsonDataPath::fromSegments($parts, JsonDataPath::FILTER_SEGMENT); + } catch (InvalidArgumentException) { + abort(422, 'Invalid filter field.'); } - - return '$."' . implode('"."', $parts) . '"'; } private function operator() From 106cedf7935469e975ca763e1529c9dbd93d3033 Mon Sep 17 00:00:00 2001 From: Miguel Angel Date: Tue, 10 Nov 2026 11:05:10 -0400 Subject: [PATCH 04/10] feat: implement aggregation JSON path resolution in Process model --- ProcessMaker/Models/Process.php | 38 ++++++++++++++++++++++++++++++--- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/ProcessMaker/Models/Process.php b/ProcessMaker/Models/Process.php index f7390f1aaa..b3c2f4867a 100644 --- a/ProcessMaker/Models/Process.php +++ b/ProcessMaker/Models/Process.php @@ -9,6 +9,7 @@ use Illuminate\Support\Arr; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Str; use Illuminate\Validation\Rule; @@ -34,6 +35,7 @@ use ProcessMaker\Package\WebEntry\Models\WebentryRoute; use ProcessMaker\Repositories\ProcessExecutionRawRepository; use ProcessMaker\Rules\BPMNValidation; +use ProcessMaker\Support\JsonDataPath; use ProcessMaker\Traits\Exportable; use ProcessMaker\Traits\ExtendedPMQL; use ProcessMaker\Traits\HasCategories; @@ -167,6 +169,8 @@ class Process extends ProcessMakerModel implements HasMedia, ProcessModelInterfa const NOT_ASSIGNABLE_USER_STATUS = ['INACTIVE', 'OUT_OF_OFFICE']; + const DEFAULT_AGGREGATION = 'amount'; + protected $connection = 'processmaker'; /** @@ -2049,13 +2053,16 @@ protected static function getProcessDefaultStageCounts(int $processId): array ->toArray(); } - protected static function getProcessStageCounts(int $processId, string $amountKey = 'amount'): array + protected static function getProcessStageCounts(int $processId, ?string $amountKey = 'amount'): array { - $rawSql = sprintf('last_stage_id, COUNT(*) AS count, SUM(CAST(JSON_EXTRACT(data, \'$.%s\') AS DECIMAL(10, 2))) AS var_aggregation_sum', $amountKey); + $amountPath = self::resolveAggregationJsonPath($processId, $amountKey); $results = ProcessRequest::where('process_id', $processId) ->groupBy('last_stage_id') - ->selectRaw($rawSql) + ->selectRaw( + 'last_stage_id, COUNT(*) AS count, SUM(CAST(JSON_EXTRACT(data, ?) AS DECIMAL(10, 2))) AS var_aggregation_sum', + [$amountPath] + ) ->get() ->toArray(); @@ -2076,6 +2083,31 @@ protected static function getProcessStageCounts(int $processId, string $amountKe return $stageData; } + /** + * Builds the JSON path used to aggregate the process request data. + * + * The stored value is never trusted: it is validated here even though it is validated on + * write, because older rows may already contain arbitrary text. An invalid or empty value + * falls back to the default `amount` variable and the path is always passed as a bound + * parameter, never interpolated into SQL. + */ + private static function resolveAggregationJsonPath(int $processId, ?string $amountKey): string + { + if ($amountKey === null || $amountKey === '') { + return JsonDataPath::fromDotNotation(self::DEFAULT_AGGREGATION); + } + + if (!JsonDataPath::isValid($amountKey)) { + Log::warning('Invalid aggregation variable stored for process, using default.', [ + 'process_id' => $processId, + ]); + + return JsonDataPath::fromDotNotation(self::DEFAULT_AGGREGATION); + } + + return JsonDataPath::fromDotNotation($amountKey); + } + /** * Formats the stages configuration for the API response. * From 56ca127121add20649fd09b51c7934e91e987045 Mon Sep 17 00:00:00 2001 From: Miguel Angel Date: Tue, 10 Nov 2026 11:07:58 -0400 Subject: [PATCH 05/10] feat: add AggregationVariable validation rule and integrate it into ProcessController and Process model --- .../Controllers/Api/ProcessController.php | 7 ++++- ProcessMaker/Models/Process.php | 2 ++ ProcessMaker/Rules/AggregationVariable.php | 28 +++++++++++++++++++ 3 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 ProcessMaker/Rules/AggregationVariable.php diff --git a/ProcessMaker/Http/Controllers/Api/ProcessController.php b/ProcessMaker/Http/Controllers/Api/ProcessController.php index 1578e8df17..b47273ce1e 100644 --- a/ProcessMaker/Http/Controllers/Api/ProcessController.php +++ b/ProcessMaker/Http/Controllers/Api/ProcessController.php @@ -44,6 +44,7 @@ use ProcessMaker\Package\Translations\Models\Language; use ProcessMaker\Package\WebEntry\Models\WebentryRoute; use ProcessMaker\Providers\WorkflowServiceProvider; +use ProcessMaker\Rules\AggregationVariable; use ProcessMaker\Rules\BPMNValidation; use ProcessMaker\Services\CaseRetentionTierService; use ProcessMaker\Traits\ProjectAssetTrait; @@ -2286,7 +2287,11 @@ public function getAggregation(Process $process) */ public function saveAggregation(Request $request, Process $process) { - $process->aggregation = $request->input('aggregation', 'amount'); + $request->validate([ + 'aggregation' => ['nullable', 'string', 'max:255', new AggregationVariable()], + ]); + + $process->aggregation = $request->input('aggregation') ?: Process::DEFAULT_AGGREGATION; $process->save(); return new ApiResource([ diff --git a/ProcessMaker/Models/Process.php b/ProcessMaker/Models/Process.php index b3c2f4867a..635acb98dd 100644 --- a/ProcessMaker/Models/Process.php +++ b/ProcessMaker/Models/Process.php @@ -34,6 +34,7 @@ use ProcessMaker\Nayra\Storage\BpmnDocument; use ProcessMaker\Package\WebEntry\Models\WebentryRoute; use ProcessMaker\Repositories\ProcessExecutionRawRepository; +use ProcessMaker\Rules\AggregationVariable; use ProcessMaker\Rules\BPMNValidation; use ProcessMaker\Support\JsonDataPath; use ProcessMaker\Traits\Exportable; @@ -430,6 +431,7 @@ public static function rules($existing = null) 'bpmn' => 'nullable', 'case_title' => 'nullable|max:200', 'alternative' => 'nullable|in:A,B', + 'aggregation' => ['nullable', 'string', 'max:255', new AggregationVariable()], ]; } diff --git a/ProcessMaker/Rules/AggregationVariable.php b/ProcessMaker/Rules/AggregationVariable.php new file mode 100644 index 0000000000..b4e9c8aa18 --- /dev/null +++ b/ProcessMaker/Rules/AggregationVariable.php @@ -0,0 +1,28 @@ + $attribute])); + } + } +} From 130ff6f6bc0aea565f42678564dc08c12bd2d194 Mon Sep 17 00:00:00 2001 From: Miguel Angel Date: Tue, 10 Nov 2026 11:08:27 -0400 Subject: [PATCH 06/10] test: add unit tests for AggregationVariable validation rule --- .../Rules/AggregationVariableTest.php | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 tests/unit/ProcessMaker/Rules/AggregationVariableTest.php diff --git a/tests/unit/ProcessMaker/Rules/AggregationVariableTest.php b/tests/unit/ProcessMaker/Rules/AggregationVariableTest.php new file mode 100644 index 0000000000..0cecc5082d --- /dev/null +++ b/tests/unit/ProcessMaker/Rules/AggregationVariableTest.php @@ -0,0 +1,48 @@ + $value], ['aggregation' => [new AggregationVariable()]]); + + $this->assertFalse($validator->fails(), $value); + } + } + + public function testItRejectsInvalidVariableNames(): void + { + $payloads = [ + "amount')) AS x, (SELECT 1) AS y, SUM(CAST(JSON_EXTRACT(data, '\$.amount", + "amount'", + 'amount"', + 'amount)', + 'my amount', + '1amount', + 'a..b', + "amount\n", + ]; + + foreach ($payloads as $payload) { + $validator = Validator::make(['aggregation' => $payload], ['aggregation' => [new AggregationVariable()]]); + + $this->assertTrue($validator->fails(), $payload); + } + } + + public function testItRejectsNonStringValues(): void + { + foreach ([123, ['amount'], true] as $value) { + $validator = Validator::make(['aggregation' => $value], ['aggregation' => [new AggregationVariable()]]); + + $this->assertTrue($validator->fails()); + } + } +} From 436037167a585359e3cd0eebbed558fdbbe2ca45 Mon Sep 17 00:00:00 2001 From: Miguel Angel Date: Tue, 10 Nov 2026 11:11:00 -0400 Subject: [PATCH 07/10] feat: integrate HasAggregationAttribute trait into Process and ProcessVersion models --- ProcessMaker/Models/Process.php | 2 ++ ProcessMaker/Models/ProcessVersion.php | 2 ++ .../Traits/HasAggregationAttribute.php | 30 +++++++++++++++++++ 3 files changed, 34 insertions(+) create mode 100644 ProcessMaker/Traits/HasAggregationAttribute.php diff --git a/ProcessMaker/Models/Process.php b/ProcessMaker/Models/Process.php index 635acb98dd..1721dab063 100644 --- a/ProcessMaker/Models/Process.php +++ b/ProcessMaker/Models/Process.php @@ -39,6 +39,7 @@ use ProcessMaker\Support\JsonDataPath; use ProcessMaker\Traits\Exportable; use ProcessMaker\Traits\ExtendedPMQL; +use ProcessMaker\Traits\HasAggregationAttribute; use ProcessMaker\Traits\HasCategories; use ProcessMaker\Traits\HasSelfServiceTasks; use ProcessMaker\Traits\HasVersioning; @@ -163,6 +164,7 @@ class Process extends ProcessMakerModel implements HasMedia, ProcessModelInterfa use ProcessTrait; use Exportable; use ProjectAssetTrait; + use HasAggregationAttribute; const categoryClass = ProcessCategory::class; diff --git a/ProcessMaker/Models/ProcessVersion.php b/ProcessMaker/Models/ProcessVersion.php index 1d5265669d..28379a3ccd 100644 --- a/ProcessMaker/Models/ProcessVersion.php +++ b/ProcessMaker/Models/ProcessVersion.php @@ -4,6 +4,7 @@ use Illuminate\Database\Eloquent\Builder; use ProcessMaker\Contracts\ProcessModelInterface; +use ProcessMaker\Traits\HasAggregationAttribute; use ProcessMaker\Traits\HasCategories; use ProcessMaker\Traits\HasSelfServiceTasks; use ProcessMaker\Traits\ProcessTrait; @@ -27,6 +28,7 @@ class ProcessVersion extends ProcessMakerModel implements ProcessModelInterface use HasSelfServiceTasks; use HasCategories; use ProcessTrait; + use HasAggregationAttribute; const categoryClass = ProcessCategory::class; diff --git a/ProcessMaker/Traits/HasAggregationAttribute.php b/ProcessMaker/Traits/HasAggregationAttribute.php new file mode 100644 index 0000000000..12cf568e31 --- /dev/null +++ b/ProcessMaker/Traits/HasAggregationAttribute.php @@ -0,0 +1,30 @@ + __('The :attribute must be a valid variable name.', ['attribute' => 'aggregation']), + ]); + } + + $this->attributes['aggregation'] = $value; + } +} From 6b2ccfa077a5c8b1d14d3e44f965323b1ce761c4 Mon Sep 17 00:00:00 2001 From: Miguel Angel Date: Tue, 10 Nov 2026 11:16:30 -0400 Subject: [PATCH 08/10] test: enhance aggregation validation tests to reject SQL injection payloads --- tests/Feature/Api/ProcessControllerTest.php | 127 ++++++++++++++++++ .../Exporters/ProcessExporterTest.php | 43 ++++++ 2 files changed, 170 insertions(+) diff --git a/tests/Feature/Api/ProcessControllerTest.php b/tests/Feature/Api/ProcessControllerTest.php index 09f7860553..af81319200 100644 --- a/tests/Feature/Api/ProcessControllerTest.php +++ b/tests/Feature/Api/ProcessControllerTest.php @@ -3,6 +3,9 @@ namespace ProcessMaker\Api\Tests\Feature; use Database\Seeders\MetricsApiEnvironmentVariableSeeder; +use Illuminate\Support\Facades\DB; +use Illuminate\Validation\ValidationException; +use PHPUnit\Framework\Attributes\DataProvider; use ProcessMaker\Models\EnvironmentVariable; use ProcessMaker\Models\Process; use ProcessMaker\Models\ProcessCategory; @@ -14,6 +17,8 @@ class ProcessControllerTest extends TestCase { use RequestHelper; + private const AGGREGATION_SQLI_PAYLOAD = "amount')) AS x, (SELECT 1) AS y, SUM(CAST(JSON_EXTRACT(data, '\$.amount"; + public function testStartProcessesReturnsActiveProcesses() { $file = Process::getProcessTemplatesPath() . '/SingleTask.bpmn'; @@ -298,6 +303,128 @@ public function testSaveAggregation() ]); } + /** + * A crafted aggregation value must be rejected and must not overwrite the stored one. + */ + public function testSaveAggregationRejectsSqlInjectionPayload() + { + $process = Process::factory()->create(['aggregation' => 'var_amount']); + + $response = $this->apiCall('POST', route('api.processes.save-aggregation', ['process' => $process->id]), [ + 'aggregation' => self::AGGREGATION_SQLI_PAYLOAD, + ]); + + $response->assertStatus(422); + $response->assertJsonValidationErrors(['aggregation']); + $this->assertSame('var_amount', $process->refresh()->aggregation); + } + + #[DataProvider('validAggregationNamesProvider')] + public function testSaveAggregationAcceptsValidVariableNames(string $name) + { + $process = Process::factory()->create(); + + $response = $this->apiCall('POST', route('api.processes.save-aggregation', ['process' => $process->id]), [ + 'aggregation' => $name, + ]); + + $response->assertStatus(200)->assertJson(['data' => $name]); + $this->assertSame($name, $process->refresh()->aggregation); + } + + public static function validAggregationNamesProvider(): array + { + return [ + ['amount'], + ['var_amount'], + ['total_amount'], + ['grant.total'], + ['a1.b_2'], + ]; + } + + public function testStoreRejectsInvalidAggregation() + { + $response = $this->apiCall('POST', route('api.processes.store'), [ + 'name' => 'Aggregation process', + 'description' => 'Process with a malicious aggregation', + 'aggregation' => self::AGGREGATION_SQLI_PAYLOAD, + ]); + + $response->assertStatus(422); + $response->assertJsonValidationErrors(['aggregation']); + $this->assertSame(0, Process::where('name', 'Aggregation process')->count()); + } + + public function testUpdateRejectsInvalidAggregation() + { + $process = Process::factory()->create(['aggregation' => 'var_amount']); + + $response = $this->apiCall('PUT', route('api.processes.update', ['process' => $process->id]), [ + 'name' => 'Aggregation process updated', + 'description' => 'Process with a malicious aggregation', + 'aggregation' => self::AGGREGATION_SQLI_PAYLOAD, + ]); + + $response->assertStatus(422); + $response->assertJsonValidationErrors(['aggregation']); + $this->assertSame('var_amount', $process->refresh()->aggregation); + } + + public function testModelRejectsInvalidAggregationWhenRequestValidationIsBypassed() + { + $process = Process::factory()->create(); + + $this->expectException(ValidationException::class); + $process->aggregation = self::AGGREGATION_SQLI_PAYLOAD; + } + + /** + * A value that is already stored in the database (before the fix) must never alter the + * executed SQL: the JSON path is bound and the default variable is used instead. + */ + public function testStageMappingIgnoresTamperedStoredAggregation() + { + $stages = [ + ['id' => 101, 'order' => 1, 'name' => 'Custom Stage 1', 'selected' => false], + ]; + $process = Process::factory()->create([ + 'status' => 'ACTIVE', + 'stages' => $stages, + ]); + ProcessRequest::factory()->count(5)->create([ + 'process_id' => $process->id, + 'status' => 'ACTIVE', + 'last_stage_id' => $stages[0]['id'], + 'last_stage_name' => 'Custom Stage 1', + 'data' => ['amount' => '10'], + ]); + + // Bypass the model mutator to simulate a value stored by a vulnerable version. + DB::table('processes')->where('id', $process->id)->update([ + 'aggregation' => self::AGGREGATION_SQLI_PAYLOAD, + ]); + + $queries = []; + DB::listen(function ($query) use (&$queries) { + $queries[] = $query; + }); + + $response = $this->apiCall('GET', route('api.processes.stage-mapping', ['process' => $process->id])); + + $response->assertStatus(200); + $stage = collect($response->json('data.stages'))->firstWhere('stage_id', $stages[0]['id']); + $this->assertEquals(50, $stage['agregation_sum']); + $this->assertEquals(5, $stage['agregation_count']); + + $stageQueries = array_filter($queries, fn ($query) => str_contains($query->sql, 'var_aggregation_sum')); + $this->assertCount(1, $stageQueries); + $stageQuery = array_values($stageQueries)[0]; + $this->assertStringContainsString('JSON_EXTRACT(data, ?)', $stageQuery->sql); + $this->assertStringNotContainsString('SELECT 1', $stageQuery->sql); + $this->assertContains('$."amount"', $stageQuery->bindings); + } + /** * Test getting default stages for a process with statistics */ diff --git a/tests/Feature/ImportExport/Exporters/ProcessExporterTest.php b/tests/Feature/ImportExport/Exporters/ProcessExporterTest.php index 408674ee05..ff84a1eb0f 100644 --- a/tests/Feature/ImportExport/Exporters/ProcessExporterTest.php +++ b/tests/Feature/ImportExport/Exporters/ProcessExporterTest.php @@ -7,6 +7,7 @@ use Illuminate\Support\Arr; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Storage; +use Illuminate\Validation\ValidationException; use ProcessMaker\ImportExport\Exporter; use ProcessMaker\ImportExport\Exporters\ProcessExporter; use ProcessMaker\ImportExport\Importer; @@ -118,6 +119,48 @@ function () use ($process, $cancelScreen, $requestDetailScreen, $user) { $this->assertEquals(1, $process->embed()->count()); } + public function testImportKeepsValidAggregation() + { + $process = $this->createProcess('basic-process', [ + 'name' => 'aggregation process', + 'aggregation' => 'grant.total', + ]); + + $this->runExportAndImport($process, ProcessExporter::class, function () use ($process) { + $process->forceDelete(); + }); + + $imported = Process::where('name', 'aggregation process')->firstOrFail(); + $this->assertSame('grant.total', $imported->aggregation); + } + + public function testImportRejectsMaliciousAggregation() + { + $process = $this->createProcess('basic-process', [ + 'name' => 'malicious aggregation process', + 'aggregation' => 'amount', + ]); + + $this->addGlobalSignalProcess(); + $payload = $this->export($process, ProcessExporter::class); + + Arr::set( + $payload, + 'export.' . $process->uuid . '.attributes.aggregation', + "amount')) AS x, (SELECT 1) AS y, SUM(CAST(JSON_EXTRACT(data, '\$.amount" + ); + $process->forceDelete(); + + try { + $this->import($payload); + $this->fail('The import should have been rejected.'); + } catch (ValidationException $e) { + $this->assertArrayHasKey('aggregation', $e->errors()); + } + + $this->assertSame(0, Process::where('name', 'malicious aggregation process')->count()); + } + public function testSignals() { $processA = $this->createProcess('signal-process-a', [ From d86e1fd20da67f915351ce363be01397d2640bcf Mon Sep 17 00:00:00 2001 From: Miguel Angel Date: Tue, 10 Nov 2026 12:27:57 -0400 Subject: [PATCH 09/10] feat: enhance aggregation handling in ProcessController and ProcessVersion models to support legacy data --- .../Controllers/Api/ProcessController.php | 11 ++++- ProcessMaker/Models/ProcessVersion.php | 9 ++++ .../Traits/HasAggregationAttribute.php | 36 ++++++++++++--- tests/Feature/Api/ProcessControllerTest.php | 45 +++++++++++++++++++ 4 files changed, 94 insertions(+), 7 deletions(-) diff --git a/ProcessMaker/Http/Controllers/Api/ProcessController.php b/ProcessMaker/Http/Controllers/Api/ProcessController.php index b47273ce1e..90b3258500 100644 --- a/ProcessMaker/Http/Controllers/Api/ProcessController.php +++ b/ProcessMaker/Http/Controllers/Api/ProcessController.php @@ -1990,9 +1990,16 @@ public function duplicate(Process $process, Request $request) $exclude = ['id', 'uuid', 'created_at', 'updated_at']; foreach ($process->getAttributes() as $attribute => $value) { - if (!in_array($attribute, $exclude)) { - $newProcess->{$attribute} = $process->{$attribute}; + if (in_array($attribute, $exclude)) { + continue; } + + if ($attribute === 'aggregation') { + $newProcess->aggregation = Process::prepareAggregation($process->aggregation, false); + continue; + } + + $newProcess->{$attribute} = $process->{$attribute}; } if ($request->has('name')) { $newProcess->name = $request->input('name'); diff --git a/ProcessMaker/Models/ProcessVersion.php b/ProcessMaker/Models/ProcessVersion.php index 28379a3ccd..a4bbfd0914 100644 --- a/ProcessMaker/Models/ProcessVersion.php +++ b/ProcessMaker/Models/ProcessVersion.php @@ -32,6 +32,15 @@ class ProcessVersion extends ProcessMakerModel implements ProcessModelInterface const categoryClass = ProcessCategory::class; + /** + * Version rows are snapshots. An aggregation stored before validation existed must not + * stop draft save, publish, or any other write that copies the process attributes. + */ + protected function rejectsInvalidAggregation(): bool + { + return false; + } + protected $connection = 'processmaker'; /** diff --git a/ProcessMaker/Traits/HasAggregationAttribute.php b/ProcessMaker/Traits/HasAggregationAttribute.php index 12cf568e31..3e7838abf7 100644 --- a/ProcessMaker/Traits/HasAggregationAttribute.php +++ b/ProcessMaker/Traits/HasAggregationAttribute.php @@ -3,28 +3,54 @@ namespace ProcessMaker\Traits; use Illuminate\Validation\ValidationException; +use ProcessMaker\Models\Process; use ProcessMaker\Support\JsonDataPath; /** * Guards the `aggregation` attribute of process models. * * The value ends up addressing a JSON key of the request data, so it must be a plain variable - * name. Validating at the model level covers every write path (API, import, versioning) even - * when request validation is bypassed or replaced. + * name. New writes are rejected. A copy of a value already stored before that rule existed + * (a version snapshot or a duplicated process) is replaced with the default instead, so + * saving BPMN is not blocked by a legacy row. */ trait HasAggregationAttribute { /** - * @throws ValidationException when the value is not a valid variable name + * @throws ValidationException when a new value is not a valid variable name */ public function setAggregationAttribute(?string $value): void { - if ($value !== null && $value !== '' && !JsonDataPath::isValid($value)) { + $this->attributes['aggregation'] = static::prepareAggregation( + $value, + $this->rejectsInvalidAggregation() + ); + } + + /** + * Process rejects invalid names. ProcessVersion does not: every save copies the current + * aggregation onto a version, including values stored before validation existed. + */ + protected function rejectsInvalidAggregation(): bool + { + return true; + } + + /** + * @throws ValidationException when $rejectInvalid is true and the value is not a variable name + */ + public static function prepareAggregation(?string $value, bool $rejectInvalid = true): ?string + { + if ($value === null || $value === '' || JsonDataPath::isValid($value)) { + return $value; + } + + if ($rejectInvalid) { throw ValidationException::withMessages([ 'aggregation' => __('The :attribute must be a valid variable name.', ['attribute' => 'aggregation']), ]); } - $this->attributes['aggregation'] = $value; + return Process::DEFAULT_AGGREGATION; } } diff --git a/tests/Feature/Api/ProcessControllerTest.php b/tests/Feature/Api/ProcessControllerTest.php index af81319200..d3f84af1b9 100644 --- a/tests/Feature/Api/ProcessControllerTest.php +++ b/tests/Feature/Api/ProcessControllerTest.php @@ -10,6 +10,7 @@ use ProcessMaker\Models\Process; use ProcessMaker\Models\ProcessCategory; use ProcessMaker\Models\ProcessRequest; +use ProcessMaker\Models\ProcessVersion; use Tests\Feature\Shared\RequestHelper; use Tests\TestCase; @@ -379,6 +380,50 @@ public function testModelRejectsInvalidAggregationWhenRequestValidationIsBypasse $process->aggregation = self::AGGREGATION_SQLI_PAYLOAD; } + /** + * A value stored before validation existed is still copied onto a version on every save. + * That copy must not reject the save, the draft, or a duplicate. + */ + public function testLegacyAggregationDoesNotBlockSaveDraftOrDuplicate() + { + $process = Process::factory()->create([ + 'name' => 'Legacy Aggregation Process', + 'description' => 'Original description', + 'aggregation' => 'amount', + ]); + DB::table('processes')->where('id', $process->id)->update([ + 'aggregation' => self::AGGREGATION_SQLI_PAYLOAD, + ]); + $process->refresh(); + + $response = $this->apiCall('PUT', route('api.processes.update', ['process' => $process->id]), [ + 'name' => 'Legacy Aggregation Process', + 'description' => 'Updated description', + ]); + + $response->assertStatus(200); + $published = ProcessVersion::where('process_id', $process->id)->orderByDesc('id')->first(); + $this->assertNotNull($published); + $this->assertSame(Process::DEFAULT_AGGREGATION, $published->aggregation); + $this->assertSame( + self::AGGREGATION_SQLI_PAYLOAD, + DB::table('processes')->where('id', $process->id)->value('aggregation') + ); + + $draft = $process->refresh()->saveDraft(); + $this->assertSame(Process::DEFAULT_AGGREGATION, $draft->aggregation); + + $response = $this->apiCall('PUT', route('api.processes.duplicate', ['process' => $process->id]), [ + 'name' => 'Legacy Aggregation Copy', + 'description' => 'Copied description', + ]); + + $response->assertStatus(201); + $copy = Process::where('name', 'Legacy Aggregation Copy')->first(); + $this->assertNotNull($copy); + $this->assertSame(Process::DEFAULT_AGGREGATION, $copy->aggregation); + } + /** * A value that is already stored in the database (before the fix) must never alter the * executed SQL: the JSON path is bound and the default variable is used instead. From 96d1fd9d833eb8ba6d548067d3a0e3efde10d55a Mon Sep 17 00:00:00 2001 From: Miguel Angel Date: Tue, 10 Nov 2026 14:10:57 -0400 Subject: [PATCH 10/10] fix(sq): replace count check with empty check in JsonDataPath --- ProcessMaker/Support/JsonDataPath.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ProcessMaker/Support/JsonDataPath.php b/ProcessMaker/Support/JsonDataPath.php index e4631a43dd..7b7a8a3ed5 100644 --- a/ProcessMaker/Support/JsonDataPath.php +++ b/ProcessMaker/Support/JsonDataPath.php @@ -30,7 +30,7 @@ final class JsonDataPath */ public static function fromSegments(array $segments, string $pattern = self::VARIABLE_SEGMENT): string { - if (count($segments) === 0) { + if (empty($segments)) { throw new InvalidArgumentException('The JSON path must contain at least one segment.'); }