From 60f1dad8a43c6214549f081056258c026b5de2a7 Mon Sep 17 00:00:00 2001 From: sanja <52755494+sanjacornelius@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:30:54 -0800 Subject: [PATCH 01/20] Add AbeRecipientSignature for personalized ABE link params --- .../Helpers/AbeRecipientSignature.php | 131 ++++++++++++++++++ .../Helpers/AbeRecipientSignatureTest.php | 52 +++++++ 2 files changed, 183 insertions(+) create mode 100644 ProcessMaker/Helpers/AbeRecipientSignature.php create mode 100644 tests/unit/Helpers/AbeRecipientSignatureTest.php diff --git a/ProcessMaker/Helpers/AbeRecipientSignature.php b/ProcessMaker/Helpers/AbeRecipientSignature.php new file mode 100644 index 0000000000..a92b054306 --- /dev/null +++ b/ProcessMaker/Helpers/AbeRecipientSignature.php @@ -0,0 +1,131 @@ + $groups + */ + public static function queryString(string $tokenAbe, string $email, int|string|null $userId, array $groups = []): string + { + $normalizedGroups = self::normalizeGroups($groups); + $params = [ + self::EMAIL => strtolower(trim($email)), + self::USER_ID => (string) (int) $userId, + self::GROUPS => self::encodeGroups($normalizedGroups), + ]; + $params[self::SIG] = self::sign($tokenAbe, $params[self::EMAIL], $params[self::USER_ID], $normalizedGroups); + + return http_build_query($params); + } + + /** + * Verify signed params from the request. Returns null if missing/invalid. + * + * @return array{email:string,user_id:int,groups:array}|null + */ + public static function verify(Request $request, string $tokenAbe): ?array + { + $email = strtolower(trim((string) $request->query(self::EMAIL, ''))); + $userId = (string) $request->query(self::USER_ID, ''); + $groupsEncoded = (string) $request->query(self::GROUPS, ''); + $sig = (string) $request->query(self::SIG, ''); + + if ($email === '' || $sig === '') { + return null; + } + + $groups = self::decodeGroups($groupsEncoded); + $expected = self::sign($tokenAbe, $email, $userId, $groups); + + if (!hash_equals($expected, $sig)) { + return null; + } + + return [ + 'email' => $email, + 'user_id' => (int) $userId, + 'groups' => $groups, + ]; + } + + /** + * @param array $groups + */ + private static function sign(string $tokenAbe, string $email, string $userId, array $groups): string + { + $canonical = implode('|', [ + $tokenAbe, + strtolower(trim($email)), + (string) (int) $userId, + self::encodeGroups($groups), + ]); + + return hash_hmac('sha256', $canonical, (string) config('app.key')); + } + + /** + * @param array $groups + * @return array + */ + private static function normalizeGroups(array $groups): array + { + $normalized = []; + foreach ($groups as $group) { + if (!is_array($group) || !isset($group['id'])) { + continue; + } + $normalized[] = [ + 'id' => (int) $group['id'], + 'name' => (string) ($group['name'] ?? ''), + ]; + } + + usort($normalized, static fn ($a, $b) => $a['id'] <=> $b['id']); + + return $normalized; + } + + /** + * @param array $groups + */ + private static function encodeGroups(array $groups): string + { + return base64_encode(json_encode(array_values($groups))); + } + + /** + * @return array + */ + private static function decodeGroups(string $encoded): array + { + if ($encoded === '') { + return []; + } + + $decoded = json_decode(base64_decode($encoded, true) ?: '', true); + if (!is_array($decoded)) { + return []; + } + + return self::normalizeGroups($decoded); + } +} diff --git a/tests/unit/Helpers/AbeRecipientSignatureTest.php b/tests/unit/Helpers/AbeRecipientSignatureTest.php new file mode 100644 index 0000000000..b28552d35a --- /dev/null +++ b/tests/unit/Helpers/AbeRecipientSignatureTest.php @@ -0,0 +1,52 @@ + 2, 'name' => 'B'], + ['id' => 1, 'name' => 'A'], + ]; + + $query = AbeRecipientSignature::queryString($tokenAbe, 'User@Example.com', 42, $groups); + parse_str($query, $params); + + $request = Request::create('/tasks/update_variable/' . $tokenAbe, 'GET', $params); + $verified = AbeRecipientSignature::verify($request, $tokenAbe); + + $this->assertNotNull($verified); + $this->assertSame('user@example.com', $verified['email']); + $this->assertSame(42, $verified['user_id']); + $this->assertSame( + [['id' => 1, 'name' => 'A'], ['id' => 2, 'name' => 'B']], + $verified['groups'] + ); + } + + public function testTamperedEmailFailsVerification(): void + { + $tokenAbe = 'token-uuid-123'; + $query = AbeRecipientSignature::queryString($tokenAbe, 'user@example.com', 1, []); + parse_str($query, $params); + $params[AbeRecipientSignature::EMAIL] = 'other@example.com'; + + $request = Request::create('/tasks/update_variable/' . $tokenAbe, 'GET', $params); + $this->assertNull(AbeRecipientSignature::verify($request, $tokenAbe)); + } + + public function testMissingSignatureReturnsNull(): void + { + $request = Request::create('/tasks/update_variable/token-uuid', 'GET', [ + AbeRecipientSignature::EMAIL => 'user@example.com', + ]); + $this->assertNull(AbeRecipientSignature::verify($request, 'token-uuid')); + } +} From e25015abeb1cffd76c3a80b73c9fadd3cbfe6a23 Mon Sep 17 00:00:00 2001 From: sanja <52755494+sanjacornelius@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:31:17 -0800 Subject: [PATCH 02/20] Add AbeResponder to build nested abe_responder request data --- ProcessMaker/Helpers/AbeResponder.php | 111 +++++++++++++++++++++++ tests/unit/Helpers/AbeResponderTest.php | 112 ++++++++++++++++++++++++ 2 files changed, 223 insertions(+) create mode 100644 ProcessMaker/Helpers/AbeResponder.php create mode 100644 tests/unit/Helpers/AbeResponderTest.php diff --git a/ProcessMaker/Helpers/AbeResponder.php b/ProcessMaker/Helpers/AbeResponder.php new file mode 100644 index 0000000000..98532fc531 --- /dev/null +++ b/ProcessMaker/Helpers/AbeResponder.php @@ -0,0 +1,111 @@ + + */ + public static function fromRequest(Request $request, string $tokenAbe): array + { + $signed = AbeRecipientSignature::verify($request, $tokenAbe); + $actedAt = Carbon::now()->toIso8601String(); + $userAgent = (string) $request->userAgent(); + + $responder = [ + 'acted_at' => $actedAt, + 'ip_address' => $request->ip(), + 'user_agent' => $userAgent, + 'device' => self::detectDevice($userAgent), + 'email_client' => self::detectEmailClient($userAgent), + ]; + + if ($signed) { + $responder['email'] = $signed['email']; + $responder['user_id'] = $signed['user_id'] ?: null; + $responder['groups'] = $signed['groups']; + } + + $authUser = self::authenticatedUser(); + if ($authUser) { + $responder['authenticated_email'] = $authUser->email; + $responder['authenticated_user_id'] = $authUser->id; + + $signedEmail = strtolower(trim((string) ($responder['email'] ?? ''))); + $authEmail = strtolower(trim((string) $authUser->email)); + $responder['identity_mismatch'] = $signedEmail !== '' && $signedEmail !== $authEmail; + } + + return $responder; + } + + private static function authenticatedUser(): ?User + { + if (!Auth::check()) { + return null; + } + + $user = Auth::user(); + if (!$user instanceof User) { + return null; + } + + // Anonymous session used for public ABE clicks is not a real identity + if (($user->username ?? null) === AnonymousUser::ANONYMOUS_USERNAME) { + return null; + } + + return $user; + } + + private static function detectDevice(string $userAgent): string + { + $ua = strtolower($userAgent); + if ($ua === '') { + return 'unknown'; + } + if (preg_match('/mobile|android|iphone|ipad|ipod|blackberry|windows phone/i', $ua)) { + return 'mobile'; + } + + return 'desktop'; + } + + private static function detectEmailClient(string $userAgent): string + { + $ua = strtolower($userAgent); + if ($ua === '') { + return 'Unknown'; + } + if (str_contains($ua, 'googleimageproxy') || str_contains($ua, 'gmail')) { + return 'Gmail'; + } + if (str_contains($ua, 'outlook') || str_contains($ua, 'microsoft office') || str_contains($ua, 'ms-office')) { + return 'Outlook'; + } + if (str_contains($ua, 'thunderbird')) { + return 'Thunderbird'; + } + if (str_contains($ua, 'yahoo')) { + return 'Yahoo Mail'; + } + if (str_contains($ua, 'applewebkit') && (str_contains($ua, 'macintosh') || str_contains($ua, 'iphone') || str_contains($ua, 'ipad'))) { + // Apple Mail / iOS Mail often look like Safari; coarse best-effort + if (!str_contains($ua, 'crios') && !str_contains($ua, 'fxios') && !str_contains($ua, 'edgios')) { + return 'Apple Mail'; + } + } + + return 'Unknown'; + } +} diff --git a/tests/unit/Helpers/AbeResponderTest.php b/tests/unit/Helpers/AbeResponderTest.php new file mode 100644 index 0000000000..bad0e65e3b --- /dev/null +++ b/tests/unit/Helpers/AbeResponderTest.php @@ -0,0 +1,112 @@ + 3, 'name' => 'Reviewers']] + ); + parse_str($signedQuery, $params); + + $request = Request::create( + '/tasks/update_variable/' . $tokenAbe, + 'GET', + $params, + [], + [], + [ + 'REMOTE_ADDR' => '203.0.113.10', + 'HTTP_USER_AGENT' => 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15', + ] + ); + + Auth::logout(); + $responder = AbeResponder::fromRequest($request, $tokenAbe); + + $this->assertSame('signed@example.com', $responder['email']); + $this->assertSame(7, $responder['user_id']); + $this->assertSame([['id' => 3, 'name' => 'Reviewers']], $responder['groups']); + $this->assertSame('203.0.113.10', $responder['ip_address']); + $this->assertSame('mobile', $responder['device']); + $this->assertArrayHasKey('acted_at', $responder); + $this->assertArrayHasKey('user_agent', $responder); + $this->assertArrayHasKey('email_client', $responder); + $this->assertArrayNotHasKey('authenticated_email', $responder); + $this->assertArrayNotHasKey('identity_mismatch', $responder); + } + + public function testIdentityMismatchWhenAuthenticatedUserDiffersFromSignedRecipient(): void + { + $authUser = User::factory()->create([ + 'email' => 'logged-in@example.com', + 'status' => 'ACTIVE', + ]); + $this->actingAs($authUser); + + $tokenAbe = 'abe-token'; + $signedQuery = AbeRecipientSignature::queryString($tokenAbe, 'signed@example.com', 9, []); + parse_str($signedQuery, $params); + $request = Request::create('/tasks/update_variable/' . $tokenAbe, 'GET', $params); + + $responder = AbeResponder::fromRequest($request, $tokenAbe); + + $this->assertSame('signed@example.com', $responder['email']); + $this->assertSame('logged-in@example.com', $responder['authenticated_email']); + $this->assertSame($authUser->id, $responder['authenticated_user_id']); + $this->assertTrue($responder['identity_mismatch']); + } + + public function testMatchingAuthenticatedUserSetsIdentityMismatchFalse(): void + { + $authUser = User::factory()->create([ + 'email' => 'same@example.com', + 'status' => 'ACTIVE', + ]); + $this->actingAs($authUser); + + $tokenAbe = 'abe-token'; + $signedQuery = AbeRecipientSignature::queryString($tokenAbe, 'same@example.com', $authUser->id, []); + parse_str($signedQuery, $params); + $request = Request::create('/tasks/update_variable/' . $tokenAbe, 'GET', $params); + + $responder = AbeResponder::fromRequest($request, $tokenAbe); + + $this->assertSame('same@example.com', $responder['email']); + $this->assertSame('same@example.com', $responder['authenticated_email']); + $this->assertFalse($responder['identity_mismatch']); + } + + public function testUnsignedLinkStillBuildsSparseResponder(): void + { + $request = Request::create('/tasks/update_variable/abe-token', 'GET', [ + 'varName' => 'res', + 'varValue' => 'yes', + ], [], [], [ + 'REMOTE_ADDR' => '198.51.100.2', + 'HTTP_USER_AGENT' => 'Mozilla/5.0 (Windows NT 10.0) Outlook', + ]); + + Auth::logout(); + $responder = AbeResponder::fromRequest($request, 'abe-token'); + + $this->assertArrayNotHasKey('email', $responder); + $this->assertArrayNotHasKey('user_id', $responder); + $this->assertSame('198.51.100.2', $responder['ip_address']); + $this->assertSame('desktop', $responder['device']); + $this->assertSame('Outlook', $responder['email_client']); + } +} From 322a4ec3b9604a857ab246ca199ffe01dece4307 Mon Sep 17 00:00:00 2001 From: sanja <52755494+sanjacornelius@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:31:35 -0800 Subject: [PATCH 03/20] Send one signed ABE email per unique recipient with merged groups --- ProcessMaker/Repositories/TokenRepository.php | 179 ++++++++++++++---- 1 file changed, 144 insertions(+), 35 deletions(-) diff --git a/ProcessMaker/Repositories/TokenRepository.php b/ProcessMaker/Repositories/TokenRepository.php index d7d25216db..80aeed1e6e 100644 --- a/ProcessMaker/Repositories/TokenRepository.php +++ b/ProcessMaker/Repositories/TokenRepository.php @@ -6,10 +6,12 @@ use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Log; use Mustache_Engine; +use ProcessMaker\Helpers\AbeRecipientSignature; use ProcessMaker\Jobs\CaseUpdate; use ProcessMaker\Mail\TaskActionByEmail; use ProcessMaker\Managers\DataManager; use ProcessMaker\Models\FeelExpressionEvaluator; +use ProcessMaker\Models\Group; use ProcessMaker\Models\Process; use ProcessMaker\Models\ProcessAbeRequestToken; use ProcessMaker\Models\ProcessCollaboration; @@ -203,40 +205,14 @@ private function validateAndSendActionByEmail(ActivityInterface $activity, Token try { $isActionsByEmail = $activity->getProperty('isActionsByEmail', false); Log::Info('Activity isActionsByEmail: ' . $isActionsByEmail); - $to = $user && $user->email ? $user->email : ''; - if ($to === '' && $token->is_self_service && is_array($token->self_service_groups)) { - $userIds = array_map('intval', array_filter( - $token->self_service_groups['users'] ?? [], - fn ($id) => is_numeric($id) && (int) $id > 0 - )); - $groupIds = array_values(array_filter( - $token->self_service_groups['groups'] ?? [], - fn ($id) => $id !== '' && $id !== null - )); - if ($groupIds !== []) { - $fromGroups = []; - $token->getInstance()->getProcess()->getOwnerDocument()->getModel() - ->getConsolidatedUsers($groupIds, $fromGroups); - $userIds = array_unique(array_merge($userIds, $fromGroups)); - } - if ($userIds !== []) { - $to = User::query() - ->whereIn('id', $userIds) - ->whereNotIn('status', Process::NOT_ASSIGNABLE_USER_STATUS) - ->whereNotNull('email') - ->where('email', '!=', '') - ->pluck('email') - ->unique() - ->implode(', '); - } - } + $recipients = $this->resolveAbeRecipients($token, $user); // If the actionByEmail is enable - if ($isActionsByEmail === 'true' && !empty($to)) { + if ($isActionsByEmail === 'true' && $recipients !== []) { $configEmail = json_decode($activity->getProperty('configEmail'), true); if (!empty($configEmail)) { Log::info('Activity configEmail: ', $configEmail); $abeRequestToken = new ProcessAbeRequestToken(); - $requireLogin = ($configEmail['requireLogin']) ? 1 : 0; + $requireLogin = !empty($configEmail['requireLogin']) ? 1 : 0; $screenCompleted = !empty($configEmail['screenCompleteRef']) ? $configEmail['screenCompleteRef'] : null; @@ -246,13 +222,25 @@ private function validateAndSendActionByEmail(ActivityInterface $activity, Token 'require_login' => $requireLogin, 'completed_screen_id' => $screenCompleted, ]); - $data = $token->getInstance()->getDataStore()->getData(); + $baseData = $token->getInstance()->getDataStore()->getData(); // Set custom variables defined in the link - $data['abe_uri'] = config('app.url'); - $data['token_abe'] = $tokenAbe->uuid; - - // Send Email - return (new TaskActionByEmail())->sendAbeEmail($configEmail, $to, $data); + $baseData['abe_uri'] = config('app.url'); + $baseData['token_abe'] = $tokenAbe->uuid; + + $mailer = new TaskActionByEmail(); + // One personalized email per unique address. Overlapping group + // membership is collapsed in resolveAbeRecipients (groups merged). + foreach ($recipients as $recipient) { + $signedQuery = AbeRecipientSignature::queryString( + $tokenAbe->uuid, + $recipient['email'], + $recipient['user_id'], + $recipient['groups'] + ); + $mailer->sendAbeEmail($configEmail, $recipient['email'], $baseData, $signedQuery); + } + + return true; } } } catch (\Exception $e) { @@ -263,6 +251,127 @@ private function validateAndSendActionByEmail(ActivityInterface $activity, Token } } + /** + * Resolve ABE recipients as one personalized entry per unique email. + * Users in multiple assigned groups are collapsed into one entry with + * groups recorded as [{id,name}]. When two users share an email, the + * first resolved user wins (one signature / one email). + * + * @return array + */ + private function resolveAbeRecipients(TokenInterface $token, ?User $user): array + { + if ($user && $user->email) { + return [[ + 'email' => $user->email, + 'user_id' => (int) $user->id, + 'groups' => [], + ]]; + } + + if (!$token->is_self_service || !is_array($token->self_service_groups)) { + return []; + } + + $assignedUserIds = array_map('intval', array_filter( + $token->self_service_groups['users'] ?? [], + fn ($id) => is_numeric($id) && (int) $id > 0 + )); + $groupIds = array_values(array_unique(array_map( + 'intval', + array_filter( + $token->self_service_groups['groups'] ?? [], + fn ($id) => $id !== '' && $id !== null && is_numeric($id) + ) + ))); + + $processModel = $this->processModelForAbeToken($token); + $groupsById = $groupIds === [] + ? collect() + : Group::query()->whereIn('id', $groupIds)->get(['id', 'name'])->keyBy('id'); + + $groupsByUserId = []; + $groupUsers = []; + foreach ($groupIds as $groupId) { + $membersForGroup = []; + $processModel->getConsolidatedUsers($groupId, $membersForGroup); + $group = $groupsById->get($groupId); + foreach ($membersForGroup as $memberId) { + $memberId = (int) $memberId; + $groupUsers[] = $memberId; + if ($group) { + $groupsByUserId[$memberId][$groupId] = [ + 'id' => (int) $group->id, + 'name' => (string) $group->name, + ]; + } + } + } + + $allUserIds = array_values(array_unique(array_merge($assignedUserIds, $groupUsers))); + if ($allUserIds === []) { + return []; + } + + $users = User::query() + ->whereIn('id', $allUserIds) + ->whereNotIn('status', Process::NOT_ASSIGNABLE_USER_STATUS) + ->whereNotNull('email') + ->where('email', '!=', '') + ->orderBy('id') + ->get() + ->keyBy('id'); + + $recipients = []; + $seenEmails = []; + foreach ($users as $userId => $recipientUser) { + $emailKey = strtolower(trim((string) $recipientUser->email)); + if ($emailKey === '' || isset($seenEmails[$emailKey])) { + continue; + } + $seenEmails[$emailKey] = true; + + $recipients[] = [ + 'email' => $recipientUser->email, + 'user_id' => (int) $recipientUser->id, + 'groups' => array_values($groupsByUserId[(int) $userId] ?? []), + ]; + } + + return $recipients; + } + + /** + * Resolve the Process model used for consolidated group membership lookups. + */ + private function processModelForAbeToken(TokenInterface $token): Process + { + if (method_exists($token, 'getInstance')) { + $instance = $token->getInstance(); + if ($instance && method_exists($instance, 'getProcess')) { + $process = $instance->getProcess(); + if ($process && method_exists($process, 'getOwnerDocument')) { + $document = $process->getOwnerDocument(); + if ($document && method_exists($document, 'getModel')) { + $model = $document->getModel(); + if ($model instanceof Process) { + return $model; + } + } + } + } + } + + if (method_exists($token, 'getAttribute')) { + $processId = $token->getAttribute('process_id'); + if ($processId) { + return Process::findOrFail($processId); + } + } + + throw new \RuntimeException('Unable to resolve Process model for ABE recipients'); + } + /** * Get due Variable * From 713fb0e24dc73e13c5184f76dbc83476b4e676b2 Mon Sep 17 00:00:00 2001 From: sanja <52755494+sanjacornelius@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:31:55 -0800 Subject: [PATCH 04/20] Append signed recipient params to ABE update_variable links in email HTML --- ProcessMaker/Mail/TaskActionByEmail.php | 32 +++++++++++++++- .../Mail/TaskActionByEmailLinkRewriteTest.php | 38 +++++++++++++++++++ 2 files changed, 68 insertions(+), 2 deletions(-) create mode 100644 tests/unit/Mail/TaskActionByEmailLinkRewriteTest.php diff --git a/ProcessMaker/Mail/TaskActionByEmail.php b/ProcessMaker/Mail/TaskActionByEmail.php index 1a21df63f4..1804bc5615 100644 --- a/ProcessMaker/Mail/TaskActionByEmail.php +++ b/ProcessMaker/Mail/TaskActionByEmail.php @@ -28,10 +28,11 @@ public function __construct() * - screenEmailRef: Reference ID to a custom email screen (integer, optional, default: 0). * @param string $to Recipient email address. * @param array $data Additional data for rendering the email content (optional). + * @param string|null $signedQuery Optional signed ABE query string to append to action links. * * @return void */ - public function sendAbeEmail($config, $to, $data) + public function sendAbeEmail($config, $to, $data, ?string $signedQuery = null) { try { // Get parameters to send the email @@ -52,7 +53,10 @@ public function sendAbeEmail($config, $to, $data) // Retrieve and render custom screen if specified $customScreen = Screen::findOrFail($emailScreenRef); $infoRenderer = $this->emailProvider->screenRenderer($customScreen->config, $data, $customScreen); - $emailConfig['body'] = $infoRenderer['body'] ?? __('No body configured'); + $body = $infoRenderer['body'] ?? __('No body configured'); + $emailConfig['body'] = $signedQuery + ? $this->appendSignedParamsToAbeLinks($body, $signedQuery) + : $body; $emailConfig['styles'] = $infoRenderer['styles'] ?? ''; } else { // Default message if no custom screen is configured @@ -74,6 +78,30 @@ public function sendAbeEmail($config, $to, $data) return true; } + /** + * Append signed recipient params to known ABE action URLs only. + */ + public function appendSignedParamsToAbeLinks(string $html, string $signedQuery): string + { + if ($signedQuery === '' || $html === '') { + return $html; + } + + return preg_replace_callback( + '/(\b(?:href)=["\'])([^"\']*\/tasks\/update_variable\/[^"\']*)(["\'])/i', + static function (array $matches) use ($signedQuery) { + $url = html_entity_decode($matches[2], ENT_QUOTES | ENT_HTML5); + if (str_contains($url, 'abe_sig=')) { + return $matches[0]; + } + $separator = str_contains($url, '?') ? '&' : '?'; + + return $matches[1] . $url . $separator . $signedQuery . $matches[3]; + }, + $html + ) ?? $html; + } + private function mustache($str, $data) { return (new Mustache_Engine())->render($str, $data); diff --git a/tests/unit/Mail/TaskActionByEmailLinkRewriteTest.php b/tests/unit/Mail/TaskActionByEmailLinkRewriteTest.php new file mode 100644 index 0000000000..b424419c07 --- /dev/null +++ b/tests/unit/Mail/TaskActionByEmailLinkRewriteTest.php @@ -0,0 +1,38 @@ +Approve +Open task +HTML; + $signed = 'abe_email=a%40b.com&abe_user_id=1&abe_groups=&abe_sig=deadbeef'; + + $result = $mailer->appendSignedParamsToAbeLinks($html, $signed); + + $this->assertStringContainsString( + 'https://pm.test/tasks/update_variable/abc-123?varName=res&varValue=yes&' . $signed, + $result + ); + $this->assertStringContainsString('href="https://pm.test/tasks/123"', $result); + $this->assertSame(1, substr_count($result, 'abe_sig=')); + } + + public function testDoesNotDoubleAppendSignature(): void + { + $mailer = new TaskActionByEmail(); + $html = 'Go'; + + $result = $mailer->appendSignedParamsToAbeLinks($html, 'abe_sig=new'); + + $this->assertSame($html, $result); + } +} From 904dbda5f44a2d55d4a43802ad8bd9132d4f3489 Mon Sep 17 00:00:00 2001 From: sanja <52755494+sanjacornelius@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:32:11 -0800 Subject: [PATCH 05/20] Store ABE click metadata under abe_responder in request data --- .../Http/Controllers/TaskController.php | 10 ++++- tests/Feature/TaskControllerTest.php | 45 +++++++++++++++++++ 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/ProcessMaker/Http/Controllers/TaskController.php b/ProcessMaker/Http/Controllers/TaskController.php index d7b658b451..ed9b9de407 100755 --- a/ProcessMaker/Http/Controllers/TaskController.php +++ b/ProcessMaker/Http/Controllers/TaskController.php @@ -10,6 +10,7 @@ use ProcessMaker\Events\ScreenBuilderStarting; use ProcessMaker\Facades\WorkflowManager; use ProcessMaker\Filters\SaveSession; +use ProcessMaker\Helpers\AbeResponder; use ProcessMaker\Helpers\DefaultColumns; use ProcessMaker\Helpers\MobileHelper; use ProcessMaker\Http\Controllers\Api\ProcessRequestController; @@ -304,8 +305,13 @@ public function updateVariable(HttpRequest $request, $abe_uuid) if ($task->status === 'CLOSED') { return $this->returnErrorResponse(__('Task already closed'), 404); } - // Update the data - $data[$request->varName] = $request->varValue; + // Update the data: action variable + nested abe_responder metadata. + // develop does not set top-level user_id/acted_at on request data + // (those live on the ABE token row), so both belong under abe_responder. + $data = [ + $request->varName => $request->varValue, + 'abe_responder' => AbeResponder::fromRequest($request, $abe->uuid), + ]; $abe->data = json_encode($data); // Define the answered_at and is_answered $abe->is_answered = true; diff --git a/tests/Feature/TaskControllerTest.php b/tests/Feature/TaskControllerTest.php index 262d17ae3c..ca20a88098 100644 --- a/tests/Feature/TaskControllerTest.php +++ b/tests/Feature/TaskControllerTest.php @@ -5,6 +5,7 @@ use Faker\Factory as Faker; use Illuminate\Support\Facades\Auth; use ProcessMaker\Facades\WorkflowManager; +use ProcessMaker\Helpers\AbeRecipientSignature; use ProcessMaker\Models\Process; use ProcessMaker\Models\ProcessAbeRequestToken; use ProcessMaker\Models\ProcessRequest; @@ -146,4 +147,48 @@ public function testReturnMessageTokenNoFound() $response->assertSee('Token not found'); $response->assertStatus(404); } + + /** + * ABE click metadata is nested under abe_responder (not flat top-level keys). + */ + public function testActionByEmailStoresResponderMetadataNestedInRequestData(): void + { + $process = Process::factory()->create([ + 'bpmn' => file_get_contents(__DIR__ . '/../Fixtures/action_by_email_process_no_require_login.bpmn'), + ]); + Screen::factory()->create(); + + $route = route('api.process_events.trigger', [$process->id, 'event' => 'node_1']); + $this->apiCall('POST', $route, []); + + $processAbeRequest = ProcessAbeRequestToken::firstOrFail(); + $signedQuery = AbeRecipientSignature::queryString( + $processAbeRequest->uuid, + 'recipient@example.com', + 55, + [['id' => 9, 'name' => 'Approvers']] + ); + + $response = $this->webCall( + 'GET', + 'tasks/update_variable/' . $processAbeRequest->uuid . '?varName=res&varValue=yes&' . $signedQuery + ); + $response->assertStatus(200); + + $request = ProcessRequest::findOrFail($processAbeRequest->process_request_id); + $data = $request->data; + + $this->assertSame('yes', $data['res'] ?? null); + $this->assertArrayHasKey('abe_responder', $data); + $this->assertIsArray($data['abe_responder']); + $this->assertSame('recipient@example.com', $data['abe_responder']['email']); + $this->assertSame(55, $data['abe_responder']['user_id']); + $this->assertSame([['id' => 9, 'name' => 'Approvers']], $data['abe_responder']['groups']); + $this->assertArrayHasKey('acted_at', $data['abe_responder']); + // Must not leak as top-level request-data keys (develop never set these there) + $this->assertArrayNotHasKey('email', $data); + $this->assertArrayNotHasKey('acted_at', $data); + $this->assertArrayNotHasKey('identity_mismatch', $data); + $this->assertArrayNotHasKey('user_id', $data); + } } From a36e05c39007e0d011a2a86d3507ce1566872dad Mon Sep 17 00:00:00 2001 From: sanja <52755494+sanjacornelius@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:32:30 -0800 Subject: [PATCH 06/20] Cover overlapping groups and shared-email recipient dedupe for ABE --- .../Api/TaskActionByEmailSelfServiceTest.php | 155 ++++++++++++++++++ 1 file changed, 155 insertions(+) diff --git a/tests/Feature/Api/TaskActionByEmailSelfServiceTest.php b/tests/Feature/Api/TaskActionByEmailSelfServiceTest.php index 7749c1be4b..cff2af466f 100644 --- a/tests/Feature/Api/TaskActionByEmailSelfServiceTest.php +++ b/tests/Feature/Api/TaskActionByEmailSelfServiceTest.php @@ -2,6 +2,7 @@ namespace Tests\Feature\Api; +use Illuminate\Support\Facades\Bus; use ProcessMaker\Models\Group; use ProcessMaker\Models\GroupMember; use ProcessMaker\Models\Process; @@ -9,6 +10,10 @@ use ProcessMaker\Models\ProcessRequestToken; use ProcessMaker\Models\ProcessTaskAssignment; use ProcessMaker\Models\User; +use ProcessMaker\Packages\Connectors\Email\Jobs\SendEmail; +use ProcessMaker\Repositories\ExecutionInstanceRepository; +use ProcessMaker\Repositories\TokenRepository; +use ReflectionMethod; use Tests\Feature\Shared\RequestHelper; use Tests\TestCase; @@ -66,4 +71,154 @@ public function testActionByEmailCreatesTokenWhenSelfServiceWithGroupAssignment( $this->assertNotNull($abeToken); $this->assertEquals($task->id, $abeToken->process_request_token_id); } + + /** + * A user in two assigned self-service groups must get one ABE email, not one per group. + */ + public function testOverlappingGroupMembershipSendsOneAbeEmail(): void + { + Bus::fake([SendEmail::class]); + + $groupA = Group::factory()->create(['status' => 'ACTIVE', 'name' => 'ABE Group A']); + $groupB = Group::factory()->create(['status' => 'ACTIVE', 'name' => 'ABE Group B']); + + $shared = User::factory()->create([ + 'status' => 'ACTIVE', + 'email' => 'shared-abe@example.com', + ]); + $onlyA = User::factory()->create([ + 'status' => 'ACTIVE', + 'email' => 'only-a@example.com', + ]); + $onlyB = User::factory()->create([ + 'status' => 'ACTIVE', + 'email' => 'only-b@example.com', + ]); + + foreach ([[$groupA->id, $shared->id], [$groupB->id, $shared->id], [$groupA->id, $onlyA->id], [$groupB->id, $onlyB->id]] as [$groupId, $userId]) { + GroupMember::factory()->create([ + 'group_id' => $groupId, + 'member_id' => $userId, + 'member_type' => User::class, + ]); + } + + $bpmn = str_replace( + ['[ASSIGNED_USERS]', '[ASSIGNED_GROUPS]', '"screenEmailRef":10'], + ['', $groupA->id . ',' . $groupB->id, '"screenEmailRef":0'], + file_get_contents(__DIR__ . '/processes/TaskActionByEmailSelfService.bpmn') + ); + + $process = Process::factory()->create(['bpmn' => $bpmn]); + ProcessTaskAssignment::factory()->create([ + 'process_id' => $process->id, + 'process_task_id' => 'node_2', + 'assignment_id' => $groupA->id, + 'assignment_type' => Group::class, + ]); + ProcessTaskAssignment::factory()->create([ + 'process_id' => $process->id, + 'process_task_id' => 'node_2', + 'assignment_id' => $groupB->id, + 'assignment_type' => Group::class, + ]); + + $route = route('api.process_events.trigger', [$process->id, 'event' => 'node_1']); + $response = $this->apiCall('POST', $route, []); + $response->assertStatus(201); + + $task = ProcessRequestToken::where('status', 'ACTIVE')->firstOrFail(); + $this->assertEquals(1, $task->is_self_service); + + $repository = new TokenRepository(app(ExecutionInstanceRepository::class)); + $method = new ReflectionMethod(TokenRepository::class, 'resolveAbeRecipients'); + $method->setAccessible(true); + $recipients = $method->invoke($repository, $task, null); + + $this->assertCount(3, $recipients); + $emails = array_column($recipients, 'email'); + $this->assertCount(3, array_unique($emails)); + + $sharedRecipient = collect($recipients)->firstWhere('user_id', $shared->id); + $this->assertNotNull($sharedRecipient); + $this->assertEqualsCanonicalizing( + [$groupA->id, $groupB->id], + array_column($sharedRecipient['groups'], 'id') + ); + + Bus::assertDispatchedTimes(SendEmail::class, 3); + + $sharedDispatches = 0; + Bus::assertDispatched(SendEmail::class, function (SendEmail $job) use (&$sharedDispatches) { + $config = (function () { + return $this->config; + })->call($job); + $to = $config['addEmails'] ?? $config['email'] ?? ''; + if ($to === 'shared-abe@example.com') { + $sharedDispatches++; + } + + return true; + }); + $this->assertSame(1, $sharedDispatches); + } + + /** + * Two different users that share an email receive one personalized ABE send (first user wins). + */ + public function testDistinctUsersSharingEmailReceiveOneAbeEmail(): void + { + Bus::fake([SendEmail::class]); + + $group = Group::factory()->create(['status' => 'ACTIVE', 'name' => 'ABE Shared Inbox']); + $sharedEmail = 'shared-inbox@example.com'; + + $userOne = User::factory()->create([ + 'status' => 'ACTIVE', + 'email' => $sharedEmail, + ]); + $userTwo = User::factory()->create([ + 'status' => 'ACTIVE', + 'email' => $sharedEmail, + ]); + + foreach ([$userOne->id, $userTwo->id] as $userId) { + GroupMember::factory()->create([ + 'group_id' => $group->id, + 'member_id' => $userId, + 'member_type' => User::class, + ]); + } + + $bpmn = str_replace( + ['[ASSIGNED_USERS]', '[ASSIGNED_GROUPS]', '"screenEmailRef":10'], + ['', (string) $group->id, '"screenEmailRef":0'], + file_get_contents(__DIR__ . '/processes/TaskActionByEmailSelfService.bpmn') + ); + + $process = Process::factory()->create(['bpmn' => $bpmn]); + ProcessTaskAssignment::factory()->create([ + 'process_id' => $process->id, + 'process_task_id' => 'node_2', + 'assignment_id' => $group->id, + 'assignment_type' => Group::class, + ]); + + $route = route('api.process_events.trigger', [$process->id, 'event' => 'node_1']); + $response = $this->apiCall('POST', $route, []); + $response->assertStatus(201); + + $task = ProcessRequestToken::where('status', 'ACTIVE')->firstOrFail(); + + $repository = new TokenRepository(app(ExecutionInstanceRepository::class)); + $method = new ReflectionMethod(TokenRepository::class, 'resolveAbeRecipients'); + $method->setAccessible(true); + $recipients = $method->invoke($repository, $task, null); + + $this->assertCount(1, $recipients); + $this->assertSame($sharedEmail, $recipients[0]['email']); + $this->assertSame($userOne->id, $recipients[0]['user_id']); + + Bus::assertDispatchedTimes(SendEmail::class, 1); + } } From fc1489a77be315797a4f2b23251ec96c3f9bcd27 Mon Sep 17 00:00:00 2001 From: sanja <52755494+sanjacornelius@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:32:47 -0800 Subject: [PATCH 07/20] Add stress tests for large and overlapping ABE recipient groups --- tests/Feature/AbeLargeRecipientGroupTest.php | 206 +++++++++++++++++++ 1 file changed, 206 insertions(+) create mode 100644 tests/Feature/AbeLargeRecipientGroupTest.php diff --git a/tests/Feature/AbeLargeRecipientGroupTest.php b/tests/Feature/AbeLargeRecipientGroupTest.php new file mode 100644 index 0000000000..fb09ec0c4f --- /dev/null +++ b/tests/Feature/AbeLargeRecipientGroupTest.php @@ -0,0 +1,206 @@ +create(['status' => 'ACTIVE', 'name' => 'ABE Large Group']); + $active = $this->createUsersInGroups([$group->id], 75, 'ACTIVE'); + $inactive = $this->createUsersInGroups([$group->id], 10, 'INACTIVE'); + + $task = $this->startAbeSelfServiceTask([$group->id]); + + $recipients = $this->resolveAbeRecipients($task); + + $this->assertCount(count($active), $recipients); + $this->assertCount(count($active), array_unique(array_column($recipients, 'email'))); + + $inactiveEmails = User::whereIn('id', $inactive)->pluck('email')->all(); + foreach ($inactiveEmails as $inactiveEmail) { + $this->assertNotContains($inactiveEmail, array_column($recipients, 'email')); + } + + Bus::assertDispatchedTimes(SendEmail::class, count($active)); + } + + /** + * Stress personalized ABE recipient resolution for large overlapping groups. + * Expected unique recipients: 500 active users + * (200 A-only + 200 B-only + 100 shared); inactive members excluded. + */ + public function testResolveAbeRecipientsDedupesLargeOverlappingGroupsWithinBudget(): void + { + Bus::fake([SendEmail::class]); + + $groupA = Group::factory()->create(['status' => 'ACTIVE', 'name' => 'ABE Group A']); + $groupB = Group::factory()->create(['status' => 'ACTIVE', 'name' => 'ABE Group B']); + + $onlyA = $this->createUsersInGroups([$groupA->id], 200, 'ACTIVE'); + $onlyB = $this->createUsersInGroups([$groupB->id], 200, 'ACTIVE'); + $shared = $this->createUsersInGroups([$groupA->id, $groupB->id], 100, 'ACTIVE'); + $inactive = $this->createUsersInGroups([$groupA->id, $groupB->id], 50, 'INACTIVE'); + + $expectedUnique = count($onlyA) + count($onlyB) + count($shared); + $this->assertSame(500, $expectedUnique); + + $task = $this->startAbeSelfServiceTask([$groupA->id, $groupB->id]); + $this->assertNotNull(ProcessAbeRequestToken::first()); + + $resolveStarted = microtime(true); + $recipients = $this->resolveAbeRecipients($task); + $resolveSeconds = microtime(true) - $resolveStarted; + + $this->assertCount($expectedUnique, $recipients); + + $emails = array_column($recipients, 'email'); + $this->assertCount($expectedUnique, array_unique($emails)); + + $inactiveEmails = User::whereIn('id', $inactive)->pluck('email')->all(); + foreach ($inactiveEmails as $inactiveEmail) { + $this->assertNotContains($inactiveEmail, $emails); + } + + $byUserId = []; + foreach ($recipients as $recipient) { + $byUserId[$recipient['user_id']] = $recipient; + } + + foreach ($onlyA as $userId) { + $this->assertSame([$groupA->id], array_column($byUserId[$userId]['groups'], 'id')); + $this->assertSame(['ABE Group A'], array_column($byUserId[$userId]['groups'], 'name')); + } + foreach ($onlyB as $userId) { + $this->assertSame([$groupB->id], array_column($byUserId[$userId]['groups'], 'id')); + } + foreach ($shared as $userId) { + $groupIds = array_column($byUserId[$userId]['groups'], 'id'); + sort($groupIds); + $this->assertSame([$groupA->id, $groupB->id], $groupIds); + } + + $tokenAbe = ProcessAbeRequestToken::first()->uuid; + $signStarted = microtime(true); + foreach ($recipients as $recipient) { + $query = AbeRecipientSignature::queryString( + $tokenAbe, + $recipient['email'], + $recipient['user_id'], + $recipient['groups'] + ); + $this->assertStringContainsString('abe_sig=', $query); + } + $signSeconds = microtime(true) - $signStarted; + + $this->assertLessThan( + 10.0, + $resolveSeconds, + sprintf('Recipient resolution took %.3fs for %d users', $resolveSeconds, $expectedUnique) + ); + $this->assertLessThan( + 5.0, + $signSeconds, + sprintf('Signing took %.3fs for %d recipients', $signSeconds, $expectedUnique) + ); + + Bus::assertDispatchedTimes(SendEmail::class, $expectedUnique); + } + + /** + * @param array $groupIds + */ + private function startAbeSelfServiceTask(array $groupIds): ProcessRequestToken + { + $bpmn = str_replace( + ['[ASSIGNED_USERS]', '[ASSIGNED_GROUPS]', '"screenEmailRef":10'], + ['', implode(',', $groupIds), '"screenEmailRef":0'], + file_get_contents(__DIR__ . '/Api/processes/TaskActionByEmailSelfService.bpmn') + ); + + $process = Process::factory()->create(['bpmn' => $bpmn]); + foreach ($groupIds as $groupId) { + ProcessTaskAssignment::factory()->create([ + 'process_id' => $process->id, + 'process_task_id' => 'node_2', + 'assignment_id' => $groupId, + 'assignment_type' => Group::class, + ]); + } + + $route = route('api.process_events.trigger', [$process->id, 'event' => 'node_1']); + $response = $this->apiCall('POST', $route, []); + $response->assertStatus(201); + + $task = ProcessRequestToken::where('status', 'ACTIVE')->firstOrFail(); + $this->assertEquals(1, $task->is_self_service); + + return $task; + } + + /** + * @return array + */ + private function resolveAbeRecipients(ProcessRequestToken $task): array + { + $repository = new TokenRepository(app(ExecutionInstanceRepository::class)); + $method = new ReflectionMethod(TokenRepository::class, 'resolveAbeRecipients'); + $method->setAccessible(true); + + return $method->invoke($repository, $task, null); + } + + /** + * @param array $groupIds + * @return array + */ + private function createUsersInGroups(array $groupIds, int $count, string $status): array + { + $users = User::factory()->count($count)->create([ + 'status' => $status, + ]); + + $now = now()->toDateTimeString(); + $memberRows = []; + foreach ($users as $user) { + foreach ($groupIds as $groupId) { + $memberRows[] = [ + 'group_id' => $groupId, + 'member_id' => $user->id, + 'member_type' => User::class, + 'created_at' => $now, + 'updated_at' => $now, + ]; + } + } + + foreach (array_chunk($memberRows, 500) as $chunk) { + DB::table('group_members')->insert($chunk); + } + + return $users->pluck('id')->all(); + } +} From 44fa8b945a54ac79817978f9c95bddf9b70e5c6b Mon Sep 17 00:00:00 2001 From: sanja <52755494+sanjacornelius@users.noreply.github.com> Date: Fri, 13 Nov 2026 20:20:05 -0800 Subject: [PATCH 08/20] Gate personalized ABE emails behind trackResponder and stagger queue dispatch --- ProcessMaker/Mail/TaskActionByEmail.php | 8 +++--- ProcessMaker/Repositories/TokenRepository.php | 26 ++++++++++++++++--- 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/ProcessMaker/Mail/TaskActionByEmail.php b/ProcessMaker/Mail/TaskActionByEmail.php index 1804bc5615..5e23805270 100644 --- a/ProcessMaker/Mail/TaskActionByEmail.php +++ b/ProcessMaker/Mail/TaskActionByEmail.php @@ -29,10 +29,11 @@ public function __construct() * @param string $to Recipient email address. * @param array $data Additional data for rendering the email content (optional). * @param string|null $signedQuery Optional signed ABE query string to append to action links. + * @param int $delaySeconds Queue delay before the job runs (throttle bulk personalized sends). * * @return void */ - public function sendAbeEmail($config, $to, $data, ?string $signedQuery = null) + public function sendAbeEmail($config, $to, $data, ?string $signedQuery = null, int $delaySeconds = 0) { try { // Get parameters to send the email @@ -63,8 +64,9 @@ public function sendAbeEmail($config, $to, $data, ?string $signedQuery = null) $emailConfig['body'] = __('No screen configured'); } - // Send the email using emailProvider - $this->emailProvider->sendAsync($emailConfig); + // Personalized ABE sends are one message per recipient (unique signed link). + // Stagger queue dispatch so SMTP test providers (e.g. Mailtrap) are not rate-limited. + $this->emailProvider->sendAsync($emailConfig, $delaySeconds); } catch (\Exception $e) { Log::error('Error sending ABE email', [ 'to' => $to, diff --git a/ProcessMaker/Repositories/TokenRepository.php b/ProcessMaker/Repositories/TokenRepository.php index 80aeed1e6e..6bc2bcd45f 100644 --- a/ProcessMaker/Repositories/TokenRepository.php +++ b/ProcessMaker/Repositories/TokenRepository.php @@ -228,16 +228,34 @@ private function validateAndSendActionByEmail(ActivityInterface $activity, Token $baseData['token_abe'] = $tokenAbe->uuid; $mailer = new TaskActionByEmail(); - // One personalized email per unique address. Overlapping group - // membership is collapsed in resolveAbeRecipients (groups merged). - foreach ($recipients as $recipient) { + $trackResponder = !empty($configEmail['trackResponder']); + + if (!$trackResponder) { + // Legacy: one email (shared link) to all recipients + $to = implode(', ', array_column($recipients, 'email')); + + return $mailer->sendAbeEmail($configEmail, $to, $baseData); + } + + // Opt-in responder tracking: one personalized email per unique address + // with a signed link. Overlapping group membership is collapsed in + // resolveAbeRecipients (groups merged). Stagger dispatches so providers + // with per-second caps (Mailtrap, etc.) are less likely to throttle. + $staggerSeconds = max(0, (int) config('app.abe_email_stagger_seconds', 1)); + foreach ($recipients as $index => $recipient) { $signedQuery = AbeRecipientSignature::queryString( $tokenAbe->uuid, $recipient['email'], $recipient['user_id'], $recipient['groups'] ); - $mailer->sendAbeEmail($configEmail, $recipient['email'], $baseData, $signedQuery); + $mailer->sendAbeEmail( + $configEmail, + $recipient['email'], + $baseData, + $signedQuery, + $index * $staggerSeconds + ); } return true; From c0255c78da1ed4a7dd0e699f7ad4dc421750588e Mon Sep 17 00:00:00 2001 From: sanja <52755494+sanjacornelius@users.noreply.github.com> Date: Fri, 13 Nov 2026 20:20:23 -0800 Subject: [PATCH 09/20] Omit abe_responder from request data unless trackResponder is enabled --- .../Http/Controllers/TaskController.php | 27 ++++++++++++++++--- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/ProcessMaker/Http/Controllers/TaskController.php b/ProcessMaker/Http/Controllers/TaskController.php index ed9b9de407..fa043f3996 100755 --- a/ProcessMaker/Http/Controllers/TaskController.php +++ b/ProcessMaker/Http/Controllers/TaskController.php @@ -305,13 +305,14 @@ public function updateVariable(HttpRequest $request, $abe_uuid) if ($task->status === 'CLOSED') { return $this->returnErrorResponse(__('Task already closed'), 404); } - // Update the data: action variable + nested abe_responder metadata. - // develop does not set top-level user_id/acted_at on request data - // (those live on the ABE token row), so both belong under abe_responder. + // Action variable always; abe_responder only when the task opted into + // responder tracking (personalized signed links). $data = [ $request->varName => $request->varValue, - 'abe_responder' => AbeResponder::fromRequest($request, $abe->uuid), ]; + if ($this->abeTrackResponderEnabled($task)) { + $data['abe_responder'] = AbeResponder::fromRequest($request, $abe->uuid); + } $abe->data = json_encode($data); // Define the answered_at and is_answered $abe->is_answered = true; @@ -346,6 +347,24 @@ public function updateVariable(HttpRequest $request, $abe_uuid) } } + /** + * Whether the task's Actions by Email config opted into responder tracking. + */ + private function abeTrackResponderEnabled(ProcessRequestToken $task): bool + { + $definition = $task->getDefinition(); + if (!is_array($definition)) { + return false; + } + + $configEmail = $definition['configEmail'] ?? null; + if (is_string($configEmail)) { + $configEmail = json_decode($configEmail, true); + } + + return is_array($configEmail) && !empty($configEmail['trackResponder']); + } + /** * Show a screen defined * @param int $screenId From 2bf3bd6d49fec2c5b4a77ab84aee16841d541459 Mon Sep 17 00:00:00 2001 From: sanja <52755494+sanjacornelius@users.noreply.github.com> Date: Fri, 13 Nov 2026 20:20:51 -0800 Subject: [PATCH 10/20] Add send-side trackResponder and stagger coverage; enable tracking in existing ABE send/click tests --- tests/Feature/AbeLargeRecipientGroupTest.php | 14 +- .../Api/TaskActionByEmailSelfServiceTest.php | 228 +++++++++++++++++- tests/Feature/TaskControllerTest.php | 38 ++- 3 files changed, 270 insertions(+), 10 deletions(-) diff --git a/tests/Feature/AbeLargeRecipientGroupTest.php b/tests/Feature/AbeLargeRecipientGroupTest.php index fb09ec0c4f..d35848d4f3 100644 --- a/tests/Feature/AbeLargeRecipientGroupTest.php +++ b/tests/Feature/AbeLargeRecipientGroupTest.php @@ -136,8 +136,18 @@ public function testResolveAbeRecipientsDedupesLargeOverlappingGroupsWithinBudge private function startAbeSelfServiceTask(array $groupIds): ProcessRequestToken { $bpmn = str_replace( - ['[ASSIGNED_USERS]', '[ASSIGNED_GROUPS]', '"screenEmailRef":10'], - ['', implode(',', $groupIds), '"screenEmailRef":0'], + [ + '[ASSIGNED_USERS]', + '[ASSIGNED_GROUPS]', + '"screenEmailRef":10', + '"requireLogin":true', + ], + [ + '', + implode(',', $groupIds), + '"screenEmailRef":0', + '"requireLogin":true,"trackResponder":true', + ], file_get_contents(__DIR__ . '/Api/processes/TaskActionByEmailSelfService.bpmn') ); diff --git a/tests/Feature/Api/TaskActionByEmailSelfServiceTest.php b/tests/Feature/Api/TaskActionByEmailSelfServiceTest.php index cff2af466f..f0fccc2786 100644 --- a/tests/Feature/Api/TaskActionByEmailSelfServiceTest.php +++ b/tests/Feature/Api/TaskActionByEmailSelfServiceTest.php @@ -2,6 +2,7 @@ namespace Tests\Feature\Api; +use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Bus; use ProcessMaker\Models\Group; use ProcessMaker\Models\GroupMember; @@ -104,8 +105,18 @@ public function testOverlappingGroupMembershipSendsOneAbeEmail(): void } $bpmn = str_replace( - ['[ASSIGNED_USERS]', '[ASSIGNED_GROUPS]', '"screenEmailRef":10'], - ['', $groupA->id . ',' . $groupB->id, '"screenEmailRef":0'], + [ + '[ASSIGNED_USERS]', + '[ASSIGNED_GROUPS]', + '"screenEmailRef":10', + '"requireLogin":true', + ], + [ + '', + $groupA->id . ',' . $groupB->id, + '"screenEmailRef":0', + '"requireLogin":true,"trackResponder":true', + ], file_get_contents(__DIR__ . '/processes/TaskActionByEmailSelfService.bpmn') ); @@ -154,6 +165,8 @@ public function testOverlappingGroupMembershipSendsOneAbeEmail(): void return $this->config; })->call($job); $to = $config['addEmails'] ?? $config['email'] ?? ''; + // Personalized path: one recipient address per job (not comma-joined). + $this->assertStringNotContainsString(',', (string) $to); if ($to === 'shared-abe@example.com') { $sharedDispatches++; } @@ -191,8 +204,18 @@ public function testDistinctUsersSharingEmailReceiveOneAbeEmail(): void } $bpmn = str_replace( - ['[ASSIGNED_USERS]', '[ASSIGNED_GROUPS]', '"screenEmailRef":10'], - ['', (string) $group->id, '"screenEmailRef":0'], + [ + '[ASSIGNED_USERS]', + '[ASSIGNED_GROUPS]', + '"screenEmailRef":10', + '"requireLogin":true', + ], + [ + '', + (string) $group->id, + '"screenEmailRef":0', + '"requireLogin":true,"trackResponder":true', + ], file_get_contents(__DIR__ . '/processes/TaskActionByEmailSelfService.bpmn') ); @@ -221,4 +244,201 @@ public function testDistinctUsersSharingEmailReceiveOneAbeEmail(): void Bus::assertDispatchedTimes(SendEmail::class, 1); } + + /** + * Without trackResponder, ABE sends one shared email (comma-joined To), not one per recipient. + */ + public function testWithoutTrackResponderSendsOneSharedAbeEmail(): void + { + Bus::fake([SendEmail::class]); + + $group = Group::factory()->create(['status' => 'ACTIVE', 'name' => 'ABE Legacy Shared']); + $users = collect([ + User::factory()->create(['status' => 'ACTIVE', 'email' => 'legacy-a@example.com']), + User::factory()->create(['status' => 'ACTIVE', 'email' => 'legacy-b@example.com']), + User::factory()->create(['status' => 'ACTIVE', 'email' => 'legacy-c@example.com']), + ]); + + foreach ($users as $user) { + GroupMember::factory()->create([ + 'group_id' => $group->id, + 'member_id' => $user->id, + 'member_type' => User::class, + ]); + } + + $bpmn = str_replace( + [ + '[ASSIGNED_USERS]', + '[ASSIGNED_GROUPS]', + '"screenEmailRef":10', + ], + [ + '', + (string) $group->id, + '"screenEmailRef":0', + ], + file_get_contents(__DIR__ . '/processes/TaskActionByEmailSelfService.bpmn') + ); + $this->assertStringNotContainsString('trackResponder', $bpmn); + + $process = Process::factory()->create(['bpmn' => $bpmn]); + ProcessTaskAssignment::factory()->create([ + 'process_id' => $process->id, + 'process_task_id' => 'node_2', + 'assignment_id' => $group->id, + 'assignment_type' => Group::class, + ]); + + $route = route('api.process_events.trigger', [$process->id, 'event' => 'node_1']); + $response = $this->apiCall('POST', $route, []); + $response->assertStatus(201); + + Bus::assertDispatchedTimes(SendEmail::class, 1); + + $job = Bus::dispatched(SendEmail::class)->first(); + $config = (function () { + return $this->config; + })->call($job); + $to = (string) ($config['addEmails'] ?? $config['email'] ?? ''); + + foreach ($users->pluck('email') as $email) { + $this->assertStringContainsString($email, $to); + } + $this->assertStringContainsString(',', $to); + $this->assertTrue($job->delay === null || $job->delay === 0); + } + + /** + * With trackResponder, personalized sends are staggered by abe_email_stagger_seconds. + */ + public function testTrackResponderStaggersPersonalizedAbeEmailDispatches(): void + { + Bus::fake([SendEmail::class]); + + $now = Carbon::parse('2026-11-13 12:00:00'); + Carbon::setTestNow($now); + config(['app.abe_email_stagger_seconds' => 3]); + + try { + $group = Group::factory()->create(['status' => 'ACTIVE', 'name' => 'ABE Stagger']); + $emails = [ + 'stagger-a@example.com', + 'stagger-b@example.com', + 'stagger-c@example.com', + ]; + foreach ($emails as $email) { + $user = User::factory()->create([ + 'status' => 'ACTIVE', + 'email' => $email, + ]); + GroupMember::factory()->create([ + 'group_id' => $group->id, + 'member_id' => $user->id, + 'member_type' => User::class, + ]); + } + + $bpmn = str_replace( + [ + '[ASSIGNED_USERS]', + '[ASSIGNED_GROUPS]', + '"screenEmailRef":10', + '"requireLogin":true', + ], + [ + '', + (string) $group->id, + '"screenEmailRef":0', + '"requireLogin":true,"trackResponder":true', + ], + file_get_contents(__DIR__ . '/processes/TaskActionByEmailSelfService.bpmn') + ); + + $process = Process::factory()->create(['bpmn' => $bpmn]); + ProcessTaskAssignment::factory()->create([ + 'process_id' => $process->id, + 'process_task_id' => 'node_2', + 'assignment_id' => $group->id, + 'assignment_type' => Group::class, + ]); + + $route = route('api.process_events.trigger', [$process->id, 'event' => 'node_1']); + $response = $this->apiCall('POST', $route, []); + $response->assertStatus(201); + + $jobs = Bus::dispatched(SendEmail::class); + $this->assertCount(3, $jobs); + + $delaySeconds = $jobs->map(function (SendEmail $job) use ($now) { + $config = (function () { + return $this->config; + })->call($job); + $to = (string) ($config['addEmails'] ?? $config['email'] ?? ''); + $this->assertStringNotContainsString(',', $to); + + if ($job->delay === null || $job->delay === 0) { + return 0; + } + + return (int) $now->diffInSeconds(Carbon::parse($job->delay)); + })->sort()->values()->all(); + + $this->assertSame([0, 3, 6], $delaySeconds); + } finally { + Carbon::setTestNow(); + } + } + + /** + * Zero stagger still personalizes, but all dispatches run without delay. + */ + public function testTrackResponderWithZeroStaggerDispatchesWithoutDelay(): void + { + Bus::fake([SendEmail::class]); + config(['app.abe_email_stagger_seconds' => 0]); + + $group = Group::factory()->create(['status' => 'ACTIVE', 'name' => 'ABE Zero Stagger']); + foreach (['zero-a@example.com', 'zero-b@example.com'] as $email) { + $user = User::factory()->create(['status' => 'ACTIVE', 'email' => $email]); + GroupMember::factory()->create([ + 'group_id' => $group->id, + 'member_id' => $user->id, + 'member_type' => User::class, + ]); + } + + $bpmn = str_replace( + [ + '[ASSIGNED_USERS]', + '[ASSIGNED_GROUPS]', + '"screenEmailRef":10', + '"requireLogin":true', + ], + [ + '', + (string) $group->id, + '"screenEmailRef":0', + '"requireLogin":true,"trackResponder":true', + ], + file_get_contents(__DIR__ . '/processes/TaskActionByEmailSelfService.bpmn') + ); + + $process = Process::factory()->create(['bpmn' => $bpmn]); + ProcessTaskAssignment::factory()->create([ + 'process_id' => $process->id, + 'process_task_id' => 'node_2', + 'assignment_id' => $group->id, + 'assignment_type' => Group::class, + ]); + + $route = route('api.process_events.trigger', [$process->id, 'event' => 'node_1']); + $response = $this->apiCall('POST', $route, []); + $response->assertStatus(201); + + Bus::assertDispatchedTimes(SendEmail::class, 2); + foreach (Bus::dispatched(SendEmail::class) as $job) { + $this->assertTrue($job->delay === null || $job->delay === 0); + } + } } diff --git a/tests/Feature/TaskControllerTest.php b/tests/Feature/TaskControllerTest.php index ca20a88098..c0fe328664 100644 --- a/tests/Feature/TaskControllerTest.php +++ b/tests/Feature/TaskControllerTest.php @@ -149,13 +149,16 @@ public function testReturnMessageTokenNoFound() } /** - * ABE click metadata is nested under abe_responder (not flat top-level keys). + * ABE click metadata is nested under abe_responder when trackResponder is enabled. */ public function testActionByEmailStoresResponderMetadataNestedInRequestData(): void { - $process = Process::factory()->create([ - 'bpmn' => file_get_contents(__DIR__ . '/../Fixtures/action_by_email_process_no_require_login.bpmn'), - ]); + $bpmn = str_replace( + '"requireLogin":false', + '"requireLogin":false,"trackResponder":true', + file_get_contents(__DIR__ . '/../Fixtures/action_by_email_process_no_require_login.bpmn') + ); + $process = Process::factory()->create(['bpmn' => $bpmn]); Screen::factory()->create(); $route = route('api.process_events.trigger', [$process->id, 'event' => 'node_1']); @@ -191,4 +194,31 @@ public function testActionByEmailStoresResponderMetadataNestedInRequestData(): v $this->assertArrayNotHasKey('identity_mismatch', $data); $this->assertArrayNotHasKey('user_id', $data); } + + /** + * Without trackResponder, request data must not include abe_responder. + */ + public function testActionByEmailOmitsResponderMetadataWhenTrackingDisabled(): void + { + $process = Process::factory()->create([ + 'bpmn' => file_get_contents(__DIR__ . '/../Fixtures/action_by_email_process_no_require_login.bpmn'), + ]); + Screen::factory()->create(); + + $route = route('api.process_events.trigger', [$process->id, 'event' => 'node_1']); + $this->apiCall('POST', $route, []); + + $processAbeRequest = ProcessAbeRequestToken::firstOrFail(); + $response = $this->webCall( + 'GET', + 'tasks/update_variable/' . $processAbeRequest->uuid . '?varName=res&varValue=yes' + ); + $response->assertStatus(200); + + $request = ProcessRequest::findOrFail($processAbeRequest->process_request_id); + $data = $request->data; + + $this->assertSame('yes', $data['res'] ?? null); + $this->assertArrayNotHasKey('abe_responder', $data); + } } From 65bc9be2fe68c21d2386e1717403ba675a0ab0ad Mon Sep 17 00:00:00 2001 From: sanja <52755494+sanjacornelius@users.noreply.github.com> Date: Fri, 13 Nov 2026 20:24:42 -0800 Subject: [PATCH 11/20] Document Track responder identity for Actions by Email --- docs/abe-responder-tracking.md | 187 +++++++++++++++++++++++++++++++++ 1 file changed, 187 insertions(+) create mode 100644 docs/abe-responder-tracking.md diff --git a/docs/abe-responder-tracking.md b/docs/abe-responder-tracking.md new file mode 100644 index 0000000000..7417a59d15 --- /dev/null +++ b/docs/abe-responder-tracking.md @@ -0,0 +1,187 @@ +# Actions by Email: Responder Tracking + +This document describes **Track responder identity** for Actions by Email (ABE): personalized signed links and the nested `abe_responder` object written into request data when someone acts from an email. + +## Overview + +By default, ABE sends a **shared** action link to all recipients. Anyone with the link can complete the task, and ProcessMaker cannot reliably tell which recipient clicked. + +When **Track responder identity** is enabled, ProcessMaker instead: + +1. Resolves unique recipients from the task assignment rules +2. Sends **one personalized email per unique email address** +3. Rewrites ABE action URLs in that email with a **signed query string** identifying the recipient (and assigned groups) +4. On click, writes an **`abe_responder`** object into request data for downstream use + +Token-row fields such as `process_abe_request_tokens.user_id` and `answered_at` continue to work as before. Responder tracking adds request-data metadata; it does not replace those columns. + +## Enabling the feature + +In the Modeler, open a Form Task with **Actions by Email** enabled. + +1. Turn on **Actions by Email** +2. Configure subject, email screen, require login, and completed screen as usual +3. Enable **Track responder identity** + +The control is stored on the task as `pm:configEmail` JSON: + +```json +{ + "subject": "RE: Form Task", + "emailServer": "", + "requireLogin": false, + "screenEmailRef": 142, + "screenCompleteRef": 10, + "trackResponder": true +} +``` + +| `trackResponder` | Behavior | +| --- | --- | +| `false` / omitted (default) | Legacy shared link; **no** `abe_responder` in request data | +| `true` | Personalized signed emails; `abe_responder` written on click | + +## How sending works + +### Recipient resolution + +Recipients come from assignment rules (assigned user, or self-service users/groups): + +- Inactive / out-of-office users are excluded +- A user in **multiple assigned groups** receives **one** email; those groups are merged into the signed payload +- If two different users share the **same email address**, only **one** email is sent (first user by id wins) + +### Personalized links + +Each email’s ABE `/tasks/update_variable/{token_abe}` links are updated automatically to append signed parameters: + +| Param | Meaning | +| --- | --- | +| `abe_email` | Recipient email (normalized) | +| `abe_user_id` | ProcessMaker user id | +| `abe_groups` | Base64 JSON of `[{ "id", "name" }, ...]` | +| `abe_sig` | HMAC-SHA256 over token + email + user id + groups (using `app.key`) | + +Authors do not need to change email screens: known ABE action URLs are rewritten when the email HTML is built. + +### Staggered dispatch + +Personalized sends are queued one job per recipient. Dispatches are staggered by default (`index × 1` second) to reduce provider “emails per second” throttling. + +Optional config: + +```php +// config/app.php or runtime config +'abe_email_stagger_seconds' => 1, +``` + +## How clicks update request data + +`TaskController::updateVariable` always sets the action variable (`varName` / `varValue`). + +**Only when `trackResponder` is true** on the task’s `configEmail`, it also sets: + +```text +abe_responder +``` + +### `abe_responder` shape + +```json +{ + "email": "user@example.com", + "user_id": 42, + "groups": [{ "id": 6, "name": "Approvers" }], + "acted_at": "2026-11-14T00:15:30+00:00", + "ip_address": "203.0.113.10", + "user_agent": "Mozilla/5.0 ...", + "device": "desktop", + "email_client": "Gmail", + "authenticated_email": "user@example.com", + "authenticated_user_id": 42, + "identity_mismatch": false +} +``` + +| Field | Required / when present | Description | +| --- | --- | --- | +| `email` | When signature verifies | Signed-link recipient email | +| `user_id` | When signature verifies | Signed-link user id | +| `groups` | When signature verifies | Assigned groups from the signature | +| `acted_at` | Always (when tracking on) | ISO-8601 action timestamp | +| `ip_address` | Always (when tracking on) | Request IP | +| `user_agent` | Always (when tracking on) | Raw User-Agent | +| `device` | Always (when tracking on) | Best-effort: `mobile`, `desktop`, or `unknown` | +| `email_client` | Always (when tracking on) | Best-effort parse (Gmail, Outlook, Apple Mail, …, Unknown) | +| `authenticated_email` | When a real user is logged in | Session user’s email | +| `authenticated_user_id` | When a real user is logged in | Session user’s id | +| `identity_mismatch` | When a real user is logged in | `true` if authenticated email ≠ signed `email` | + +Notes: + +- `email` is **always** the signed recipient when the signature is valid—not the logged-in user’s email. +- If the clicker is logged in as a different person, the action is **still allowed**; mismatch is recorded via `identity_mismatch` plus `authenticated_*`. +- Anonymous / public ABE sessions are not treated as authenticated identity. +- **Unsigned / legacy links** (no valid signature): action still succeeds; `abe_responder` is sparse (timestamp, IP, UA, device, email client—and authenticated fields if logged in). No signed `email` / `user_id` / `groups`. + +When `trackResponder` is **false**, request data contains only the action field (for example `res: "yes"`)—**not** `abe_responder`. + +## Downstream usage + +After the task completes, process request data includes `abe_responder` (when tracking was on). Use it in: + +- Scripts / data connectors +- Conditional flows +- Collections / reports +- Completed screens + +Example Mustache / data path: + +```text +{{abe_responder.email}} +{{abe_responder.acted_at}} +{{abe_responder.identity_mismatch}} +``` + +## Limitations and operational risks + +Personalized tracking means **N recipients ≈ N email sends**. + +Large assignment groups can hit: + +- Per-second rate limits (e.g. Mailtrap testing: `550 5.7.0 Too many emails per second`) +- Daily external-send quotas (e.g. Microsoft `*.onmicrosoft.com`: `550 5.7.236`) +- Provider reputation / spam filtering under burst volume + +Recommendations: + +- Prefer production ESPs or a custom sending domain (not `onmicrosoft.com` test mailboxes) for large groups +- Keep stagger enabled; increase `abe_email_stagger_seconds` if needed +- Avoid large groups of fake/external addresses in test tenants +- Expect slower overall delivery as group size grows (staggered queue) + +Other client/security notes: + +- Corporate link wrappers (Safe Links, etc.) usually preserve query params; if `abe_sig` is stripped, the click falls back to sparse `abe_responder` +- `device` / `email_client` are best-effort User-Agent heuristics, not definitive device attestation + +## Related code + +| Area | Location | +| --- | --- | +| UI opt-in | `connector-send-email` → `resources/js/connectors/email/send/ActionsByEmail.vue` | +| Recipient resolution + send | `ProcessMaker/Repositories/TokenRepository.php` | +| Link rewrite + queue send | `ProcessMaker/Mail/TaskActionByEmail.php` | +| Signature | `ProcessMaker/Helpers/AbeRecipientSignature.php` | +| Request-data builder | `ProcessMaker/Helpers/AbeResponder.php` | +| Click handler | `ProcessMaker/Http/Controllers/TaskController.php` (`updateVariable`) | +| Stagger helper | `package-actions-by-email` → `EmailProvider::sendAsync($config, $delaySeconds)` | + +## Tests + +- `tests/unit/Helpers/AbeRecipientSignatureTest.php` +- `tests/unit/Helpers/AbeResponderTest.php` +- `tests/unit/Mail/TaskActionByEmailLinkRewriteTest.php` +- `tests/Feature/Api/TaskActionByEmailSelfServiceTest.php` +- `tests/Feature/AbeLargeRecipientGroupTest.php` +- `tests/Feature/TaskControllerTest.php` (nested `abe_responder` when enabled; omitted when disabled) From 8a91e6f680ecd77ac38c2ffffc1835208fecd911 Mon Sep 17 00:00:00 2001 From: sanja <52755494+sanjacornelius@users.noreply.github.com> Date: Sat, 14 Nov 2026 17:38:55 -0800 Subject: [PATCH 12/20] Preserve signed ABE click params across Require Login via abe_click_ticket --- .../Http/Controllers/TaskController.php | 121 +++++++++++++++--- .../Http/Middleware/EncryptCookies.php | 5 +- 2 files changed, 105 insertions(+), 21 deletions(-) diff --git a/ProcessMaker/Http/Controllers/TaskController.php b/ProcessMaker/Http/Controllers/TaskController.php index fa043f3996..8ae756aca3 100755 --- a/ProcessMaker/Http/Controllers/TaskController.php +++ b/ProcessMaker/Http/Controllers/TaskController.php @@ -6,10 +6,13 @@ use Illuminate\Auth\Events\Login; use Illuminate\Http\Request as HttpRequest; use Illuminate\Support\Facades\Auth; +use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Request; +use Illuminate\Support\Str; use ProcessMaker\Events\ScreenBuilderStarting; use ProcessMaker\Facades\WorkflowManager; use ProcessMaker\Filters\SaveSession; +use ProcessMaker\Helpers\AbeRecipientSignature; use ProcessMaker\Helpers\AbeResponder; use ProcessMaker\Helpers\DefaultColumns; use ProcessMaker\Helpers\MobileHelper; @@ -256,6 +259,17 @@ public function quickFillEdit(ProcessRequestToken $task) ]); } + /** + * Short-lived cookie that points at a cache entry with the full ABE click query. + * Needed because showLoginForm clears the session cookie, so url.intended alone + * is not reliable for preserving signed recipient params across Require Login. + */ + public const ABE_CLICK_TICKET_COOKIE = 'abe_click_ticket'; + + private const ABE_CLICK_CACHE_PREFIX = 'abe_click:'; + + private const ABE_CLICK_CACHE_TTL_MINUTES = 20; + /** * Update variable. * @@ -264,12 +278,6 @@ public function quickFillEdit(ProcessRequestToken $task) */ public function updateVariable(HttpRequest $request, $abe_uuid) { - // Validar los parámetros GET - $request->validate([ - 'varName' => 'required|string', - 'varValue' => 'required|string', - ]); - try { // Verificar si la respuesta ya ha sido enviada $abe = ProcessAbeRequestToken::where('uuid', $abe_uuid)->first(); @@ -277,22 +285,19 @@ public function updateVariable(HttpRequest $request, $abe_uuid) if (!$abe) { return $this->returnErrorResponse(__('Token not found'), 404); } + + // Restore signed click query if Require Login dropped it from the URL. + $this->restoreAbeClickQuery($request, $abe); + + // Validar los parámetros GET (after restore so varName/varValue survive login) + $request->validate([ + 'varName' => 'required|string', + 'varValue' => 'required|string', + ]); + // Review if the autentication is required if ($abe->require_login && Auth::user()->username === AnonymousUser::ANONYMOUS_USERNAME) { - $request->session()->put('url.intended', url()->full()); - $cookie = cookie( - 'processmaker_intended', - url()->full(), - 10, - '/', - null, - true, - true, - false, - config('session.same_site') ?: 'lax' - ); - - return redirect('login')->withCookie($cookie); + return $this->redirectAbeClickToLogin($request, $abe); } if ($abe->is_answered) { return $this->returnErrorResponse(__('This response has already been answered'), 200); @@ -365,6 +370,82 @@ private function abeTrackResponderEnabled(ProcessRequestToken $task): bool return is_array($configEmail) && !empty($configEmail['trackResponder']); } + /** + * Park the full ABE click query in cache and send the user to login. + * Login clears the session cookie, so a short ticket cookie is the durable key. + */ + private function redirectAbeClickToLogin(HttpRequest $request, ProcessAbeRequestToken $abe) + { + $ticket = Str::random(40); + Cache::put( + self::ABE_CLICK_CACHE_PREFIX . $ticket, + [ + 'abe_uuid' => $abe->uuid, + 'query' => $request->query(), + ], + now()->addMinutes(self::ABE_CLICK_CACHE_TTL_MINUTES) + ); + + // Keep a short intended URL; query is restored from cache after login. + $intended = route('tasks.abe.update', ['token_abe' => $abe->uuid]); + $request->session()->put('url.intended', $intended); + + $sameSite = config('session.same_site') ?: 'lax'; + $intendedCookie = cookie( + 'processmaker_intended', + $intended, + self::ABE_CLICK_CACHE_TTL_MINUTES, + '/', + null, + true, + true, + false, + $sameSite + ); + $ticketCookie = cookie( + self::ABE_CLICK_TICKET_COOKIE, + $ticket, + self::ABE_CLICK_CACHE_TTL_MINUTES, + '/', + null, + true, + true, + false, + $sameSite + ); + + return redirect('login')->withCookie($intendedCookie)->withCookie($ticketCookie); + } + + /** + * Merge a parked ABE click query back onto the request when the signature is missing. + */ + private function restoreAbeClickQuery(HttpRequest $request, ProcessAbeRequestToken $abe): void + { + if ((string) $request->query(AbeRecipientSignature::SIG, '') !== '') { + return; + } + + $ticket = (string) $request->cookie(self::ABE_CLICK_TICKET_COOKIE, ''); + if ($ticket === '') { + return; + } + + $pending = Cache::pull(self::ABE_CLICK_CACHE_PREFIX . $ticket); + if (!is_array($pending) || ($pending['abe_uuid'] ?? null) !== $abe->uuid) { + return; + } + + $query = $pending['query'] ?? null; + if (!is_array($query) || $query === []) { + return; + } + + $request->query->replace(array_merge($request->query->all(), $query)); + // Keep input() / validate() in sync for GET requests. + $request->request->replace(array_merge($request->request->all(), $query)); + } + /** * Show a screen defined * @param int $screenId diff --git a/ProcessMaker/Http/Middleware/EncryptCookies.php b/ProcessMaker/Http/Middleware/EncryptCookies.php index 56273fb944..04956da762 100644 --- a/ProcessMaker/Http/Middleware/EncryptCookies.php +++ b/ProcessMaker/Http/Middleware/EncryptCookies.php @@ -21,6 +21,9 @@ class EncryptCookies extends BaseEncrypter */ 'device_id', 'fromTriggerStartEvent', - 'language' + 'language', + // Opaque ABE Require-Login ticket (random id → cache). Must survive login + // form session-cookie reset without depending on Laravel cookie encryption. + 'abe_click_ticket', ]; } From 71ccb41d636becb2a32241fef83a4cbaaef527d0 Mon Sep 17 00:00:00 2001 From: sanja <52755494+sanjacornelius@users.noreply.github.com> Date: Sat, 14 Nov 2026 17:39:13 -0800 Subject: [PATCH 13/20] Omit identity_mismatch unless a signed ABE recipient is present to compare --- ProcessMaker/Helpers/AbeResponder.php | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/ProcessMaker/Helpers/AbeResponder.php b/ProcessMaker/Helpers/AbeResponder.php index 98532fc531..3d90d5a8fd 100644 --- a/ProcessMaker/Helpers/AbeResponder.php +++ b/ProcessMaker/Helpers/AbeResponder.php @@ -41,9 +41,14 @@ public static function fromRequest(Request $request, string $tokenAbe): array $responder['authenticated_email'] = $authUser->email; $responder['authenticated_user_id'] = $authUser->id; + // Only compare when a signed recipient is present. If the signature + // is missing/invalid (e.g. query params dropped after login redirect), + // do not claim identity_mismatch false — there is nothing to match. $signedEmail = strtolower(trim((string) ($responder['email'] ?? ''))); - $authEmail = strtolower(trim((string) $authUser->email)); - $responder['identity_mismatch'] = $signedEmail !== '' && $signedEmail !== $authEmail; + if ($signedEmail !== '') { + $authEmail = strtolower(trim((string) $authUser->email)); + $responder['identity_mismatch'] = $signedEmail !== $authEmail; + } } return $responder; From fdb33c3f42d87bceca14e4a59f0db8fbb685244f Mon Sep 17 00:00:00 2001 From: sanja <52755494+sanjacornelius@users.noreply.github.com> Date: Sat, 14 Nov 2026 17:39:26 -0800 Subject: [PATCH 14/20] Test Require Login preserves signed recipient and omits mismatch without a signature --- tests/Feature/TaskControllerTest.php | 67 +++++++++++++++++++++++++ tests/unit/Helpers/AbeResponderTest.php | 21 ++++++++ 2 files changed, 88 insertions(+) diff --git a/tests/Feature/TaskControllerTest.php b/tests/Feature/TaskControllerTest.php index c0fe328664..d009eb917d 100644 --- a/tests/Feature/TaskControllerTest.php +++ b/tests/Feature/TaskControllerTest.php @@ -4,8 +4,11 @@ use Faker\Factory as Faker; use Illuminate\Support\Facades\Auth; +use Illuminate\Support\Facades\Cache; use ProcessMaker\Facades\WorkflowManager; use ProcessMaker\Helpers\AbeRecipientSignature; +use ProcessMaker\Http\Controllers\TaskController; +use ProcessMaker\Models\AnonymousUser; use ProcessMaker\Models\Process; use ProcessMaker\Models\ProcessAbeRequestToken; use ProcessMaker\Models\ProcessRequest; @@ -221,4 +224,68 @@ public function testActionByEmailOmitsResponderMetadataWhenTrackingDisabled(): v $this->assertSame('yes', $data['res'] ?? null); $this->assertArrayNotHasKey('abe_responder', $data); } + + /** + * Require Login + tracking: signed recipient survives login even if the query + * string is dropped; a different logged-in user sets identity_mismatch. + */ + public function testRequireLoginPreservesSignedRecipientAndSetsIdentityMismatch(): void + { + $bpmn = str_replace( + '"requireLogin":true', + '"requireLogin":true,"trackResponder":true', + file_get_contents(__DIR__ . '/../Fixtures/action_by_email_process_require_login.bpmn') + ); + $process = Process::factory()->create(['bpmn' => $bpmn]); + Screen::factory()->create(); + + $route = route('api.process_events.trigger', [$process->id, 'event' => 'node_1']); + $this->apiCall('POST', $route, []); + + $processAbeRequest = ProcessAbeRequestToken::firstOrFail(); + $this->assertEquals(1, $processAbeRequest->require_login); + + $signedEmail = 'original-recipient@example.com'; + $signedQuery = AbeRecipientSignature::queryString( + $processAbeRequest->uuid, + $signedEmail, + 55, + [['id' => 9, 'name' => 'Approvers']] + ); + + $anonymous = User::where('username', AnonymousUser::ANONYMOUS_USERNAME)->firstOrFail(); + + $clickUrl = 'tasks/update_variable/' . $processAbeRequest->uuid + . '?varName=res&varValue=yes&' . $signedQuery; + // Do not use webCall() — it re-authenticates as the default test user. + $redirect = $this->actingAs($anonymous, 'web')->get($clickUrl); + $redirect->assertRedirect('login'); + $redirect->assertPlainCookie(TaskController::ABE_CLICK_TICKET_COOKIE); + + $ticket = $redirect->getCookie(TaskController::ABE_CLICK_TICKET_COOKIE, false)->getValue(); + $this->assertNotEmpty($ticket); + $this->assertTrue(Cache::has('abe_click:' . $ticket)); + + // Simulate post-login return with query string stripped (session cleared on login form). + $forwardedUser = User::factory()->create([ + 'email' => 'forwarded-user@example.com', + 'status' => 'ACTIVE', + ]); + + $response = $this->actingAs($forwardedUser, 'web') + ->withUnencryptedCookie(TaskController::ABE_CLICK_TICKET_COOKIE, $ticket) + ->get('tasks/update_variable/' . $processAbeRequest->uuid); + $response->assertStatus(200); + + $request = ProcessRequest::findOrFail($processAbeRequest->process_request_id); + $data = $request->data; + $responder = $data['abe_responder'] ?? null; + + $this->assertIsArray($responder); + $this->assertSame($signedEmail, $responder['email']); + $this->assertSame(55, $responder['user_id']); + $this->assertSame('forwarded-user@example.com', $responder['authenticated_email']); + $this->assertSame($forwardedUser->id, $responder['authenticated_user_id']); + $this->assertTrue($responder['identity_mismatch']); + } } diff --git a/tests/unit/Helpers/AbeResponderTest.php b/tests/unit/Helpers/AbeResponderTest.php index bad0e65e3b..68dc11c78b 100644 --- a/tests/unit/Helpers/AbeResponderTest.php +++ b/tests/unit/Helpers/AbeResponderTest.php @@ -109,4 +109,25 @@ public function testUnsignedLinkStillBuildsSparseResponder(): void $this->assertSame('desktop', $responder['device']); $this->assertSame('Outlook', $responder['email_client']); } + + public function testAuthenticatedUnsignedClickOmitsIdentityMismatch(): void + { + $authUser = User::factory()->create([ + 'email' => 'logged-in@example.com', + 'status' => 'ACTIVE', + ]); + $this->actingAs($authUser); + + $request = Request::create('/tasks/update_variable/abe-token', 'GET', [ + 'varName' => 'res', + 'varValue' => 'yes', + ]); + + $responder = AbeResponder::fromRequest($request, 'abe-token'); + + $this->assertSame('logged-in@example.com', $responder['authenticated_email']); + $this->assertSame($authUser->id, $responder['authenticated_user_id']); + $this->assertArrayNotHasKey('email', $responder); + $this->assertArrayNotHasKey('identity_mismatch', $responder); + } } From 6a4fa3ec2bbd41d7fe90f45176ca3d7aec14252f Mon Sep 17 00:00:00 2001 From: sanja <52755494+sanjacornelius@users.noreply.github.com> Date: Sat, 14 Nov 2026 17:39:37 -0800 Subject: [PATCH 15/20] Document abe_click_ticket restore and forward + Require Login mismatch behavior --- docs/abe-responder-tracking.md | 41 +++++++++++++++++++++++++++++++--- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git a/docs/abe-responder-tracking.md b/docs/abe-responder-tracking.md index 7417a59d15..78c337978d 100644 --- a/docs/abe-responder-tracking.md +++ b/docs/abe-responder-tracking.md @@ -123,9 +123,41 @@ Notes: - If the clicker is logged in as a different person, the action is **still allowed**; mismatch is recorded via `identity_mismatch` plus `authenticated_*`. - Anonymous / public ABE sessions are not treated as authenticated identity. - **Unsigned / legacy links** (no valid signature): action still succeeds; `abe_responder` is sparse (timestamp, IP, UA, device, email client—and authenticated fields if logged in). No signed `email` / `user_id` / `groups`. +- **Forwarded emails:** If User A receives a personalized ABE email and forwards it to User B, and User B clicks an action button, `abe_responder.email` / `user_id` / `groups` still record **User A** (the signed recipient). The link identity travels with the message; forwarding does not re-bind it to B. With **Require Login**, if B logs in as B, the action still completes and `identity_mismatch` is set to `true` with `authenticated_*` identifying B—ProcessMaker does **not** block the click today. Downstream processes can branch on `identity_mismatch` if they need to handle forwards. When `trackResponder` is **false**, request data contains only the action field (for example `res: "yes"`)—**not** `abe_responder`. +## Require Login and signed params + +**Require Login** redirects anonymous clickers to the login page before the ABE action completes. The login form clears the ProcessMaker **session cookie**, which historically could drop the signed query string (`abe_email`, `abe_user_id`, `abe_groups`, `abe_sig`). After login as a different user, only the authenticated identity remained—so forwards looked like “User B was tracked” and `identity_mismatch` never became `true`. + +### How signed params survive login + +When Require Login redirects to login, ProcessMaker: + +1. Parks the **full click query** (action + signed recipient params) in **cache** for a short TTL (~20 minutes) +2. Sets a short opaque cookie: `abe_click_ticket` (not encrypted; listed in `EncryptCookies` exceptions) +3. Sets `processmaker_intended` / `url.intended` to the ABE `update_variable` route (query restored from cache, not only from the URL) + +When the user returns to `update_variable` after login, the handler restores the parked query from the ticket **even if the browser URL has no query string**, then builds `abe_responder` as usual. + +### Expected result after a forward + Require Login + +| Field | Value | +| --- | --- | +| `abe_responder.email` / `user_id` / `groups` | Original signed recipient (User A) | +| `abe_responder.authenticated_email` / `authenticated_user_id` | Who logged in (User B) | +| `abe_responder.identity_mismatch` | `true` when A’s signed email ≠ B’s login email | +| ABE token row `user_id` | Logged-in user (User B) | + +`identity_mismatch` is only set when **both** a valid signed recipient and a real logged-in user are present. If the signature cannot be restored, signed `email` is omitted and `identity_mismatch` is omitted (not forced to `false`). + +### How to test forwards + Require Login + +1. Log out of ProcessMaker (or use a private window) before B clicks. If A’s session is still active, Require Login will **not** prompt, Auth stays A, and `identity_mismatch` stays `false`. +2. Open the forwarded link while logged out → log in as **B**. +3. Confirm request data: `email` = A, `authenticated_email` = B, `identity_mismatch` = `true`. + ## Downstream usage After the task completes, process request data includes `abe_responder` (when tracking was on). Use it in: @@ -162,8 +194,10 @@ Recommendations: Other client/security notes: -- Corporate link wrappers (Safe Links, etc.) usually preserve query params; if `abe_sig` is stripped, the click falls back to sparse `abe_responder` +- Corporate link wrappers (Safe Links, etc.) usually preserve query params; if `abe_sig` is stripped **and** there is no `abe_click_ticket` restore, the click falls back to sparse `abe_responder` - `device` / `email_client` are best-effort User-Agent heuristics, not definitive device attestation +- Forwarded personalized links cannot prove the clicker owns the intended inbox; signed attribution stays with the original recipient. `identity_mismatch` only appears when both a valid signature and a real logged-in user are present and their emails differ. +- The `abe_click_ticket` cookie is a random cache key (no PII). Pending click payloads expire from cache after the TTL; a missing/expired ticket cannot restore the signature. ## Related code @@ -174,7 +208,8 @@ Other client/security notes: | Link rewrite + queue send | `ProcessMaker/Mail/TaskActionByEmail.php` | | Signature | `ProcessMaker/Helpers/AbeRecipientSignature.php` | | Request-data builder | `ProcessMaker/Helpers/AbeResponder.php` | -| Click handler | `ProcessMaker/Http/Controllers/TaskController.php` (`updateVariable`) | +| Click handler + Require Login ticket | `ProcessMaker/Http/Controllers/TaskController.php` (`updateVariable`, `abe_click_ticket`) | +| Unencrypted ticket cookie | `ProcessMaker/Http/Middleware/EncryptCookies.php` (`abe_click_ticket` in `$except`) | | Stagger helper | `package-actions-by-email` → `EmailProvider::sendAsync($config, $delaySeconds)` | ## Tests @@ -184,4 +219,4 @@ Other client/security notes: - `tests/unit/Mail/TaskActionByEmailLinkRewriteTest.php` - `tests/Feature/Api/TaskActionByEmailSelfServiceTest.php` - `tests/Feature/AbeLargeRecipientGroupTest.php` -- `tests/Feature/TaskControllerTest.php` (nested `abe_responder` when enabled; omitted when disabled) +- `tests/Feature/TaskControllerTest.php` (nested `abe_responder` when enabled; omitted when disabled; Require Login preserves signed recipient and sets `identity_mismatch`) From beef46df8560da1412c777efe89303e0ffd798c8 Mon Sep 17 00:00:00 2001 From: sanja <52755494+sanjacornelius@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:50:49 -0800 Subject: [PATCH 16/20] Render the ABE email screen once per mailer and reuse it for personalized sends --- ProcessMaker/Mail/TaskActionByEmail.php | 83 ++++++++++++++----- ProcessMaker/Repositories/TokenRepository.php | 6 +- 2 files changed, 65 insertions(+), 24 deletions(-) diff --git a/ProcessMaker/Mail/TaskActionByEmail.php b/ProcessMaker/Mail/TaskActionByEmail.php index 5e23805270..478c3e7f51 100644 --- a/ProcessMaker/Mail/TaskActionByEmail.php +++ b/ProcessMaker/Mail/TaskActionByEmail.php @@ -11,9 +11,17 @@ class TaskActionByEmail { private $emailProvider; - public function __construct() + /** + * Shared screen/subject render for a single personalized-send batch. + * Personalized ABE sends reuse this and only rewrite signed links per recipient. + * + * @var array{subject:string,body:string,styles:string,emailServer:mixed}|null + */ + private $sharedContent = null; + + public function __construct(?EmailProvider $emailProvider = null) { - $this->emailProvider = new EmailProvider(); + $this->emailProvider = $emailProvider ?? new EmailProvider(); } /** @@ -22,6 +30,10 @@ public function __construct() * This method constructs and sends an email using the provided configuration, * recipient email address, and additional data for rendering the email content. * + * When the same TaskActionByEmail instance sends to multiple personalized + * recipients, the email screen is rendered once and reused; only signed + * action-link params are applied per recipient. + * * @param array $config Configuration object containing email settings, including: * - emailServer: The email server ID (integer, optional, default: 0). * - subject: The subject of the email (string, optional, default: ''). @@ -36,32 +48,25 @@ public function __construct() public function sendAbeEmail($config, $to, $data, ?string $signedQuery = null, int $delaySeconds = 0) { try { - // Get parameters to send the email - $emailServer = $config['emailServer'] ?? 0; - $subject = $config['subject'] ?? ''; - $emailScreenRef = $config['screenEmailRef'] ?? 0; + $shared = $this->sharedEmailContent($config, $data); + $emailServer = $shared['emailServer']; + + $body = $signedQuery + ? $this->appendSignedParamsToAbeLinks($shared['body'], $signedQuery) + : $shared['body']; $emailConfig = [ - 'subject' => $this->mustache($subject, $data), + 'subject' => $shared['subject'], 'addEmails' => $to, 'email' => $to, 'type' => 'html', 'json_data' => '{}', 'emailServer' => $emailServer, + 'body' => $body, ]; - if (!empty($emailScreenRef)) { - // Retrieve and render custom screen if specified - $customScreen = Screen::findOrFail($emailScreenRef); - $infoRenderer = $this->emailProvider->screenRenderer($customScreen->config, $data, $customScreen); - $body = $infoRenderer['body'] ?? __('No body configured'); - $emailConfig['body'] = $signedQuery - ? $this->appendSignedParamsToAbeLinks($body, $signedQuery) - : $body; - $emailConfig['styles'] = $infoRenderer['styles'] ?? ''; - } else { - // Default message if no custom screen is configured - $emailConfig['body'] = __('No screen configured'); + if ($shared['styles'] !== '') { + $emailConfig['styles'] = $shared['styles']; } // Personalized ABE sends are one message per recipient (unique signed link). @@ -70,9 +75,9 @@ public function sendAbeEmail($config, $to, $data, ?string $signedQuery = null, i } catch (\Exception $e) { Log::error('Error sending ABE email', [ 'to' => $to, - 'emailServer' => $emailServer, - 'subject' => $subject, - 'screen' => $emailScreenRef, + 'emailServer' => $emailServer ?? ($config['emailServer'] ?? 0), + 'subject' => $config['subject'] ?? '', + 'screen' => $config['screenEmailRef'] ?? 0, 'error' => $e->getMessage(), ]); } @@ -80,6 +85,40 @@ public function sendAbeEmail($config, $to, $data, ?string $signedQuery = null, i return true; } + /** + * Render subject/body/styles once per mailer instance for a recipient batch. + * + * @return array{subject:string,body:string,styles:string,emailServer:mixed} + */ + private function sharedEmailContent(array $config, array $data): array + { + if ($this->sharedContent !== null) { + return $this->sharedContent; + } + + $emailServer = $config['emailServer'] ?? 0; + $subject = $this->mustache($config['subject'] ?? '', $data); + $emailScreenRef = $config['screenEmailRef'] ?? 0; + $body = __('No screen configured'); + $styles = ''; + + if (!empty($emailScreenRef)) { + $customScreen = Screen::findOrFail($emailScreenRef); + $infoRenderer = $this->emailProvider->screenRenderer($customScreen->config, $data, $customScreen); + $body = $infoRenderer['body'] ?? __('No body configured'); + $styles = $infoRenderer['styles'] ?? ''; + } + + $this->sharedContent = [ + 'subject' => $subject, + 'body' => $body, + 'styles' => $styles, + 'emailServer' => $emailServer, + ]; + + return $this->sharedContent; + } + /** * Append signed recipient params to known ABE action URLs only. */ diff --git a/ProcessMaker/Repositories/TokenRepository.php b/ProcessMaker/Repositories/TokenRepository.php index 6bc2bcd45f..4b5af5ed31 100644 --- a/ProcessMaker/Repositories/TokenRepository.php +++ b/ProcessMaker/Repositories/TokenRepository.php @@ -239,8 +239,10 @@ private function validateAndSendActionByEmail(ActivityInterface $activity, Token // Opt-in responder tracking: one personalized email per unique address // with a signed link. Overlapping group membership is collapsed in - // resolveAbeRecipients (groups merged). Stagger dispatches so providers - // with per-second caps (Mailtrap, etc.) are less likely to throttle. + // resolveAbeRecipients (groups merged). The shared mailer instance + // renders the email screen once; only signed links differ per send. + // Stagger dispatches so providers with per-second caps (Mailtrap, + // etc.) are less likely to throttle. $staggerSeconds = max(0, (int) config('app.abe_email_stagger_seconds', 1)); foreach ($recipients as $index => $recipient) { $signedQuery = AbeRecipientSignature::queryString( From 95e0ab438e9708cb27d54c189bca8a217fb853dc Mon Sep 17 00:00:00 2001 From: sanja <52755494+sanjacornelius@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:50:59 -0800 Subject: [PATCH 17/20] Assert personalized ABE batches render the email screen once per recipient group --- .../TaskActionByEmailSharedRenderTest.php | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 tests/unit/Mail/TaskActionByEmailSharedRenderTest.php diff --git a/tests/unit/Mail/TaskActionByEmailSharedRenderTest.php b/tests/unit/Mail/TaskActionByEmailSharedRenderTest.php new file mode 100644 index 0000000000..6ffd1ab012 --- /dev/null +++ b/tests/unit/Mail/TaskActionByEmailSharedRenderTest.php @@ -0,0 +1,69 @@ +create([ + 'config' => [['items' => []]], + ]); + + $body = 'Approve'; + $provider = Mockery::mock(EmailProvider::class); + $provider->shouldReceive('screenRenderer') + ->once() + ->andReturn(['body' => $body, 'styles' => '/* shared */']); + + $dispatched = []; + $provider->shouldReceive('sendAsync') + ->twice() + ->andReturnUsing(function (array $emailConfig, int $delaySeconds = 0) use (&$dispatched) { + $dispatched[] = [ + 'to' => $emailConfig['email'] ?? null, + 'body' => $emailConfig['body'] ?? '', + 'styles' => $emailConfig['styles'] ?? null, + 'delay' => $delaySeconds, + ]; + }); + + $mailer = new TaskActionByEmail($provider); + $config = [ + 'subject' => 'ABE {{token_abe}}', + 'emailServer' => 0, + 'screenEmailRef' => $screen->id, + ]; + $data = ['token_abe' => 'tok-1']; + + $mailer->sendAbeEmail($config, 'a@example.com', $data, 'abe_sig=one', 0); + $mailer->sendAbeEmail($config, 'b@example.com', $data, 'abe_sig=two', 3); + + $this->assertCount(2, $dispatched); + $this->assertSame('a@example.com', $dispatched[0]['to']); + $this->assertSame('b@example.com', $dispatched[1]['to']); + $this->assertSame(0, $dispatched[0]['delay']); + $this->assertSame(3, $dispatched[1]['delay']); + $this->assertSame('/* shared */', $dispatched[0]['styles']); + $this->assertSame('/* shared */', $dispatched[1]['styles']); + $this->assertStringContainsString('abe_sig=one', $dispatched[0]['body']); + $this->assertStringContainsString('abe_sig=two', $dispatched[1]['body']); + $this->assertStringNotContainsString('abe_sig=two', $dispatched[0]['body']); + $this->assertStringNotContainsString('abe_sig=one', $dispatched[1]['body']); + } +} From 2eb5d70175afa8206544ab6be79d29c69b4b931e Mon Sep 17 00:00:00 2001 From: sanja <52755494+sanjacornelius@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:51:07 -0800 Subject: [PATCH 18/20] Note that personalized ABE tracking renders the email screen once per activation --- docs/abe-responder-tracking.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/abe-responder-tracking.md b/docs/abe-responder-tracking.md index 78c337978d..67a0825c58 100644 --- a/docs/abe-responder-tracking.md +++ b/docs/abe-responder-tracking.md @@ -177,7 +177,7 @@ Example Mustache / data path: ## Limitations and operational risks -Personalized tracking means **N recipients ≈ N email sends**. +Personalized tracking means **N recipients ≈ N email sends**. The email **screen is rendered once** per task activation and reused for every personalized recipient; only signed action-link params are applied per send. Queue dispatch is still staggered per recipient. Large assignment groups can hit: From a70b0a069f9b2a45bf48a09676b7b7ac3e614483 Mon Sep 17 00:00:00 2001 From: sanja <52755494+sanjacornelius@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:07:39 -0800 Subject: [PATCH 19/20] Rethrow ValidationException from updateVariable so missing ABE query params are not HTTP 500 --- ProcessMaker/Http/Controllers/TaskController.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ProcessMaker/Http/Controllers/TaskController.php b/ProcessMaker/Http/Controllers/TaskController.php index 8ae756aca3..7634ad2c84 100755 --- a/ProcessMaker/Http/Controllers/TaskController.php +++ b/ProcessMaker/Http/Controllers/TaskController.php @@ -9,6 +9,7 @@ use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Request; use Illuminate\Support\Str; +use Illuminate\Validation\ValidationException; use ProcessMaker\Events\ScreenBuilderStarting; use ProcessMaker\Facades\WorkflowManager; use ProcessMaker\Filters\SaveSession; @@ -344,6 +345,9 @@ public function updateVariable(HttpRequest $request, $abe_uuid) return $this->showScreen($abe->completed_screen_id); } } + } catch (ValidationException $e) { + // Missing/invalid query after a failed Require Login restore must not become HTTP 500. + throw $e; } catch (\Exception $e) { return response()->json([ 'message' => 'Error updating variable', From a04dd64aa0a6c9208ccb1fafeb150c683a95ab00 Mon Sep 17 00:00:00 2001 From: sanja <52755494+sanjacornelius@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:07:54 -0800 Subject: [PATCH 20/20] Assert expired `abe_click` restore returns 422 validation errors, not HTTP 500 --- tests/Feature/TaskControllerTest.php | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/tests/Feature/TaskControllerTest.php b/tests/Feature/TaskControllerTest.php index d009eb917d..733250f40f 100644 --- a/tests/Feature/TaskControllerTest.php +++ b/tests/Feature/TaskControllerTest.php @@ -288,4 +288,30 @@ public function testRequireLoginPreservesSignedRecipientAndSetsIdentityMismatch( $this->assertSame($forwardedUser->id, $responder['authenticated_user_id']); $this->assertTrue($responder['identity_mismatch']); } + + /** + * Failed Require Login restore (expired ticket / missing query) must be a + * validation error, not HTTP 500 "Error updating variable". + */ + public function testMissingAbeClickQueryAfterFailedRestoreReturnsValidationError(): void + { + $process = Process::factory()->create([ + 'bpmn' => file_get_contents(__DIR__ . '/../Fixtures/action_by_email_process_require_login.bpmn'), + ]); + Screen::factory()->create(); + + $route = route('api.process_events.trigger', [$process->id, 'event' => 'node_1']); + $this->apiCall('POST', $route, []); + + $processAbeRequest = ProcessAbeRequestToken::firstOrFail(); + $user = User::factory()->create(['status' => 'ACTIVE']); + + $response = $this->actingAs($user, 'web') + ->withUnencryptedCookie(TaskController::ABE_CLICK_TICKET_COOKIE, 'expired-or-unknown-ticket') + ->getJson('tasks/update_variable/' . $processAbeRequest->uuid); + + $response->assertStatus(422); + $response->assertJsonValidationErrors(['varName', 'varValue']); + $response->assertJsonMissing(['message' => 'Error updating variable']); + } }