Skip to content
Merged
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
7 changes: 5 additions & 2 deletions ProcessMaker/Http/Controllers/Api/ImportController.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public function preview(Request $request, $version = null): JsonResponse
return response()->json(['error' => $e->getMessage()], 400);
}

$options = new Options([]);
$options = new Options([], $request->user()?->id);
$importer = new Importer($payload, $options);

$manifest = $importer->previewImport();
Expand Down Expand Up @@ -80,7 +80,10 @@ public function import(Request $request): JsonResponse
return response()->json(['error' => $e->getMessage()], 400);
}

$options = new Options(json_decode(file_get_contents(utf8_decode($request->file('options'))), true));
$options = new Options(
json_decode(file_get_contents(utf8_decode($request->file('options'))), true),
$request->user()?->id
);
$importer = new Importer($payload, $options);
$manifest = $importer->doImport();

Expand Down
32 changes: 32 additions & 0 deletions ProcessMaker/Http/Controllers/Api/ScriptController.php
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,7 @@ public function show(Script $script)
*/
public function store(Request $request)
{
$this->authorizeModulesExecution($request);
$request->validate(Script::rules());
$script = new Script();
$script->fill($request->input());
Expand Down Expand Up @@ -421,6 +422,7 @@ public function store(Request $request)
*/
public function update(Script $script, Request $request)
{
$this->authorizeModulesExecution($request, $script);
$request->validate(Script::rules($script));
$script->fill($request->input());
$original = array_intersect_key($script->getOriginal(), $script->getDirty());
Expand All @@ -437,6 +439,20 @@ public function update(Script $script, Request $request)
return response($request, 204);
}

private function authorizeModulesExecution(Request $request, ?Script $script = null): void
{
$executionMode = $request->input('execution_mode', $script?->execution_mode);
if ($executionMode !== Script::EXECUTION_MODE_MODULES) {
return;
}

if ($this->canUseModules($request)) {
return;
}

$request->merge(['execution_mode' => Script::EXECUTION_MODE_BARE]);
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
/**
* Update a draft script.
*
Expand Down Expand Up @@ -514,6 +530,7 @@ public function draft(Script $script, Request $request)
*/
public function duplicate(Script $script, Request $request)
{
$this->authorizeModulesExecution($request, $script);
$request->validate(Script::rules());
$newScript = new Script();

Expand All @@ -532,12 +549,27 @@ public function duplicate(Script $script, Request $request)
$newScript->description = $request->input('description');
}

$newScript->execution_mode = $request->input(
'execution_mode',
$script->execution_mode === Script::EXECUTION_MODE_MODULES
&& $this->canUseModules($request)
? Script::EXECUTION_MODE_MODULES
: Script::EXECUTION_MODE_BARE
);
$newScript->saveOrFail();
ScriptDuplicated::dispatch($newScript, $newScript->getChanges());

return new ScriptResource($newScript);
}

private function canUseModules(Request $request): bool
{
return (bool) (
$request->user()?->is_administrator
|| $request->user()?->can('run-in-process-modules')
);
}

/**
* Delete a script in a process.
*
Expand Down
17 changes: 17 additions & 0 deletions ProcessMaker/ImportExport/Exporters/ScriptExporter.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Illuminate\Support\Facades\Log;
use ProcessMaker\ImportExport\DependentType;
use ProcessMaker\Models\EnvironmentVariable;
use ProcessMaker\Models\Script;
use ProcessMaker\Models\ScriptCategory;
use ProcessMaker\Models\User;

Expand Down Expand Up @@ -51,6 +52,13 @@ public function import() : bool
// Update environment variable references in script code
$this->updateEnvironmentVariableReferences();

if (
$this->model->execution_mode === Script::EXECUTION_MODE_MODULES
&& !$this->canUseModules()
) {
$this->model->execution_mode = Script::EXECUTION_MODE_BARE;
}

// Pre-save cleanup for data source scripts to prevent constraint violations
if ($this->mode === 'update' && $this->model->exists) {
// Check if this script has any data source relationships that might cause conflicts
Expand All @@ -70,6 +78,15 @@ public function import() : bool
return $this->model->save();
}

private function canUseModules(): bool
{
$user = $this->options->importingUserId
? User::find($this->options->importingUserId)
: auth()->user();

return (bool) ($user?->is_administrator || $user?->can('run-in-process-modules'));
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

private function getEnvironmentVariables() : array
{
$environmentVariables = EnvironmentVariable::get();
Expand Down
2 changes: 1 addition & 1 deletion ProcessMaker/Jobs/ImportV2.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ private function runImport($logger)
return;
}

$options = new Options($options);
$options = new Options($options, $this->userId);
$importer = new Importer($payload, $options, $logger);
if ($this->isPreview) {
$manifest = $importer->previewImport();
Expand Down
19 changes: 18 additions & 1 deletion ProcessMaker/Jobs/TestScript.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use ProcessMaker\Models\User;
use ProcessMaker\ScriptRunners\InProcessPhpRunner;
use ProcessMaker\ScriptRuntime\ScriptExecutionContext;
use ProcessMaker\Services\ScriptExecutionModeResolver;
use Throwable;

class TestScript implements ShouldQueue
Expand Down Expand Up @@ -133,7 +134,15 @@ private function runInProcessPreview(): array
}
$timeout = max(1, $timeout);

if (config('core-service-task.execution', 'modules') === 'modules') {
$executionMode = app(ScriptExecutionModeResolver::class)->resolve($this->script);
if (
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
$executionMode === Script::EXECUTION_MODE_MODULES
&& !$this->canUseModules()
) {
$executionMode = Script::EXECUTION_MODE_BARE;
}

if ($executionMode === Script::EXECUTION_MODE_MODULES) {
$context = new ScriptExecutionContext(
data: $this->data,
config: $this->configuration,
Expand All @@ -158,6 +167,14 @@ private function runInProcessPreview(): array
return ['output' => $output];
}

private function canUseModules(): bool
{
return (bool) (
$this->current_user?->is_administrator
|| $this->current_user?->can('run-in-process-modules')
);
}

/**
* Send a response to the user interface
*
Expand Down
22 changes: 22 additions & 0 deletions ProcessMaker/Models/Script.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
* @property text code
* @property int timeout
* @property bool allow_in_process
* @property string execution_mode
*
* @OA\Schema(
* schema="scriptsEditable",
Expand All @@ -40,6 +41,7 @@
* @OA\Property(property="code", type="string"),
* @OA\Property(property="timeout", type="integer"),
* @OA\Property(property="allow_in_process", type="boolean"),
* @OA\Property(property="execution_mode", type="string", enum={"bare", "modules"}),
* @OA\Property(property="run_as_user_id", type="integer"),
* @OA\Property(property="key", type="string"),
* @OA\Property(property="script_category_id", type="integer"),
Expand All @@ -65,6 +67,15 @@
*/
class Script extends ProcessMakerModel implements ScriptInterface
{
public const EXECUTION_MODE_BARE = 'bare';

public const EXECUTION_MODE_MODULES = 'modules';

public const EXECUTION_MODES = [
self::EXECUTION_MODE_BARE,
self::EXECUTION_MODE_MODULES,
];

use SerializeToIso8601;
use HideSystemResources;
use HasCategories;
Expand All @@ -90,6 +101,7 @@ class Script extends ProcessMakerModel implements ScriptInterface
'retry_attempts' => 'integer',
'retry_wait_time' => 'integer',
'allow_in_process' => 'boolean',
'execution_mode' => 'string',
];

protected $appends = [
Expand Down Expand Up @@ -120,6 +132,15 @@ public static function boot()
]);
}

