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
18 changes: 9 additions & 9 deletions ProcessMaker/Filters/BaseFilter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down
18 changes: 15 additions & 3 deletions ProcessMaker/Http/Controllers/Api/ProcessController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -1989,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');
Expand Down Expand Up @@ -2286,7 +2294,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([
Expand Down
42 changes: 39 additions & 3 deletions ProcessMaker/Models/Process.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -33,9 +34,12 @@
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;
use ProcessMaker\Traits\ExtendedPMQL;
use ProcessMaker\Traits\HasAggregationAttribute;
use ProcessMaker\Traits\HasCategories;
use ProcessMaker\Traits\HasSelfServiceTasks;
use ProcessMaker\Traits\HasVersioning;
Expand Down Expand Up @@ -160,13 +164,16 @@ class Process extends ProcessMakerModel implements HasMedia, ProcessModelInterfa
use ProcessTrait;
use Exportable;
use ProjectAssetTrait;
use HasAggregationAttribute;

const categoryClass = ProcessCategory::class;

const ASSIGNMENT_PROCESS = 'Assignment process';

const NOT_ASSIGNABLE_USER_STATUS = ['INACTIVE', 'OUT_OF_OFFICE'];

const DEFAULT_AGGREGATION = 'amount';

protected $connection = 'processmaker';

/**
Expand Down Expand Up @@ -426,6 +433,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()],
];
}

Expand Down Expand Up @@ -2049,13 +2057,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();

Expand All @@ -2076,6 +2087,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.
*
Expand Down
11 changes: 11 additions & 0 deletions ProcessMaker/Models/ProcessVersion.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -27,9 +28,19 @@ class ProcessVersion extends ProcessMakerModel implements ProcessModelInterface
use HasSelfServiceTasks;
use HasCategories;
use ProcessTrait;
use HasAggregationAttribute;

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';

/**
Expand Down
28 changes: 28 additions & 0 deletions ProcessMaker/Rules/AggregationVariable.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

namespace ProcessMaker\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use ProcessMaker\Support\JsonDataPath;

/**
* Validates the variable name used to aggregate request data in the process stages.
*
* Accepts dot separated variable names (e.g. "amount", "grant.total"). Mirrors the modeler
* validation in AgregationProperty.vue so the UI and the API agree.
*/
class AggregationVariable implements ValidationRule
{
/**
* Run the validation rule.
*
* @param \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (!is_string($value) || !JsonDataPath::isValid($value)) {
$fail(__('The :attribute must be a valid variable name.', ['attribute' => $attribute]));
}
}
}
69 changes: 69 additions & 0 deletions ProcessMaker/Support/JsonDataPath.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?php

namespace ProcessMaker\Support;

use InvalidArgumentException;

/**
* Builds a safe MySQL JSON path (e.g. $."a"."b") from user supplied key names.
*
* Every segment is validated against a strict allow-list and then wrapped in double quotes,
* so key names can never be interpreted as path syntax. The returned path is meant to be
* passed as a bound parameter to JSON_EXTRACT(), never interpolated into raw SQL.
*/
final class JsonDataPath
{
/**
* Any Unicode letter or number plus underscore, hyphen and space. Used by advanced filters.
*/
public const FILTER_SEGMENT = '/^[\p{L}\p{N}_\- ]+$/u';

/**
* Variable-name style segments. Mirrors the modeler AgregationProperty.vue validation.
*/
public const VARIABLE_SEGMENT = '/^[A-Za-z][0-9A-Za-z_$]*$/';

/**
* @param array<int, string> $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 (empty($segments)) {
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;
}
}
56 changes: 56 additions & 0 deletions ProcessMaker/Traits/HasAggregationAttribute.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

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. 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 a new value is not a valid variable name
*/
public function setAggregationAttribute(?string $value): void
{
$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']),
]);
}

return Process::DEFAULT_AGGREGATION;
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
}
Loading
Loading