From 8ecfb29ff640dc5b2b72361318f082a98cc6388e Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Wed, 11 Nov 2026 11:55:06 -0400 Subject: [PATCH 01/29] fix(FOUR-34369): eager-load processRequest.process in optimized index query Register constrained with() for processRequest.process when the client requests that include on indexOptimizedBaseQuery. It was listed in handledIncludes but never applied, so the nested process was missing or lazy-loaded per row. https://processmaker.atlassian.net/browse/FOUR-34369 --- .../Traits/TaskControllerIndexMethods.php | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/ProcessMaker/Traits/TaskControllerIndexMethods.php b/ProcessMaker/Traits/TaskControllerIndexMethods.php index 3f2c56436e..f554b09177 100644 --- a/ProcessMaker/Traits/TaskControllerIndexMethods.php +++ b/ProcessMaker/Traits/TaskControllerIndexMethods.php @@ -119,6 +119,29 @@ private function indexOptimizedBaseQuery($request) $with['draft'] = fn ($q) => $q->select(['id', 'uuid', 'process_request_token_id']); } + if (in_array('processRequest.process', $includes, true)) { + if (!isset($with['processRequest'])) { + $processRequestColumns = [ + 'id', + 'uuid', + 'case_number', + 'case_title', + 'name', + 'status', + 'user_id', + 'process_id', + 'parent_id', + ]; + $with['processRequest'] = function ($q) use ($includeData, $processRequestColumns) { + $q->select($processRequestColumns); + if (!$includeData) { + $q->exclude(['data']); + } + }; + } + $with['processRequest.process'] = fn ($q) => $q->select(['id', 'name', 'uuid']); + } + $handledIncludes = ['data', 'processRequest', 'process', 'user', 'draft', 'processRequest.process']; $additionalIncludes = array_values(array_diff($includes, $handledIncludes)); From 49c3be3bd412887f80d1a54a6020aaec5442eb58 Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Wed, 11 Nov 2026 12:10:13 -0400 Subject: [PATCH 02/29] fix(FOUR-34369): index tasks and requests after raw token persistence Raw UPDATEs in TokenPersistenceRawRepository bypass Eloquent save(), so Scout never ran when TOKEN_PERSISTENCE_RAW_ENABLED was on. Invoke ModelObserver::saved after token and process request raw updates so indexed search stays in sync on activate/complete. https://processmaker.atlassian.net/browse/FOUR-34369 --- .../TokenPersistenceRawRepository.php | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/ProcessMaker/Repositories/TokenPersistenceRawRepository.php b/ProcessMaker/Repositories/TokenPersistenceRawRepository.php index 726b7ff2f8..40c28ddcb7 100644 --- a/ProcessMaker/Repositories/TokenPersistenceRawRepository.php +++ b/ProcessMaker/Repositories/TokenPersistenceRawRepository.php @@ -5,7 +5,10 @@ namespace ProcessMaker\Repositories; use Carbon\Carbon; +use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\DB; +use Laravel\Scout\ModelObserver; +use Laravel\Scout\Searchable; use ProcessMaker\Models\ProcessRequest; use ProcessMaker\Models\ProcessRequestToken; @@ -102,6 +105,7 @@ public function persistInstanceUpdated(ProcessRequest $instance): void $this->runUpdate('process_requests', (int) $instance->getKey(), $payload); $instance->syncChanges(); + $this->syncSearchIndexAfterRawPersist($instance); } /** @@ -128,6 +132,7 @@ private function updateToken(ProcessRequestToken $token, array $fields): void $this->runUpdate('process_request_tokens', $tokenId, $payload); $token->syncChanges(); + $this->syncSearchIndexAfterRawPersist($token); } /** @@ -159,4 +164,16 @@ private function serializeColumnValue(string $field, mixed $value): mixed return $value; } + + /** + * Raw UPDATE bypasses Eloquent save(); run Scout's saved handler on searchable models. + */ + private function syncSearchIndexAfterRawPersist(Model $model): void + { + if (!in_array(Searchable::class, class_uses_recursive($model), true)) { + return; + } + + (new ModelObserver)->saved($model); + } } From 9ef26c3f17356a18ee30bc75c1bc977d1162ec39 Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Wed, 11 Nov 2026 12:30:41 -0400 Subject: [PATCH 03/29] fix(FOUR-34369): select correct columns for optimized draft eager load indexOptimizedBaseQuery used process_request_token_id and uuid on TaskDraft, but drafts are keyed by task_id and the table has no uuid column. Align the include with TaskResource and show-fast: id, task_id, data. https://processmaker.atlassian.net/browse/FOUR-34369 --- ProcessMaker/Traits/TaskControllerIndexMethods.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ProcessMaker/Traits/TaskControllerIndexMethods.php b/ProcessMaker/Traits/TaskControllerIndexMethods.php index f554b09177..fc92dd4a06 100644 --- a/ProcessMaker/Traits/TaskControllerIndexMethods.php +++ b/ProcessMaker/Traits/TaskControllerIndexMethods.php @@ -116,7 +116,7 @@ private function indexOptimizedBaseQuery($request) } if (in_array('draft', $includes, true)) { - $with['draft'] = fn ($q) => $q->select(['id', 'uuid', 'process_request_token_id']); + $with['draft'] = fn ($q) => $q->select(['id', 'task_id', 'data']); } if (in_array('processRequest.process', $includes, true)) { From fbecbcbc6f02a07c03ea93ca221928186003504b Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Wed, 11 Nov 2026 14:38:50 -0400 Subject: [PATCH 04/29] fix(FOUR-34369): authorize v1.1 task completion before closed check With TASK_UPDATE_V1_1_ENABLED, PUT /api/1.1/tasks/{id} returned 422 for another user's CLOSED tasks before Gate::authorize, leaking closed state. Run the update policy first to match v1.0 and return 403 for unauthorized callers on both open and closed tasks. https://processmaker.atlassian.net/browse/FOUR-34369 --- .../Services/TaskCompletionRawService.php | 8 +++---- .../Api/V1_1/TaskControllerUpdateTest.php | 24 +++++++++++++++++++ 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/ProcessMaker/Services/TaskCompletionRawService.php b/ProcessMaker/Services/TaskCompletionRawService.php index ca56244a9c..f9822cf539 100644 --- a/ProcessMaker/Services/TaskCompletionRawService.php +++ b/ProcessMaker/Services/TaskCompletionRawService.php @@ -42,10 +42,6 @@ public function completeTask(int $taskId, array $payload, User $user): array throw new NotFoundHttpException(__('Task not found')); } - if ($taskRow->status === 'CLOSED') { - abort(422, __('Task already closed')); - } - $processRow = $this->repository->findProcessForComplete((int) $taskRow->process_id); if ($processRow === null) { @@ -57,6 +53,10 @@ public function completeTask(int $taskId, array $payload, User $user): array $this->engineBridge->hydrateTokenForPolicy($taskRow, $processRow) ); + if ($taskRow->status === 'CLOSED') { + abort(422, __('Task already closed')); + } + $requestRow = $this->repository->findProcessRequestForComplete((int) $taskRow->process_request_id); if ($requestRow === null) { diff --git a/tests/Feature/Api/V1_1/TaskControllerUpdateTest.php b/tests/Feature/Api/V1_1/TaskControllerUpdateTest.php index 5d5a38638b..71af5e49d0 100644 --- a/tests/Feature/Api/V1_1/TaskControllerUpdateTest.php +++ b/tests/Feature/Api/V1_1/TaskControllerUpdateTest.php @@ -198,4 +198,28 @@ public function testUpdateDeniesUnauthorizedUser(): void $response->assertStatus(403); } + + public function testUpdateDeniesUnauthorizedUserWhenTaskAlreadyClosed(): void + { + Config::set('app.task_update_v1_1_enabled', true); + + $caller = User::factory()->create(['is_administrator' => false]); + $assignee = User::factory()->create(['is_administrator' => false]); + $task = ProcessRequestToken::factory()->create([ + 'user_id' => $assignee->id, + 'status' => 'CLOSED', + ]); + + $response = $this->actingAs($caller, 'api')->json( + 'PUT', + '/api/' . preg_replace('/^.*\/api\//i', '', route('api.1.1.tasks.update', $task->id)), + [ + 'status' => 'COMPLETED', + 'data' => ['foo' => 'bar'], + ] + ); + + $response->assertStatus(403); + $response->assertJsonMissing(['message' => 'Task already closed']); + } } From a78a842595f3988319d1f8d17d072dfd3135dad0 Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Wed, 11 Nov 2026 14:41:47 -0400 Subject: [PATCH 05/29] chore(FOUR-34369): align composer.json with develop Restore version and package-savedsearch constraint to match origin/develop, reverting local branch overrides. https://processmaker.atlassian.net/browse/FOUR-34369 --- composer.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index da9ecc69a0..318d58c582 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "processmaker/processmaker", - "version": "2026.17.1-p3", + "version": "2026.16.5", "description": "BPM PHP Software", "keywords": [ "php bpm processmaker" @@ -183,7 +183,7 @@ "package-product-analytics": "1.5.12", "package-projects": "1.12.12", "package-rpa": "1.1.2", - "package-savedsearch": "dev-epic/FOUR-32144", + "package-savedsearch": "1.43.24", "package-slideshow": "1.4.3", "package-smart-extract": "1.0.4", "package-signature": "1.15.6", From d9f56e29f2c45209dbea4f5300da356ee6e1483f Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Wed, 11 Nov 2026 17:20:05 -0400 Subject: [PATCH 06/29] refactor(FOUR-34369): lower cognitive complexity of optimized index eager loads Extract helpers for include parsing and optimized with() building so indexOptimizedBaseQuery satisfies Sonar S3776 without changing query behavior. https://processmaker.atlassian.net/browse/FOUR-34369 --- .../Traits/TaskControllerIndexMethods.php | 112 ++++++++++-------- 1 file changed, 63 insertions(+), 49 deletions(-) diff --git a/ProcessMaker/Traits/TaskControllerIndexMethods.php b/ProcessMaker/Traits/TaskControllerIndexMethods.php index fc92dd4a06..053c544352 100644 --- a/ProcessMaker/Traits/TaskControllerIndexMethods.php +++ b/ProcessMaker/Traits/TaskControllerIndexMethods.php @@ -79,32 +79,46 @@ private function indexBaseQuery($request) private function indexOptimizedBaseQuery($request) { - $includes = $request->has('include') - ? array_map('trim', explode(',', $request->input('include'))) - : []; + $includes = $this->parseIndexIncludeList($request); $includeData = in_array('data', $includes, true); $query = ProcessRequestToken::query(); + $with = $this->buildOptimizedIndexWith($includes, $includeData); + + $handledIncludes = ['data', 'processRequest', 'process', 'user', 'draft', 'processRequest.process']; + $additionalIncludes = array_values(array_diff($includes, $handledIncludes)); + + if (!empty($with)) { + $query->with($with); + } + + if (!empty($additionalIncludes)) { + $query->with($additionalIncludes); + } + + return $query; + } + + private function parseIndexIncludeList($request): array + { + if (!$request->has('include')) { + return []; + } + + return array_map('trim', explode(',', $request->input('include'))); + } + + /** + * @return array + */ + private function buildOptimizedIndexWith(array $includes, bool $includeData): array + { $with = []; - if (in_array('processRequest', $includes, true)) { - $processRequestColumns = [ - 'id', - 'uuid', - 'case_number', - 'case_title', - 'name', - 'status', - 'user_id', - 'process_id', - 'parent_id', - ]; - $with['processRequest'] = function ($q) use ($includeData, $processRequestColumns) { - $q->select($processRequestColumns); - if (!$includeData) { - $q->exclude(['data']); - } - }; + $needsProcessRequest = in_array('processRequest', $includes, true) + || in_array('processRequest.process', $includes, true); + if ($needsProcessRequest) { + $with['processRequest'] = $this->optimizedProcessRequestEagerLoad($includeData); } if (in_array('process', $includes, true)) { @@ -120,40 +134,40 @@ private function indexOptimizedBaseQuery($request) } if (in_array('processRequest.process', $includes, true)) { - if (!isset($with['processRequest'])) { - $processRequestColumns = [ - 'id', - 'uuid', - 'case_number', - 'case_title', - 'name', - 'status', - 'user_id', - 'process_id', - 'parent_id', - ]; - $with['processRequest'] = function ($q) use ($includeData, $processRequestColumns) { - $q->select($processRequestColumns); - if (!$includeData) { - $q->exclude(['data']); - } - }; - } $with['processRequest.process'] = fn ($q) => $q->select(['id', 'name', 'uuid']); } - $handledIncludes = ['data', 'processRequest', 'process', 'user', 'draft', 'processRequest.process']; - $additionalIncludes = array_values(array_diff($includes, $handledIncludes)); + return $with; + } - if (!empty($with)) { - $query->with($with); - } + /** + * @return list + */ + private function optimizedProcessRequestSelectColumns(): array + { + return [ + 'id', + 'uuid', + 'case_number', + 'case_title', + 'name', + 'status', + 'user_id', + 'process_id', + 'parent_id', + ]; + } - if (!empty($additionalIncludes)) { - $query->with($additionalIncludes); - } + private function optimizedProcessRequestEagerLoad(bool $includeData): \Closure + { + $processRequestColumns = $this->optimizedProcessRequestSelectColumns(); - return $query; + return function ($q) use ($includeData, $processRequestColumns) { + $q->select($processRequestColumns); + if (!$includeData) { + $q->exclude(['data']); + } + }; } private function resolveIndexFields($request): ?array From 257a64ca9f260605b69697de8a74d87e12b3478a Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Thu, 12 Nov 2026 08:56:22 -0400 Subject: [PATCH 07/29] fix(FOUR-34369): hide draft payload on task index without view permission Eager-load task drafts without data on the optimized index and gate includeDraft on ProcessRequestTokenPolicy::view so view-all_requests cannot read other assignees' unsubmitted form data via include=draft. --- ProcessMaker/Traits/TaskControllerIndexMethods.php | 2 +- ProcessMaker/Traits/TaskResourceIncludes.php | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/ProcessMaker/Traits/TaskControllerIndexMethods.php b/ProcessMaker/Traits/TaskControllerIndexMethods.php index 053c544352..2a02581365 100644 --- a/ProcessMaker/Traits/TaskControllerIndexMethods.php +++ b/ProcessMaker/Traits/TaskControllerIndexMethods.php @@ -130,7 +130,7 @@ private function buildOptimizedIndexWith(array $includes, bool $includeData): ar } if (in_array('draft', $includes, true)) { - $with['draft'] = fn ($q) => $q->select(['id', 'task_id', 'data']); + $with['draft'] = fn ($q) => $q->select(['id', 'task_id']); } if (in_array('processRequest.process', $includes, true)) { diff --git a/ProcessMaker/Traits/TaskResourceIncludes.php b/ProcessMaker/Traits/TaskResourceIncludes.php index 92b4bcd3d8..351d1b2c50 100644 --- a/ProcessMaker/Traits/TaskResourceIncludes.php +++ b/ProcessMaker/Traits/TaskResourceIncludes.php @@ -70,6 +70,19 @@ private function includeDraft() return ['draft' => null]; } + if (!$draft) { + return ['draft' => null]; + } + + $user = Auth::user(); + if (!$user || !$user->can('view', $this->resource)) { + return ['draft' => $draft->only(['id', 'task_id'])]; + } + + if (!array_key_exists('data', $draft->getAttributes())) { + $draft = TaskDraft::query()->whereKey($draft->getKey())->first(['id', 'task_id', 'data']); + } + return ['draft' => $draft]; } From d618f493095981d64c4f150f8299b78f3ae2bd75 Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Thu, 12 Nov 2026 08:57:41 -0400 Subject: [PATCH 08/29] fix(FOUR-34369): hide draft payload on task index without view permission Eager-load task drafts without data on the optimized index and gate includeDraft on ProcessRequestTokenPolicy::view so view-all_requests cannot read other assignees' unsubmitted form data via include=draft. https://processmaker.atlassian.net/browse/FOUR-34369 --- tests/Feature/Api/TasksTest.php | 53 +++++++++++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 2 deletions(-) diff --git a/tests/Feature/Api/TasksTest.php b/tests/Feature/Api/TasksTest.php index 94002630a0..feb2df56ee 100644 --- a/tests/Feature/Api/TasksTest.php +++ b/tests/Feature/Api/TasksTest.php @@ -2,13 +2,13 @@ namespace Tests\Feature\Api; -use PHPUnit\Framework\Attributes\Group as TestGroup; use Carbon\Carbon; use Database\Seeders\PermissionSeeder; use Facades\ProcessMaker\RollbackProcessRequest; use Illuminate\Foundation\Testing\WithFaker; use Illuminate\Support\Facades\Notification; use Mockery; +use PHPUnit\Framework\Attributes\Group as TestGroup; use ProcessMaker\Facades\WorkflowManager; use ProcessMaker\Http\Controllers\Api\TaskController; use ProcessMaker\Models\Group; @@ -22,6 +22,7 @@ use ProcessMaker\Models\Screen; use ProcessMaker\Models\ScreenVersion; use ProcessMaker\Models\Setting; +use ProcessMaker\Models\TaskDraft; use ProcessMaker\Models\User; use ProcessMaker\Notifications\ActivityActivatedNotification; use ProcessMaker\Providers\AuthServiceProvider; @@ -33,7 +34,6 @@ * Tests routes related to tokens list and show * the creation, update and deletion are controller by the engine * and should not be changed by endpoints - * */ #[TestGroup('process_tests')] class TasksTest extends TestCase @@ -191,6 +191,55 @@ public function testGetListClosedTasks() $this->assertEquals(count($response->json()['data']), 3); } + /** + * Task list with include=draft must not expose another assignee's draft payload + * to users who only have view-all_requests (list) without ProcessRequestTokenPolicy::view. + */ + public function testTaskIndexExcludesOtherUsersDraftDataWithoutViewPermission() + { + $this->initializePermissions(); + config(['app.task_drafts_enabled' => true]); + + $viewer = User::factory()->create(); + $viewer->giveDirectPermission('view-all_requests'); + $this->user = $viewer; + + $assignee = User::factory()->create(); + $processRequest = ProcessRequest::factory()->create(); + + $otherTask = ProcessRequestToken::factory()->create([ + 'process_request_id' => $processRequest->id, + 'status' => 'ACTIVE', + 'user_id' => $assignee->id, + ]); + TaskDraft::factory()->create([ + 'task_id' => $otherTask->id, + 'data' => ['secret' => 'other-user-draft'], + ]); + + $ownTask = ProcessRequestToken::factory()->create([ + 'process_request_id' => $processRequest->id, + 'status' => 'ACTIVE', + 'user_id' => $viewer->id, + ]); + TaskDraft::factory()->create([ + 'task_id' => $ownTask->id, + 'data' => ['mine' => 'own-draft'], + ]); + + $response = $this->apiCall('GET', route('api.tasks.index', ['include' => 'draft'])); + $response->assertStatus(200); + + $tasks = collect($response->json('data'))->keyBy('id'); + + $otherDraft = $tasks[$otherTask->id]['draft']; + $this->assertNotNull($otherDraft); + $this->assertArrayNotHasKey('data', $otherDraft); + + $ownDraft = $tasks[$ownTask->id]['draft']; + $this->assertEquals('own-draft', $ownDraft['data']['mine'] ?? null); + } + /** * You only see non system type tasks. */ From dd5188d1029029bf51a6a99836c0a9e1e784bfe3 Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Thu, 12 Nov 2026 09:25:59 -0400 Subject: [PATCH 09/29] fix(FOUR-34369): hydrate token for draft view policy on partial projections ProcessRequestTokenPolicy::view needs user_id and process.manager_id; the optimized index and fast show omit them. Load missing attributes before gating draft.data, and eager-load manager_id when include=draft. https://processmaker.atlassian.net/browse/FOUR-34369 --- .../TaskV11ShowFastRepository.php | 2 +- .../Traits/TaskControllerIndexMethods.php | 12 +++-- ProcessMaker/Traits/TaskResourceIncludes.php | 50 ++++++++++++++++++- tests/Feature/Api/TasksTest.php | 32 ++++++++++++ 4 files changed, 90 insertions(+), 6 deletions(-) diff --git a/ProcessMaker/Repositories/TaskV11ShowFastRepository.php b/ProcessMaker/Repositories/TaskV11ShowFastRepository.php index 42b4e70da2..1313077c79 100644 --- a/ProcessMaker/Repositories/TaskV11ShowFastRepository.php +++ b/ProcessMaker/Repositories/TaskV11ShowFastRepository.php @@ -50,7 +50,7 @@ public function findForShow(int $taskId): ProcessRequestToken } if ($token->process_id) { - $process = Process::query()->select(['id', 'name'])->find($token->process_id); + $process = Process::query()->select(['id', 'name', 'manager_id'])->find($token->process_id); $token->setRelation('process', $process); } diff --git a/ProcessMaker/Traits/TaskControllerIndexMethods.php b/ProcessMaker/Traits/TaskControllerIndexMethods.php index 2a02581365..7ce95d9bcd 100644 --- a/ProcessMaker/Traits/TaskControllerIndexMethods.php +++ b/ProcessMaker/Traits/TaskControllerIndexMethods.php @@ -121,10 +121,6 @@ private function buildOptimizedIndexWith(array $includes, bool $includeData): ar $with['processRequest'] = $this->optimizedProcessRequestEagerLoad($includeData); } - if (in_array('process', $includes, true)) { - $with['process'] = fn ($q) => $q->select(['id', 'name', 'uuid']); - } - if (in_array('user', $includes, true)) { $with['user'] = fn ($q) => $q->select(['id', 'firstname', 'lastname', 'avatar', 'status']); } @@ -133,6 +129,14 @@ private function buildOptimizedIndexWith(array $includes, bool $includeData): ar $with['draft'] = fn ($q) => $q->select(['id', 'task_id']); } + if (in_array('process', $includes, true) || in_array('draft', $includes, true)) { + $processColumns = ['id', 'manager_id']; + if (in_array('process', $includes, true)) { + $processColumns = array_values(array_unique(array_merge($processColumns, ['name', 'uuid']))); + } + $with['process'] = fn ($q) => $q->select($processColumns); + } + if (in_array('processRequest.process', $includes, true)) { $with['processRequest.process'] = fn ($q) => $q->select(['id', 'name', 'uuid']); } diff --git a/ProcessMaker/Traits/TaskResourceIncludes.php b/ProcessMaker/Traits/TaskResourceIncludes.php index 351d1b2c50..858781fed2 100644 --- a/ProcessMaker/Traits/TaskResourceIncludes.php +++ b/ProcessMaker/Traits/TaskResourceIncludes.php @@ -6,7 +6,9 @@ use ProcessMaker\Http\Resources\ScreenVersion as ScreenVersionResource; use ProcessMaker\Http\Resources\Users; use ProcessMaker\Managers\DataManager; +use ProcessMaker\Models\Process; use ProcessMaker\Models\ProcessRequest; +use ProcessMaker\Models\ProcessRequestToken; use ProcessMaker\Models\ScreenVersion as ScreenVersionModel; use ProcessMaker\Models\TaskDraft; use ProcessMaker\Models\User; @@ -75,7 +77,12 @@ private function includeDraft() } $user = Auth::user(); - if (!$user || !$user->can('view', $this->resource)) { + if (!$user) { + return ['draft' => $draft->only(['id', 'task_id'])]; + } + + $this->ensureTokenAttributesForViewPolicy($this->resource); + if (!$user->can('view', $this->resource)) { return ['draft' => $draft->only(['id', 'task_id'])]; } @@ -202,6 +209,47 @@ private function includeElementDestination() return ['elementDestination' => $elementDestination]; } + /** + * Partial token/process projections (optimized index, fast show) may omit columns + * required by ProcessRequestTokenPolicy::view before including draft payloads. + */ + private function ensureTokenAttributesForViewPolicy(ProcessRequestToken $token): void + { + $tokenColumns = []; + foreach (['user_id', 'process_id', 'is_self_service'] as $column) { + if (!array_key_exists($column, $token->getAttributes())) { + $tokenColumns[] = $column; + } + } + + if ($tokenColumns !== []) { + $row = ProcessRequestToken::query() + ->whereKey($token->getKey()) + ->first(array_merge(['id'], $tokenColumns)); + if ($row) { + foreach ($tokenColumns as $column) { + $token->setAttribute($column, $row->{$column}); + } + } + } + + if ($token->is_self_service && !array_key_exists('self_service_groups', $token->getAttributes())) { + $groups = ProcessRequestToken::query()->whereKey($token->getKey())->value('self_service_groups'); + $token->setAttribute('self_service_groups', $groups); + } + + $process = $token->relationLoaded('process') ? $token->process : null; + if ($process && !array_key_exists('manager_id', $process->getAttributes())) { + $managerIds = Process::query()->whereKey($process->getKey())->value('manager_id'); + $process->setAttribute('manager_id', $managerIds); + } elseif (!$token->relationLoaded('process') && $token->process_id) { + $token->setRelation( + 'process', + Process::query()->whereKey($token->process_id)->first(['id', 'manager_id']) + ); + } + } + private function loadUserRequestPermission(ProcessRequest $request, User $user, array $permissions) { $permissions[] = [ diff --git a/tests/Feature/Api/TasksTest.php b/tests/Feature/Api/TasksTest.php index feb2df56ee..ce7654c33b 100644 --- a/tests/Feature/Api/TasksTest.php +++ b/tests/Feature/Api/TasksTest.php @@ -240,6 +240,38 @@ public function testTaskIndexExcludesOtherUsersDraftDataWithoutViewPermission() $this->assertEquals('own-draft', $ownDraft['data']['mine'] ?? null); } + public function testTaskIndexIncludesOwnDraftDataWhenTokenProjectionOmitsUserId() + { + $this->initializePermissions(); + config([ + 'app.task_drafts_enabled' => true, + 'app.processmaker_optimized_tasks_enabled' => true, + ]); + + $assignee = User::factory()->create(); + $this->user = $assignee; + + $processRequest = ProcessRequest::factory()->create(); + $task = ProcessRequestToken::factory()->create([ + 'process_request_id' => $processRequest->id, + 'status' => 'ACTIVE', + 'user_id' => $assignee->id, + ]); + TaskDraft::factory()->create([ + 'task_id' => $task->id, + 'data' => ['field' => 'assignee-draft'], + ]); + + $response = $this->apiCall('GET', route('api.tasks.index', [ + 'include' => 'draft', + 'fields' => 'id,element_name,status', + ])); + + $response->assertStatus(200); + $tasks = collect($response->json('data'))->keyBy('id'); + $this->assertEquals('assignee-draft', $tasks[$task->id]['draft']['data']['field'] ?? null); + } + /** * You only see non system type tasks. */ From 51641b4e5e95340d4c0b9458cbbb687b0f1df4d8 Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Thu, 12 Nov 2026 09:46:06 -0400 Subject: [PATCH 10/29] fix(FOUR-34369): gate draft data on task index and fix manager checks Omit draft payloads for list callers without task view rights; eager-load draft without data on the optimized index. Resolve manager checks from process.properties (not a DB column), avoid attaching process on draft-only includes, and hydrate partial tokens for assignee/self-service policy checks without leaking process config in list JSON. https://processmaker.atlassian.net/browse/FOUR-34369 --- .../TaskV11ShowFastRepository.php | 2 +- .../Traits/TaskControllerIndexMethods.php | 10 +-- ProcessMaker/Traits/TaskResourceIncludes.php | 82 +++++++++++++++++-- 3 files changed, 79 insertions(+), 15 deletions(-) diff --git a/ProcessMaker/Repositories/TaskV11ShowFastRepository.php b/ProcessMaker/Repositories/TaskV11ShowFastRepository.php index 1313077c79..e73596587a 100644 --- a/ProcessMaker/Repositories/TaskV11ShowFastRepository.php +++ b/ProcessMaker/Repositories/TaskV11ShowFastRepository.php @@ -50,7 +50,7 @@ public function findForShow(int $taskId): ProcessRequestToken } if ($token->process_id) { - $process = Process::query()->select(['id', 'name', 'manager_id'])->find($token->process_id); + $process = Process::query()->select(['id', 'name', 'properties'])->find($token->process_id); $token->setRelation('process', $process); } diff --git a/ProcessMaker/Traits/TaskControllerIndexMethods.php b/ProcessMaker/Traits/TaskControllerIndexMethods.php index 7ce95d9bcd..dd6ea3f419 100644 --- a/ProcessMaker/Traits/TaskControllerIndexMethods.php +++ b/ProcessMaker/Traits/TaskControllerIndexMethods.php @@ -129,12 +129,12 @@ private function buildOptimizedIndexWith(array $includes, bool $includeData): ar $with['draft'] = fn ($q) => $q->select(['id', 'task_id']); } - if (in_array('process', $includes, true) || in_array('draft', $includes, true)) { - $processColumns = ['id', 'manager_id']; - if (in_array('process', $includes, true)) { - $processColumns = array_values(array_unique(array_merge($processColumns, ['name', 'uuid']))); + if (in_array('process', $includes, true)) { + $processColumns = ['id', 'name', 'uuid']; + if (in_array('draft', $includes, true)) { + $processColumns[] = 'properties'; } - $with['process'] = fn ($q) => $q->select($processColumns); + $with['process'] = fn ($q) => $q->select(array_values(array_unique($processColumns))); } if (in_array('processRequest.process', $includes, true)) { diff --git a/ProcessMaker/Traits/TaskResourceIncludes.php b/ProcessMaker/Traits/TaskResourceIncludes.php index 858781fed2..67510fe1b5 100644 --- a/ProcessMaker/Traits/TaskResourceIncludes.php +++ b/ProcessMaker/Traits/TaskResourceIncludes.php @@ -82,7 +82,7 @@ private function includeDraft() } $this->ensureTokenAttributesForViewPolicy($this->resource); - if (!$user->can('view', $this->resource)) { + if (!$this->userCanViewTaskForDraft($user)) { return ['draft' => $draft->only(['id', 'task_id'])]; } @@ -239,15 +239,79 @@ private function ensureTokenAttributesForViewPolicy(ProcessRequestToken $token): } $process = $token->relationLoaded('process') ? $token->process : null; - if ($process && !array_key_exists('manager_id', $process->getAttributes())) { - $managerIds = Process::query()->whereKey($process->getKey())->value('manager_id'); - $process->setAttribute('manager_id', $managerIds); - } elseif (!$token->relationLoaded('process') && $token->process_id) { - $token->setRelation( - 'process', - Process::query()->whereKey($token->process_id)->first(['id', 'manager_id']) - ); + if ($process && !array_key_exists('properties', $process->getAttributes())) { + $properties = Process::query()->whereKey($process->getKey())->value('properties'); + $process->setAttribute('properties', $properties); + } + } + + /** + * Mirrors ProcessRequestTokenPolicy::view without lazy-loading process on the token + * (loaded process relations are serialized by Task::toArray before includes run). + */ + private function userCanViewTaskForDraft(User $user): bool + { + if ($user->is_administrator) { + return true; } + + $token = $this->resource; + if ((int) $token->user_id === (int) $user->id) { + return true; + } + + if (in_array($user->id, $this->managerIdsForTaskProcess($token), true)) { + return true; + } + + return $user->canSelfServe($token); + } + + /** + * @return list + */ + private function managerIdsForTaskProcess(ProcessRequestToken $token): array + { + $process = $token->relationLoaded('process') ? $token->process : null; + if ($process) { + if (!array_key_exists('properties', $process->getAttributes())) { + $properties = Process::query()->whereKey($process->getKey())->value('properties'); + $process->setAttribute('properties', $this->decodeJsonColumn($properties)); + } + + return $process->manager_id ?? []; + } + + if (!$token->process_id) { + return []; + } + + $properties = Process::query()->whereKey($token->process_id)->value('properties'); + $managerId = ($this->decodeJsonColumn($properties))['manager_id'] ?? null; + + if ($managerId === null || $managerId === 'undefined') { + return []; + } + + return is_array($managerId) ? $managerId : [$managerId]; + } + + /** + * @return array + */ + private function decodeJsonColumn(mixed $value): array + { + if (is_array($value)) { + return $value; + } + + if (!is_string($value) || $value === '') { + return []; + } + + $decoded = json_decode($value, true); + + return is_array($decoded) ? $decoded : []; } private function loadUserRequestPermission(ProcessRequest $request, User $user, array $permissions) From 752fb97dbf2255a13c7bf056881fde9ebe107af8 Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Thu, 12 Nov 2026 10:10:42 -0400 Subject: [PATCH 11/29] fix(FOUR-34369): align draft manager gate with loose id comparison Match ProcessRequestTokenPolicy::view when manager_id values in process properties are stored as strings. https://processmaker.atlassian.net/browse/FOUR-34369 --- ProcessMaker/Traits/TaskResourceIncludes.php | 4 +-- tests/Feature/Api/TasksTest.php | 32 ++++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/ProcessMaker/Traits/TaskResourceIncludes.php b/ProcessMaker/Traits/TaskResourceIncludes.php index 67510fe1b5..dc0318a121 100644 --- a/ProcessMaker/Traits/TaskResourceIncludes.php +++ b/ProcessMaker/Traits/TaskResourceIncludes.php @@ -260,7 +260,7 @@ private function userCanViewTaskForDraft(User $user): bool return true; } - if (in_array($user->id, $this->managerIdsForTaskProcess($token), true)) { + if (in_array($user->id, $this->managerIdsForTaskProcess($token))) { return true; } @@ -268,7 +268,7 @@ private function userCanViewTaskForDraft(User $user): bool } /** - * @return list + * @return list */ private function managerIdsForTaskProcess(ProcessRequestToken $token): array { diff --git a/tests/Feature/Api/TasksTest.php b/tests/Feature/Api/TasksTest.php index ce7654c33b..3b922a390b 100644 --- a/tests/Feature/Api/TasksTest.php +++ b/tests/Feature/Api/TasksTest.php @@ -272,6 +272,38 @@ public function testTaskIndexIncludesOwnDraftDataWhenTokenProjectionOmitsUserId( $this->assertEquals('assignee-draft', $tasks[$task->id]['draft']['data']['field'] ?? null); } + public function testTaskIndexIncludesDraftDataForProcessManagerWithStringManagerIds() + { + $this->initializePermissions(); + config(['app.task_drafts_enabled' => true]); + + $manager = User::factory()->create(); + $manager->giveDirectPermission('view-all_requests'); + $assignee = User::factory()->create(); + $this->user = $manager; + + $process = Process::factory()->create([ + 'properties' => ['manager_id' => [(string) $manager->id]], + ]); + $processRequest = ProcessRequest::factory()->create(['process_id' => $process->id]); + $task = ProcessRequestToken::factory()->create([ + 'process_id' => $process->id, + 'process_request_id' => $processRequest->id, + 'status' => 'ACTIVE', + 'user_id' => $assignee->id, + ]); + TaskDraft::factory()->create([ + 'task_id' => $task->id, + 'data' => ['manager_visible' => 'manager-draft'], + ]); + + $response = $this->apiCall('GET', route('api.tasks.index', ['include' => 'draft'])); + $response->assertStatus(200); + + $draft = collect($response->json('data'))->keyBy('id')[$task->id]['draft']; + $this->assertEquals('manager-draft', $draft['data']['manager_visible'] ?? null); + } + /** * You only see non system type tasks. */ From 90d2d07f113c8c4b939093d4b2e677ec047639dd Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Thu, 12 Nov 2026 10:13:42 -0400 Subject: [PATCH 12/29] fix(FOUR-34369): resolve process managers without serializing properties Load manager IDs from a targeted properties query for draft gating instead of selecting properties onto the task process relation in showFast and the optimized task index. https://processmaker.atlassian.net/browse/FOUR-34369 --- .../TaskV11ShowFastRepository.php | 2 +- .../Traits/TaskControllerIndexMethods.php | 6 +-- ProcessMaker/Traits/TaskResourceIncludes.php | 38 +++++++------------ 3 files changed, 16 insertions(+), 30 deletions(-) diff --git a/ProcessMaker/Repositories/TaskV11ShowFastRepository.php b/ProcessMaker/Repositories/TaskV11ShowFastRepository.php index e73596587a..42b4e70da2 100644 --- a/ProcessMaker/Repositories/TaskV11ShowFastRepository.php +++ b/ProcessMaker/Repositories/TaskV11ShowFastRepository.php @@ -50,7 +50,7 @@ public function findForShow(int $taskId): ProcessRequestToken } if ($token->process_id) { - $process = Process::query()->select(['id', 'name', 'properties'])->find($token->process_id); + $process = Process::query()->select(['id', 'name'])->find($token->process_id); $token->setRelation('process', $process); } diff --git a/ProcessMaker/Traits/TaskControllerIndexMethods.php b/ProcessMaker/Traits/TaskControllerIndexMethods.php index dd6ea3f419..baf7b56b29 100644 --- a/ProcessMaker/Traits/TaskControllerIndexMethods.php +++ b/ProcessMaker/Traits/TaskControllerIndexMethods.php @@ -130,11 +130,7 @@ private function buildOptimizedIndexWith(array $includes, bool $includeData): ar } if (in_array('process', $includes, true)) { - $processColumns = ['id', 'name', 'uuid']; - if (in_array('draft', $includes, true)) { - $processColumns[] = 'properties'; - } - $with['process'] = fn ($q) => $q->select(array_values(array_unique($processColumns))); + $with['process'] = fn ($q) => $q->select(['id', 'name', 'uuid']); } if (in_array('processRequest.process', $includes, true)) { diff --git a/ProcessMaker/Traits/TaskResourceIncludes.php b/ProcessMaker/Traits/TaskResourceIncludes.php index dc0318a121..2160ec524c 100644 --- a/ProcessMaker/Traits/TaskResourceIncludes.php +++ b/ProcessMaker/Traits/TaskResourceIncludes.php @@ -210,8 +210,8 @@ private function includeElementDestination() } /** - * Partial token/process projections (optimized index, fast show) may omit columns - * required by ProcessRequestTokenPolicy::view before including draft payloads. + * Partial token projections (optimized index, fast show) may omit columns + * required for draft visibility checks (assignee, self-service). */ private function ensureTokenAttributesForViewPolicy(ProcessRequestToken $token): void { @@ -237,12 +237,6 @@ private function ensureTokenAttributesForViewPolicy(ProcessRequestToken $token): $groups = ProcessRequestToken::query()->whereKey($token->getKey())->value('self_service_groups'); $token->setAttribute('self_service_groups', $groups); } - - $process = $token->relationLoaded('process') ? $token->process : null; - if ($process && !array_key_exists('properties', $process->getAttributes())) { - $properties = Process::query()->whereKey($process->getKey())->value('properties'); - $process->setAttribute('properties', $properties); - } } /** @@ -273,27 +267,23 @@ private function userCanViewTaskForDraft(User $user): bool private function managerIdsForTaskProcess(ProcessRequestToken $token): array { $process = $token->relationLoaded('process') ? $token->process : null; - if ($process) { - if (!array_key_exists('properties', $process->getAttributes())) { - $properties = Process::query()->whereKey($process->getKey())->value('properties'); - $process->setAttribute('properties', $this->decodeJsonColumn($properties)); - } - - return $process->manager_id ?? []; - } - - if (!$token->process_id) { + $processId = $process?->getKey() ?? $token->process_id; + if (!$processId) { return []; } - $properties = Process::query()->whereKey($token->process_id)->value('properties'); - $managerId = ($this->decodeJsonColumn($properties))['manager_id'] ?? null; - - if ($managerId === null || $managerId === 'undefined') { - return []; + if ($process && array_key_exists('properties', $process->getAttributes())) { + $properties = $this->decodeJsonColumn($process->getAttribute('properties')); + } else { + $properties = $this->decodeJsonColumn( + Process::query()->whereKey($processId)->value('properties') + ); } - return is_array($managerId) ? $managerId : [$managerId]; + $standIn = new Process(); + $standIn->setAttribute('properties', $properties); + + return $standIn->manager_id ?? []; } /** From 1df22bc0064ae116985490eb011e153cfccd6c2f Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Thu, 12 Nov 2026 11:07:43 -0400 Subject: [PATCH 13/29] fix(FOUR-34369): align v1.1 task show include parsing with draft gates Use TaskDraftIncludes for v1.1 preprocessInclude/fromTokenWithIncludes and load the draft relation only for exact include=draft, not draft.* tokens. https://processmaker.atlassian.net/browse/FOUR-34369 --- ProcessMaker/Http/Resources/Task.php | 15 ++- .../Http/Resources/V1_1/TaskResource.php | 50 ++++++---- .../Traits/TaskControllerIndexMethods.php | 35 ++++--- ProcessMaker/Traits/TaskResourceIncludes.php | 56 +++++++---- tests/Feature/Api/TasksTest.php | 92 +++++++++++++++++++ 5 files changed, 191 insertions(+), 57 deletions(-) diff --git a/ProcessMaker/Http/Resources/Task.php b/ProcessMaker/Http/Resources/Task.php index 7bf2eae8ff..765a15920d 100644 --- a/ProcessMaker/Http/Resources/Task.php +++ b/ProcessMaker/Http/Resources/Task.php @@ -12,6 +12,7 @@ use ProcessMaker\Models\ProcessRequestToken; use ProcessMaker\Models\User; use ProcessMaker\Services\SmartExtractConfiguration; +use ProcessMaker\Support\TaskDraftIncludes; use ProcessMaker\Traits\TaskResourceIncludes; class Task extends ApiResource @@ -52,13 +53,18 @@ class Task extends ApiResource */ public function toArray($request) { + $include = TaskDraftIncludes::parseIncludeList((string) $request->input('include', '')); + $array = parent::toArray($request); - $include = explode(',', $request->input('include', '')); + $array = $this->sanitizeDraftInTaskArray($array, $request); $this->process = $this->resource->process; foreach ($this->includeMethods as $key) { - if (!in_array($key, $include)) { + if ($key === 'draft' && TaskDraftIncludes::includesDraft($include)) { + continue; + } + if (!in_array($key, $include, true)) { continue; } $method = 'include' . ucfirst($key); @@ -82,9 +88,10 @@ public function toArray($request) private function addCanViewParentRequest(&$array, $request) { - $parentProcessRequest = $this->processRequest->parentRequest; + $processRequest = $this->processRequest; + $parentProcessRequest = $processRequest?->parentRequest; $array['can_view_parent_request'] = - $parentProcessRequest && $request->user()->can('view', $parentProcessRequest); + $parentProcessRequest && $request->user()?->can('view', $parentProcessRequest); } private function addAssignableUsers(&$array, $include) diff --git a/ProcessMaker/Http/Resources/V1_1/TaskResource.php b/ProcessMaker/Http/Resources/V1_1/TaskResource.php index c4b934177f..78f472c9fc 100644 --- a/ProcessMaker/Http/Resources/V1_1/TaskResource.php +++ b/ProcessMaker/Http/Resources/V1_1/TaskResource.php @@ -12,6 +12,7 @@ use ProcessMaker\Http\Resources\Task; use ProcessMaker\Models\ProcessRequestToken; use ProcessMaker\ProcessTranslations\ProcessTranslation; +use ProcessMaker\Support\TaskDraftIncludes; use ProcessMaker\Traits\TaskResourceIncludes; use ProcessMaker\Traits\TaskScreenResourceTrait; @@ -173,19 +174,19 @@ public static function preprocessInclude(Request $request, Builder $query): self $query->addSelect($field); } - $include = $request->query('include', []); - if ($include) { - $include = explode(',', $include); - } - $include = array_merge($include, self::$defaultIncludes); + $parsed = self::parseV11RequestIncludes($request); + $include = array_merge($parsed, self::$defaultIncludes); - if (in_array('data', $include)) { + if (in_array('data', $include, true)) { $query->addSelect('process_request_id'); self::$defaultFieldsFor['processRequest'][] = 'data'; } foreach (self::$includeMethods as $key) { - if (!in_array($key, $include)) { + if (!in_array($key, $include, true)) { + continue; + } + if ($key === 'draft' && !in_array('draft', $parsed, true)) { continue; } @@ -194,7 +195,10 @@ public static function preprocessInclude(Request $request, Builder $query): self $model = $query->first(); foreach (self::$includeMethods as $key) { - if (!in_array($key, $include)) { + if (!in_array($key, $include, true)) { + continue; + } + if ($key === 'draft' && !in_array('draft', $parsed, true)) { continue; } @@ -209,14 +213,14 @@ public static function preprocessInclude(Request $request, Builder $query): self */ public static function fromTokenWithIncludes(ProcessRequestToken $token, Request $request): self { - $include = $request->query('include', []); - if ($include) { - $include = explode(',', $include); - } - $include = array_merge($include, self::$defaultIncludes); + $parsed = self::parseV11RequestIncludes($request); + $include = array_merge($parsed, self::$defaultIncludes); foreach (self::$includeMethods as $key) { - if (!in_array($key, $include)) { + if (!in_array($key, $include, true)) { + continue; + } + if ($key === 'draft' && !in_array('draft', $parsed, true)) { continue; } @@ -243,15 +247,21 @@ public static function fromTokenWithIncludes(ProcessRequestToken $token, Request return new static($token); } + /** @return list */ + private static function parseV11RequestIncludes(Request $request): array + { + return TaskDraftIncludes::parseIncludeList((string) $request->input('include', '')); + } + private function processInclude(Request $request, array $array) { - $include = $request->query('include', []); - if ($include) { - $include = explode(',', $include); - } + $include = self::parseV11RequestIncludes($request); foreach (self::$includeMethods as $key) { - if (!in_array($key, $include)) { + if ($key === 'draft' && TaskDraftIncludes::includesDraft($include)) { + continue; + } + if (!in_array($key, $include, true)) { continue; } @@ -264,6 +274,6 @@ private function processInclude(Request $request, array $array) } } - return $array; + return $this->sanitizeDraftInTaskArray($array, $request); } } diff --git a/ProcessMaker/Traits/TaskControllerIndexMethods.php b/ProcessMaker/Traits/TaskControllerIndexMethods.php index baf7b56b29..7f7323d8f6 100644 --- a/ProcessMaker/Traits/TaskControllerIndexMethods.php +++ b/ProcessMaker/Traits/TaskControllerIndexMethods.php @@ -16,6 +16,7 @@ use ProcessMaker\Package\SavedSearch\Models\SavedSearch; use ProcessMaker\Query\SyntaxError; use ProcessMaker\Services\SmartExtractConfiguration; +use ProcessMaker\Support\TaskDraftIncludes; trait TaskControllerIndexMethods { @@ -38,10 +39,8 @@ trait TaskControllerIndexMethods private function indexBaseQuery($request) { - // Parse the includes parameter - $includes = $request->has('include') ? explode(',', $request->input('include')) : []; - // Determine if the data should be included - $includeData = in_array('data', $includes); + $includes = $this->parseIndexIncludeList($request); + $includeData = in_array('data', $includes, true); $query = ProcessRequestToken::exclude(['data']); @@ -61,18 +60,20 @@ private function indexBaseQuery($request) // review if bpmn is required here processRequest.processVersion.process // 'processRequest.processVersion.process' => fn($q) => $q->exclude(['svg', 'warnings']), 'user', - 'draft', ]); - $include = $request->input('include') ? explode(',', $request->input('include')) : []; - - foreach (['data'] as $key) { - if (in_array($key, $include)) { - unset($include[array_search($key, $include)]); - } + if (TaskDraftIncludes::includesDraft($includes)) { + $query->with(['draft' => TaskDraftIncludes::constrainedEagerLoad()]); } - $query->with($include); + $additionalIncludes = array_values(array_filter( + $includes, + fn (string $token) => $token !== 'data' && !TaskDraftIncludes::isDraftToken($token) + )); + + if ($additionalIncludes !== []) { + $query->with($additionalIncludes); + } return $query; } @@ -87,6 +88,10 @@ private function indexOptimizedBaseQuery($request) $handledIncludes = ['data', 'processRequest', 'process', 'user', 'draft', 'processRequest.process']; $additionalIncludes = array_values(array_diff($includes, $handledIncludes)); + $additionalIncludes = array_values(array_filter( + $additionalIncludes, + fn (string $token) => !TaskDraftIncludes::isDraftToken($token) + )); if (!empty($with)) { $query->with($with); @@ -105,7 +110,7 @@ private function parseIndexIncludeList($request): array return []; } - return array_map('trim', explode(',', $request->input('include'))); + return TaskDraftIncludes::parseIncludeList((string) $request->input('include')); } /** @@ -125,8 +130,8 @@ private function buildOptimizedIndexWith(array $includes, bool $includeData): ar $with['user'] = fn ($q) => $q->select(['id', 'firstname', 'lastname', 'avatar', 'status']); } - if (in_array('draft', $includes, true)) { - $with['draft'] = fn ($q) => $q->select(['id', 'task_id']); + if (TaskDraftIncludes::includesDraft($includes)) { + $with['draft'] = TaskDraftIncludes::constrainedEagerLoad(); } if (in_array('process', $includes, true)) { diff --git a/ProcessMaker/Traits/TaskResourceIncludes.php b/ProcessMaker/Traits/TaskResourceIncludes.php index 2160ec524c..f5e36add7b 100644 --- a/ProcessMaker/Traits/TaskResourceIncludes.php +++ b/ProcessMaker/Traits/TaskResourceIncludes.php @@ -13,6 +13,7 @@ use ProcessMaker\Models\TaskDraft; use ProcessMaker\Models\User; use ProcessMaker\ProcessTranslations\ScreenTranslation; +use ProcessMaker\Support\TaskDraftIncludes; use StdClass; trait TaskResourceIncludes @@ -58,39 +59,61 @@ private function includeProcessRequest() return ['process_request' => $this->processRequest->attributesToArray()]; } - private function includeDraft() + /** + * Strips or redacts draft on task index/show; parent::toArray() may serialize the relation first. + */ + protected function sanitizeDraftInTaskArray(array $array, $request): array { - $draft = $this->draft; - if ($draft && !TaskDraft::draftsEnabled()) { - // Drafts are used to get data from quick-fill to the screen, - // but drafts are disabled so we need to delete it now that - // it's been accessed. - $draft->delete(); + $include = TaskDraftIncludes::parseIncludeList((string) $request->input('include', '')); + + if (!TaskDraftIncludes::includesDraft($include)) { + unset($array['draft']); - // Return null to prevent the frontend from trying to load - // files from the deleted draft - return ['draft' => null]; + return $array; } + $array['draft'] = $this->resolveDraftPayloadForResponse(); + + return $array; + } + + /** @return array|TaskDraft|null */ + private function resolveDraftPayloadForResponse(): array|TaskDraft|null + { + $draft = $this->draft; if (!$draft) { - return ['draft' => null]; + return null; } $user = Auth::user(); + + if (!TaskDraft::draftsEnabled()) { + if (!$user) { + return null; + } + $this->ensureTokenAttributesForViewPolicy($this->resource); + if (!$this->userCanViewTaskForDraft($user)) { + return null; + } + $draft->delete(); + + return null; + } + if (!$user) { - return ['draft' => $draft->only(['id', 'task_id'])]; + return $draft->only(['id', 'task_id']); } $this->ensureTokenAttributesForViewPolicy($this->resource); if (!$this->userCanViewTaskForDraft($user)) { - return ['draft' => $draft->only(['id', 'task_id'])]; + return $draft->only(['id', 'task_id']); } if (!array_key_exists('data', $draft->getAttributes())) { $draft = TaskDraft::query()->whereKey($draft->getKey())->first(['id', 'task_id', 'data']); } - return ['draft' => $draft]; + return $draft; } private function includeComponent() @@ -239,10 +262,7 @@ private function ensureTokenAttributesForViewPolicy(ProcessRequestToken $token): } } - /** - * Mirrors ProcessRequestTokenPolicy::view without lazy-loading process on the token - * (loaded process relations are serialized by Task::toArray before includes run). - */ + /** @see ProcessRequestTokenPolicy::view — avoids lazy-loading process on list rows */ private function userCanViewTaskForDraft(User $user): bool { if ($user->is_administrator) { diff --git a/tests/Feature/Api/TasksTest.php b/tests/Feature/Api/TasksTest.php index 3b922a390b..46218cc764 100644 --- a/tests/Feature/Api/TasksTest.php +++ b/tests/Feature/Api/TasksTest.php @@ -304,6 +304,98 @@ public function testTaskIndexIncludesDraftDataForProcessManagerWithStringManager $this->assertEquals('manager-draft', $draft['data']['manager_visible'] ?? null); } + public function testTaskIndexNestedDraftIncludeDoesNotExposeOtherUsersDraftData() + { + $this->initializePermissions(); + config([ + 'app.task_drafts_enabled' => true, + 'app.processmaker_optimized_tasks_enabled' => true, + ]); + + $viewer = User::factory()->create(); + $viewer->giveDirectPermission('view-all_requests'); + $this->user = $viewer; + $assignee = User::factory()->create(); + + $processRequest = ProcessRequest::factory()->create(); + $otherTask = ProcessRequestToken::factory()->create([ + 'process_request_id' => $processRequest->id, + 'status' => 'ACTIVE', + 'user_id' => $assignee->id, + ]); + TaskDraft::factory()->create([ + 'task_id' => $otherTask->id, + 'data' => ['secret' => 'nested-bypass'], + ]); + + $response = $this->apiCall('GET', route('api.tasks.index', ['include' => 'draft.media'])); + $response->assertStatus(200); + + $draft = collect($response->json('data'))->keyBy('id')[$otherTask->id]['draft'] ?? null; + $this->assertNotNull($draft); + $this->assertArrayNotHasKey('data', $draft); + } + + public function testLegacyTaskIndexWithoutIncludeDoesNotEmbedDraftRelation() + { + $this->initializePermissions(); + config([ + 'app.task_drafts_enabled' => true, + 'app.processmaker_optimized_tasks_enabled' => false, + ]); + + $assignee = User::factory()->create(); + $this->user = $assignee; + $processRequest = ProcessRequest::factory()->create(); + $task = ProcessRequestToken::factory()->create([ + 'process_request_id' => $processRequest->id, + 'status' => 'ACTIVE', + 'user_id' => $assignee->id, + ]); + TaskDraft::factory()->create([ + 'task_id' => $task->id, + 'data' => ['leaked' => 'legacy-index'], + ]); + + $response = $this->apiCall('GET', route('api.tasks.index')); + $response->assertStatus(200); + + $row = collect($response->json('data'))->keyBy('id')[$task->id]; + $this->assertArrayNotHasKey('draft', $row); + } + + public function testTaskIndexWithDraftsDisabledDoesNotDeleteAnotherUsersDraft() + { + $this->initializePermissions(); + config([ + 'app.task_drafts_enabled' => false, + 'app.processmaker_optimized_tasks_enabled' => true, + ]); + + $viewer = User::factory()->create(); + $viewer->giveDirectPermission('view-all_requests'); + $this->user = $viewer; + $assignee = User::factory()->create(); + + $processRequest = ProcessRequest::factory()->create(); + $otherTask = ProcessRequestToken::factory()->create([ + 'process_request_id' => $processRequest->id, + 'status' => 'ACTIVE', + 'user_id' => $assignee->id, + ]); + $draft = TaskDraft::factory()->create([ + 'task_id' => $otherTask->id, + 'data' => ['secret' => 'must-survive'], + ]); + + $response = $this->apiCall('GET', route('api.tasks.index', ['include' => 'draft'])); + $response->assertStatus(200); + + $this->assertDatabaseHas('task_drafts', ['id' => $draft->id, 'task_id' => $otherTask->id]); + $otherRow = collect($response->json('data'))->keyBy('id')[$otherTask->id]; + $this->assertNull($otherRow['draft'] ?? null); + } + /** * You only see non system type tasks. */ From c9b172158d317ae2c7175a2a7d89b4600ab04328 Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Thu, 12 Nov 2026 11:32:34 -0400 Subject: [PATCH 14/29] fix(FOUR-34369): add TaskDraftIncludes support class for task draft gates Include the helper referenced by task index and task resources for parsing include=draft tokens, constrained eager loads, and draft.* filtering. --- ProcessMaker/Support/TaskDraftIncludes.php | 42 ++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 ProcessMaker/Support/TaskDraftIncludes.php diff --git a/ProcessMaker/Support/TaskDraftIncludes.php b/ProcessMaker/Support/TaskDraftIncludes.php new file mode 100644 index 0000000000..5dc0ddde0f --- /dev/null +++ b/ProcessMaker/Support/TaskDraftIncludes.php @@ -0,0 +1,42 @@ + */ + public const EAGER_COLUMNS = ['id', 'task_id']; + + /** @return list */ + public static function parseIncludeList(string $include): array + { + if ($include === '') { + return []; + } + + return array_values(array_filter(array_map('trim', explode(',', $include)))); + } + + public static function includesDraft(array $includes): bool + { + foreach ($includes as $token) { + if (self::isDraftToken($token)) { + return true; + } + } + + return false; + } + + public static function isDraftToken(string $token): bool + { + return $token === 'draft' || str_starts_with($token, 'draft.'); + } + + public static function constrainedEagerLoad(): \Closure + { + return fn ($q) => $q->select(self::EAGER_COLUMNS); + } +} From 36a628bb9e6519f6ea9906550f5107326c81e08e Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Thu, 12 Nov 2026 13:01:09 -0400 Subject: [PATCH 15/29] fix(FOUR-34369): match draft includes by path segment not substring isDraftToken no longer uses str_contains('.draft'), which falsely blocked includes such as processRequest.draftApproval. Treat draft only when the token is draft, starts with draft., ends with .draft, or contains a .draft. segment so nested draft paths stay gated without dropping unrelated includes. https://processmaker.atlassian.net/browse/FOUR-34369 --- ProcessMaker/Support/TaskDraftIncludes.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ProcessMaker/Support/TaskDraftIncludes.php b/ProcessMaker/Support/TaskDraftIncludes.php index 24a9bb8a80..0d9b50bdce 100644 --- a/ProcessMaker/Support/TaskDraftIncludes.php +++ b/ProcessMaker/Support/TaskDraftIncludes.php @@ -39,7 +39,8 @@ public static function isDraftToken(string $token): bool { return $token === 'draft' || str_starts_with($token, 'draft.') - || str_contains($token, '.draft'); + || str_ends_with($token, '.draft') + || str_contains($token, '.draft.'); } public static function constrainedEagerLoad(): \Closure From fb8ffafba951825cf2367998c176674031edd69f Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Thu, 12 Nov 2026 13:07:06 -0400 Subject: [PATCH 16/29] fix(FOUR-34369): redact task draft whenever the relation is loaded Apply draft visibility on any loaded draft payload (including draft.*-style includes), tighten optimized additionalIncludes filtering, and add legacy draft.media and disabled-draft media regression tests. https://processmaker.atlassian.net/browse/FOUR-34369 --- ProcessMaker/Http/Resources/Task.php | 2 +- .../Http/Resources/V1_1/TaskResource.php | 2 +- .../Traits/TaskControllerIndexMethods.php | 6 +- ProcessMaker/Traits/TaskResourceIncludes.php | 15 +++-- tests/Feature/Api/TasksTest.php | 64 +++++++++++++++++++ 5 files changed, 79 insertions(+), 10 deletions(-) diff --git a/ProcessMaker/Http/Resources/Task.php b/ProcessMaker/Http/Resources/Task.php index 765a15920d..5764a37ec7 100644 --- a/ProcessMaker/Http/Resources/Task.php +++ b/ProcessMaker/Http/Resources/Task.php @@ -61,7 +61,7 @@ public function toArray($request) $this->process = $this->resource->process; foreach ($this->includeMethods as $key) { - if ($key === 'draft' && TaskDraftIncludes::includesDraft($include)) { + if ($key === 'draft' && (TaskDraftIncludes::includesDraft($include) || $this->resource->relationLoaded('draft'))) { continue; } if (!in_array($key, $include, true)) { diff --git a/ProcessMaker/Http/Resources/V1_1/TaskResource.php b/ProcessMaker/Http/Resources/V1_1/TaskResource.php index dcfbf42e73..94edd54bc4 100644 --- a/ProcessMaker/Http/Resources/V1_1/TaskResource.php +++ b/ProcessMaker/Http/Resources/V1_1/TaskResource.php @@ -258,7 +258,7 @@ private function processInclude(Request $request, array $array) $include = self::parseV11RequestIncludes($request); foreach (self::$includeMethods as $key) { - if ($key === 'draft' && TaskDraftIncludes::includesDraft($include)) { + if ($key === 'draft' && (TaskDraftIncludes::includesDraft($include) || $this->resource->relationLoaded('draft'))) { continue; } if (!in_array($key, $include, true)) { diff --git a/ProcessMaker/Traits/TaskControllerIndexMethods.php b/ProcessMaker/Traits/TaskControllerIndexMethods.php index 0c5f7fc408..01e40aec45 100644 --- a/ProcessMaker/Traits/TaskControllerIndexMethods.php +++ b/ProcessMaker/Traits/TaskControllerIndexMethods.php @@ -92,10 +92,10 @@ private function indexOptimizedBaseQuery($request) $with = $this->buildOptimizedIndexWith($includes, $includeData); $handledIncludes = ['data', 'processRequest', 'process', 'user', 'draft', 'processRequest.process']; - $additionalIncludes = array_values(array_diff($includes, $handledIncludes)); $additionalIncludes = array_values(array_filter( - $additionalIncludes, - fn (string $token) => !TaskDraftIncludes::isDraftToken($token) + $includes, + fn (string $token) => !in_array($token, $handledIncludes, true) + && !TaskDraftIncludes::isDraftToken($token) )); if (!empty($with)) { diff --git a/ProcessMaker/Traits/TaskResourceIncludes.php b/ProcessMaker/Traits/TaskResourceIncludes.php index fc09f44be7..74bfe03be4 100644 --- a/ProcessMaker/Traits/TaskResourceIncludes.php +++ b/ProcessMaker/Traits/TaskResourceIncludes.php @@ -66,14 +66,19 @@ protected function sanitizeDraftInTaskArray(array $array, $request): array { $include = TaskDraftIncludes::parseIncludeList((string) $request->input('include', '')); - if (!TaskDraftIncludes::includesDraft($include)) { - unset($array['draft']); + $draftPayload = $this->resource->relationLoaded('draft') + ? $this->draft + : ($array['draft'] ?? null); - return $array; + if ($draftPayload !== null || array_key_exists('draft', $array)) { + $array['draft'] = $this->resolveDraftPayloadForToken($this->resource, $draftPayload); + } elseif (!TaskDraftIncludes::includesDraft($include)) { + unset($array['draft']); } - $array['draft'] = $this->resolveDraftPayloadForToken($this->resource, $this->draft); - $this->redactNestedDraftsInArray($array); + if (TaskDraftIncludes::includesDraft($include)) { + $this->redactNestedDraftsInArray($array); + } return $array; } diff --git a/tests/Feature/Api/TasksTest.php b/tests/Feature/Api/TasksTest.php index b2ba4230e3..1de46a6cbf 100644 --- a/tests/Feature/Api/TasksTest.php +++ b/tests/Feature/Api/TasksTest.php @@ -304,6 +304,38 @@ public function testTaskIndexIncludesDraftDataForProcessManagerWithStringManager $this->assertEquals('manager-draft', $draft['data']['manager_visible'] ?? null); } + public function testLegacyTaskIndexDraftMediaDoesNotExposeOtherUsersDraftData() + { + $this->initializePermissions(); + config([ + 'app.task_drafts_enabled' => true, + 'app.processmaker_optimized_tasks_enabled' => false, + ]); + + $viewer = User::factory()->create(); + $viewer->giveDirectPermission('view-all_requests'); + $this->user = $viewer; + $assignee = User::factory()->create(); + + $processRequest = ProcessRequest::factory()->create(); + $otherTask = ProcessRequestToken::factory()->create([ + 'process_request_id' => $processRequest->id, + 'status' => 'ACTIVE', + 'user_id' => $assignee->id, + ]); + TaskDraft::factory()->create([ + 'task_id' => $otherTask->id, + 'data' => ['secret' => 'legacy-draft-media'], + ]); + + $response = $this->apiCall('GET', route('api.tasks.index', ['include' => 'draft.media'])); + $response->assertStatus(200); + + $draft = collect($response->json('data'))->keyBy('id')[$otherTask->id]['draft'] ?? null; + $this->assertNotNull($draft); + $this->assertArrayNotHasKey('data', $draft); + } + public function testTaskIndexNestedDraftIncludeDoesNotExposeOtherUsersDraftData() { $this->initializePermissions(); @@ -495,6 +527,38 @@ public function testTaskIndexWithDraftsDisabledDoesNotDeleteAnotherUsersDraft() $this->assertNull($otherRow['draft'] ?? null); } + public function testTaskIndexDraftMediaWithDraftsDisabledDoesNotDeleteAnotherUsersDraft() + { + $this->initializePermissions(); + config([ + 'app.task_drafts_enabled' => false, + 'app.processmaker_optimized_tasks_enabled' => true, + ]); + + $viewer = User::factory()->create(); + $viewer->giveDirectPermission('view-all_requests'); + $this->user = $viewer; + $assignee = User::factory()->create(); + + $processRequest = ProcessRequest::factory()->create(); + $otherTask = ProcessRequestToken::factory()->create([ + 'process_request_id' => $processRequest->id, + 'status' => 'ACTIVE', + 'user_id' => $assignee->id, + ]); + $draft = TaskDraft::factory()->create([ + 'task_id' => $otherTask->id, + 'data' => ['secret' => 'must-survive-media'], + ]); + + $response = $this->apiCall('GET', route('api.tasks.index', ['include' => 'draft.media'])); + $response->assertStatus(200); + + $this->assertDatabaseHas('task_drafts', ['id' => $draft->id, 'task_id' => $otherTask->id]); + $otherRow = collect($response->json('data'))->keyBy('id')[$otherTask->id]; + $this->assertNull($otherRow['draft'] ?? null); + } + /** * You only see non system type tasks. */ From 35b1f64cd9501fa85e326c4713cd60f968a821d1 Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Thu, 12 Nov 2026 13:26:09 -0400 Subject: [PATCH 17/29] fix(FOUR-34369): bind draft policy to persisted tokens on v1.1 show Redact nested drafts only under tokens lists, load tokens and drafts from the database with task_id constraints, and ignore planted id/draft objects in request_data. https://processmaker.atlassian.net/browse/FOUR-34369 --- ProcessMaker/Traits/TaskResourceIncludes.php | 125 +++++++++++++------ tests/Feature/Api/TasksTest.php | 49 ++++++++ 2 files changed, 135 insertions(+), 39 deletions(-) diff --git a/ProcessMaker/Traits/TaskResourceIncludes.php b/ProcessMaker/Traits/TaskResourceIncludes.php index 74bfe03be4..18ad4d54db 100644 --- a/ProcessMaker/Traits/TaskResourceIncludes.php +++ b/ProcessMaker/Traits/TaskResourceIncludes.php @@ -20,6 +20,20 @@ trait TaskResourceIncludes { use TaskScreenResourceTrait; + /** Do not treat case/request payload trees as task token rows. */ + private const DRAFT_REDACT_EXCLUDED_KEYS = [ + 'request_data', + 'data', + 'screen', + 'config', + 'nested', + 'definition', + 'interstitial_screen', + 'user_request_permission', + 'elementDestination', + 'loop_context', + ]; + private function getData() { if ($this->loadedData) { @@ -88,18 +102,14 @@ protected function sanitizeDraftInTaskArray(array $array, $request): array */ private function resolveDraftPayloadForToken(ProcessRequestToken $token, mixed $draft): array|TaskDraft|null { - if ($draft === null) { + $token = $this->tokenFromPersistedId($token->getKey()); + if (!$token) { return null; } - if (!$draft instanceof TaskDraft) { - if (!is_array($draft) || !isset($draft['id'], $draft['task_id'])) { - return is_array($draft) - ? array_intersect_key($draft, array_flip(['id', 'task_id'])) - : null; - } - $draft = (new TaskDraft())->setRawAttributes($draft, true); - $draft->exists = true; + $draft = $this->taskDraftForToken($token, $draft); + if (!$draft) { + return null; } $user = Auth::user(); @@ -127,31 +137,80 @@ private function resolveDraftPayloadForToken(ProcessRequestToken $token, mixed $ } if (!array_key_exists('data', $draft->getAttributes())) { - $draft = TaskDraft::query()->whereKey($draft->getKey())->first(['id', 'task_id', 'data']); + $draft = TaskDraft::query() + ->whereKey($draft->getKey()) + ->where('task_id', $token->id) + ->first(['id', 'task_id', 'data']); } return $draft; } + private function tokenFromPersistedId(int|string|null $tokenId): ?ProcessRequestToken + { + if ($tokenId === null || $tokenId === '') { + return null; + } + + return ProcessRequestToken::query()->whereKey($tokenId)->first([ + 'id', + 'user_id', + 'process_id', + 'process_request_id', + 'is_self_service', + ]); + } + + /** + * Resolve draft only when task_id matches the persisted token id (never trust nested JSON). + */ + private function taskDraftForToken(ProcessRequestToken $token, mixed $draft): ?TaskDraft + { + if ($draft === null) { + return TaskDraft::query() + ->where('task_id', $token->id) + ->first(['id', 'task_id', 'data']); + } + + $draftId = $draft instanceof TaskDraft + ? $draft->getKey() + : (is_array($draft) ? ($draft['id'] ?? null) : null); + + if ($draftId !== null) { + return TaskDraft::query() + ->whereKey($draftId) + ->where('task_id', $token->id) + ->first(['id', 'task_id', 'data']); + } + + if ($draft instanceof TaskDraft) { + return TaskDraft::query() + ->where('task_id', $token->id) + ->first(['id', 'task_id', 'data']); + } + + return null; + } + /** * @param array $array */ private function redactNestedDraftsInArray(array &$array): void { - foreach ($array as &$value) { - if (!is_array($value)) { + foreach ($array as $key => &$value) { + if (!is_array($value) || in_array($key, self::DRAFT_REDACT_EXCLUDED_KEYS, true)) { continue; } - if (array_is_list($value)) { + + if ($key === 'tokens' && array_is_list($value)) { foreach ($value as &$item) { if (is_array($item)) { $this->redactDraftOnSerializedToken($item); - $this->redactNestedDraftsInArray($item); } } continue; } - $this->redactDraftOnSerializedToken($value); + $this->redactNestedDraftsInArray($value); } } @@ -165,15 +224,12 @@ private function redactDraftOnSerializedToken(array &$row): void return; } - $token = new ProcessRequestToken(); - $token->setRawAttributes([ - 'id' => $row['id'], - 'user_id' => $row['user_id'] ?? null, - 'process_id' => $row['process_id'] ?? null, - 'process_request_id' => $row['process_request_id'] ?? null, - 'is_self_service' => $row['is_self_service'] ?? null, - ], true); - $token->exists = true; + $token = $this->tokenFromPersistedId($row['id']); + if (!$token) { + unset($row['draft']); + + return; + } $row['draft'] = $this->resolveDraftPayloadForToken($token, $row['draft']); } @@ -300,21 +356,12 @@ private function includeElementDestination() */ private function ensureTokenAttributesForViewPolicy(ProcessRequestToken $token): void { - $tokenColumns = []; - foreach (['user_id', 'process_id', 'is_self_service'] as $column) { - if (!array_key_exists($column, $token->getAttributes())) { - $tokenColumns[] = $column; - } - } - - if ($tokenColumns !== []) { - $row = ProcessRequestToken::query() - ->whereKey($token->getKey()) - ->first(array_merge(['id'], $tokenColumns)); - if ($row) { - foreach ($tokenColumns as $column) { - $token->setAttribute($column, $row->{$column}); - } + $row = ProcessRequestToken::query() + ->whereKey($token->getKey()) + ->first(['id', 'user_id', 'process_id', 'is_self_service']); + if ($row) { + foreach (['user_id', 'process_id', 'is_self_service'] as $column) { + $token->setAttribute($column, $row->{$column}); } } diff --git a/tests/Feature/Api/TasksTest.php b/tests/Feature/Api/TasksTest.php index 1de46a6cbf..9ff466cbe6 100644 --- a/tests/Feature/Api/TasksTest.php +++ b/tests/Feature/Api/TasksTest.php @@ -559,6 +559,55 @@ public function testTaskIndexDraftMediaWithDraftsDisabledDoesNotDeleteAnotherUse $this->assertNull($otherRow['draft'] ?? null); } + public function testV11TaskShowIgnoresPlantedDraftObjectsInRequestData() + { + $this->initializePermissions(); + config(['app.task_drafts_enabled' => true]); + + $assignee = User::factory()->create(); + $this->user = $assignee; + $otherAssignee = User::factory()->create(); + + $processRequest = ProcessRequest::factory()->create(); + $ownTask = ProcessRequestToken::factory()->create([ + 'process_request_id' => $processRequest->id, + 'status' => 'ACTIVE', + 'user_id' => $assignee->id, + ]); + $otherTask = ProcessRequestToken::factory()->create([ + 'process_request_id' => $processRequest->id, + 'status' => 'ACTIVE', + 'user_id' => $otherAssignee->id, + ]); + $otherDraft = TaskDraft::factory()->create([ + 'task_id' => $otherTask->id, + 'data' => ['secret' => 'request-data-plant'], + ]); + + $processRequest->update([ + 'data' => [ + 'draft_trap' => [ + 'id' => $ownTask->id, + 'user_id' => $assignee->id, + 'draft' => [ + 'id' => $otherDraft->id, + 'task_id' => $ownTask->id, + ], + ], + ], + ]); + + $response = $this->apiCall( + 'GET', + route('api.1.1.tasks.show', $ownTask->id) . '?include=draft,requestData' + ); + $response->assertStatus(200); + + $json = json_encode($response->json()); + $this->assertStringNotContainsString('request-data-plant', $json); + $this->assertDatabaseHas('task_drafts', ['id' => $otherDraft->id]); + } + /** * You only see non system type tasks. */ From 96bafa5abba410626b540f161fc244f9d38c9dc8 Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Thu, 12 Nov 2026 13:32:23 -0400 Subject: [PATCH 18/29] fix(FOUR-34369): harden task draft includes on index and show Honor includesDraft on show (omit fast-path preloads without include, resolve when requested). Bind draft policy to persisted tokens and task_id-scoped rows; redact nested drafts only under tokens, not request_data. Tighten optimized index filters and add show/plant/disabled-draft regression tests. https://processmaker.atlassian.net/browse/FOUR-34369 --- ProcessMaker/Http/Resources/Task.php | 2 +- .../Http/Resources/V1_1/TaskResource.php | 2 +- ProcessMaker/Traits/TaskResourceIncludes.php | 17 ++++--- tests/Feature/Api/TasksTest.php | 46 +++++++++++++++++++ 4 files changed, 56 insertions(+), 11 deletions(-) diff --git a/ProcessMaker/Http/Resources/Task.php b/ProcessMaker/Http/Resources/Task.php index 5764a37ec7..765a15920d 100644 --- a/ProcessMaker/Http/Resources/Task.php +++ b/ProcessMaker/Http/Resources/Task.php @@ -61,7 +61,7 @@ public function toArray($request) $this->process = $this->resource->process; foreach ($this->includeMethods as $key) { - if ($key === 'draft' && (TaskDraftIncludes::includesDraft($include) || $this->resource->relationLoaded('draft'))) { + if ($key === 'draft' && TaskDraftIncludes::includesDraft($include)) { continue; } if (!in_array($key, $include, true)) { diff --git a/ProcessMaker/Http/Resources/V1_1/TaskResource.php b/ProcessMaker/Http/Resources/V1_1/TaskResource.php index 94edd54bc4..dcfbf42e73 100644 --- a/ProcessMaker/Http/Resources/V1_1/TaskResource.php +++ b/ProcessMaker/Http/Resources/V1_1/TaskResource.php @@ -258,7 +258,7 @@ private function processInclude(Request $request, array $array) $include = self::parseV11RequestIncludes($request); foreach (self::$includeMethods as $key) { - if ($key === 'draft' && (TaskDraftIncludes::includesDraft($include) || $this->resource->relationLoaded('draft'))) { + if ($key === 'draft' && TaskDraftIncludes::includesDraft($include)) { continue; } if (!in_array($key, $include, true)) { diff --git a/ProcessMaker/Traits/TaskResourceIncludes.php b/ProcessMaker/Traits/TaskResourceIncludes.php index 18ad4d54db..ae4835d290 100644 --- a/ProcessMaker/Traits/TaskResourceIncludes.php +++ b/ProcessMaker/Traits/TaskResourceIncludes.php @@ -80,19 +80,18 @@ protected function sanitizeDraftInTaskArray(array $array, $request): array { $include = TaskDraftIncludes::parseIncludeList((string) $request->input('include', '')); + if (!TaskDraftIncludes::includesDraft($include)) { + unset($array['draft']); + + return $array; + } + $draftPayload = $this->resource->relationLoaded('draft') ? $this->draft : ($array['draft'] ?? null); - if ($draftPayload !== null || array_key_exists('draft', $array)) { - $array['draft'] = $this->resolveDraftPayloadForToken($this->resource, $draftPayload); - } elseif (!TaskDraftIncludes::includesDraft($include)) { - unset($array['draft']); - } - - if (TaskDraftIncludes::includesDraft($include)) { - $this->redactNestedDraftsInArray($array); - } + $array['draft'] = $this->resolveDraftPayloadForToken($this->resource, $draftPayload); + $this->redactNestedDraftsInArray($array); return $array; } diff --git a/tests/Feature/Api/TasksTest.php b/tests/Feature/Api/TasksTest.php index 9ff466cbe6..a94ad678d8 100644 --- a/tests/Feature/Api/TasksTest.php +++ b/tests/Feature/Api/TasksTest.php @@ -559,6 +559,52 @@ public function testTaskIndexDraftMediaWithDraftsDisabledDoesNotDeleteAnotherUse $this->assertNull($otherRow['draft'] ?? null); } + public function testV11TaskShowOmitsDraftWithoutIncludeDespiteFastPathPreload() + { + $this->initializePermissions(); + config(['app.task_drafts_enabled' => true]); + + $assignee = User::factory()->create(); + $this->user = $assignee; + $processRequest = ProcessRequest::factory()->create(); + $task = ProcessRequestToken::factory()->create([ + 'process_request_id' => $processRequest->id, + 'status' => 'ACTIVE', + 'user_id' => $assignee->id, + ]); + TaskDraft::factory()->create([ + 'task_id' => $task->id, + 'data' => ['field' => 'show-fast-preload'], + ]); + + $response = $this->apiCall('GET', route('api.1.1.tasks.show', $task->id)); + $response->assertStatus(200); + $this->assertArrayNotHasKey('draft', $response->json()); + } + + public function testTaskShowIncludesDraftWhenRequested() + { + $this->initializePermissions(); + config(['app.task_drafts_enabled' => true]); + + $assignee = User::factory()->create(); + $this->user = $assignee; + $processRequest = ProcessRequest::factory()->create(); + $task = ProcessRequestToken::factory()->create([ + 'process_request_id' => $processRequest->id, + 'status' => 'ACTIVE', + 'user_id' => $assignee->id, + ]); + TaskDraft::factory()->create([ + 'task_id' => $task->id, + 'data' => ['field' => 'show-with-include'], + ]); + + $response = $this->apiCall('GET', route('api.tasks.show', $task->id) . '?include=draft'); + $response->assertStatus(200); + $this->assertEquals('show-with-include', $response->json('draft.data.field')); + } + public function testV11TaskShowIgnoresPlantedDraftObjectsInRequestData() { $this->initializePermissions(); From 736bbb4d6afba1da9a6bfda3fa8535b9ecb392ec Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Thu, 12 Nov 2026 14:16:31 -0400 Subject: [PATCH 19/29] fix(FOUR-34369): treat draft include paths case-insensitively Normalize draft segment detection so mixed-case includes cannot bypass eager-load filters or sanitize/redaction on nested token drafts. https://processmaker.atlassian.net/browse/FOUR-34369 --- ProcessMaker/Support/TaskDraftIncludes.php | 16 +++++--- tests/Feature/Api/TasksTest.php | 43 ++++++++++++++++++++++ 2 files changed, 53 insertions(+), 6 deletions(-) diff --git a/ProcessMaker/Support/TaskDraftIncludes.php b/ProcessMaker/Support/TaskDraftIncludes.php index 0d9b50bdce..15af969cb5 100644 --- a/ProcessMaker/Support/TaskDraftIncludes.php +++ b/ProcessMaker/Support/TaskDraftIncludes.php @@ -37,10 +37,12 @@ public static function includesDraft(array $includes): bool public static function isDraftToken(string $token): bool { - return $token === 'draft' - || str_starts_with($token, 'draft.') - || str_ends_with($token, '.draft') - || str_contains($token, '.draft.'); + $lower = strtolower($token); + + return $lower === 'draft' + || str_starts_with($lower, 'draft.') + || str_ends_with($lower, '.draft') + || str_contains($lower, '.draft.'); } public static function constrainedEagerLoad(): \Closure @@ -57,11 +59,13 @@ public static function nestedDraftEagerLoadMap(array $includes): array $constrained = fn ($q) => $q->with(['draft' => self::constrainedEagerLoad()]); foreach ($includes as $token) { - if (!self::isDraftToken($token) || $token === 'draft' || str_starts_with($token, 'draft.')) { + $lower = strtolower($token); + if (!self::isDraftToken($token) || $lower === 'draft' || str_starts_with($lower, 'draft.')) { continue; } foreach (self::NESTED_DRAFT_RELATIONS as $relation) { - if ($token === "{$relation}.draft" || str_starts_with($token, "{$relation}.")) { + $relationLower = strtolower($relation); + if ($lower === "{$relationLower}.draft" || str_starts_with($lower, "{$relationLower}.")) { $with[$relation] = $constrained; break; } diff --git a/tests/Feature/Api/TasksTest.php b/tests/Feature/Api/TasksTest.php index a94ad678d8..867cc57246 100644 --- a/tests/Feature/Api/TasksTest.php +++ b/tests/Feature/Api/TasksTest.php @@ -418,6 +418,49 @@ public function testTaskIndexProcessRequestTokensDraftDoesNotExposeOtherUsersDra $this->assertEquals('own-nested-pr', $ownDraft['data']['mine'] ?? null); } + public function testTaskIndexProcessRequestTokensDraftCaseInsensitiveDoesNotExposeOtherUsersDraftData() + { + $this->initializePermissions(); + config([ + 'app.task_drafts_enabled' => true, + 'app.processmaker_optimized_tasks_enabled' => true, + ]); + + $viewer = User::factory()->create(); + $viewer->giveDirectPermission('view-all_requests'); + $this->user = $viewer; + $assignee = User::factory()->create(); + + $processRequest = ProcessRequest::factory()->create(); + $otherTask = ProcessRequestToken::factory()->create([ + 'process_request_id' => $processRequest->id, + 'status' => 'ACTIVE', + 'user_id' => $assignee->id, + ]); + TaskDraft::factory()->create([ + 'task_id' => $otherTask->id, + 'data' => ['secret' => 'case-insensitive-nested'], + ]); + + $ownTask = ProcessRequestToken::factory()->create([ + 'process_request_id' => $processRequest->id, + 'status' => 'ACTIVE', + 'user_id' => $viewer->id, + ]); + + $response = $this->apiCall('GET', route('api.tasks.index', [ + 'include' => 'processRequest.tokens.Draft', + ])); + $response->assertStatus(200); + + $row = collect($response->json('data'))->firstWhere('id', $ownTask->id); + $tokens = collect($row['process_request']['tokens'] ?? [])->keyBy('id'); + $otherDraft = $tokens[$otherTask->id]['draft'] ?? null; + + $this->assertNotNull($otherDraft); + $this->assertArrayNotHasKey('data', $otherDraft); + } + public function testTaskIndexProcessRequestsTokensDraftDoesNotExposeOtherUsersDraftData() { $this->initializePermissions(); From d8d53acb3eaf4ea20d9e78ed9ee021c58dc963fc Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Thu, 12 Nov 2026 16:00:48 -0400 Subject: [PATCH 20/29] refactor(FOUR-34369): reduce return count in draft payload helpers Split resolveDraftPayloadForToken for Sonar S1142 and extract draftIdFromPayload to clear nested ternary S3358 without changing draft authorization behavior. https://processmaker.atlassian.net/browse/FOUR-34369 --- ProcessMaker/Traits/TaskResourceIncludes.php | 80 ++++++++++++-------- 1 file changed, 47 insertions(+), 33 deletions(-) diff --git a/ProcessMaker/Traits/TaskResourceIncludes.php b/ProcessMaker/Traits/TaskResourceIncludes.php index ae4835d290..c81d311b24 100644 --- a/ProcessMaker/Traits/TaskResourceIncludes.php +++ b/ProcessMaker/Traits/TaskResourceIncludes.php @@ -111,27 +111,33 @@ private function resolveDraftPayloadForToken(ProcessRequestToken $token, mixed $ return null; } - $user = Auth::user(); - if (!TaskDraft::draftsEnabled()) { - if (!$user) { - return null; - } - $this->ensureTokenAttributesForViewPolicy($token); - if (!$this->userCanViewTaskForDraft($user, $token)) { - return null; - } - $draft->delete(); + return $this->resolveDraftPayloadWhenDraftsDisabled(Auth::user(), $token, $draft); + } + + return $this->resolveDraftPayloadWhenDraftsEnabled(Auth::user(), $token, $draft); + } + /** + * @return array|null + */ + private function resolveDraftPayloadWhenDraftsDisabled(?User $user, ProcessRequestToken $token, TaskDraft $draft): ?array + { + if (!$user || !$this->callerCanViewTaskForDraft($user, $token)) { return null; } - if (!$user) { - return $draft->only(['id', 'task_id']); - } + $draft->delete(); - $this->ensureTokenAttributesForViewPolicy($token); - if (!$this->userCanViewTaskForDraft($user, $token)) { + return null; + } + + /** + * @return array|TaskDraft|null + */ + private function resolveDraftPayloadWhenDraftsEnabled(?User $user, ProcessRequestToken $token, TaskDraft $draft): array|TaskDraft|null + { + if (!$user || !$this->callerCanViewTaskForDraft($user, $token)) { return $draft->only(['id', 'task_id']); } @@ -145,6 +151,13 @@ private function resolveDraftPayloadForToken(ProcessRequestToken $token, mixed $ return $draft; } + private function callerCanViewTaskForDraft(User $user, ProcessRequestToken $token): bool + { + $this->ensureTokenAttributesForViewPolicy($token); + + return $this->userCanViewTaskForDraft($user, $token); + } + private function tokenFromPersistedId(int|string|null $tokenId): ?ProcessRequestToken { if ($tokenId === null || $tokenId === '') { @@ -165,16 +178,15 @@ private function tokenFromPersistedId(int|string|null $tokenId): ?ProcessRequest */ private function taskDraftForToken(ProcessRequestToken $token, mixed $draft): ?TaskDraft { + $boundQuery = fn () => TaskDraft::query() + ->where('task_id', $token->id) + ->first(['id', 'task_id', 'data']); + if ($draft === null) { - return TaskDraft::query() - ->where('task_id', $token->id) - ->first(['id', 'task_id', 'data']); + return $boundQuery(); } - $draftId = $draft instanceof TaskDraft - ? $draft->getKey() - : (is_array($draft) ? ($draft['id'] ?? null) : null); - + $draftId = $this->draftIdFromPayload($draft); if ($draftId !== null) { return TaskDraft::query() ->whereKey($draftId) @@ -182,10 +194,17 @@ private function taskDraftForToken(ProcessRequestToken $token, mixed $draft): ?T ->first(['id', 'task_id', 'data']); } + return $draft instanceof TaskDraft ? $boundQuery() : null; + } + + private function draftIdFromPayload(mixed $draft): int|string|null + { if ($draft instanceof TaskDraft) { - return TaskDraft::query() - ->where('task_id', $token->id) - ->first(['id', 'task_id', 'data']); + return $draft->getKey(); + } + + if (is_array($draft)) { + return $draft['id'] ?? null; } return null; @@ -378,15 +397,10 @@ private function userCanViewTaskForDraft(User $user, ?ProcessRequestToken $token } $token ??= $this->resource; - if ((int) $token->user_id === (int) $user->id) { - return true; - } - - if (in_array($user->id, $this->managerIdsForTaskProcess($token))) { - return true; - } - return $user->canSelfServe($token); + return (int) $token->user_id === (int) $user->id + || in_array($user->id, $this->managerIdsForTaskProcess($token)) + || $user->canSelfServe($token); } /** From b64d057c2a243cb12476198ad00ec960d7001c16 Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Thu, 12 Nov 2026 16:41:42 -0400 Subject: [PATCH 21/29] fix(FOUR-34369): coerce null process index pmql query to empty string Passing null into applyProcessIndexPmql triggered a TypeError after the Sonar refactor added a string type hint; normalize pmql before the call. https://processmaker.atlassian.net/browse/FOUR-34369 --- ProcessMaker/Http/Controllers/Api/ProcessController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ProcessMaker/Http/Controllers/Api/ProcessController.php b/ProcessMaker/Http/Controllers/Api/ProcessController.php index 279525d456..8e4f55b1ef 100644 --- a/ProcessMaker/Http/Controllers/Api/ProcessController.php +++ b/ProcessMaker/Http/Controllers/Api/ProcessController.php @@ -158,7 +158,7 @@ public function index(Request $request) // Filter by category status $processes->categoryStatus($request->input('cat_status', null)); - $pmqlError = $this->applyProcessIndexPmql($processes, $request->input('pmql', '')); + $pmqlError = $this->applyProcessIndexPmql($processes, (string) ($request->input('pmql') ?? '')); if ($pmqlError !== null) { return $pmqlError; } From 1e891d0fb41cef06f241fe4c5045c81fb760e20f Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Thu, 12 Nov 2026 20:52:26 -0400 Subject: [PATCH 22/29] refactor(FOUR-34369): reduce return statements in resolveDraftPayloadForToken Merge token and draft early-exit guards for Sonar S1142 without changing draft authorization behavior. https://processmaker.atlassian.net/browse/FOUR-34369 --- ProcessMaker/Traits/TaskResourceIncludes.php | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/ProcessMaker/Traits/TaskResourceIncludes.php b/ProcessMaker/Traits/TaskResourceIncludes.php index c81d311b24..11b90cb991 100644 --- a/ProcessMaker/Traits/TaskResourceIncludes.php +++ b/ProcessMaker/Traits/TaskResourceIncludes.php @@ -102,12 +102,8 @@ protected function sanitizeDraftInTaskArray(array $array, $request): array private function resolveDraftPayloadForToken(ProcessRequestToken $token, mixed $draft): array|TaskDraft|null { $token = $this->tokenFromPersistedId($token->getKey()); - if (!$token) { - return null; - } - - $draft = $this->taskDraftForToken($token, $draft); - if (!$draft) { + $draft = $token !== null ? $this->taskDraftForToken($token, $draft) : null; + if ($token === null || $draft === null) { return null; } From f2f36bf8d0c897e426916d969b19d2dece247a94 Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Thu, 12 Nov 2026 21:08:10 -0400 Subject: [PATCH 23/29] fix(FOUR-34369): scope root draft sanitization and eager load to root includes Nested draft includes (e.g. processRequest.tokens.draft) no longer eager-load, resolve, or delete the parent task draft when only nested paths are requested. Root draft.* includes still use constrained eager load with nested relations (draft.media). https://processmaker.atlassian.net/browse/FOUR-34369 --- ProcessMaker/Http/Resources/Task.php | 2 +- .../Http/Resources/V1_1/TaskResource.php | 8 +-- ProcessMaker/Support/TaskDraftIncludes.php | 57 ++++++++++++++- .../Traits/TaskControllerIndexMethods.php | 8 +-- ProcessMaker/Traits/TaskResourceIncludes.php | 17 +++-- tests/Feature/Api/TasksTest.php | 70 +++++++++++++++++++ 6 files changed, 147 insertions(+), 15 deletions(-) diff --git a/ProcessMaker/Http/Resources/Task.php b/ProcessMaker/Http/Resources/Task.php index 765a15920d..d0f734ffa8 100644 --- a/ProcessMaker/Http/Resources/Task.php +++ b/ProcessMaker/Http/Resources/Task.php @@ -61,7 +61,7 @@ public function toArray($request) $this->process = $this->resource->process; foreach ($this->includeMethods as $key) { - if ($key === 'draft' && TaskDraftIncludes::includesDraft($include)) { + if ($key === 'draft' && TaskDraftIncludes::includesRootDraft($include)) { continue; } if (!in_array($key, $include, true)) { diff --git a/ProcessMaker/Http/Resources/V1_1/TaskResource.php b/ProcessMaker/Http/Resources/V1_1/TaskResource.php index dcfbf42e73..1bb6a08a8d 100644 --- a/ProcessMaker/Http/Resources/V1_1/TaskResource.php +++ b/ProcessMaker/Http/Resources/V1_1/TaskResource.php @@ -186,7 +186,7 @@ public static function preprocessInclude(Request $request, Builder $query): self if (!in_array($key, $include, true)) { continue; } - if ($key === 'draft' && !in_array('draft', $parsed, true)) { + if ($key === 'draft' && !TaskDraftIncludes::includesRootDraft($parsed)) { continue; } @@ -198,7 +198,7 @@ public static function preprocessInclude(Request $request, Builder $query): self if (!in_array($key, $include, true)) { continue; } - if ($key === 'draft' && !in_array('draft', $parsed, true)) { + if ($key === 'draft' && !TaskDraftIncludes::includesRootDraft($parsed)) { continue; } @@ -220,7 +220,7 @@ public static function fromTokenWithIncludes(ProcessRequestToken $token, Request if (!in_array($key, $include, true)) { continue; } - if ($key === 'draft' && !in_array('draft', $parsed, true)) { + if ($key === 'draft' && !TaskDraftIncludes::includesRootDraft($parsed)) { continue; } @@ -258,7 +258,7 @@ private function processInclude(Request $request, array $array) $include = self::parseV11RequestIncludes($request); foreach (self::$includeMethods as $key) { - if ($key === 'draft' && TaskDraftIncludes::includesDraft($include)) { + if ($key === 'draft' && TaskDraftIncludes::includesRootDraft($include)) { continue; } if (!in_array($key, $include, true)) { diff --git a/ProcessMaker/Support/TaskDraftIncludes.php b/ProcessMaker/Support/TaskDraftIncludes.php index 15af969cb5..6960651993 100644 --- a/ProcessMaker/Support/TaskDraftIncludes.php +++ b/ProcessMaker/Support/TaskDraftIncludes.php @@ -25,9 +25,15 @@ public static function parseIncludeList(string $include): array } public static function includesDraft(array $includes): bool + { + return self::includesRootDraft($includes) || self::includesNestedDraft($includes); + } + + public static function includesRootDraft(array $includes): bool { foreach ($includes as $token) { - if (self::isDraftToken($token)) { + $lower = strtolower(trim($token)); + if ($lower === 'draft' || str_starts_with($lower, 'draft.')) { return true; } } @@ -35,6 +41,23 @@ public static function includesDraft(array $includes): bool return false; } + public static function includesNestedDraft(array $includes): bool + { + foreach ($includes as $token) { + if (!self::isDraftToken($token)) { + continue; + } + $lower = strtolower(trim($token)); + if ($lower === 'draft' || str_starts_with($lower, 'draft.')) { + continue; + } + + return true; + } + + return false; + } + public static function isDraftToken(string $token): bool { $lower = strtolower($token); @@ -50,6 +73,38 @@ public static function constrainedEagerLoad(): \Closure return fn ($q) => $q->select(self::EAGER_COLUMNS); } + /** + * @return list + */ + public static function rootDraftNestedRelations(array $includes): array + { + $relations = []; + foreach ($includes as $token) { + $lower = strtolower(trim($token)); + if (!str_starts_with($lower, 'draft.') || $lower === 'draft') { + continue; + } + $suffix = substr($lower, strlen('draft.')); + if ($suffix !== '') { + $relations[] = $suffix; + } + } + + return array_values(array_unique($relations)); + } + + public static function rootDraftEagerLoad(array $includes): \Closure + { + $nested = self::rootDraftNestedRelations($includes); + + return function ($q) use ($nested) { + $q->select(self::EAGER_COLUMNS); + if ($nested !== []) { + $q->with($nested); + } + }; + } + /** * @return array */ diff --git a/ProcessMaker/Traits/TaskControllerIndexMethods.php b/ProcessMaker/Traits/TaskControllerIndexMethods.php index b8acef0608..893ff86e28 100644 --- a/ProcessMaker/Traits/TaskControllerIndexMethods.php +++ b/ProcessMaker/Traits/TaskControllerIndexMethods.php @@ -62,8 +62,8 @@ private function indexBaseQuery($request) 'user', ]); - if (TaskDraftIncludes::includesDraft($includes)) { - $query->with(['draft' => TaskDraftIncludes::constrainedEagerLoad()]); + if (TaskDraftIncludes::includesRootDraft($includes)) { + $query->with(['draft' => TaskDraftIncludes::rootDraftEagerLoad($includes)]); } $nestedDraftWith = TaskDraftIncludes::nestedDraftEagerLoadMap($includes); @@ -135,8 +135,8 @@ private function buildOptimizedIndexWith(array $includes, bool $includeData): ar $with['user'] = fn ($q) => $q->select(['id', 'firstname', 'lastname', 'avatar', 'status']); } - if (TaskDraftIncludes::includesDraft($includes)) { - $with['draft'] = TaskDraftIncludes::constrainedEagerLoad(); + if (TaskDraftIncludes::includesRootDraft($includes)) { + $with['draft'] = TaskDraftIncludes::rootDraftEagerLoad($includes); } if (in_array('process', $includes, true)) { diff --git a/ProcessMaker/Traits/TaskResourceIncludes.php b/ProcessMaker/Traits/TaskResourceIncludes.php index 11b90cb991..7f1bd7a53c 100644 --- a/ProcessMaker/Traits/TaskResourceIncludes.php +++ b/ProcessMaker/Traits/TaskResourceIncludes.php @@ -86,12 +86,19 @@ protected function sanitizeDraftInTaskArray(array $array, $request): array return $array; } - $draftPayload = $this->resource->relationLoaded('draft') - ? $this->draft - : ($array['draft'] ?? null); + if (TaskDraftIncludes::includesRootDraft($include)) { + $draftPayload = $this->resource->relationLoaded('draft') + ? $this->draft + : ($array['draft'] ?? null); - $array['draft'] = $this->resolveDraftPayloadForToken($this->resource, $draftPayload); - $this->redactNestedDraftsInArray($array); + $array['draft'] = $this->resolveDraftPayloadForToken($this->resource, $draftPayload); + } else { + unset($array['draft']); + } + + if (TaskDraftIncludes::includesNestedDraft($include)) { + $this->redactNestedDraftsInArray($array); + } return $array; } diff --git a/tests/Feature/Api/TasksTest.php b/tests/Feature/Api/TasksTest.php index 2b21832067..07e9e8affd 100644 --- a/tests/Feature/Api/TasksTest.php +++ b/tests/Feature/Api/TasksTest.php @@ -370,6 +370,76 @@ public function testTaskIndexNestedDraftIncludeDoesNotExposeOtherUsersDraftData( $this->assertArrayNotHasKey('data', $draft); } + public function testTaskIndexNestedDraftIncludeWithDraftsDisabledDoesNotDeleteOwnParentDraft() + { + $this->initializePermissions(); + config([ + 'app.task_drafts_enabled' => false, + 'app.processmaker_optimized_tasks_enabled' => true, + ]); + + $assignee = User::factory()->create(); + $this->user = $assignee; + $processRequest = ProcessRequest::factory()->create(); + $parentTask = ProcessRequestToken::factory()->create([ + 'process_request_id' => $processRequest->id, + 'status' => 'ACTIVE', + 'user_id' => $assignee->id, + ]); + $parentDraft = TaskDraft::factory()->create([ + 'task_id' => $parentTask->id, + 'data' => ['parent' => 'must-survive-nested-include'], + ]); + + $response = $this->apiCall('GET', route('api.tasks.index', [ + 'include' => 'processRequest.tokens.draft', + ])); + $response->assertStatus(200); + + $this->assertDatabaseHas('task_drafts', [ + 'id' => $parentDraft->id, + 'task_id' => $parentTask->id, + ]); + $row = collect($response->json('data'))->keyBy('id')[$parentTask->id]; + $this->assertArrayNotHasKey('draft', $row); + } + + public function testTaskIndexProcessRequestsTokensDraftWithDraftsDisabledDoesNotDeleteOwnParentDraft() + { + $this->initializePermissions(); + config([ + 'app.task_drafts_enabled' => false, + 'app.processmaker_optimized_tasks_enabled' => true, + ]); + + $assignee = User::factory()->create(); + $this->user = $assignee; + $process = Process::factory()->create(); + $processRequest = ProcessRequest::factory()->create(['process_id' => $process->id]); + $parentTask = ProcessRequestToken::factory()->create([ + 'process_request_id' => $processRequest->id, + 'process_id' => $process->id, + 'status' => 'ACTIVE', + 'user_id' => $assignee->id, + ]); + $parentDraft = TaskDraft::factory()->create([ + 'task_id' => $parentTask->id, + 'data' => ['parent' => 'must-survive-process-requests'], + ]); + + $response = $this->apiCall('GET', route('api.tasks.index', [ + 'include' => 'process,process.requests.tokens.draft', + ])); + $response->assertStatus(200); + + $this->assertDatabaseHas('task_drafts', [ + 'id' => $parentDraft->id, + 'task_id' => $parentTask->id, + ]); + $row = collect($response->json('data'))->keyBy('id')[$parentTask->id]; + $this->assertArrayNotHasKey('draft', $row); + } + public function testTaskIndexProcessRequestTokensDraftDoesNotExposeOtherUsersDraftData() { $this->initializePermissions(); From 982f6bce0e4fc422548d702f5a1dfa6e4f8c6ba3 Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Thu, 12 Nov 2026 21:17:30 -0400 Subject: [PATCH 24/29] fix(FOUR-34369): treat Laravel include column suffixes in draft token parsing Strip :* and :col from include paths so nested draft eager loads and sanitization apply to processRequest.tokens.draft:* variants; redact nested drafts defensively when serialized token trees contain draft payloads. https://processmaker.atlassian.net/browse/FOUR-3436fix(FOUR-34369): treat Laravel include column suffixes in draft token parsing Strip :* and :col from include paths so nested draft eager loads and sanitization apply to processRequest.tokens.draft:* variants; redact nested drafts defensively when serialized token trees contain draft payloads. https://processmaker.atlassian.net/browse/FOUR-343699 --- ProcessMaker/Support/TaskDraftIncludes.php | 48 +++++++---- ProcessMaker/Traits/TaskResourceIncludes.php | 30 +++++++ tests/Feature/Api/TasksTest.php | 88 ++++++++++++++++++++ 3 files changed, 151 insertions(+), 15 deletions(-) diff --git a/ProcessMaker/Support/TaskDraftIncludes.php b/ProcessMaker/Support/TaskDraftIncludes.php index 6960651993..01c7aed992 100644 --- a/ProcessMaker/Support/TaskDraftIncludes.php +++ b/ProcessMaker/Support/TaskDraftIncludes.php @@ -32,8 +32,8 @@ public static function includesDraft(array $includes): bool public static function includesRootDraft(array $includes): bool { foreach ($includes as $token) { - $lower = strtolower(trim($token)); - if ($lower === 'draft' || str_starts_with($lower, 'draft.')) { + $path = strtolower(self::relationPathFromIncludeToken($token)); + if ($path === 'draft' || str_starts_with($path, 'draft.')) { return true; } } @@ -47,8 +47,8 @@ public static function includesNestedDraft(array $includes): bool if (!self::isDraftToken($token)) { continue; } - $lower = strtolower(trim($token)); - if ($lower === 'draft' || str_starts_with($lower, 'draft.')) { + $path = strtolower(self::relationPathFromIncludeToken($token)); + if ($path === 'draft' || str_starts_with($path, 'draft.')) { continue; } @@ -58,14 +58,32 @@ public static function includesNestedDraft(array $includes): bool return false; } + /** + * Laravel include tokens may end with :col or :*; only the relation path is significant here. + */ + public static function relationPathFromIncludeToken(string $token): string + { + $token = trim($token); + if ($token === '') { + return ''; + } + + $colonAt = strpos($token, ':'); + if ($colonAt === false) { + return $token; + } + + return substr($token, 0, $colonAt); + } + public static function isDraftToken(string $token): bool { - $lower = strtolower($token); + $path = strtolower(self::relationPathFromIncludeToken($token)); - return $lower === 'draft' - || str_starts_with($lower, 'draft.') - || str_ends_with($lower, '.draft') - || str_contains($lower, '.draft.'); + return $path === 'draft' + || str_starts_with($path, 'draft.') + || str_ends_with($path, '.draft') + || str_contains($path, '.draft.'); } public static function constrainedEagerLoad(): \Closure @@ -80,11 +98,11 @@ public static function rootDraftNestedRelations(array $includes): array { $relations = []; foreach ($includes as $token) { - $lower = strtolower(trim($token)); - if (!str_starts_with($lower, 'draft.') || $lower === 'draft') { + $path = strtolower(self::relationPathFromIncludeToken($token)); + if (!str_starts_with($path, 'draft.') || $path === 'draft') { continue; } - $suffix = substr($lower, strlen('draft.')); + $suffix = substr($path, strlen('draft.')); if ($suffix !== '') { $relations[] = $suffix; } @@ -114,13 +132,13 @@ public static function nestedDraftEagerLoadMap(array $includes): array $constrained = fn ($q) => $q->with(['draft' => self::constrainedEagerLoad()]); foreach ($includes as $token) { - $lower = strtolower($token); - if (!self::isDraftToken($token) || $lower === 'draft' || str_starts_with($lower, 'draft.')) { + $path = strtolower(self::relationPathFromIncludeToken($token)); + if (!self::isDraftToken($token) || $path === 'draft' || str_starts_with($path, 'draft.')) { continue; } foreach (self::NESTED_DRAFT_RELATIONS as $relation) { $relationLower = strtolower($relation); - if ($lower === "{$relationLower}.draft" || str_starts_with($lower, "{$relationLower}.")) { + if ($path === "{$relationLower}.draft" || str_starts_with($path, "{$relationLower}.")) { $with[$relation] = $constrained; break; } diff --git a/ProcessMaker/Traits/TaskResourceIncludes.php b/ProcessMaker/Traits/TaskResourceIncludes.php index 7f1bd7a53c..e9981b752e 100644 --- a/ProcessMaker/Traits/TaskResourceIncludes.php +++ b/ProcessMaker/Traits/TaskResourceIncludes.php @@ -82,6 +82,9 @@ protected function sanitizeDraftInTaskArray(array $array, $request): array if (!TaskDraftIncludes::includesDraft($include)) { unset($array['draft']); + if ($this->arrayContainsNestedTokenDrafts($array)) { + $this->redactNestedDraftsInArray($array); + } return $array; } @@ -255,6 +258,33 @@ private function redactDraftOnSerializedToken(array &$row): void $row['draft'] = $this->resolveDraftPayloadForToken($token, $row['draft']); } + /** + * @param array $array + */ + private function arrayContainsNestedTokenDrafts(array $array): bool + { + foreach ($array as $key => $value) { + if (!is_array($value) || in_array($key, self::DRAFT_REDACT_EXCLUDED_KEYS, true)) { + continue; + } + + if ($key === 'tokens' && array_is_list($value)) { + foreach ($value as $item) { + if (is_array($item) && array_key_exists('draft', $item)) { + return true; + } + } + continue; + } + + if ($this->arrayContainsNestedTokenDrafts($value)) { + return true; + } + } + + return false; + } + private function includeComponent() { $component = $this->getScreenVersion() ? $this->getScreenVersion()->parent->renderComponent() : null; diff --git a/tests/Feature/Api/TasksTest.php b/tests/Feature/Api/TasksTest.php index 07e9e8affd..42c96b0d01 100644 --- a/tests/Feature/Api/TasksTest.php +++ b/tests/Feature/Api/TasksTest.php @@ -533,6 +533,94 @@ public function testTaskIndexProcessRequestTokensDraftCaseInsensitiveDoesNotExpo $this->assertArrayNotHasKey('data', $otherDraft); } + public function testTaskIndexProcessRequestTokensDraftWildcardSelectDoesNotExposeOtherUsersDraftData() + { + $this->initializePermissions(); + config([ + 'app.task_drafts_enabled' => true, + 'app.processmaker_optimized_tasks_enabled' => true, + ]); + + $viewer = User::factory()->create(); + $viewer->giveDirectPermission('view-all_requests'); + $this->user = $viewer; + $assignee = User::factory()->create(); + + $processRequest = ProcessRequest::factory()->create(); + $otherTask = ProcessRequestToken::factory()->create([ + 'process_request_id' => $processRequest->id, + 'status' => 'ACTIVE', + 'user_id' => $assignee->id, + ]); + TaskDraft::factory()->create([ + 'task_id' => $otherTask->id, + 'data' => ['secret' => 'laravel-include-wildcard'], + ]); + + $ownTask = ProcessRequestToken::factory()->create([ + 'process_request_id' => $processRequest->id, + 'status' => 'ACTIVE', + 'user_id' => $viewer->id, + ]); + + $response = $this->apiCall('GET', route('api.tasks.index', [ + 'include' => 'processRequest.tokens.draft:*', + ])); + $response->assertStatus(200); + + $row = collect($response->json('data'))->firstWhere('id', $ownTask->id); + $tokens = collect($row['process_request']['tokens'] ?? [])->keyBy('id'); + $otherDraft = $tokens[$otherTask->id]['draft'] ?? null; + + $this->assertNotNull($otherDraft); + $this->assertArrayNotHasKey('data', $otherDraft); + $json = json_encode($response->json()); + $this->assertStringNotContainsString('laravel-include-wildcard', $json); + } + + public function testTaskIndexProcessRequestTokensDraftTrailingColonDoesNotExposeOtherUsersDraftData() + { + $this->initializePermissions(); + config([ + 'app.task_drafts_enabled' => true, + 'app.processmaker_optimized_tasks_enabled' => true, + ]); + + $viewer = User::factory()->create(); + $viewer->giveDirectPermission('view-all_requests'); + $this->user = $viewer; + $assignee = User::factory()->create(); + + $processRequest = ProcessRequest::factory()->create(); + $otherTask = ProcessRequestToken::factory()->create([ + 'process_request_id' => $processRequest->id, + 'status' => 'ACTIVE', + 'user_id' => $assignee->id, + ]); + TaskDraft::factory()->create([ + 'task_id' => $otherTask->id, + 'data' => ['secret' => 'laravel-include-trailing-colon'], + ]); + + $ownTask = ProcessRequestToken::factory()->create([ + 'process_request_id' => $processRequest->id, + 'status' => 'ACTIVE', + 'user_id' => $viewer->id, + ]); + + $response = $this->apiCall('GET', route('api.tasks.index', [ + 'include' => 'processRequest.tokens.draft:', + ])); + $response->assertStatus(200); + + $row = collect($response->json('data'))->firstWhere('id', $ownTask->id); + $tokens = collect($row['process_request']['tokens'] ?? [])->keyBy('id'); + $otherDraft = $tokens[$otherTask->id]['draft'] ?? null; + + $this->assertNotNull($otherDraft); + $this->assertArrayNotHasKey('data', $otherDraft); + } + public function testTaskIndexProcessRequestsTokensDraftDoesNotExposeOtherUsersDraftData() { $this->initializePermissions(); From 89b063626ed2e75da11e7f90381c357b57349fad Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Thu, 12 Nov 2026 21:22:59 -0400 Subject: [PATCH 25/29] fix(FOUR-34369): only consume task drafts on root include when drafts disabled Nested draft redaction suppresses payload without deleting rows; root include=draft retains legacy delete-on-access for assignees. https://processmaker.atlassian.net/browse/FOUR-34369 --- ProcessMaker/Traits/TaskResourceIncludes.php | 28 +++++++++++++++----- tests/Feature/Api/TasksTest.php | 8 ++++++ 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/ProcessMaker/Traits/TaskResourceIncludes.php b/ProcessMaker/Traits/TaskResourceIncludes.php index e9981b752e..6381c75a94 100644 --- a/ProcessMaker/Traits/TaskResourceIncludes.php +++ b/ProcessMaker/Traits/TaskResourceIncludes.php @@ -94,7 +94,7 @@ protected function sanitizeDraftInTaskArray(array $array, $request): array ? $this->draft : ($array['draft'] ?? null); - $array['draft'] = $this->resolveDraftPayloadForToken($this->resource, $draftPayload); + $array['draft'] = $this->resolveDraftPayloadForToken($this->resource, $draftPayload, true); } else { unset($array['draft']); } @@ -109,8 +109,11 @@ protected function sanitizeDraftInTaskArray(array $array, $request): array /** * @return array|TaskDraft|null */ - private function resolveDraftPayloadForToken(ProcessRequestToken $token, mixed $draft): array|TaskDraft|null - { + private function resolveDraftPayloadForToken( + ProcessRequestToken $token, + mixed $draft, + bool $consumeDraftWhenDisabled = false, + ): array|TaskDraft|null { $token = $this->tokenFromPersistedId($token->getKey()); $draft = $token !== null ? $this->taskDraftForToken($token, $draft) : null; if ($token === null || $draft === null) { @@ -118,7 +121,12 @@ private function resolveDraftPayloadForToken(ProcessRequestToken $token, mixed $ } if (!TaskDraft::draftsEnabled()) { - return $this->resolveDraftPayloadWhenDraftsDisabled(Auth::user(), $token, $draft); + return $this->resolveDraftPayloadWhenDraftsDisabled( + Auth::user(), + $token, + $draft, + $consumeDraftWhenDisabled + ); } return $this->resolveDraftPayloadWhenDraftsEnabled(Auth::user(), $token, $draft); @@ -127,13 +135,19 @@ private function resolveDraftPayloadForToken(ProcessRequestToken $token, mixed $ /** * @return array|null */ - private function resolveDraftPayloadWhenDraftsDisabled(?User $user, ProcessRequestToken $token, TaskDraft $draft): ?array - { + private function resolveDraftPayloadWhenDraftsDisabled( + ?User $user, + ProcessRequestToken $token, + TaskDraft $draft, + bool $consumeDraftWhenDisabled, + ): ?array { if (!$user || !$this->callerCanViewTaskForDraft($user, $token)) { return null; } - $draft->delete(); + if ($consumeDraftWhenDisabled) { + $draft->delete(); + } return null; } diff --git a/tests/Feature/Api/TasksTest.php b/tests/Feature/Api/TasksTest.php index 42c96b0d01..25c0c40ced 100644 --- a/tests/Feature/Api/TasksTest.php +++ b/tests/Feature/Api/TasksTest.php @@ -386,6 +386,11 @@ public function testTaskIndexNestedDraftIncludeWithDraftsDisabledDoesNotDeleteOw 'status' => 'ACTIVE', 'user_id' => $assignee->id, ]); + ProcessRequestToken::factory()->create([ + 'process_request_id' => $processRequest->id, + 'status' => 'ACTIVE', + 'user_id' => User::factory()->create()->id, + ]); $parentDraft = TaskDraft::factory()->create([ 'task_id' => $parentTask->id, 'data' => ['parent' => 'must-survive-nested-include'], @@ -402,6 +407,9 @@ public function testTaskIndexNestedDraftIncludeWithDraftsDisabledDoesNotDeleteOw ]); $row = collect($response->json('data'))->keyBy('id')[$parentTask->id]; $this->assertArrayNotHasKey('draft', $row); + $nestedDraft = collect($row['process_request']['tokens'] ?? []) + ->firstWhere('id', $parentTask->id)['draft'] ?? null; + $this->assertNull($nestedDraft); } public function testTaskIndexProcessRequestsTokensDraftWithDraftsDisabledDoesNotDeleteOwnParentDraft() From 365fd5f02e0b5c42625bed641b95876940c88826 Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Thu, 12 Nov 2026 22:03:20 -0400 Subject: [PATCH 26/29] test(FOUR-34369): assert nested draft include does not delete assignee drafts for managers When task drafts are disabled, process managers listing with processRequest.tokens.draft must not remove other assignees' task_drafts rows. https://processmaker.atlassian.net/browse/FOUR-34369 --- tests/Feature/Api/TasksTest.php | 47 +++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/tests/Feature/Api/TasksTest.php b/tests/Feature/Api/TasksTest.php index 25c0c40ced..1aff9d5c43 100644 --- a/tests/Feature/Api/TasksTest.php +++ b/tests/Feature/Api/TasksTest.php @@ -706,6 +706,53 @@ public function testLegacyTaskIndexWithoutIncludeDoesNotEmbedDraftRelation() $this->assertArrayNotHasKey('draft', $row); } + public function testTaskIndexNestedDraftWithDraftsDisabledDoesNotDeleteOtherAssigneeDraftForManager() + { + $this->initializePermissions(); + config([ + 'app.task_drafts_enabled' => false, + 'app.processmaker_optimized_tasks_enabled' => true, + ]); + + $manager = User::factory()->create(); + $assignee = User::factory()->create(); + $this->user = $manager; + + $process = Process::factory()->create([ + 'properties' => ['manager_id' => [$manager->id]], + ]); + $processRequest = ProcessRequest::factory()->create(['process_id' => $process->id]); + $otherTask = ProcessRequestToken::factory()->create([ + 'process_id' => $process->id, + 'process_request_id' => $processRequest->id, + 'status' => 'ACTIVE', + 'user_id' => $assignee->id, + ]); + $managerTask = ProcessRequestToken::factory()->create([ + 'process_id' => $process->id, + 'process_request_id' => $processRequest->id, + 'status' => 'ACTIVE', + 'user_id' => $manager->id, + ]); + $otherDraft = TaskDraft::factory()->create([ + 'task_id' => $otherTask->id, + 'data' => ['secret' => 'manager-nested-must-not-delete'], + ]); + + $response = $this->apiCall('GET', route('api.tasks.index', [ + 'include' => 'processRequest.tokens.draft', + ])); + $response->assertStatus(200); + + $this->assertDatabaseHas('task_drafts', [ + 'id' => $otherDraft->id, + 'task_id' => $otherTask->id, + ]); + $row = collect($response->json('data'))->firstWhere('id', $managerTask->id); + $nested = collect($row['process_request']['tokens'] ?? [])->keyBy('id')[$otherTask->id]['draft'] ?? null; + $this->assertNull($nested); + } + public function testTaskIndexWithDraftsDisabledDoesNotDeleteAnotherUsersDraft() { $this->initializePermissions(); From 4ed37b4aaa4b9bc2117f02e060c852a7b80bd744 Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Thu, 12 Nov 2026 23:01:36 -0400 Subject: [PATCH 27/29] perf(FOUR-34369): batch draft policy token loads on include=draft Avoid per-row token queries on optimized index when draft is included; prefetch nested token rows for redaction and cache process manager ids. https://processmaker.atlassian.net/browse/FOUR-34369 --- ProcessMaker/Http/Middleware/BrowserCache.php | 2 +- ProcessMaker/Traits/TaskResourceIncludes.php | 198 +++++++++++-- composer.json | 4 +- tests/Feature/Api/TasksTest.php | 268 ++++-------------- 4 files changed, 245 insertions(+), 227 deletions(-) diff --git a/ProcessMaker/Http/Middleware/BrowserCache.php b/ProcessMaker/Http/Middleware/BrowserCache.php index 8eeaf90c0b..2200338e21 100644 --- a/ProcessMaker/Http/Middleware/BrowserCache.php +++ b/ProcessMaker/Http/Middleware/BrowserCache.php @@ -10,7 +10,7 @@ class BrowserCache * Handle an incoming request. * * @param \Illuminate\Http\Request $request - * @param Closure $next + * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) diff --git a/ProcessMaker/Traits/TaskResourceIncludes.php b/ProcessMaker/Traits/TaskResourceIncludes.php index 6381c75a94..138183c452 100644 --- a/ProcessMaker/Traits/TaskResourceIncludes.php +++ b/ProcessMaker/Traits/TaskResourceIncludes.php @@ -20,6 +20,21 @@ trait TaskResourceIncludes { use TaskScreenResourceTrait; + /** @var array */ + private array $draftPolicyTokenCache = []; + + /** @var array> */ + private array $processManagerIdsCache = []; + + private const DRAFT_POLICY_TOKEN_COLUMNS = [ + 'id', + 'user_id', + 'process_id', + 'process_request_id', + 'is_self_service', + 'self_service_groups', + ]; + /** Do not treat case/request payload trees as task token rows. */ private const DRAFT_REDACT_EXCLUDED_KEYS = [ 'request_data', @@ -83,6 +98,7 @@ protected function sanitizeDraftInTaskArray(array $array, $request): array if (!TaskDraftIncludes::includesDraft($include)) { unset($array['draft']); if ($this->arrayContainsNestedTokenDrafts($array)) { + $this->prefetchDraftPolicyTokensForNestedArray($array); $this->redactNestedDraftsInArray($array); } @@ -100,6 +116,7 @@ protected function sanitizeDraftInTaskArray(array $array, $request): array } if (TaskDraftIncludes::includesNestedDraft($include)) { + $this->prefetchDraftPolicyTokensForNestedArray($array); $this->redactNestedDraftsInArray($array); } @@ -114,7 +131,7 @@ private function resolveDraftPayloadForToken( mixed $draft, bool $consumeDraftWhenDisabled = false, ): array|TaskDraft|null { - $token = $this->tokenFromPersistedId($token->getKey()); + $token = $this->persistedTokenForDraftPolicy($token); $draft = $token !== null ? $this->taskDraftForToken($token, $draft) : null; if ($token === null || $draft === null) { return null; @@ -178,19 +195,50 @@ private function callerCanViewTaskForDraft(User $user, ProcessRequestToken $toke return $this->userCanViewTaskForDraft($user, $token); } - private function tokenFromPersistedId(int|string|null $tokenId): ?ProcessRequestToken + private function persistedTokenForDraftPolicy(ProcessRequestToken $candidate): ?ProcessRequestToken { + $tokenId = $candidate->getKey(); if ($tokenId === null || $tokenId === '') { return null; } - return ProcessRequestToken::query()->whereKey($tokenId)->first([ - 'id', - 'user_id', - 'process_id', - 'process_request_id', - 'is_self_service', - ]); + if ($this->resource instanceof ProcessRequestToken + && (int) $this->resource->getKey() === (int) $tokenId + && $this->tokenHasDraftPolicyAttributes($this->resource)) { + return $this->resource; + } + + if ($this->tokenHasDraftPolicyAttributes($candidate)) { + return $candidate; + } + + if (array_key_exists($tokenId, $this->draftPolicyTokenCache)) { + return $this->draftPolicyTokenCache[$tokenId]; + } + + $loaded = ProcessRequestToken::query() + ->whereKey($tokenId) + ->first(self::DRAFT_POLICY_TOKEN_COLUMNS); + + $this->draftPolicyTokenCache[$tokenId] = $loaded; + + return $loaded; + } + + private function tokenHasDraftPolicyAttributes(ProcessRequestToken $token): bool + { + $attrs = $token->getAttributes(); + foreach (['user_id', 'process_id', 'is_self_service'] as $column) { + if (!array_key_exists($column, $attrs)) { + return false; + } + } + + if ($token->is_self_service && !array_key_exists('self_service_groups', $attrs)) { + return false; + } + + return true; } /** @@ -262,7 +310,7 @@ private function redactDraftOnSerializedToken(array &$row): void return; } - $token = $this->tokenFromPersistedId($row['id']); + $token = $this->tokenFromNestedTokenRow($row); if (!$token) { unset($row['draft']); @@ -272,6 +320,89 @@ private function redactDraftOnSerializedToken(array &$row): void $row['draft'] = $this->resolveDraftPayloadForToken($token, $row['draft']); } + /** + * @param array $array + */ + private function prefetchDraftPolicyTokensForNestedArray(array $array): void + { + $ids = []; + $this->collectNestedTokenIdsWithDraft($array, $ids); + $ids = array_values(array_unique(array_filter($ids))); + if ($ids === []) { + return; + } + + $toLoad = []; + foreach ($ids as $id) { + if (array_key_exists($id, $this->draftPolicyTokenCache)) { + continue; + } + $toLoad[] = $id; + } + + if ($toLoad === []) { + return; + } + + $rows = ProcessRequestToken::query() + ->whereIn('id', $toLoad) + ->get(self::DRAFT_POLICY_TOKEN_COLUMNS); + + foreach ($rows as $row) { + $this->draftPolicyTokenCache[$row->getKey()] = $row; + } + + foreach ($toLoad as $id) { + if (!array_key_exists($id, $this->draftPolicyTokenCache)) { + $this->draftPolicyTokenCache[$id] = null; + } + } + } + + /** + * @param array $array + * @param list $ids + */ + private function collectNestedTokenIdsWithDraft(array $array, array &$ids): void + { + foreach ($array as $key => $value) { + if (!is_array($value) || in_array($key, self::DRAFT_REDACT_EXCLUDED_KEYS, true)) { + continue; + } + + if ($key === 'tokens' && array_is_list($value)) { + foreach ($value as $item) { + if (is_array($item) && isset($item['draft'], $item['id'])) { + $ids[] = $item['id']; + } + } + continue; + } + + $this->collectNestedTokenIdsWithDraft($value, $ids); + } + } + + /** + * @param array $row + */ + private function tokenFromNestedTokenRow(array $row): ?ProcessRequestToken + { + if (!isset($row['id'])) { + return null; + } + + $candidate = new ProcessRequestToken(); + $candidate->exists = true; + foreach (self::DRAFT_POLICY_TOKEN_COLUMNS as $column) { + if (array_key_exists($column, $row)) { + $candidate->setAttribute($column, $row[$column]); + } + } + + return $this->persistedTokenForDraftPolicy($candidate); + } + /** * @param array $array */ @@ -421,18 +552,40 @@ private function includeElementDestination() */ private function ensureTokenAttributesForViewPolicy(ProcessRequestToken $token): void { - $row = ProcessRequestToken::query() - ->whereKey($token->getKey()) - ->first(['id', 'user_id', 'process_id', 'is_self_service']); + if ($this->tokenHasDraftPolicyAttributes($token)) { + return; + } + + $tokenId = $token->getKey(); + $cached = $tokenId !== null ? ($this->draftPolicyTokenCache[$tokenId] ?? null) : null; + if ($cached instanceof ProcessRequestToken && $this->tokenHasDraftPolicyAttributes($cached)) { + $this->mergeDraftPolicyAttributes($token, $cached); + + return; + } + + $columns = ['id', 'user_id', 'process_id', 'is_self_service']; + $needsGroups = (bool) $token->is_self_service + && !array_key_exists('self_service_groups', $token->getAttributes()); + if ($needsGroups) { + $columns[] = 'self_service_groups'; + } + + $row = ProcessRequestToken::query()->whereKey($tokenId)->first($columns); if ($row) { - foreach (['user_id', 'process_id', 'is_self_service'] as $column) { - $token->setAttribute($column, $row->{$column}); + $this->mergeDraftPolicyAttributes($token, $row); + if ($tokenId !== null) { + $this->draftPolicyTokenCache[$tokenId] = $row; } } + } - if ($token->is_self_service && !array_key_exists('self_service_groups', $token->getAttributes())) { - $groups = ProcessRequestToken::query()->whereKey($token->getKey())->value('self_service_groups'); - $token->setAttribute('self_service_groups', $groups); + private function mergeDraftPolicyAttributes(ProcessRequestToken $token, ProcessRequestToken $source): void + { + foreach (['user_id', 'process_id', 'is_self_service', 'self_service_groups'] as $column) { + if (array_key_exists($column, $source->getAttributes())) { + $token->setAttribute($column, $source->getAttribute($column)); + } } } @@ -461,6 +614,10 @@ private function managerIdsForTaskProcess(ProcessRequestToken $token): array return []; } + if (array_key_exists($processId, $this->processManagerIdsCache)) { + return $this->processManagerIdsCache[$processId]; + } + if ($process && array_key_exists('properties', $process->getAttributes())) { $properties = $this->decodeJsonColumn($process->getAttribute('properties')); } else { @@ -472,7 +629,10 @@ private function managerIdsForTaskProcess(ProcessRequestToken $token): array $standIn = new Process(); $standIn->setAttribute('properties', $properties); - return $standIn->manager_id ?? []; + $managerIds = $standIn->manager_id ?? []; + $this->processManagerIdsCache[$processId] = $managerIds; + + return $managerIds; } /** diff --git a/composer.json b/composer.json index 318d58c582..da9ecc69a0 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "processmaker/processmaker", - "version": "2026.16.5", + "version": "2026.17.1-p3", "description": "BPM PHP Software", "keywords": [ "php bpm processmaker" @@ -183,7 +183,7 @@ "package-product-analytics": "1.5.12", "package-projects": "1.12.12", "package-rpa": "1.1.2", - "package-savedsearch": "1.43.24", + "package-savedsearch": "dev-epic/FOUR-32144", "package-slideshow": "1.4.3", "package-smart-extract": "1.0.4", "package-signature": "1.15.6", diff --git a/tests/Feature/Api/TasksTest.php b/tests/Feature/Api/TasksTest.php index 1aff9d5c43..13e51fa8a1 100644 --- a/tests/Feature/Api/TasksTest.php +++ b/tests/Feature/Api/TasksTest.php @@ -9,6 +9,7 @@ use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Notification; use Mockery; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Group as TestGroup; use ProcessMaker\Facades\WorkflowManager; use ProcessMaker\Http\Controllers\Api\TaskController; @@ -306,44 +307,26 @@ public function testTaskIndexIncludesDraftDataForProcessManagerWithStringManager $this->assertEquals('manager-draft', $draft['data']['manager_visible'] ?? null); } - public function testLegacyTaskIndexDraftMediaDoesNotExposeOtherUsersDraftData() + /** + * @return array + */ + public static function taskIndexRootDraftMediaRedactionProvider(): array { - $this->initializePermissions(); - config([ - 'app.task_drafts_enabled' => true, - 'app.processmaker_optimized_tasks_enabled' => false, - ]); - - $viewer = User::factory()->create(); - $viewer->giveDirectPermission('view-all_requests'); - $this->user = $viewer; - $assignee = User::factory()->create(); - - $processRequest = ProcessRequest::factory()->create(); - $otherTask = ProcessRequestToken::factory()->create([ - 'process_request_id' => $processRequest->id, - 'status' => 'ACTIVE', - 'user_id' => $assignee->id, - ]); - TaskDraft::factory()->create([ - 'task_id' => $otherTask->id, - 'data' => ['secret' => 'legacy-draft-media'], - ]); - - $response = $this->apiCall('GET', route('api.tasks.index', ['include' => 'draft.media'])); - $response->assertStatus(200); - - $draft = collect($response->json('data'))->keyBy('id')[$otherTask->id]['draft'] ?? null; - $this->assertNotNull($draft); - $this->assertArrayNotHasKey('data', $draft); + return [ + 'legacy' => [false, 'legacy-draft-media'], + 'optimized' => [true, 'optimized-draft-media'], + ]; } - public function testTaskIndexNestedDraftIncludeDoesNotExposeOtherUsersDraftData() - { + #[DataProvider('taskIndexRootDraftMediaRedactionProvider')] + public function testTaskIndexDraftMediaDoesNotExposeOtherUsersDraftData( + bool $optimizedIndex, + string $secret, + ): void { $this->initializePermissions(); config([ 'app.task_drafts_enabled' => true, - 'app.processmaker_optimized_tasks_enabled' => true, + 'app.processmaker_optimized_tasks_enabled' => $optimizedIndex, ]); $viewer = User::factory()->create(); @@ -359,7 +342,7 @@ public function testTaskIndexNestedDraftIncludeDoesNotExposeOtherUsersDraftData( ]); TaskDraft::factory()->create([ 'task_id' => $otherTask->id, - 'data' => ['secret' => 'nested-bypass'], + 'data' => ['secret' => $secret], ]); $response = $this->apiCall('GET', route('api.tasks.index', ['include' => 'draft.media'])); @@ -448,58 +431,26 @@ public function testTaskIndexProcessRequestsTokensDraftWithDraftsDisabledDoesNot $this->assertArrayNotHasKey('draft', $row); } - public function testTaskIndexProcessRequestTokensDraftDoesNotExposeOtherUsersDraftData() + /** + * @return array + */ + public static function taskIndexProcessRequestTokensDraftRedactionProvider(): array { - $this->initializePermissions(); - config([ - 'app.task_drafts_enabled' => true, - 'app.processmaker_optimized_tasks_enabled' => true, - ]); - - $viewer = User::factory()->create(); - $viewer->giveDirectPermission('view-all_requests'); - $this->user = $viewer; - $assignee = User::factory()->create(); - - $processRequest = ProcessRequest::factory()->create(); - $otherTask = ProcessRequestToken::factory()->create([ - 'process_request_id' => $processRequest->id, - 'status' => 'ACTIVE', - 'user_id' => $assignee->id, - ]); - TaskDraft::factory()->create([ - 'task_id' => $otherTask->id, - 'data' => ['secret' => 'nested-process-request-token'], - ]); - - $ownTask = ProcessRequestToken::factory()->create([ - 'process_request_id' => $processRequest->id, - 'status' => 'ACTIVE', - 'user_id' => $viewer->id, - ]); - TaskDraft::factory()->create([ - 'task_id' => $ownTask->id, - 'data' => ['mine' => 'own-nested-pr'], - ]); - - $response = $this->apiCall('GET', route('api.tasks.index', [ - 'include' => 'processRequest.tokens.draft', - ])); - $response->assertStatus(200); - - $row = collect($response->json('data'))->firstWhere('id', $ownTask->id); - $tokens = collect($row['process_request']['tokens'] ?? [])->keyBy('id'); - - $otherDraft = $tokens[$otherTask->id]['draft'] ?? null; - $this->assertNotNull($otherDraft); - $this->assertArrayNotHasKey('data', $otherDraft); - - $ownDraft = $tokens[$ownTask->id]['draft'] ?? null; - $this->assertEquals('own-nested-pr', $ownDraft['data']['mine'] ?? null); + return [ + 'standard' => ['processRequest.tokens.draft', 'nested-process-request-token', true, null], + 'case_insensitive' => ['processRequest.tokens.Draft', 'case-insensitive-nested', false, null], + 'wildcard_select' => ['processRequest.tokens.draft:*', 'laravel-include-wildcard', false, 'laravel-include-wildcard'], + 'trailing_colon' => ['processRequest.tokens.draft:', 'laravel-include-trailing-colon', false, null], + ]; } - public function testTaskIndexProcessRequestTokensDraftCaseInsensitiveDoesNotExposeOtherUsersDraftData() - { + #[DataProvider('taskIndexProcessRequestTokensDraftRedactionProvider')] + public function testTaskIndexProcessRequestTokensDraftDoesNotExposeOtherUsersDraftData( + string $include, + string $otherSecret, + bool $createOwnDraft, + ?string $jsonMustNotContain, + ): void { $this->initializePermissions(); config([ 'app.task_drafts_enabled' => true, @@ -519,7 +470,7 @@ public function testTaskIndexProcessRequestTokensDraftCaseInsensitiveDoesNotExpo ]); TaskDraft::factory()->create([ 'task_id' => $otherTask->id, - 'data' => ['secret' => 'case-insensitive-nested'], + 'data' => ['secret' => $otherSecret], ]); $ownTask = ProcessRequestToken::factory()->create([ @@ -527,106 +478,31 @@ public function testTaskIndexProcessRequestTokensDraftCaseInsensitiveDoesNotExpo 'status' => 'ACTIVE', 'user_id' => $viewer->id, ]); + if ($createOwnDraft) { + TaskDraft::factory()->create([ + 'task_id' => $ownTask->id, + 'data' => ['mine' => 'own-nested-pr'], + ]); + } - $response = $this->apiCall('GET', route('api.tasks.index', [ - 'include' => 'processRequest.tokens.Draft', - ])); + $response = $this->apiCall('GET', route('api.tasks.index', ['include' => $include])); $response->assertStatus(200); $row = collect($response->json('data'))->firstWhere('id', $ownTask->id); $tokens = collect($row['process_request']['tokens'] ?? [])->keyBy('id'); - $otherDraft = $tokens[$otherTask->id]['draft'] ?? null; - - $this->assertNotNull($otherDraft); - $this->assertArrayNotHasKey('data', $otherDraft); - } - - public function testTaskIndexProcessRequestTokensDraftWildcardSelectDoesNotExposeOtherUsersDraftData() - { - $this->initializePermissions(); - config([ - 'app.task_drafts_enabled' => true, - 'app.processmaker_optimized_tasks_enabled' => true, - ]); - $viewer = User::factory()->create(); - $viewer->giveDirectPermission('view-all_requests'); - $this->user = $viewer; - $assignee = User::factory()->create(); - - $processRequest = ProcessRequest::factory()->create(); - $otherTask = ProcessRequestToken::factory()->create([ - 'process_request_id' => $processRequest->id, - 'status' => 'ACTIVE', - 'user_id' => $assignee->id, - ]); - TaskDraft::factory()->create([ - 'task_id' => $otherTask->id, - 'data' => ['secret' => 'laravel-include-wildcard'], - ]); - - $ownTask = ProcessRequestToken::factory()->create([ - 'process_request_id' => $processRequest->id, - 'status' => 'ACTIVE', - 'user_id' => $viewer->id, - ]); - - $response = $this->apiCall('GET', route('api.tasks.index', [ - 'include' => 'processRequest.tokens.draft:*', - ])); - $response->assertStatus(200); - - $row = collect($response->json('data'))->firstWhere('id', $ownTask->id); - $tokens = collect($row['process_request']['tokens'] ?? [])->keyBy('id'); $otherDraft = $tokens[$otherTask->id]['draft'] ?? null; - $this->assertNotNull($otherDraft); $this->assertArrayNotHasKey('data', $otherDraft); - $json = json_encode($response->json()); - $this->assertStringNotContainsString('laravel-include-wildcard', $json); - } - - public function testTaskIndexProcessRequestTokensDraftTrailingColonDoesNotExposeOtherUsersDraftData() - { - $this->initializePermissions(); - config([ - 'app.task_drafts_enabled' => true, - 'app.processmaker_optimized_tasks_enabled' => true, - ]); - - $viewer = User::factory()->create(); - $viewer->giveDirectPermission('view-all_requests'); - $this->user = $viewer; - $assignee = User::factory()->create(); - - $processRequest = ProcessRequest::factory()->create(); - $otherTask = ProcessRequestToken::factory()->create([ - 'process_request_id' => $processRequest->id, - 'status' => 'ACTIVE', - 'user_id' => $assignee->id, - ]); - TaskDraft::factory()->create([ - 'task_id' => $otherTask->id, - 'data' => ['secret' => 'laravel-include-trailing-colon'], - ]); - $ownTask = ProcessRequestToken::factory()->create([ - 'process_request_id' => $processRequest->id, - 'status' => 'ACTIVE', - 'user_id' => $viewer->id, - ]); - - $response = $this->apiCall('GET', route('api.tasks.index', [ - 'include' => 'processRequest.tokens.draft:', - ])); - $response->assertStatus(200); - - $row = collect($response->json('data'))->firstWhere('id', $ownTask->id); - $tokens = collect($row['process_request']['tokens'] ?? [])->keyBy('id'); - $otherDraft = $tokens[$otherTask->id]['draft'] ?? null; + if ($createOwnDraft) { + $ownDraft = $tokens[$ownTask->id]['draft'] ?? null; + $this->assertEquals('own-nested-pr', $ownDraft['data']['mine'] ?? null); + } - $this->assertNotNull($otherDraft); - $this->assertArrayNotHasKey('data', $otherDraft); + if ($jsonMustNotContain !== null) { + $this->assertStringNotContainsString($jsonMustNotContain, json_encode($response->json())); + } } public function testTaskIndexProcessRequestsTokensDraftDoesNotExposeOtherUsersDraftData() @@ -753,40 +629,22 @@ public function testTaskIndexNestedDraftWithDraftsDisabledDoesNotDeleteOtherAssi $this->assertNull($nested); } - public function testTaskIndexWithDraftsDisabledDoesNotDeleteAnotherUsersDraft() + /** + * @return array + */ + public static function taskIndexDraftsDisabledRootIncludePreservesOtherDraftProvider(): array { - $this->initializePermissions(); - config([ - 'app.task_drafts_enabled' => false, - 'app.processmaker_optimized_tasks_enabled' => true, - ]); - - $viewer = User::factory()->create(); - $viewer->giveDirectPermission('view-all_requests'); - $this->user = $viewer; - $assignee = User::factory()->create(); - - $processRequest = ProcessRequest::factory()->create(); - $otherTask = ProcessRequestToken::factory()->create([ - 'process_request_id' => $processRequest->id, - 'status' => 'ACTIVE', - 'user_id' => $assignee->id, - ]); - $draft = TaskDraft::factory()->create([ - 'task_id' => $otherTask->id, - 'data' => ['secret' => 'must-survive'], - ]); - - $response = $this->apiCall('GET', route('api.tasks.index', ['include' => 'draft'])); - $response->assertStatus(200); - - $this->assertDatabaseHas('task_drafts', ['id' => $draft->id, 'task_id' => $otherTask->id]); - $otherRow = collect($response->json('data'))->keyBy('id')[$otherTask->id]; - $this->assertNull($otherRow['draft'] ?? null); + return [ + 'draft' => ['draft', 'must-survive'], + 'draft_media' => ['draft.media', 'must-survive-media'], + ]; } - public function testTaskIndexDraftMediaWithDraftsDisabledDoesNotDeleteAnotherUsersDraft() - { + #[DataProvider('taskIndexDraftsDisabledRootIncludePreservesOtherDraftProvider')] + public function testTaskIndexWithDraftsDisabledDoesNotDeleteAnotherUsersDraft( + string $include, + string $secret, + ): void { $this->initializePermissions(); config([ 'app.task_drafts_enabled' => false, @@ -806,10 +664,10 @@ public function testTaskIndexDraftMediaWithDraftsDisabledDoesNotDeleteAnotherUse ]); $draft = TaskDraft::factory()->create([ 'task_id' => $otherTask->id, - 'data' => ['secret' => 'must-survive-media'], + 'data' => ['secret' => $secret], ]); - $response = $this->apiCall('GET', route('api.tasks.index', ['include' => 'draft.media'])); + $response = $this->apiCall('GET', route('api.tasks.index', ['include' => $include])); $response->assertStatus(200); $this->assertDatabaseHas('task_drafts', ['id' => $draft->id, 'task_id' => $otherTask->id]); From 6a7f7f2ddc9a2506ae384931985293ed352faf3c Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Thu, 12 Nov 2026 23:21:39 -0400 Subject: [PATCH 28/29] fix(FOUR-34369): trust DB for nested draft policy and limit consume to assignee Reject serialized token policy fields, require authoritative attrs on root resource, and avoid deleting assignee drafts when managers list with include=draft while drafts are disabled. https://processmaker.atlassian.net/browse/FOUR-34369 --- ProcessMaker/Traits/TaskResourceIncludes.php | 41 ++++++++++++++------ tests/Feature/Api/TasksTest.php | 39 +++++++++++++++++++ 2 files changed, 69 insertions(+), 11 deletions(-) diff --git a/ProcessMaker/Traits/TaskResourceIncludes.php b/ProcessMaker/Traits/TaskResourceIncludes.php index 138183c452..e79ff38107 100644 --- a/ProcessMaker/Traits/TaskResourceIncludes.php +++ b/ProcessMaker/Traits/TaskResourceIncludes.php @@ -162,7 +162,9 @@ private function resolveDraftPayloadWhenDraftsDisabled( return null; } - if ($consumeDraftWhenDisabled) { + if ($consumeDraftWhenDisabled + && $user + && (int) $user->id === (int) $token->user_id) { $draft->delete(); } @@ -208,10 +210,6 @@ private function persistedTokenForDraftPolicy(ProcessRequestToken $candidate): ? return $this->resource; } - if ($this->tokenHasDraftPolicyAttributes($candidate)) { - return $candidate; - } - if (array_key_exists($tokenId, $this->draftPolicyTokenCache)) { return $this->draftPolicyTokenCache[$tokenId]; } @@ -394,11 +392,7 @@ private function tokenFromNestedTokenRow(array $row): ?ProcessRequestToken $candidate = new ProcessRequestToken(); $candidate->exists = true; - foreach (self::DRAFT_POLICY_TOKEN_COLUMNS as $column) { - if (array_key_exists($column, $row)) { - $candidate->setAttribute($column, $row[$column]); - } - } + $candidate->setAttribute('id', $row['id']); return $this->persistedTokenForDraftPolicy($candidate); } @@ -552,7 +546,7 @@ private function includeElementDestination() */ private function ensureTokenAttributesForViewPolicy(ProcessRequestToken $token): void { - if ($this->tokenHasDraftPolicyAttributes($token)) { + if ($this->tokenDraftPolicyAttributesAreAuthoritative($token)) { return; } @@ -589,6 +583,31 @@ private function mergeDraftPolicyAttributes(ProcessRequestToken $token, ProcessR } } + /** + * Serialized nested token rows must not satisfy policy checks without a DB row. + */ + private function tokenDraftPolicyAttributesAreAuthoritative(ProcessRequestToken $token): bool + { + if (!$this->tokenHasDraftPolicyAttributes($token)) { + return false; + } + + $tokenId = $token->getKey(); + if ($tokenId === null || $tokenId === '') { + return false; + } + + if ($this->resource instanceof ProcessRequestToken + && (int) $this->resource->getKey() === (int) $tokenId + && $this->tokenHasDraftPolicyAttributes($this->resource)) { + return true; + } + + $cached = $this->draftPolicyTokenCache[$tokenId] ?? null; + + return $cached instanceof ProcessRequestToken && $cached === $token; + } + /** @see ProcessRequestTokenPolicy::view — avoids lazy-loading process on list rows */ private function userCanViewTaskForDraft(User $user, ?ProcessRequestToken $token = null): bool { diff --git a/tests/Feature/Api/TasksTest.php b/tests/Feature/Api/TasksTest.php index 13e51fa8a1..fac331b53f 100644 --- a/tests/Feature/Api/TasksTest.php +++ b/tests/Feature/Api/TasksTest.php @@ -629,6 +629,45 @@ public function testTaskIndexNestedDraftWithDraftsDisabledDoesNotDeleteOtherAssi $this->assertNull($nested); } + public function testTaskIndexRootDraftWithDraftsDisabledDoesNotDeleteOtherAssigneeDraftForManager() + { + $this->initializePermissions(); + config([ + 'app.task_drafts_enabled' => false, + 'app.processmaker_optimized_tasks_enabled' => true, + ]); + + $manager = User::factory()->create(); + $manager->giveDirectPermission('view-all_requests'); + $assignee = User::factory()->create(); + $this->user = $manager; + + $process = Process::factory()->create([ + 'properties' => ['manager_id' => [$manager->id]], + ]); + $processRequest = ProcessRequest::factory()->create(['process_id' => $process->id]); + $assigneeTask = ProcessRequestToken::factory()->create([ + 'process_id' => $process->id, + 'process_request_id' => $processRequest->id, + 'status' => 'ACTIVE', + 'user_id' => $assignee->id, + ]); + $assigneeDraft = TaskDraft::factory()->create([ + 'task_id' => $assigneeTask->id, + 'data' => ['secret' => 'manager-root-must-not-consume'], + ]); + + $response = $this->apiCall('GET', route('api.tasks.index', ['include' => 'draft'])); + $response->assertStatus(200); + + $this->assertDatabaseHas('task_drafts', [ + 'id' => $assigneeDraft->id, + 'task_id' => $assigneeTask->id, + ]); + $row = collect($response->json('data'))->keyBy('id')[$assigneeTask->id]; + $this->assertNull($row['draft'] ?? null); + } + /** * @return array */ From f43c706abe399fb5b48f9a4643d1eddeffc92a1e Mon Sep 17 00:00:00 2001 From: Roly Gutierrez Date: Fri, 13 Nov 2026 08:34:43 -0400 Subject: [PATCH 29/29] fix(tasks): pass managed visibility flag in optimized index test(cache): enable metrics in ScreenCacheFactoryTest setUp refactor(FOUR-34369): reduce Sonar complexity in TaskResourceIncludes https://processmaker.atlassian.net/browse/FOUR-34369 --- .../Controllers/Api/V1_1/TaskController.php | 10 +++- ProcessMaker/Traits/TaskResourceIncludes.php | 60 ++++++++++++------- .../Cache/Screens/ScreenCacheFactoryTest.php | 1 + 3 files changed, 45 insertions(+), 26 deletions(-) diff --git a/ProcessMaker/Http/Controllers/Api/V1_1/TaskController.php b/ProcessMaker/Http/Controllers/Api/V1_1/TaskController.php index de2f399cda..bf1b2a8e8b 100644 --- a/ProcessMaker/Http/Controllers/Api/V1_1/TaskController.php +++ b/ProcessMaker/Http/Controllers/Api/V1_1/TaskController.php @@ -21,8 +21,8 @@ use ProcessMaker\Models\User; use ProcessMaker\ProcessTranslations\TranslationManager; use ProcessMaker\Repositories\TaskV11ShowFastRepository; -use ProcessMaker\Traits\TaskControllerIndexMethods; use ProcessMaker\Services\TaskCompletionRawService; +use ProcessMaker\Traits\TaskControllerIndexMethods; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; class TaskController extends Controller @@ -61,12 +61,16 @@ public function indexOptimized(Request $request, $getTotal = false, ?User $user $query = $this->indexOptimizedBaseQuery($request); $this->applyIndexFieldSelection($query, $request); $this->applyFilters($query, $request); - $this->excludeNonVisibleTasks($query, $request); + $resolveManagedProcessVisibility = $this->excludeNonVisibleTasks( + $query, + $request, + $request->input('processesIManage') === 'true' + ); $this->applyColumnOrdering($query, $request); $this->applyStatusFilter($query, $request); if ($request->input('processesIManage') === 'true') { - $this->applyProcessManager($query, $user, $request); + $this->applyProcessManager($query, $user, $request, $resolveManagedProcessVisibility); } else { $this->applyForCurrentUser($query, $user); } diff --git a/ProcessMaker/Traits/TaskResourceIncludes.php b/ProcessMaker/Traits/TaskResourceIncludes.php index e79ff38107..3bd80cd285 100644 --- a/ProcessMaker/Traits/TaskResourceIncludes.php +++ b/ProcessMaker/Traits/TaskResourceIncludes.php @@ -210,17 +210,13 @@ private function persistedTokenForDraftPolicy(ProcessRequestToken $candidate): ? return $this->resource; } - if (array_key_exists($tokenId, $this->draftPolicyTokenCache)) { - return $this->draftPolicyTokenCache[$tokenId]; + if (!array_key_exists($tokenId, $this->draftPolicyTokenCache)) { + $this->draftPolicyTokenCache[$tokenId] = ProcessRequestToken::query() + ->whereKey($tokenId) + ->first(self::DRAFT_POLICY_TOKEN_COLUMNS); } - $loaded = ProcessRequestToken::query() - ->whereKey($tokenId) - ->first(self::DRAFT_POLICY_TOKEN_COLUMNS); - - $this->draftPolicyTokenCache[$tokenId] = $loaded; - - return $loaded; + return $this->draftPolicyTokenCache[$tokenId]; } private function tokenHasDraftPolicyAttributes(ProcessRequestToken $token): bool @@ -403,20 +399,37 @@ private function tokenFromNestedTokenRow(array $row): ?ProcessRequestToken private function arrayContainsNestedTokenDrafts(array $array): bool { foreach ($array as $key => $value) { - if (!is_array($value) || in_array($key, self::DRAFT_REDACT_EXCLUDED_KEYS, true)) { + if (!$this->isNestedDraftTraversalCandidate($key, $value)) { continue; } - if ($key === 'tokens' && array_is_list($value)) { - foreach ($value as $item) { - if (is_array($item) && array_key_exists('draft', $item)) { - return true; - } - } - continue; + if ($this->nestedTokenDraftsPresentAtKey($key, $value)) { + return true; } + } + + return false; + } + + /** + * @param array $value + */ + private function nestedTokenDraftsPresentAtKey(string|int $key, array $value): bool + { + if ($key === 'tokens' && array_is_list($value)) { + return $this->serializedTokenListContainsDraft($value); + } + + return $this->arrayContainsNestedTokenDrafts($value); + } - if ($this->arrayContainsNestedTokenDrafts($value)) { + /** + * @param list $tokens + */ + private function serializedTokenListContainsDraft(array $tokens): bool + { + foreach ($tokens as $item) { + if (is_array($item) && array_key_exists('draft', $item)) { return true; } } @@ -424,6 +437,11 @@ private function arrayContainsNestedTokenDrafts(array $array): bool return false; } + private function isNestedDraftTraversalCandidate(mixed $key, mixed $value): bool + { + return is_array($value) && !in_array($key, self::DRAFT_REDACT_EXCLUDED_KEYS, true); + } + private function includeComponent() { $component = $this->getScreenVersion() ? $this->getScreenVersion()->parent->renderComponent() : null; @@ -588,12 +606,8 @@ private function mergeDraftPolicyAttributes(ProcessRequestToken $token, ProcessR */ private function tokenDraftPolicyAttributesAreAuthoritative(ProcessRequestToken $token): bool { - if (!$this->tokenHasDraftPolicyAttributes($token)) { - return false; - } - $tokenId = $token->getKey(); - if ($tokenId === null || $tokenId === '') { + if (!$this->tokenHasDraftPolicyAttributes($token) || $tokenId === null || $tokenId === '') { return false; } diff --git a/tests/unit/ProcessMaker/Cache/Screens/ScreenCacheFactoryTest.php b/tests/unit/ProcessMaker/Cache/Screens/ScreenCacheFactoryTest.php index 6c48424212..56b8d9b1d3 100644 --- a/tests/unit/ProcessMaker/Cache/Screens/ScreenCacheFactoryTest.php +++ b/tests/unit/ProcessMaker/Cache/Screens/ScreenCacheFactoryTest.php @@ -21,6 +21,7 @@ protected function setUp(): void { parent::setUp(); ScreenCacheFactory::setTestInstance(null); + Config::set('metrics.enabled', true); // Bind necessary dependencies $this->app->singleton(ScreenCompiledManager::class);