if (
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
$script->execution_mode === self::EXECUTION_MODE_MODULES
&& (!$script->allow_in_process || strtolower((string) $script->language) !== 'php')
) {
throw \Illuminate\Validation\ValidationException::withMessages([
'execution_mode' => [__('Modules execution requires an allowed PHP script.')],
]);
}

// Execute the clear cache callback
$clearCacheCallback($script);
});
Expand Down Expand Up @@ -164,6 +185,7 @@ public static function rules($existing = null)
'run_as_user_id' => 'required',
'timeout' => 'integer|min:0|max:65535',
'allow_in_process' => 'sometimes|boolean',
'execution_mode' => ['sometimes', Rule::in(self::EXECUTION_MODES)],
'script_category_id' => [new CategoryRule($existing)],
];
}
Expand Down
6 changes: 5 additions & 1 deletion ProcessMaker/ScriptRunners/ScriptRunner.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use ProcessMaker\Models\ScriptExecutor;
use ProcessMaker\Models\User;
use ProcessMaker\ScriptRuntime\ScriptExecutionContext;
use ProcessMaker\Services\ScriptExecutionModeResolver;

class ScriptRunner
{
Expand Down Expand Up @@ -115,7 +116,10 @@ private function runInProcess($code, array $data, array $config, $timeout, ?User
{
$effectiveTimeout = $this->resolveTimeout((int) $timeout, (int) $this->script->timeout);

if (config('core-service-task.execution', 'modules') === 'modules') {
if (
app(ScriptExecutionModeResolver::class)->resolve($this->script)
=== Script::EXECUTION_MODE_MODULES
) {
$context = new ScriptExecutionContext(
data: $data,
config: $config,
Expand Down
100 changes: 96 additions & 4 deletions ProcessMaker/ScriptRuntime/ScriptRuntime.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ public function run(string $code, ScriptExecutionContext $context): mixed
{
$instances = $this->instantiateModules($context);
$scriptPath = $this->writeTempScript($code);
$hasExplicitReturn = $this->hasExplicitReturn($code);
$accessToken = null;
$envSnapshot = null;

Expand All @@ -75,15 +76,28 @@ public function run(string $code, ScriptExecutionContext $context): mixed
'modules' => array_keys($instances),
]);

return (static function (string $__scriptPath, ScriptExecutionContext $__context, array $__instances) {
$result = (static function (
string $__scriptPath,
ScriptExecutionContext $__context,
array $__instances,
bool $__hasExplicitReturn
) {
$result = ['response' => 'Error: add a result array'];
extract([
'data' => $__context->data,
'config' => $__context->config,
'modules' => $__instances,
] + $__instances, EXTR_SKIP);
], EXTR_SKIP);
extract($__instances, EXTR_SKIP);

return include $__scriptPath;
})($scriptPath, $context, $instances);
$output = include $__scriptPath;

return (($output === 1 || $output === null) && !$__hasExplicitReturn)
? $result
: $output;
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
})($scriptPath, $context, $instances, $hasExplicitReturn);

return $result;
} catch (Throwable $exception) {
throw new ScriptException($exception->getMessage(), (int) $exception->getCode(), $exception);
} finally {
Expand Down Expand Up @@ -223,4 +237,82 @@ private function normalizeCode(string $code): string

return "<?php\n" . $code;
}

private function hasExplicitReturn(string $code): bool
{
$braceDepth = 0;
$functionBodyDepths = [];
$pendingFunctionBody = false;

foreach (token_get_all($code) as $token) {
if (is_array($token)) {
if ($this->isTopLevelReturn($token, $functionBodyDepths)) {
return true;
}

$this->processArrayToken($token, $braceDepth, $pendingFunctionBody);
continue;
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

if ($token === '{') {
$this->openBrace(
$braceDepth,
$functionBodyDepths,
$pendingFunctionBody
);
continue;
}

if ($token === '}') {
$this->closeBrace($braceDepth, $functionBodyDepths);
continue;
}

if ($token === ';') {
$pendingFunctionBody = false;
}
}

return false;
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

private function isTopLevelReturn(array $token, array $functionBodyDepths): bool
{
return $token[0] === T_RETURN && empty($functionBodyDepths);
}

private function processArrayToken(
array $token,
int &$braceDepth,
bool &$pendingFunctionBody
): void {
if ($token[0] === T_FUNCTION) {
$pendingFunctionBody = true;
}

if ($token[0] === T_CURLY_OPEN) {
$braceDepth++;
}
}

private function openBrace(
int &$braceDepth,
array &$functionBodyDepths,
bool &$pendingFunctionBody
): void {
$braceDepth++;
if ($pendingFunctionBody) {
$functionBodyDepths[] = $braceDepth;
$pendingFunctionBody = false;
}
}

private function closeBrace(int &$braceDepth, array &$functionBodyDepths): void
{
if (!empty($functionBodyDepths) && end($functionBodyDepths) === $braceDepth) {
array_pop($functionBodyDepths);
}

$braceDepth--;
}
}
Loading
Loading