diff --git a/ProcessMaker/Http/Controllers/Api/ProcessController.php b/ProcessMaker/Http/Controllers/Api/ProcessController.php index 95d18c853f..8e4f55b1ef 100644 --- a/ProcessMaker/Http/Controllers/Api/ProcessController.php +++ b/ProcessMaker/Http/Controllers/Api/ProcessController.php @@ -34,11 +34,11 @@ use ProcessMaker\Models\Process; use ProcessMaker\Models\ProcessLaunchpad; use ProcessMaker\Models\ProcessPermission; -use ProcessMaker\Models\User; use ProcessMaker\Models\ProcessVersion; use ProcessMaker\Models\Screen; use ProcessMaker\Models\Script; use ProcessMaker\Models\Template; +use ProcessMaker\Models\User; use ProcessMaker\Nayra\Exceptions\ElementNotFoundException; use ProcessMaker\Nayra\Services\FixBpmnSchemaService; use ProcessMaker\Nayra\Storage\BpmnDocument; @@ -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; } 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/Http/Resources/Task.php b/ProcessMaker/Http/Resources/Task.php index 7bf2eae8ff..d0f734ffa8 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::includesRootDraft($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 b186f4fc58..1bb6a08a8d 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' && !TaskDraftIncludes::includesRootDraft($parsed)) { 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' && !TaskDraftIncludes::includesRootDraft($parsed)) { continue; } @@ -209,10 +213,14 @@ public static function preprocessInclude(Request $request, Builder $query): self */ public static function fromTokenWithIncludes(ProcessRequestToken $token, Request $request): self { - $include = self::resolveRequestIncludes($request); + $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' && !TaskDraftIncludes::includesRootDraft($parsed)) { continue; } @@ -226,14 +234,10 @@ public static function fromTokenWithIncludes(ProcessRequestToken $token, Request return new static($token); } - private static function resolveRequestIncludes(Request $request): array + /** @return list */ + private static function parseV11RequestIncludes(Request $request): array { - $include = $request->query('include', []); - if ($include) { - $include = explode(',', $include); - } - - return array_merge($include, self::$defaultIncludes); + return TaskDraftIncludes::parseIncludeList((string) $request->input('include', '')); } private static function includeRelationshipAlreadyLoaded(ProcessRequestToken $token, string $key): bool @@ -251,13 +255,13 @@ private static function includeRelationshipAlreadyLoaded(ProcessRequestToken $to 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::includesRootDraft($include)) { + continue; + } + if (!in_array($key, $include, true)) { continue; } @@ -270,6 +274,6 @@ private function processInclude(Request $request, array $array) } } - return $array; + return $this->sanitizeDraftInTaskArray($array, $request); } } 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); + } } 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/ProcessMaker/Support/TaskDraftIncludes.php b/ProcessMaker/Support/TaskDraftIncludes.php new file mode 100644 index 0000000000..01c7aed992 --- /dev/null +++ b/ProcessMaker/Support/TaskDraftIncludes.php @@ -0,0 +1,150 @@ + */ + public const EAGER_COLUMNS = ['id', 'task_id']; + + private const NESTED_DRAFT_RELATIONS = [ + 'processRequest.tokens', + 'process.requests.tokens', + ]; + + /** @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 + { + return self::includesRootDraft($includes) || self::includesNestedDraft($includes); + } + + public static function includesRootDraft(array $includes): bool + { + foreach ($includes as $token) { + $path = strtolower(self::relationPathFromIncludeToken($token)); + if ($path === 'draft' || str_starts_with($path, 'draft.')) { + return true; + } + } + + return false; + } + + public static function includesNestedDraft(array $includes): bool + { + foreach ($includes as $token) { + if (!self::isDraftToken($token)) { + continue; + } + $path = strtolower(self::relationPathFromIncludeToken($token)); + if ($path === 'draft' || str_starts_with($path, 'draft.')) { + continue; + } + + return true; + } + + 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 + { + $path = strtolower(self::relationPathFromIncludeToken($token)); + + return $path === 'draft' + || str_starts_with($path, 'draft.') + || str_ends_with($path, '.draft') + || str_contains($path, '.draft.'); + } + + 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) { + $path = strtolower(self::relationPathFromIncludeToken($token)); + if (!str_starts_with($path, 'draft.') || $path === 'draft') { + continue; + } + $suffix = substr($path, 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 + */ + public static function nestedDraftEagerLoadMap(array $includes): array + { + $with = []; + $constrained = fn ($q) => $q->with(['draft' => self::constrainedEagerLoad()]); + + foreach ($includes as $token) { + $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 ($path === "{$relationLower}.draft" || str_starts_with($path, "{$relationLower}.")) { + $with[$relation] = $constrained; + break; + } + } + } + + return $with; + } +} diff --git a/ProcessMaker/Traits/TaskControllerIndexMethods.php b/ProcessMaker/Traits/TaskControllerIndexMethods.php index fa1a8b593e..893ff86e28 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,76 +60,133 @@ 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')) : []; + if (TaskDraftIncludes::includesRootDraft($includes)) { + $query->with(['draft' => TaskDraftIncludes::rootDraftEagerLoad($includes)]); + } - foreach (['data'] as $key) { - if (in_array($key, $include)) { - unset($include[array_search($key, $include)]); - } + $nestedDraftWith = TaskDraftIncludes::nestedDraftEagerLoadMap($includes); + if ($nestedDraftWith !== []) { + $query->with($nestedDraftWith); } - $query->with($include); + $additionalIncludes = array_values(array_filter( + $includes, + fn (string $token) => $token !== 'data' && !TaskDraftIncludes::isDraftToken($token) + )); + + if ($additionalIncludes !== []) { + $query->with($additionalIncludes); + } return $query; } 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 = []; + $with = $this->buildOptimizedIndexWith($includes, $includeData); - 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']); - } - }; + $handledIncludes = ['data', 'processRequest', 'process', 'user', 'draft', 'processRequest.process']; + $additionalIncludes = array_values(array_filter( + $includes, + fn (string $token) => !in_array($token, $handledIncludes, true) + && !TaskDraftIncludes::isDraftToken($token) + )); + + if (!empty($with)) { + $query->with($with); } - if (in_array('process', $includes, true)) { - $with['process'] = fn ($q) => $q->select(['id', 'name', 'uuid']); + if (!empty($additionalIncludes)) { + $query->with($additionalIncludes); + } + + return $query; + } + + private function parseIndexIncludeList($request): array + { + if (!$request->has('include')) { + return []; + } + + return TaskDraftIncludes::parseIncludeList((string) $request->input('include')); + } + + /** + * @return array + */ + private function buildOptimizedIndexWith(array $includes, bool $includeData): array + { + $with = []; + + $needsProcessRequest = in_array('processRequest', $includes, true) + || in_array('processRequest.process', $includes, true); + if ($needsProcessRequest) { + $with['processRequest'] = $this->optimizedProcessRequestEagerLoad($includeData); } if (in_array('user', $includes, true)) { $with['user'] = fn ($q) => $q->select(['id', 'firstname', 'lastname', 'avatar', 'status']); } - if (in_array('draft', $includes, true)) { - $with['draft'] = fn ($q) => $q->select(['id', 'uuid', 'process_request_token_id']); + if (TaskDraftIncludes::includesRootDraft($includes)) { + $with['draft'] = TaskDraftIncludes::rootDraftEagerLoad($includes); } - $handledIncludes = ['data', 'processRequest', 'process', 'user', 'draft', 'processRequest.process']; - $additionalIncludes = array_values(array_diff($includes, $handledIncludes)); + if (in_array('process', $includes, true)) { + $with['process'] = fn ($q) => $q->select(['id', 'name', 'uuid']); + } - if (!empty($with)) { - $query->with($with); + if (in_array('processRequest.process', $includes, true)) { + $with['processRequest.process'] = fn ($q) => $q->select(['id', 'name', 'uuid']); } - if (!empty($additionalIncludes)) { - $query->with($additionalIncludes); + $nestedDraftWith = TaskDraftIncludes::nestedDraftEagerLoadMap($includes); + if (array_key_exists('processRequest.tokens', $nestedDraftWith) && !isset($with['processRequest'])) { + $with['processRequest'] = $this->optimizedProcessRequestEagerLoad($includeData); + } + if (array_key_exists('process.requests.tokens', $nestedDraftWith) && !isset($with['process'])) { + $with['process'] = fn ($q) => $q->select(['id', 'name', 'uuid']); } + $with = array_merge($with, $nestedDraftWith); - return $query; + return $with; + } + + /** + * @return list + */ + private function optimizedProcessRequestSelectColumns(): array + { + return [ + 'id', + 'uuid', + 'case_number', + 'case_title', + 'name', + 'status', + 'user_id', + 'process_id', + 'parent_id', + ]; + } + + private function optimizedProcessRequestEagerLoad(bool $includeData): \Closure + { + $processRequestColumns = $this->optimizedProcessRequestSelectColumns(); + + return function ($q) use ($includeData, $processRequestColumns) { + $q->select($processRequestColumns); + if (!$includeData) { + $q->exclude(['data']); + } + }; } private function resolveIndexFields($request): ?array diff --git a/ProcessMaker/Traits/TaskResourceIncludes.php b/ProcessMaker/Traits/TaskResourceIncludes.php index 92b4bcd3d8..3bd80cd285 100644 --- a/ProcessMaker/Traits/TaskResourceIncludes.php +++ b/ProcessMaker/Traits/TaskResourceIncludes.php @@ -6,17 +6,49 @@ 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; use ProcessMaker\ProcessTranslations\ScreenTranslation; +use ProcessMaker\Support\TaskDraftIncludes; use StdClass; 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', + 'data', + 'screen', + 'config', + 'nested', + 'definition', + 'interstitial_screen', + 'user_request_permission', + 'elementDestination', + 'loop_context', + ]; + private function getData() { if ($this->loadedData) { @@ -56,21 +88,358 @@ 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. + $include = TaskDraftIncludes::parseIncludeList((string) $request->input('include', '')); + + if (!TaskDraftIncludes::includesDraft($include)) { + unset($array['draft']); + if ($this->arrayContainsNestedTokenDrafts($array)) { + $this->prefetchDraftPolicyTokensForNestedArray($array); + $this->redactNestedDraftsInArray($array); + } + + return $array; + } + + if (TaskDraftIncludes::includesRootDraft($include)) { + $draftPayload = $this->resource->relationLoaded('draft') + ? $this->draft + : ($array['draft'] ?? null); + + $array['draft'] = $this->resolveDraftPayloadForToken($this->resource, $draftPayload, true); + } else { + unset($array['draft']); + } + + if (TaskDraftIncludes::includesNestedDraft($include)) { + $this->prefetchDraftPolicyTokensForNestedArray($array); + $this->redactNestedDraftsInArray($array); + } + + return $array; + } + + /** + * @return array|TaskDraft|null + */ + private function resolveDraftPayloadForToken( + ProcessRequestToken $token, + mixed $draft, + bool $consumeDraftWhenDisabled = false, + ): array|TaskDraft|null { + $token = $this->persistedTokenForDraftPolicy($token); + $draft = $token !== null ? $this->taskDraftForToken($token, $draft) : null; + if ($token === null || $draft === null) { + return null; + } + + if (!TaskDraft::draftsEnabled()) { + return $this->resolveDraftPayloadWhenDraftsDisabled( + Auth::user(), + $token, + $draft, + $consumeDraftWhenDisabled + ); + } + + return $this->resolveDraftPayloadWhenDraftsEnabled(Auth::user(), $token, $draft); + } + + /** + * @return array|null + */ + private function resolveDraftPayloadWhenDraftsDisabled( + ?User $user, + ProcessRequestToken $token, + TaskDraft $draft, + bool $consumeDraftWhenDisabled, + ): ?array { + if (!$user || !$this->callerCanViewTaskForDraft($user, $token)) { + return null; + } + + if ($consumeDraftWhenDisabled + && $user + && (int) $user->id === (int) $token->user_id) { $draft->delete(); + } + + 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']); + } + + if (!array_key_exists('data', $draft->getAttributes())) { + $draft = TaskDraft::query() + ->whereKey($draft->getKey()) + ->where('task_id', $token->id) + ->first(['id', 'task_id', 'data']); + } + + return $draft; + } - // Return null to prevent the frontend from trying to load - // files from the deleted draft - return ['draft' => null]; + private function callerCanViewTaskForDraft(User $user, ProcessRequestToken $token): bool + { + $this->ensureTokenAttributesForViewPolicy($token); + + return $this->userCanViewTaskForDraft($user, $token); + } + + private function persistedTokenForDraftPolicy(ProcessRequestToken $candidate): ?ProcessRequestToken + { + $tokenId = $candidate->getKey(); + if ($tokenId === null || $tokenId === '') { + return null; + } + + if ($this->resource instanceof ProcessRequestToken + && (int) $this->resource->getKey() === (int) $tokenId + && $this->tokenHasDraftPolicyAttributes($this->resource)) { + return $this->resource; } - return ['draft' => $draft]; + if (!array_key_exists($tokenId, $this->draftPolicyTokenCache)) { + $this->draftPolicyTokenCache[$tokenId] = ProcessRequestToken::query() + ->whereKey($tokenId) + ->first(self::DRAFT_POLICY_TOKEN_COLUMNS); + } + + return $this->draftPolicyTokenCache[$tokenId]; + } + + 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; + } + + /** + * Resolve draft only when task_id matches the persisted token id (never trust nested JSON). + */ + 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 $boundQuery(); + } + + $draftId = $this->draftIdFromPayload($draft); + if ($draftId !== null) { + return TaskDraft::query() + ->whereKey($draftId) + ->where('task_id', $token->id) + ->first(['id', 'task_id', 'data']); + } + + return $draft instanceof TaskDraft ? $boundQuery() : null; + } + + private function draftIdFromPayload(mixed $draft): int|string|null + { + if ($draft instanceof TaskDraft) { + return $draft->getKey(); + } + + if (is_array($draft)) { + return $draft['id'] ?? null; + } + + return null; + } + + /** + * @param array $array + */ + private function redactNestedDraftsInArray(array &$array): 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)) { + $this->redactDraftOnSerializedToken($item); + } + } + continue; + } + + $this->redactNestedDraftsInArray($value); + } + } + + /** + * @param array $row + */ + private function redactDraftOnSerializedToken(array &$row): void + { + if (!isset($row['draft'], $row['id'])) { + return; + } + + $token = $this->tokenFromNestedTokenRow($row); + if (!$token) { + unset($row['draft']); + + return; + } + + $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; + $candidate->setAttribute('id', $row['id']); + + return $this->persistedTokenForDraftPolicy($candidate); + } + + /** + * @param array $array + */ + private function arrayContainsNestedTokenDrafts(array $array): bool + { + foreach ($array as $key => $value) { + if (!$this->isNestedDraftTraversalCandidate($key, $value)) { + 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); + } + + /** + * @param list $tokens + */ + private function serializedTokenListContainsDraft(array $tokens): bool + { + foreach ($tokens as $item) { + if (is_array($item) && array_key_exists('draft', $item)) { + return true; + } + } + + 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() @@ -189,6 +558,134 @@ private function includeElementDestination() return ['elementDestination' => $elementDestination]; } + /** + * Partial token projections (optimized index, fast show) may omit columns + * required for draft visibility checks (assignee, self-service). + */ + private function ensureTokenAttributesForViewPolicy(ProcessRequestToken $token): void + { + if ($this->tokenDraftPolicyAttributesAreAuthoritative($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) { + $this->mergeDraftPolicyAttributes($token, $row); + if ($tokenId !== null) { + $this->draftPolicyTokenCache[$tokenId] = $row; + } + } + } + + 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)); + } + } + } + + /** + * Serialized nested token rows must not satisfy policy checks without a DB row. + */ + private function tokenDraftPolicyAttributesAreAuthoritative(ProcessRequestToken $token): bool + { + $tokenId = $token->getKey(); + if (!$this->tokenHasDraftPolicyAttributes($token) || $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 + { + if ($user->is_administrator) { + return true; + } + + $token ??= $this->resource; + + return (int) $token->user_id === (int) $user->id + || in_array($user->id, $this->managerIdsForTaskProcess($token)) + || $user->canSelfServe($token); + } + + /** + * @return list + */ + private function managerIdsForTaskProcess(ProcessRequestToken $token): array + { + $process = $token->relationLoaded('process') ? $token->process : null; + $processId = $process?->getKey() ?? $token->process_id; + if (!$processId) { + 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 { + $properties = $this->decodeJsonColumn( + Process::query()->whereKey($processId)->value('properties') + ); + } + + $standIn = new Process(); + $standIn->setAttribute('properties', $properties); + + $managerIds = $standIn->manager_id ?? []; + $this->processManagerIdsCache[$processId] = $managerIds; + + return $managerIds; + } + + /** + * @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) { $permissions[] = [ diff --git a/tests/Feature/Api/TasksTest.php b/tests/Feature/Api/TasksTest.php index f4c428a2ff..fac331b53f 100644 --- a/tests/Feature/Api/TasksTest.php +++ b/tests/Feature/Api/TasksTest.php @@ -2,7 +2,6 @@ namespace Tests\Feature\Api; -use PHPUnit\Framework\Attributes\Group as TestGroup; use Carbon\Carbon; use Database\Seeders\PermissionSeeder; use Facades\ProcessMaker\RollbackProcessRequest; @@ -10,6 +9,8 @@ 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; use ProcessMaker\Models\Group; @@ -23,6 +24,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; @@ -35,7 +37,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 @@ -193,6 +194,621 @@ 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); + } + + 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); + } + + 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); + } + + /** + * @return array + */ + public static function taskIndexRootDraftMediaRedactionProvider(): array + { + return [ + 'legacy' => [false, 'legacy-draft-media'], + 'optimized' => [true, 'optimized-draft-media'], + ]; + } + + #[DataProvider('taskIndexRootDraftMediaRedactionProvider')] + public function testTaskIndexDraftMediaDoesNotExposeOtherUsersDraftData( + bool $optimizedIndex, + string $secret, + ): void { + $this->initializePermissions(); + config([ + 'app.task_drafts_enabled' => true, + 'app.processmaker_optimized_tasks_enabled' => $optimizedIndex, + ]); + + $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' => $secret], + ]); + + $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 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, + ]); + 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'], + ]); + + $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); + $nestedDraft = collect($row['process_request']['tokens'] ?? []) + ->firstWhere('id', $parentTask->id)['draft'] ?? null; + $this->assertNull($nestedDraft); + } + + 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); + } + + /** + * @return array + */ + public static function taskIndexProcessRequestTokensDraftRedactionProvider(): array + { + 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], + ]; + } + + #[DataProvider('taskIndexProcessRequestTokensDraftRedactionProvider')] + public function testTaskIndexProcessRequestTokensDraftDoesNotExposeOtherUsersDraftData( + string $include, + string $otherSecret, + bool $createOwnDraft, + ?string $jsonMustNotContain, + ): void { + $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' => $otherSecret], + ]); + + $ownTask = ProcessRequestToken::factory()->create([ + 'process_request_id' => $processRequest->id, + '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' => $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); + + if ($createOwnDraft) { + $ownDraft = $tokens[$ownTask->id]['draft'] ?? null; + $this->assertEquals('own-nested-pr', $ownDraft['data']['mine'] ?? null); + } + + if ($jsonMustNotContain !== null) { + $this->assertStringNotContainsString($jsonMustNotContain, json_encode($response->json())); + } + } + + public function testTaskIndexProcessRequestsTokensDraftDoesNotExposeOtherUsersDraftData() + { + $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(); + + $process = Process::factory()->create(); + $viewerRequest = ProcessRequest::factory()->create(['process_id' => $process->id]); + $otherRequest = ProcessRequest::factory()->create(['process_id' => $process->id]); + + $otherTask = ProcessRequestToken::factory()->create([ + 'process_request_id' => $otherRequest->id, + 'process_id' => $process->id, + 'status' => 'ACTIVE', + 'user_id' => $assignee->id, + ]); + TaskDraft::factory()->create([ + 'task_id' => $otherTask->id, + 'data' => ['secret' => 'nested-process-requests'], + ]); + + $ownTask = ProcessRequestToken::factory()->create([ + 'process_request_id' => $viewerRequest->id, + 'process_id' => $process->id, + 'status' => 'ACTIVE', + 'user_id' => $viewer->id, + ]); + + $response = $this->apiCall('GET', route('api.tasks.index', [ + 'include' => 'process.requests.tokens.draft', + ])); + $response->assertStatus(200); + + $row = collect($response->json('data'))->firstWhere('id', $ownTask->id); + $otherDraft = collect($row['process']['requests'] ?? []) + ->flatMap(fn ($request) => $request['tokens'] ?? []) + ->firstWhere('id', $otherTask->id)['draft'] ?? null; + + $this->assertNotNull($otherDraft); + $this->assertArrayNotHasKey('data', $otherDraft); + } + + 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 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 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 + */ + public static function taskIndexDraftsDisabledRootIncludePreservesOtherDraftProvider(): array + { + return [ + 'draft' => ['draft', 'must-survive'], + 'draft_media' => ['draft.media', 'must-survive-media'], + ]; + } + + #[DataProvider('taskIndexDraftsDisabledRootIncludePreservesOtherDraftProvider')] + public function testTaskIndexWithDraftsDisabledDoesNotDeleteAnotherUsersDraft( + string $include, + string $secret, + ): void { + $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' => $secret], + ]); + + $response = $this->apiCall('GET', route('api.tasks.index', ['include' => $include])); + $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); + } + + 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(); + 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. */ 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']); + } } 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);